@ac-kit/format-pem 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,55 @@
1
+ # @ac-kit/format-pem
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [0b4fe43]
8
+ - Updated dependencies [0b4fe43]
9
+ - Updated dependencies [0b4fe43]
10
+ - Updated dependencies [0b4fe43]
11
+ - Updated dependencies [0b4fe43]
12
+ - Updated dependencies [0b4fe43]
13
+ - Updated dependencies [0b4fe43]
14
+ - Updated dependencies [0b4fe43]
15
+ - Updated dependencies [0b4fe43]
16
+ - Updated dependencies [0b4fe43]
17
+ - Updated dependencies [0b4fe43]
18
+ - Updated dependencies [0b4fe43]
19
+ - Updated dependencies [0b4fe43]
20
+ - Updated dependencies [0b4fe43]
21
+ - Updated dependencies [0b4fe43]
22
+ - Updated dependencies [0b4fe43]
23
+ - Updated dependencies [0b4fe43]
24
+ - @ac-kit/core@0.13.0
25
+
26
+ ## 0.1.0
27
+
28
+ ### Minor Changes
29
+
30
+ - 34e8cfa: First release: read and write PEM text (RFC 7468) such as `-----BEGIN CERTIFICATE-----`
31
+ blocks. Decode the first block found among other text, every block of a
32
+ bundle, or exactly one pasted block; keep only the labels you expect; choose
33
+ the RFC's strict, standard or lax syntax; and cap the text length and decoded
34
+ size for untrusted input. Failures throw `PemError` with a `reason`, the
35
+ offset where decoding stopped and the exceeded limit. Encode bytes as a block
36
+ wrapped at 64 characters.
37
+
38
+ ### Patch Changes
39
+
40
+ - Updated dependencies [34e8cfa]
41
+ - Updated dependencies [34e8cfa]
42
+ - Updated dependencies [34e8cfa]
43
+ - Updated dependencies [34e8cfa]
44
+ - Updated dependencies [34e8cfa]
45
+ - Updated dependencies [34e8cfa]
46
+ - Updated dependencies [34e8cfa]
47
+ - Updated dependencies [34e8cfa]
48
+ - Updated dependencies [34e8cfa]
49
+ - Updated dependencies [34e8cfa]
50
+ - Updated dependencies [34e8cfa]
51
+ - Updated dependencies [34e8cfa]
52
+ - Updated dependencies [34e8cfa]
53
+ - Updated dependencies [34e8cfa]
54
+ - Updated dependencies [34e8cfa]
55
+ - @ac-kit/core@0.12.0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/format-pem
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
+ Read and write PEM, the `-----BEGIN CERTIFICATE-----` text that certificates,
4
+ keys and certificate requests travel in, as RFC 7468 specifies it. Portable ESM
5
+ with no Node.js built-ins.
6
+
7
+ ```ts
8
+ import { decodePem, encodePem } from "@ac-kit/format-pem";
9
+
10
+ const pem = encodePem("CERTIFICATE", derBytes);
11
+ const { label, data } = decodePem(pem);
12
+ // label: "CERTIFICATE", data: the same bytes as derBytes
13
+ ```
14
+
15
+ A PEM block is a label and the bytes its Base64 spells. This package handles
16
+ the text encoding only: it does not look inside the bytes, so a `CERTIFICATE`
17
+ block is not checked to hold a certificate.
18
+
19
+ ## Requirements
20
+
21
+ Uses `Uint8Array.fromBase64` and `Uint8Array.prototype.toBase64` (ES2026):
22
+ Node 25+ and current browsers ship them; elsewhere, load a polyfill first.
23
+
24
+ ## Decode one block
25
+
26
+ `decodePem(text, options?)` returns the first block in `text` as
27
+ `{ label, data }`. Text before, between and after blocks is ignored, so a
28
+ certificate printed with its subject above it reads as it is:
29
+
30
+ ```ts
31
+ import { decodePem } from "@ac-kit/format-pem";
32
+
33
+ decodePem("-----BEGIN TEST-----\nAgEq\n-----END TEST-----\n");
34
+ // { label: "TEST", data: Uint8Array [2, 1, 42] }
35
+ ```
36
+
37
+ With `label`, blocks with another label are skipped and the first one with an
38
+ accepted label is returned; pass several labels as an array:
39
+
40
+ ```ts
41
+ import { decodePem } from "@ac-kit/format-pem";
42
+
43
+ const key = decodePem(bundleText, { label: "PRIVATE KEY" });
44
+ ```
45
+
46
+ With `exact: true`, the text must be the one block and nothing else but
47
+ whitespace, which suits a field where a user pastes a single certificate:
48
+
49
+ ```ts
50
+ import { decodePem } from "@ac-kit/format-pem";
51
+
52
+ decodePem(" -----BEGIN TEST-----\n Ag Eq \n-----END TEST----- \n", {
53
+ syntax: "lax",
54
+ exact: true,
55
+ maxTextLength: 196_608,
56
+ maxDataLength: 65_536,
57
+ }).data; // Uint8Array [2, 1, 42]
58
+ ```
59
+
60
+ ## Decode every block
61
+
62
+ `decodePemAll(text, options?)` returns every block, in order, and an empty
63
+ array when there is none. It takes the same `syntax`, `label` and limit
64
+ options; `label` leaves the other blocks out.
65
+
66
+ ```ts
67
+ import { decodePemAll } from "@ac-kit/format-pem";
68
+
69
+ const bundle = [
70
+ "subject=CN=leaf",
71
+ "-----BEGIN CERTIFICATE-----",
72
+ "AQI=",
73
+ "-----END CERTIFICATE-----",
74
+ "-----BEGIN PRIVATE KEY-----",
75
+ "Aw==",
76
+ "-----END PRIVATE KEY-----",
77
+ "",
78
+ ].join("\n");
79
+
80
+ decodePemAll(bundle).map((block) => block.label);
81
+ // ["CERTIFICATE", "PRIVATE KEY"]
82
+ decodePemAll(bundle, { label: "PRIVATE KEY" })[0]?.data; // Uint8Array [3]
83
+ ```
84
+
85
+ Once a `-----BEGIN` line is found, its block must be well formed, even when its
86
+ label is not wanted: a malformed block throws rather than being skipped. A block
87
+ left out by `label` is checked but not decoded.
88
+
89
+ ## Syntax
90
+
91
+ RFC 7468 gives three grammars, and `syntax` picks the one the text is held to:
92
+
93
+ - `"strict"` — what `encodePem` writes: lines of exactly 64 characters but the
94
+ last, no other whitespace, a line break after each boundary line. Use it to
95
+ check that a generator conforms.
96
+ - `"standard"` (the default) — line-oriented: lines of any length, blanks
97
+ (space, tab) at the end of a line, blank lines before the data.
98
+ - `"lax"` — whitespace anywhere between the boundaries, and around the block on
99
+ its lines. Use it for text people paste.
100
+
101
+ ```ts
102
+ import { decodePem } from "@ac-kit/format-pem";
103
+
104
+ const pasted = "-----BEGIN TEST-----\n Ag Eq\n-----END TEST-----\n";
105
+ decodePem(pasted, { syntax: "lax" }).data; // Uint8Array [2, 1, 42]
106
+ decodePem(pasted); // throws PemError, reason "invalidLayout"
107
+ ```
108
+
109
+ Whatever the syntax:
110
+
111
+ - a `-----BEGIN` line starts its line (after whitespace, under `lax`), and so
112
+ does a `-----END` line under `strict` and `standard`;
113
+ - line breaks may be CRLF, CR or LF;
114
+ - a label is printable ASCII, with single spaces or hyphens between other
115
+ characters, and the labels of both boundaries must be equal;
116
+ - the Base64 is strict: the standard alphabet only, the `=` padding required,
117
+ no unused bits set.
118
+
119
+ RFC 7468 lets a parser skip characters outside the Base64 alphabet, accept
120
+ mismatched labels, and, in its lax grammar, read Base64 without its padding.
121
+ This package refuses all three, so a block has one reading. That also refuses
122
+ the `Proc-Type:` headers of legacy encrypted PEM (RFC 1421), which RFC 7468
123
+ does not allow either.
124
+
125
+ ## Limits and errors
126
+
127
+ `maxTextLength` refuses a longer text, in UTF-16 code units, before reading
128
+ it. `maxDataLength` refuses to decode more bytes, over every block returned,
129
+ before decoding the block that would pass it. Both default to no limit; set
130
+ them for text from an untrusted source.
131
+
132
+ Everything wrong with the text throws a `PemError`, a `SyntaxError` with:
133
+
134
+ - `reason` — `"textTooLong"`, `"dataTooLarge"`, `"noBlock"`,
135
+ `"surroundingText"`, `"invalidBoundary"`, `"missingEnd"`,
136
+ `"labelMismatch"`, `"unexpectedLabel"`, `"invalidLayout"` or
137
+ `"invalidBase64"`;
138
+ - `offset` — where in the text decoding gave up, in UTF-16 code units;
139
+ - `limit` — the exceeded maximum, for `"textTooLong"` and `"dataTooLarge"`.
140
+
141
+ ```ts
142
+ import { decodePem, PemError } from "@ac-kit/format-pem";
143
+
144
+ try {
145
+ decodePem(text, { maxDataLength: 65_536 });
146
+ } catch (error) {
147
+ if (error instanceof PemError && error.reason === "dataTooLarge") {
148
+ console.log(`Over ${error.limit} bytes`);
149
+ }
150
+ }
151
+ ```
152
+
153
+ An invalid option — an unknown `syntax`, a `label` outside the RFC 7468
154
+ grammar, a limit that is not a non-negative integer — throws a `RangeError`.
155
+
156
+ Decoding is linear in the text read, and memory linear in the bytes returned.
157
+
158
+ ## Encode
159
+
160
+ `encodePem(label, data)` writes one block in the strict form, with LF line
161
+ breaks and a final LF. An invalid label throws a `RangeError`.
162
+
163
+ ```ts
164
+ import { encodePem } from "@ac-kit/format-pem";
165
+
166
+ encodePem("TEST DATA", Uint8Array.of(1, 2, 3, 0xff, 0, 0xab));
167
+ // "-----BEGIN TEST DATA-----\nAQID/wCr\n-----END TEST DATA-----\n"
168
+ ```
169
+
170
+ Empty data is written with an empty line between the boundaries, which the
171
+ `standard` and `lax` syntaxes read back; the strict grammar has no form for it.
172
+
173
+ ## API reference
174
+
175
+ See the [generated API reference](https://anthochamp.pages.grenadine.io/node-essentials/api/format-pem/).
@@ -0,0 +1,48 @@
1
+ import type { PemSyntax } from "./pem-syntax.js";
2
+ /** A block whose framing and layout were checked, not yet decoded. */
3
+ export type PemFrame_ = {
4
+ readonly label: string;
5
+ /** Offset of the `-----BEGIN `. */
6
+ readonly start: number;
7
+ /** Offset just past the `-----BEGIN ` line's closing `-----`. */
8
+ readonly dataStart: number;
9
+ /** Offset of the `-----END `. */
10
+ readonly dataEnd: number;
11
+ /** Offset just past the `-----END ` line, its line break included. */
12
+ readonly end: number;
13
+ /** Exactly how many bytes the Base64 decodes to. */
14
+ readonly dataLength: number;
15
+ /** Offset of the last Base64 character, where unused bits would be. */
16
+ readonly lastCharOffset: number;
17
+ /**
18
+ * Whether a vertical tab, which `Uint8Array.fromBase64` does not skip,
19
+ * occurs.
20
+ */
21
+ readonly hasVerticalTab: boolean;
22
+ };
23
+ /**
24
+ * Offset of the next `-----BEGIN ` at or after `from` that starts its line
25
+ * (after inline whitespace, under `lax`), or `-1`.
26
+ *
27
+ * Linear in the text scanned: each candidate looks back only over the
28
+ * whitespace before it, which ends at a character the previous search passed.
29
+ */
30
+ export declare function findPemBegin_(text: string, from: number, syntax: PemSyntax): number;
31
+ /**
32
+ * Checks the block whose `-----BEGIN ` is at `start` against `syntax`, without
33
+ * decoding it.
34
+ *
35
+ * Linear in the length of the block, and in the rest of the text when the block
36
+ * is not closed.
37
+ *
38
+ * @throws {PemError} When the block breaks `syntax`.
39
+ */
40
+ export declare function readPemFrame_(text: string, start: number, syntax: PemSyntax): PemFrame_;
41
+ /**
42
+ * The bytes of a checked frame.
43
+ *
44
+ * @throws {PemError} `invalidBase64` when the last character has unused bits
45
+ * set, the one rule the layout checks leave to `Uint8Array.fromBase64`.
46
+ */
47
+ export declare function decodePemFrame_(text: string, frame: PemFrame_): Uint8Array<ArrayBuffer>;
48
+ //# sourceMappingURL=_pem-frame.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_pem-frame.d.ts","sourceRoot":"","sources":["../src/_pem-frame.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,sEAAsE;AACtE,MAAM,MAAM,SAAS,GAAG;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mCAAmC;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,iEAAiE;IACjE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,iCAAiC;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,sEAAsE;IACtE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,oDAAoD;IACpD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,uEAAuE;IACvE,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;CACjC,CAAC;AA4SF;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC5B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,SAAS,GACf,MAAM,CAoBR;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,SAAS,GACf,SAAS,CA8CX;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,SAAS,GACd,UAAU,CAAC,WAAW,CAAC,CAezB"}
@@ -0,0 +1,315 @@
1
+ import { CR, EQUALS, FF, HT, HYPHEN_MINUS, isAsciiBlank, isAsciiStandardBase64Char, isAsciiWhitespace, LF, SPACE, VT, } from "@ac-kit/core";
2
+ import { BEGIN_PREFIX_, BOUNDARY_SUFFIX_, END_PREFIX_, isPemLabel_, } from "./_pem-label.js";
3
+ import { PemError } from "./pem-error.js";
4
+ const BASE64_QUANTUM_CHARS_ = 4;
5
+ const BASE64_QUANTUM_BYTES_ = 3;
6
+ const MAX_PADDING_ = 2;
7
+ const STRICT_LINE_LENGTH_ = 64;
8
+ function isLineBreak_(code) {
9
+ return code === LF || code === CR;
10
+ }
11
+ /** RFC 7468 `W` without the line breaks. */
12
+ function isInlineWhitespace_(code) {
13
+ return code === SPACE || code === HT || code === VT || code === FF;
14
+ }
15
+ /** Offset just past the CRLF, CR or LF at `index`; `index` when there is none. */
16
+ function skipLineBreak_(text, index) {
17
+ const code = text.charCodeAt(index);
18
+ if (code === CR) {
19
+ return text.charCodeAt(index + 1) === LF ? index + 2 : index + 1;
20
+ }
21
+ return code === LF ? index + 1 : index;
22
+ }
23
+ function skipWhile_(text, index, limit, isSkipped) {
24
+ let cursor = index;
25
+ while (cursor < limit && isSkipped(text.charCodeAt(cursor))) {
26
+ cursor++;
27
+ }
28
+ return cursor;
29
+ }
30
+ /**
31
+ * The reason for a line that does not end where a line break was due, at
32
+ * `index`. Whitespace the syntax does not allow there, data resuming after
33
+ * blanks, and an `-----END ` that does not start its line are layout errors;
34
+ * any other character (outside the alphabet, or data after the padding) is a
35
+ * Base64 one.
36
+ */
37
+ function lineEndFailure_(text, index, dataEnd, isAfterBlanks) {
38
+ if (index === dataEnd) {
39
+ return new PemError("invalidLayout", index);
40
+ }
41
+ const code = text.charCodeAt(index);
42
+ const isLayout = isAsciiWhitespace(code) ||
43
+ (isAfterBlanks && (isAsciiStandardBase64Char(code) || code === EQUALS));
44
+ return new PemError(isLayout ? "invalidLayout" : "invalidBase64", index);
45
+ }
46
+ function shapeOf_(charCount, padding, lastCharOffset, hasVerticalTab, dataEnd) {
47
+ const length = charCount + padding;
48
+ if (length % BASE64_QUANTUM_CHARS_ !== 0) {
49
+ throw new PemError("invalidBase64", dataEnd);
50
+ }
51
+ return {
52
+ dataLength: (length / BASE64_QUANTUM_CHARS_) * BASE64_QUANTUM_BYTES_ - padding,
53
+ lastCharOffset,
54
+ hasVerticalTab,
55
+ };
56
+ }
57
+ /** RFC 7468 Figure 3: `preeb eol strictbase64text`, up to the `posteb`. */
58
+ function checkStrictBody_(text, dataStart, dataEnd) {
59
+ let cursor = skipLineBreak_(text, dataStart);
60
+ if (cursor === dataStart) {
61
+ throw new PemError("invalidBoundary", dataStart);
62
+ }
63
+ let charCount = 0;
64
+ let padding = 0;
65
+ let lastCharOffset = dataStart;
66
+ let isFinal = false;
67
+ while (cursor < dataEnd) {
68
+ if (isFinal) {
69
+ throw new PemError("invalidLayout", cursor);
70
+ }
71
+ const lineStart = cursor;
72
+ cursor = skipWhile_(text, cursor, dataEnd, isAsciiStandardBase64Char);
73
+ lastCharOffset = cursor - 1;
74
+ const paddingStart = cursor;
75
+ cursor = skipWhile_(text, cursor, dataEnd, (code) => code === EQUALS);
76
+ const next = skipLineBreak_(text, cursor);
77
+ if (next === cursor) {
78
+ throw lineEndFailure_(text, cursor, dataEnd, false);
79
+ }
80
+ const lineLength = cursor - lineStart;
81
+ const linePadding = cursor - paddingStart;
82
+ if (linePadding > MAX_PADDING_) {
83
+ throw new PemError("invalidBase64", paddingStart);
84
+ }
85
+ if (lineLength === 0 || lineLength > STRICT_LINE_LENGTH_) {
86
+ throw new PemError("invalidLayout", lineStart);
87
+ }
88
+ isFinal = lineLength < STRICT_LINE_LENGTH_ || linePadding > 0;
89
+ charCount += lineLength - linePadding;
90
+ padding += linePadding;
91
+ cursor = next;
92
+ }
93
+ if (charCount === 0) {
94
+ throw new PemError("invalidLayout", dataEnd);
95
+ }
96
+ return shapeOf_(charCount, padding, lastCharOffset, false, dataEnd);
97
+ }
98
+ /**
99
+ * RFC 7468 Figure 1: `preeb *WSP eol *eolWSP base64text`, up to the `posteb`.
100
+ * `base64finl` may be an empty line, and may carry its second `=` alone on the
101
+ * line after the first.
102
+ */
103
+ function checkStandardBody_(text, dataStart, dataEnd) {
104
+ const beginLineEnd = skipWhile_(text, dataStart, dataEnd, isAsciiBlank);
105
+ let cursor = skipLineBreak_(text, beginLineEnd);
106
+ if (cursor === beginLineEnd) {
107
+ throw new PemError("invalidBoundary", beginLineEnd);
108
+ }
109
+ const leadingStart = cursor;
110
+ cursor = skipWhile_(text, cursor, dataEnd, (code) => isAsciiBlank(code) || isLineBreak_(code));
111
+ if (cursor === dataEnd) {
112
+ // No data: what was skipped must hold the empty final line's line break.
113
+ if (cursor === leadingStart ||
114
+ !isLineBreak_(text.charCodeAt(dataEnd - 1))) {
115
+ throw new PemError("invalidLayout", dataEnd);
116
+ }
117
+ return { dataLength: 0, lastCharOffset: dataStart, hasVerticalTab: false };
118
+ }
119
+ let charCount = 0;
120
+ let padding = 0;
121
+ let lastCharOffset = dataStart;
122
+ let isFinal = false;
123
+ let isPaddingOpen = false;
124
+ while (cursor < dataEnd) {
125
+ const lineStart = cursor;
126
+ cursor = skipWhile_(text, cursor, dataEnd, isAsciiStandardBase64Char);
127
+ const lineChars = cursor - lineStart;
128
+ const paddingStart = cursor;
129
+ cursor = skipWhile_(text, cursor, dataEnd, (code) => code === EQUALS);
130
+ const linePadding = cursor - paddingStart;
131
+ const blanksEnd = skipWhile_(text, cursor, dataEnd, isAsciiBlank);
132
+ const next = skipLineBreak_(text, blanksEnd);
133
+ if (next === blanksEnd) {
134
+ throw lineEndFailure_(text, blanksEnd, dataEnd, blanksEnd > cursor);
135
+ }
136
+ if (isFinal) {
137
+ if (!isPaddingOpen || lineChars !== 0 || linePadding !== 1) {
138
+ // Data after the padding is a Base64 error; any other line after
139
+ // the last one (data after an empty line, a second empty line) is
140
+ // a layout one.
141
+ throw padding > 0 && lineChars + linePadding > 0
142
+ ? new PemError("invalidBase64", lineStart)
143
+ : new PemError("invalidLayout", lineStart);
144
+ }
145
+ isPaddingOpen = false;
146
+ }
147
+ else if (linePadding > MAX_PADDING_) {
148
+ throw new PemError("invalidBase64", paddingStart);
149
+ }
150
+ else {
151
+ isFinal = lineChars === 0 || linePadding > 0;
152
+ isPaddingOpen = linePadding === 1;
153
+ }
154
+ if (lineChars > 0) {
155
+ lastCharOffset = paddingStart - 1;
156
+ }
157
+ charCount += lineChars;
158
+ padding += linePadding;
159
+ cursor = next;
160
+ }
161
+ return shapeOf_(charCount, padding, lastCharOffset, false, dataEnd);
162
+ }
163
+ /** RFC 7468 Figure 2: `laxbase64text`, between the boundaries. */
164
+ function checkLaxBody_(text, dataStart, dataEnd) {
165
+ let charCount = 0;
166
+ let padding = 0;
167
+ let lastCharOffset = dataStart;
168
+ let hasVerticalTab = false;
169
+ for (let cursor = dataStart; cursor < dataEnd; cursor++) {
170
+ const code = text.charCodeAt(cursor);
171
+ if (isAsciiWhitespace(code)) {
172
+ hasVerticalTab ||= code === VT;
173
+ }
174
+ else if (isAsciiStandardBase64Char(code) && padding === 0) {
175
+ charCount++;
176
+ lastCharOffset = cursor;
177
+ }
178
+ else if (code === EQUALS && padding < MAX_PADDING_) {
179
+ padding++;
180
+ }
181
+ else {
182
+ throw new PemError("invalidBase64", cursor);
183
+ }
184
+ }
185
+ return shapeOf_(charCount, padding, lastCharOffset, hasVerticalTab, dataEnd);
186
+ }
187
+ const BODY_CHECKERS_ = {
188
+ strict: checkStrictBody_,
189
+ standard: checkStandardBody_,
190
+ lax: checkLaxBody_,
191
+ };
192
+ /** Offset of the `-----` closing a boundary whose label starts at `labelStart`. */
193
+ function readLabelEnd_(text, labelStart) {
194
+ const labelEnd = text.indexOf(BOUNDARY_SUFFIX_, labelStart);
195
+ if (labelEnd === -1 || !isPemLabel_(text.slice(labelStart, labelEnd))) {
196
+ throw new PemError("invalidBoundary", labelStart);
197
+ }
198
+ return labelEnd;
199
+ }
200
+ /** Offset just past what may follow the `-----END ` line's closing `-----`. */
201
+ function skipEndLine_(text, index, syntax) {
202
+ if (syntax === "strict") {
203
+ const next = skipLineBreak_(text, index);
204
+ if (next === index) {
205
+ throw index === text.length
206
+ ? new PemError("invalidLayout", index)
207
+ : new PemError("invalidBoundary", index);
208
+ }
209
+ return next;
210
+ }
211
+ const lineEnd = skipWhile_(text, index, text.length, syntax === "lax" ? isInlineWhitespace_ : isAsciiBlank);
212
+ if (lineEnd === text.length) {
213
+ return lineEnd;
214
+ }
215
+ const next = skipLineBreak_(text, lineEnd);
216
+ if (next === lineEnd) {
217
+ throw new PemError("invalidBoundary", lineEnd);
218
+ }
219
+ return next;
220
+ }
221
+ /**
222
+ * Offset of the next `-----BEGIN ` at or after `from` that starts its line
223
+ * (after inline whitespace, under `lax`), or `-1`.
224
+ *
225
+ * Linear in the text scanned: each candidate looks back only over the
226
+ * whitespace before it, which ends at a character the previous search passed.
227
+ */
228
+ export function findPemBegin_(text, from, syntax) {
229
+ let index = text.indexOf(BEGIN_PREFIX_, from);
230
+ while (index !== -1) {
231
+ let lineStart = index;
232
+ if (syntax === "lax") {
233
+ while (lineStart > 0 &&
234
+ isInlineWhitespace_(text.charCodeAt(lineStart - 1))) {
235
+ lineStart--;
236
+ }
237
+ }
238
+ if (lineStart === 0 || isLineBreak_(text.charCodeAt(lineStart - 1))) {
239
+ return index;
240
+ }
241
+ index = text.indexOf(BEGIN_PREFIX_, index + 1);
242
+ }
243
+ return -1;
244
+ }
245
+ /**
246
+ * Checks the block whose `-----BEGIN ` is at `start` against `syntax`, without
247
+ * decoding it.
248
+ *
249
+ * Linear in the length of the block, and in the rest of the text when the block
250
+ * is not closed.
251
+ *
252
+ * @throws {PemError} When the block breaks `syntax`.
253
+ */
254
+ export function readPemFrame_(text, start, syntax) {
255
+ const labelStart = start + BEGIN_PREFIX_.length;
256
+ const labelEnd = readLabelEnd_(text, labelStart);
257
+ const label = text.slice(labelStart, labelEnd);
258
+ const dataStart = labelEnd + BOUNDARY_SUFFIX_.length;
259
+ if (text.charCodeAt(dataStart) === HYPHEN_MINUS &&
260
+ !text.startsWith(END_PREFIX_, dataStart)) {
261
+ throw new PemError("invalidBoundary", dataStart);
262
+ }
263
+ const dataEnd = text.indexOf(END_PREFIX_, dataStart);
264
+ if (dataEnd === -1) {
265
+ throw new PemError("missingEnd", start);
266
+ }
267
+ let shape;
268
+ try {
269
+ shape = BODY_CHECKERS_[syntax](text, dataStart, dataEnd);
270
+ }
271
+ catch (error) {
272
+ // A body holding the next block's BEGIN line lacks its own END line;
273
+ // say so rather than report the hyphens as Base64.
274
+ if (error instanceof PemError &&
275
+ text.lastIndexOf(BEGIN_PREFIX_, dataEnd) > start) {
276
+ throw new PemError("missingEnd", start);
277
+ }
278
+ throw error;
279
+ }
280
+ const endLabelStart = dataEnd + END_PREFIX_.length;
281
+ const endLabelEnd = readLabelEnd_(text, endLabelStart);
282
+ if (text.slice(endLabelStart, endLabelEnd) !== label) {
283
+ throw new PemError("labelMismatch", endLabelStart);
284
+ }
285
+ return {
286
+ label,
287
+ start,
288
+ dataStart,
289
+ dataEnd,
290
+ end: skipEndLine_(text, endLabelEnd + BOUNDARY_SUFFIX_.length, syntax),
291
+ ...shape,
292
+ };
293
+ }
294
+ /**
295
+ * The bytes of a checked frame.
296
+ *
297
+ * @throws {PemError} `invalidBase64` when the last character has unused bits
298
+ * set, the one rule the layout checks leave to `Uint8Array.fromBase64`.
299
+ */
300
+ export function decodePemFrame_(text, frame) {
301
+ let base64 = text.slice(frame.dataStart, frame.dataEnd);
302
+ if (frame.hasVerticalTab) {
303
+ base64 = base64.replaceAll("\v", "");
304
+ }
305
+ try {
306
+ return Uint8Array.fromBase64(base64, { lastChunkHandling: "strict" });
307
+ }
308
+ catch (error) {
309
+ if (!(error instanceof SyntaxError)) {
310
+ throw error;
311
+ }
312
+ throw new PemError("invalidBase64", frame.lastCharOffset);
313
+ }
314
+ }
315
+ //# sourceMappingURL=_pem-frame.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_pem-frame.js","sourceRoot":"","sources":["../src/_pem-frame.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,EAAE,EACF,MAAM,EACN,EAAE,EACF,EAAE,EACF,YAAY,EACZ,YAAY,EACZ,yBAAyB,EACzB,iBAAiB,EACjB,EAAE,EACF,KAAK,EACL,EAAE,GACF,MAAM,cAAc,CAAC;AAEtB,OAAO,EACN,aAAa,EACb,gBAAgB,EAChB,WAAW,EACX,WAAW,GACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AA8B1C,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAE/B,SAAS,YAAY,CAAC,IAAY;IACjC,OAAO,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AAED,4CAA4C;AAC5C,SAAS,mBAAmB,CAAC,IAAY;IACxC,OAAO,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,CAAC;AACpE,CAAC;AAED,kFAAkF;AAClF,SAAS,cAAc,CAAC,IAAY,EAAE,KAAa;IAClD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,C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IAAI,CAAC,CAAC,KAAK,YAAY,WAAW,CAAC,EAAE,CAAC;YACrC,MAAM,KAAK,CAAC;QACb,CAAC;QAED,MAAM,IAAI,QAAQ,CAAC,eAAe,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IAC3D,CAAC;AACF,CAAC"}
@@ -0,0 +1,18 @@
1
+ /** The `-----BEGIN ` that opens a pre-encapsulation boundary. */
2
+ export declare const BEGIN_PREFIX_ = "-----BEGIN ";
3
+ /** The `-----END ` that opens a post-encapsulation boundary. */
4
+ export declare const END_PREFIX_ = "-----END ";
5
+ /** The five hyphen-minus characters that close both boundaries. */
6
+ export declare const BOUNDARY_SUFFIX_ = "-----";
7
+ /**
8
+ * Whether `label` matches RFC 7468 §3 `label = [ labelchar *( ["-" / SP]
9
+ * labelchar ) ]`, where `labelchar` is printable ASCII except hyphen-minus:
10
+ * empty, or no space or hyphen-minus at either end or next to another. The
11
+ * grammar admits lowercase although §2 calls labels uppercase; the grammar is
12
+ * followed.
13
+ *
14
+ * Because a valid label never holds two hyphen-minus characters in a row, the
15
+ * first `-----` after `-----BEGIN ` is always where the label ends.
16
+ */
17
+ export declare function isPemLabel_(label: string): boolean;
18
+ //# sourceMappingURL=_pem-label.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_pem-label.d.ts","sourceRoot":"","sources":["../src/_pem-label.ts"],"names":[],"mappings":"AAEA,iEAAiE;AACjE,eAAO,MAAM,aAAa,gBAAgB,CAAC;AAC3C,gEAAgE;AAChE,eAAO,MAAM,WAAW,cAAc,CAAC;AACvC,mEAAmE;AACnE,eAAO,MAAM,gBAAgB,UAAU,CAAC;AAExC;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAclD"}
@@ -0,0 +1,34 @@
1
+ import { HYPHEN_MINUS, isAsciiGraphic, SPACE } from "@ac-kit/core";
2
+ /** The `-----BEGIN ` that opens a pre-encapsulation boundary. */
3
+ export const BEGIN_PREFIX_ = "-----BEGIN ";
4
+ /** The `-----END ` that opens a post-encapsulation boundary. */
5
+ export const END_PREFIX_ = "-----END ";
6
+ /** The five hyphen-minus characters that close both boundaries. */
7
+ export const BOUNDARY_SUFFIX_ = "-----";
8
+ /**
9
+ * Whether `label` matches RFC 7468 §3 `label = [ labelchar *( ["-" / SP]
10
+ * labelchar ) ]`, where `labelchar` is printable ASCII except hyphen-minus:
11
+ * empty, or no space or hyphen-minus at either end or next to another. The
12
+ * grammar admits lowercase although §2 calls labels uppercase; the grammar is
13
+ * followed.
14
+ *
15
+ * Because a valid label never holds two hyphen-minus characters in a row, the
16
+ * first `-----` after `-----BEGIN ` is always where the label ends.
17
+ */
18
+ export function isPemLabel_(label) {
19
+ let isAfterLabelChar = false;
20
+ for (let index = 0; index < label.length; index++) {
21
+ const code = label.charCodeAt(index);
22
+ if (code !== HYPHEN_MINUS && isAsciiGraphic(code)) {
23
+ isAfterLabelChar = true;
24
+ }
25
+ else if ((code === HYPHEN_MINUS || code === SPACE) && isAfterLabelChar) {
26
+ isAfterLabelChar = false;
27
+ }
28
+ else {
29
+ return false;
30
+ }
31
+ }
32
+ return label.length === 0 || isAfterLabelChar;
33
+ }
34
+ //# sourceMappingURL=_pem-label.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_pem-label.js","sourceRoot":"","sources":["../src/_pem-label.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAEnE,iEAAiE;AACjE,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAC;AAC3C,gEAAgE;AAChE,MAAM,CAAC,MAAM,WAAW,GAAG,WAAW,CAAC;AACvC,mEAAmE;AACnE,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC;;;;;;;;;GASG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IACxC,IAAI,gBAAgB,GAAG,KAAK,CAAC;IAC7B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,IAAI,KAAK,YAAY,IAAI,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC;YACnD,gBAAgB,GAAG,IAAI,CAAC;QACzB,CAAC;aAAM,IAAI,CAAC,IAAI,KAAK,YAAY,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,gBAAgB,EAAE,CAAC;YAC1E,gBAAgB,GAAG,KAAK,CAAC;QAC1B,CAAC;aAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACd,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,gBAAgB,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,107 @@
1
+ import type { PemSyntax } from "./pem-syntax.js";
2
+ /** One decoded PEM block. */
3
+ export type PemBlock = {
4
+ /** The label of its boundaries, such as `CERTIFICATE`. */
5
+ label: string;
6
+ /** The bytes its Base64 spells. */
7
+ data: Uint8Array<ArrayBuffer>;
8
+ };
9
+ /** How {@link decodePemAll} reads its text. */
10
+ export type DecodePemAllOptions = {
11
+ /** The RFC 7468 grammar the text is held to. Defaults to `standard`. */
12
+ readonly syntax?: PemSyntax;
13
+ /**
14
+ * The label, or labels, a block must carry to be returned, compared exactly.
15
+ * Blocks with another label are checked but neither decoded nor returned.
16
+ * Defaults to any label.
17
+ */
18
+ readonly label?: string | readonly string[];
19
+ /**
20
+ * Refuse a text longer than this, in UTF-16 code units, before reading it.
21
+ * Defaults to no limit.
22
+ */
23
+ readonly maxTextLength?: number;
24
+ /**
25
+ * Refuse to decode more bytes than this, over every block returned, before
26
+ * decoding any that would pass it. Defaults to no limit.
27
+ */
28
+ readonly maxDataLength?: number;
29
+ };
30
+ /** How {@link decodePem} reads its text. */
31
+ export type DecodePemOptions = DecodePemAllOptions & {
32
+ /**
33
+ * Require the text to be exactly one block: nothing before its `-----BEGIN `
34
+ * line and nothing after its `-----END ` line, except the whitespace `syntax`
35
+ * allows there (under `standard`, blanks and one line break after the block;
36
+ * under `lax`, any whitespace on both sides). Defaults to `false`: the first
37
+ * block is found among any other text.
38
+ */
39
+ readonly exact?: boolean;
40
+ };
41
+ /**
42
+ * The first PEM block (RFC 7468) in `text`, such as a certificate or a key
43
+ * pasted with explanatory text around it. Use {@link decodePemAll} for a bundle
44
+ * whose every block matters, such as a certificate chain.
45
+ *
46
+ * A block starts at a `-----BEGIN ` line and ends at the next `-----END ` line;
47
+ * any other text between blocks is ignored. Once a `-----BEGIN ` line is found,
48
+ * its block must be well formed under `options.syntax`: a malformed block
49
+ * throws rather than being skipped. With `options.label`, blocks with another
50
+ * label are skipped, and the first block with an accepted label is returned.
51
+ *
52
+ * Time is linear in the text read up to the end of the returned block; memory
53
+ * is linear in that block's size.
54
+ *
55
+ * @example
56
+ * decodePem("-----BEGIN TEST-----\nAgEq\n-----END TEST-----\n");
57
+ * // { label: "TEST", data: Uint8Array [2, 1, 42] }
58
+ *
59
+ * @example
60
+ * // One block pasted by a user, any whitespace allowed
61
+ * decodePem(" -----BEGIN TEST-----\n Ag Eq \n-----END TEST----- \n", {
62
+ * syntax: "lax",
63
+ * exact: true,
64
+ * maxTextLength: 196_608,
65
+ * maxDataLength: 65_536,
66
+ * }).data; // Uint8Array [2, 1, 42]
67
+ *
68
+ * @throws {PemError} When the text holds no block (`noBlock`), none with an
69
+ * accepted label (`unexpectedLabel`), or a malformed one, or is over a limit;
70
+ * see {@link PemErrorReason}.
71
+ * @throws {RangeError} When an option is invalid: an unknown `syntax`, a label
72
+ * outside the RFC 7468 grammar, or a limit that is not a non-negative
73
+ * integer.
74
+ */
75
+ export declare function decodePem(text: string, options?: DecodePemOptions): PemBlock;
76
+ /**
77
+ * Every PEM block (RFC 7468) in `text`, in order, such as the certificates of a
78
+ * chain; an empty array when there is none. Use {@link decodePem} when only one
79
+ * block is expected.
80
+ *
81
+ * Text between blocks is ignored, but every block found must be well formed
82
+ * under `options.syntax`. With `options.label`, blocks with another label are
83
+ * checked and left out.
84
+ *
85
+ * Time is linear in `text.length`; memory is linear in the bytes returned.
86
+ *
87
+ * @example
88
+ * const bundle = [
89
+ * "subject=CN=leaf",
90
+ * "-----BEGIN CERTIFICATE-----",
91
+ * "AQI=",
92
+ * "-----END CERTIFICATE-----",
93
+ * "-----BEGIN PRIVATE KEY-----",
94
+ * "Aw==",
95
+ * "-----END PRIVATE KEY-----",
96
+ * "",
97
+ * ].join("\n");
98
+ * decodePemAll(bundle).map((block) => block.label);
99
+ * // ["CERTIFICATE", "PRIVATE KEY"]
100
+ * decodePemAll(bundle, { label: "PRIVATE KEY" })[0]?.data; // Uint8Array [3]
101
+ *
102
+ * @throws {PemError} When a block is malformed, or the text or the bytes
103
+ * returned are over a limit; see {@link PemErrorReason}.
104
+ * @throws {RangeError} When an option is invalid, as for {@link decodePem}.
105
+ */
106
+ export declare function decodePemAll(text: string, options?: DecodePemAllOptions): PemBlock[];
107
+ //# sourceMappingURL=decode-pem.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decode-pem.d.ts","sourceRoot":"","sources":["../src/decode-pem.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,6BAA6B;AAC7B,MAAM,MAAM,QAAQ,GAAG;IACtB,0DAA0D;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;CAC9B,CAAC;AAEF,+CAA+C;AAC/C,MAAM,MAAM,mBAAmB,GAAG;IACjC,wEAAwE;IACxE,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IAC5C;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,4CAA4C;AAC5C,MAAM,MAAM,gBAAgB,GAAG,mBAAmB,GAAG;IACpD;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAgHF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,QAAQ,CAsB5E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,YAAY,CAC3B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,mBAAmB,GAC3B,QAAQ,EAAE,CAiBZ"}
@@ -0,0 +1,171 @@
1
+ import { describeValue, isAsciiWhitespace } from "@ac-kit/core";
2
+ import { decodePemFrame_, findPemBegin_, readPemFrame_, } from "./_pem-frame.js";
3
+ import { BEGIN_PREFIX_, isPemLabel_ } from "./_pem-label.js";
4
+ import { PemError } from "./pem-error.js";
5
+ const SYNTAXES_ = ["strict", "standard", "lax"];
6
+ function checkLimit_(name, value) {
7
+ if (value === undefined) {
8
+ return Number.POSITIVE_INFINITY;
9
+ }
10
+ if (!(Number.isSafeInteger(value) && value >= 0) &&
11
+ value !== Number.POSITIVE_INFINITY) {
12
+ throw new RangeError(`${name} must be a non-negative integer, got ${describeValue(value)}`);
13
+ }
14
+ return value;
15
+ }
16
+ function resolveSettings_(text, options) {
17
+ const syntax = options?.syntax ?? "standard";
18
+ if (!SYNTAXES_.includes(syntax)) {
19
+ throw new RangeError(`Unknown PEM syntax ${describeValue(syntax, { reveal: "kind" })}`);
20
+ }
21
+ const label = options?.label;
22
+ const labels = typeof label === "string" ? [label] : label;
23
+ for (const accepted of labels ?? []) {
24
+ if (!isPemLabel_(accepted)) {
25
+ throw new RangeError(`Invalid PEM label ${describeValue(accepted, { reveal: "kind" })}`);
26
+ }
27
+ }
28
+ const maxTextLength = checkLimit_("maxTextLength", options?.maxTextLength);
29
+ const maxDataLength = checkLimit_("maxDataLength", options?.maxDataLength);
30
+ if (text.length > maxTextLength) {
31
+ throw new PemError("textTooLong", maxTextLength, maxTextLength);
32
+ }
33
+ return { syntax, labels, maxDataLength };
34
+ }
35
+ function isAccepted_(settings, frame) {
36
+ return settings.labels === undefined || settings.labels.includes(frame.label);
37
+ }
38
+ function toBlock_(text, frame, settings, decodedLength) {
39
+ if (frame.dataLength > settings.maxDataLength - decodedLength) {
40
+ throw new PemError("dataTooLarge", frame.start, settings.maxDataLength);
41
+ }
42
+ return { label: frame.label, data: decodePemFrame_(text, frame) };
43
+ }
44
+ /** Offset of the block in `text`, which must be all of it but whitespace. */
45
+ function findExactBegin_(text, syntax) {
46
+ const start = syntax === "lax" ? skipWhitespace_(text, 0) : 0;
47
+ if (text.startsWith(BEGIN_PREFIX_, start)) {
48
+ return start;
49
+ }
50
+ throw text.includes(BEGIN_PREFIX_, start)
51
+ ? new PemError("surroundingText", start)
52
+ : new PemError("noBlock", 0);
53
+ }
54
+ function skipWhitespace_(text, index) {
55
+ let cursor = index;
56
+ while (cursor < text.length && isAsciiWhitespace(text.charCodeAt(cursor))) {
57
+ cursor++;
58
+ }
59
+ return cursor;
60
+ }
61
+ function decodeExact_(text, settings) {
62
+ const frame = readPemFrame_(text, findExactBegin_(text, settings.syntax), settings.syntax);
63
+ const end = settings.syntax === "lax" ? skipWhitespace_(text, frame.end) : frame.end;
64
+ if (end !== text.length) {
65
+ throw new PemError("surroundingText", end);
66
+ }
67
+ if (!isAccepted_(settings, frame)) {
68
+ throw new PemError("unexpectedLabel", frame.start);
69
+ }
70
+ return toBlock_(text, frame, settings, 0);
71
+ }
72
+ /**
73
+ * The first PEM block (RFC 7468) in `text`, such as a certificate or a key
74
+ * pasted with explanatory text around it. Use {@link decodePemAll} for a bundle
75
+ * whose every block matters, such as a certificate chain.
76
+ *
77
+ * A block starts at a `-----BEGIN ` line and ends at the next `-----END ` line;
78
+ * any other text between blocks is ignored. Once a `-----BEGIN ` line is found,
79
+ * its block must be well formed under `options.syntax`: a malformed block
80
+ * throws rather than being skipped. With `options.label`, blocks with another
81
+ * label are skipped, and the first block with an accepted label is returned.
82
+ *
83
+ * Time is linear in the text read up to the end of the returned block; memory
84
+ * is linear in that block's size.
85
+ *
86
+ * @example
87
+ * decodePem("-----BEGIN TEST-----\nAgEq\n-----END TEST-----\n");
88
+ * // { label: "TEST", data: Uint8Array [2, 1, 42] }
89
+ *
90
+ * @example
91
+ * // One block pasted by a user, any whitespace allowed
92
+ * decodePem(" -----BEGIN TEST-----\n Ag Eq \n-----END TEST----- \n", {
93
+ * syntax: "lax",
94
+ * exact: true,
95
+ * maxTextLength: 196_608,
96
+ * maxDataLength: 65_536,
97
+ * }).data; // Uint8Array [2, 1, 42]
98
+ *
99
+ * @throws {PemError} When the text holds no block (`noBlock`), none with an
100
+ * accepted label (`unexpectedLabel`), or a malformed one, or is over a limit;
101
+ * see {@link PemErrorReason}.
102
+ * @throws {RangeError} When an option is invalid: an unknown `syntax`, a label
103
+ * outside the RFC 7468 grammar, or a limit that is not a non-negative
104
+ * integer.
105
+ */
106
+ export function decodePem(text, options) {
107
+ const settings = resolveSettings_(text, options);
108
+ if (options?.exact === true) {
109
+ return decodeExact_(text, settings);
110
+ }
111
+ let start = findPemBegin_(text, 0, settings.syntax);
112
+ if (start === -1) {
113
+ throw new PemError("noBlock", 0);
114
+ }
115
+ const firstStart = start;
116
+ while (start !== -1) {
117
+ const frame = readPemFrame_(text, start, settings.syntax);
118
+ if (isAccepted_(settings, frame)) {
119
+ return toBlock_(text, frame, settings, 0);
120
+ }
121
+ start = findPemBegin_(text, frame.end, settings.syntax);
122
+ }
123
+ throw new PemError("unexpectedLabel", firstStart);
124
+ }
125
+ /**
126
+ * Every PEM block (RFC 7468) in `text`, in order, such as the certificates of a
127
+ * chain; an empty array when there is none. Use {@link decodePem} when only one
128
+ * block is expected.
129
+ *
130
+ * Text between blocks is ignored, but every block found must be well formed
131
+ * under `options.syntax`. With `options.label`, blocks with another label are
132
+ * checked and left out.
133
+ *
134
+ * Time is linear in `text.length`; memory is linear in the bytes returned.
135
+ *
136
+ * @example
137
+ * const bundle = [
138
+ * "subject=CN=leaf",
139
+ * "-----BEGIN CERTIFICATE-----",
140
+ * "AQI=",
141
+ * "-----END CERTIFICATE-----",
142
+ * "-----BEGIN PRIVATE KEY-----",
143
+ * "Aw==",
144
+ * "-----END PRIVATE KEY-----",
145
+ * "",
146
+ * ].join("\n");
147
+ * decodePemAll(bundle).map((block) => block.label);
148
+ * // ["CERTIFICATE", "PRIVATE KEY"]
149
+ * decodePemAll(bundle, { label: "PRIVATE KEY" })[0]?.data; // Uint8Array [3]
150
+ *
151
+ * @throws {PemError} When a block is malformed, or the text or the bytes
152
+ * returned are over a limit; see {@link PemErrorReason}.
153
+ * @throws {RangeError} When an option is invalid, as for {@link decodePem}.
154
+ */
155
+ export function decodePemAll(text, options) {
156
+ const settings = resolveSettings_(text, options);
157
+ const blocks = [];
158
+ let decodedLength = 0;
159
+ let start = findPemBegin_(text, 0, settings.syntax);
160
+ while (start !== -1) {
161
+ const frame = readPemFrame_(text, start, settings.syntax);
162
+ if (isAccepted_(settings, frame)) {
163
+ const block = toBlock_(text, frame, settings, decodedLength);
164
+ decodedLength += block.data.length;
165
+ blocks.push(block);
166
+ }
167
+ start = findPemBegin_(text, frame.end, settings.syntax);
168
+ }
169
+ return blocks;
170
+ }
171
+ //# sourceMappingURL=decode-pem.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decode-pem.js","sourceRoot":"","sources":["../src/decode-pem.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEhE,OAAO,EACN,eAAe,EACf,aAAa,EAEb,aAA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E,OAAO,CAAC,CAAC;IACjD,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;IACtB,IAAI,KAAK,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACpD,OAAO,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC1D,IAAI,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC;YAClC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC;YAC7D,aAAa,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC;YACnC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,CAAC;QAED,KAAK,GAAG,aAAa,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `data` as one PEM block (RFC 7468) in the strict form the RFC asks generators
3
+ * for: the Base64 wrapped at 64 characters, LF line endings, and an LF after
4
+ * the `-----END ` line.
5
+ *
6
+ * Empty `data` gives an empty line between the boundaries, the form the RFC's
7
+ * standard grammar allows for it; the strict grammar has no form for empty
8
+ * data, so `decodePem` with `syntax: "strict"` refuses it.
9
+ *
10
+ * Time and memory are linear in `data.length`.
11
+ *
12
+ * @example
13
+ * encodePem("TEST DATA", Uint8Array.of(1, 2, 3, 0xff, 0, 0xab));
14
+ * // "-----BEGIN TEST DATA-----\nAQID/wCr\n-----END TEST DATA-----\n"
15
+ *
16
+ * @param label The type label, such as `CERTIFICATE` or `PRIVATE KEY`:
17
+ * printable ASCII, single spaces or hyphen-minus between other characters, or
18
+ * empty.
19
+ * @throws {RangeError} When `label` is not an RFC 7468 label.
20
+ */
21
+ export declare function encodePem(label: string, data: Uint8Array): string;
22
+ //# sourceMappingURL=encode-pem.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encode-pem.d.ts","sourceRoot":"","sources":["../src/encode-pem.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,MAAM,CAcjE"}
@@ -0,0 +1,35 @@
1
+ import { describeValue } from "@ac-kit/core";
2
+ import { BEGIN_PREFIX_, BOUNDARY_SUFFIX_, END_PREFIX_, isPemLabel_, } from "./_pem-label.js";
3
+ const LINE_LENGTH_ = 64;
4
+ /**
5
+ * `data` as one PEM block (RFC 7468) in the strict form the RFC asks generators
6
+ * for: the Base64 wrapped at 64 characters, LF line endings, and an LF after
7
+ * the `-----END ` line.
8
+ *
9
+ * Empty `data` gives an empty line between the boundaries, the form the RFC's
10
+ * standard grammar allows for it; the strict grammar has no form for empty
11
+ * data, so `decodePem` with `syntax: "strict"` refuses it.
12
+ *
13
+ * Time and memory are linear in `data.length`.
14
+ *
15
+ * @example
16
+ * encodePem("TEST DATA", Uint8Array.of(1, 2, 3, 0xff, 0, 0xab));
17
+ * // "-----BEGIN TEST DATA-----\nAQID/wCr\n-----END TEST DATA-----\n"
18
+ *
19
+ * @param label The type label, such as `CERTIFICATE` or `PRIVATE KEY`:
20
+ * printable ASCII, single spaces or hyphen-minus between other characters, or
21
+ * empty.
22
+ * @throws {RangeError} When `label` is not an RFC 7468 label.
23
+ */
24
+ export function encodePem(label, data) {
25
+ if (!isPemLabel_(label)) {
26
+ throw new RangeError(`Invalid PEM label ${describeValue(label, { reveal: "kind" })}`);
27
+ }
28
+ const base64 = data.toBase64();
29
+ const lines = [];
30
+ for (let start = 0; start < base64.length; start += LINE_LENGTH_) {
31
+ lines.push(base64.slice(start, start + LINE_LENGTH_));
32
+ }
33
+ return `${BEGIN_PREFIX_}${label}${BOUNDARY_SUFFIX_}\n${lines.join("\n")}\n${END_PREFIX_}${label}${BOUNDARY_SUFFIX_}\n`;
34
+ }
35
+ //# sourceMappingURL=encode-pem.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encode-pem.js","sourceRoot":"","sources":["../src/encode-pem.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EACN,aAAa,EACb,gBAAgB,EAChB,WAAW,EACX,WAAW,GACX,MAAM,iBAAiB,CAAC;AAEzB,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,SAAS,CAAC,KAAa,EAAE,IAAgB;IACxD,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,UAAU,CACnB,qBAAqB,aAAa,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,CAC/D,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;IAC/B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,IAAI,YAAY,EAAE,CAAC;QAClE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC;IACvD,CAAC;IAED,OAAO,GAAG,aAAa,GAAG,KAAK,GAAG,gBAAgB,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,WAAW,GAAG,KAAK,GAAG,gBAAgB,IAAI,CAAC;AACxH,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from "./decode-pem.js";
2
+ export * from "./encode-pem.js";
3
+ export * from "./pem-error.js";
4
+ export * from "./pem-syntax.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./decode-pem.js";
2
+ export * from "./encode-pem.js";
3
+ export * from "./pem-error.js";
4
+ export * from "./pem-syntax.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What a {@link PemError} reports:
3
+ *
4
+ * - `textTooLong` — the text is longer than `maxTextLength`; `limit` is that
5
+ * maximum, in UTF-16 code units.
6
+ * - `dataTooLarge` — the decoded bytes would exceed `maxDataLength`; `limit` is
7
+ * that maximum, in bytes.
8
+ * - `noBlock` — the text holds no `-----BEGIN ` line.
9
+ * - `surroundingText` — `exact` decoding found something other than the one
10
+ * block, and the whitespace its syntax allows, in the text.
11
+ * - `invalidBoundary` — a `-----BEGIN ` or `-----END ` line is malformed: a label
12
+ * outside the RFC 7468 grammar, a missing closing `-----`, or text after it
13
+ * on the line that the syntax does not allow.
14
+ * - `missingEnd` — a `-----BEGIN ` line has no `-----END ` after it.
15
+ * - `labelMismatch` — the `-----END ` label differs from the `-----BEGIN ` one.
16
+ * - `unexpectedLabel` — blocks were found, but none with an accepted label.
17
+ * - `invalidLayout` — whitespace or line lengths the selected syntax forbids, or
18
+ * a `-----END ` boundary that does not start its line.
19
+ * - `invalidBase64` — a character outside the standard Base64 alphabet, missing,
20
+ * misplaced or excess `=` padding, or non-zero unused bits in the last
21
+ * character.
22
+ */
23
+ export type PemErrorReason = "textTooLong" | "dataTooLarge" | "noBlock" | "surroundingText" | "invalidBoundary" | "missingEnd" | "labelMismatch" | "unexpectedLabel" | "invalidLayout" | "invalidBase64";
24
+ /**
25
+ * Text that `decodePem` or `decodePemAll` refuses. A `RangeError` from them is
26
+ * a caller error instead: an invalid option.
27
+ */
28
+ export declare class PemError extends SyntaxError {
29
+ /** What is wrong, for a program; `message` says it for a person. */
30
+ readonly reason: PemErrorReason;
31
+ /** UTF-16 offset in the text where decoding gave up. */
32
+ readonly offset: number;
33
+ /** The exceeded maximum, for `textTooLong` and `dataTooLarge` only. */
34
+ readonly limit: number | undefined;
35
+ constructor(reason: PemErrorReason, offset: number, limit?: number);
36
+ }
37
+ //# sourceMappingURL=pem-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pem-error.d.ts","sourceRoot":"","sources":["../src/pem-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,cAAc,GACvB,aAAa,GACb,cAAc,GACd,SAAS,GACT,iBAAiB,GACjB,iBAAiB,GACjB,YAAY,GACZ,eAAe,GACf,iBAAiB,GACjB,eAAe,GACf,eAAe,CAAC;AAenB;;;GAGG;AACH,qBAAa,QAAS,SAAQ,WAAW;IACxC,oEAAoE;IACpE,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAEnC,YAAY,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,EAUjE;CACD"}
@@ -0,0 +1,34 @@
1
+ const MESSAGES_ = {
2
+ textTooLong: "PEM text is over the length limit",
3
+ dataTooLarge: "PEM data is over the size limit",
4
+ noBlock: "No PEM block found",
5
+ surroundingText: "Text surrounds the PEM block",
6
+ invalidBoundary: "Malformed PEM encapsulation boundary",
7
+ missingEnd: "PEM block has no END line",
8
+ labelMismatch: "PEM END label differs from the BEGIN label",
9
+ unexpectedLabel: "No PEM block with an accepted label",
10
+ invalidLayout: "PEM layout not allowed by the selected syntax",
11
+ invalidBase64: "PEM block holds invalid Base64",
12
+ };
13
+ /**
14
+ * Text that `decodePem` or `decodePemAll` refuses. A `RangeError` from them is
15
+ * a caller error instead: an invalid option.
16
+ */
17
+ export class PemError extends SyntaxError {
18
+ /** What is wrong, for a program; `message` says it for a person. */
19
+ reason;
20
+ /** UTF-16 offset in the text where decoding gave up. */
21
+ offset;
22
+ /** The exceeded maximum, for `textTooLong` and `dataTooLarge` only. */
23
+ limit;
24
+ constructor(reason, offset, limit) {
25
+ super(limit === undefined
26
+ ? `${MESSAGES_[reason]} at offset ${offset}`
27
+ : `${MESSAGES_[reason]} of ${limit} at offset ${offset}`);
28
+ this.name = "PemError";
29
+ this.reason = reason;
30
+ this.offset = offset;
31
+ this.limit = limit;
32
+ }
33
+ }
34
+ //# sourceMappingURL=pem-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pem-error.js","sourceRoot":"","sources":["../src/pem-error.ts"],"names":[],"mappings":"AAkCA,MAAM,SAAS,GAAG;IACjB,WAAW,EAAE,mCAAmC;IAChD,YAAY,EAAE,iCAAiC;IAC/C,OAAO,EAAE,oBAAoB;IAC7B,eAAe,EAAE,8BAA8B;IAC/C,eAAe,EAAE,sCAAsC;IACvD,UAAU,EAAE,2BAA2B;IACvC,aAAa,EAAE,4CAA4C;IAC3D,eAAe,EAAE,qCAAqC;IACtD,aAAa,EAAE,+CAA+C;IAC9D,aAAa,EAAE,gCAAgC;CACG,CAAC;AAEpD;;;GAGG;AACH,MAAM,OAAO,QAAS,SAAQ,WAAW;IACxC,oEAAoE;IAC3D,MAAM,CAAiB;IAChC,wDAAwD;IAC/C,MAAM,CAAS;IACxB,uEAAuE;IAC9D,KAAK,CAAqB;IAEnC,YAAY,MAAsB,EAAE,MAAc,EAAE,KAAc;QACjE,KAAK,CACJ,KAAK,KAAK,SAAS;YAClB,CAAC,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,cAAc,MAAM,EAAE;YAC5C,CAAC,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,OAAO,KAAK,cAAc,MAAM,EAAE,CACzD,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,CAAC;CACD"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Which RFC 7468 §3 grammar a decoder holds the text to:
3
+ *
4
+ * - `strict` (Figure 3) — what `encodePem` writes: no whitespace but line breaks,
5
+ * every Base64 line 64 characters except the last, a line break after both
6
+ * boundaries, and at least one byte of data.
7
+ * - `standard` (Figure 1) — line-oriented: lines of any length, blanks (space,
8
+ * tab) at the end of any line and in blank lines before the data, an empty
9
+ * last line, and the second `=` of the padding alone on the line after the
10
+ * first.
11
+ * - `lax` (Figure 2) — not line-oriented: whitespace (space, tab, line breaks,
12
+ * vertical tab, form feed) anywhere between the boundaries, before a
13
+ * `-----BEGIN ` on its line and after a `-----END ` one.
14
+ *
15
+ * Under every syntax a `-----BEGIN ` starts its line (after whitespace, under
16
+ * `lax`), as does a `-----END ` under `strict` and `standard`; line breaks are
17
+ * CRLF, CR or LF; the labels on both boundaries must be equal; and the Base64
18
+ * is strict: the standard alphabet, the `=` padding required, no unused bits
19
+ * set. A character outside the alphabet is refused rather than skipped, so RFC
20
+ * 1421 headers (`Proc-Type:`) are refused too.
21
+ */
22
+ export type PemSyntax = "strict" | "standard" | "lax";
23
+ //# sourceMappingURL=pem-syntax.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pem-syntax.d.ts","sourceRoot":"","sources":["../src/pem-syntax.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,UAAU,GAAG,KAAK,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=pem-syntax.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pem-syntax.js","sourceRoot":"","sources":["../src/pem-syntax.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@ac-kit/format-pem",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "PEM textual encoding (RFC 7468): encode and decode certificates, keys and other labelled binary data.",
5
+ "keywords": [
6
+ "pem",
7
+ "rfc-7468",
8
+ "textual-encoding",
9
+ "x509"
10
+ ],
11
+ "homepage": "https://anthochamp.pages.grenadine.io/node-essentials/api/format-pem/",
12
+ "bugs": {
13
+ "url": "https://git.grenadine.io/anthochamp/node-essentials/issues"
14
+ },
15
+ "license": "BSD-3-Clause",
16
+ "author": "Anthony Champagne <dev@anthonychampagne.fr>",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://git.grenadine.io/anthochamp/node-essentials.git",
20
+ "directory": "packages/format-pem"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "main": "./dist/index.js",
28
+ "exports": {
29
+ ".": "./dist/index.js"
30
+ },
31
+ "publishConfig": {
32
+ "main": "./dist/index.js",
33
+ "exports": {
34
+ ".": "./dist/index.js"
35
+ },
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "compile": "tsc -p ./tsconfig.build.json -outDir dist",
40
+ "compile:check": "tsc -noEmit -p ./tsconfig.json",
41
+ "clean": "rimraf dist",
42
+ "build": "yarn clean && yarn compile",
43
+ "test": "yarn run -T vitest run",
44
+ "prepack": "yarn build"
45
+ },
46
+ "dependencies": {
47
+ "@ac-kit/core": "^0.13.0",
48
+ "@types/web": "^0.0.367"
49
+ },
50
+ "devDependencies": {
51
+ "@ac-kit/crypto-hash": "0.1.12",
52
+ "@ac-kit/tsconfig": "0.1.0",
53
+ "@ac-kit/typedoc-config": "0.1.0",
54
+ "@ac-kit/vitest-config": "0.2.0",
55
+ "@typescript/native": "typescript@7.0.2",
56
+ "rimraf": "6.1.4",
57
+ "typedoc": "0.28.20",
58
+ "typescript": "@typescript/typescript6@6.0.2",
59
+ "vite": "8.4.0",
60
+ "vitest": "5.1.2"
61
+ },
62
+ "engines": {
63
+ "node": ">=24"
64
+ }
6
65
  }