mergeseal 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/intoto.js CHANGED
@@ -1,19 +1,100 @@
1
1
  /**
2
2
  * in-toto Statement v1 for a receipt whose compact seal already verified.
3
- * This module does not call Fulcio or Rekor and does not wrap a DSSE envelope.
3
+ * The predicate timestamp is the seal's issuance time as RFC 3339.
4
+ * DSSE is an opt-in envelope. This module does not call Fulcio or Rekor.
5
+ *
6
+ * Copyright 2026 MergeSeal
7
+ * MergeSeal <team@mergeseal.dev>
4
8
  */
9
+ import { concat, utf8 } from "./v1_1/bytes.js";
5
10
  import { CertificateError } from "./v1_1/types.js";
6
11
  export const IN_TOTO_STATEMENT_TYPE = "https://in-toto.io/Statement/v1";
7
12
  export const MERGESEAL_PREDICATE_TYPE = "https://mergeseal.dev/receipt/v1";
13
+ export const DSSE_PAYLOAD_TYPE = "application/vnd.in-toto+json";
8
14
  const MAX_COMPACT_BYTES = 192;
9
15
  const MAX_TIER = 7;
10
16
  const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
17
+ const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/u;
18
+ const BASE64_STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19
+ const BASE64_DEC = new Int16Array(128).fill(-1);
20
+ for (let index = 0; index < BASE64_STD.length; index += 1) {
21
+ BASE64_DEC[BASE64_STD.charCodeAt(index)] = index;
22
+ }
11
23
  export function toInTotoStatement(receipt) {
12
- if (receipt.verified !== true) {
24
+ const statement = statementFrom(receipt);
25
+ if (statement === undefined) {
13
26
  throw new CertificateError("invalid_input", "in-toto statement requires a verified receipt");
14
27
  }
15
- if (!validReceipt(receipt)) {
16
- throw new CertificateError("invalid_input", "in-toto statement requires a verified receipt");
28
+ return statement;
29
+ }
30
+ /**
31
+ * DSSE Pre-Authentication Encoding, version 1.
32
+ * `PAE(type, body) = "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body`.
33
+ */
34
+ export function dssePreAuthEncoding(payloadType, payload) {
35
+ const typeBytes = utf8(payloadType);
36
+ const head = utf8(`DSSEv1 ${typeBytes.length} `);
37
+ const mid = utf8(` ${payload.length} `);
38
+ return concat([head, typeBytes, mid, payload]);
39
+ }
40
+ /** Opt-in. The export command does not call this. */
41
+ export function signDsseEnvelope(statement, signer) {
42
+ const payload = utf8(canonicalStatementJson(statement));
43
+ const signature = signer.sign(dssePreAuthEncoding(DSSE_PAYLOAD_TYPE, payload));
44
+ if (signature.length === 0) {
45
+ throw new CertificateError("invalid_input", "DSSE signer returned an empty signature");
46
+ }
47
+ const signed = {
48
+ keyid: signer.keyId,
49
+ sig: encodeBase64(signature),
50
+ };
51
+ return {
52
+ payload: encodeBase64(payload),
53
+ payloadType: DSSE_PAYLOAD_TYPE,
54
+ signatures: [signed],
55
+ };
56
+ }
57
+ /**
58
+ * Verifies one signature over the payload bytes, then parses those same bytes.
59
+ * The envelope is not read again after verification.
60
+ */
61
+ export function verifyDsseEnvelope(envelope, verifier) {
62
+ if (envelope.payloadType !== DSSE_PAYLOAD_TYPE) {
63
+ throw new CertificateError("invalid_input", "DSSE payloadType is not an in-toto statement");
64
+ }
65
+ if (envelope.signatures.length !== 1) {
66
+ throw new CertificateError("invalid_input", "DSSE envelope needs one signature");
67
+ }
68
+ const signature = envelope.signatures[0];
69
+ const payload = decodeBase64(envelope.payload);
70
+ const rawSig = decodeBase64(signature.sig);
71
+ if (payload === undefined || rawSig === undefined) {
72
+ throw new CertificateError("invalid_input", "DSSE envelope is not base64");
73
+ }
74
+ const authenticated = dssePreAuthEncoding(envelope.payloadType, payload);
75
+ if (!verifier.verify(authenticated, rawSig, signature.keyid)) {
76
+ throw new CertificateError("bad_signature", "DSSE signature did not verify");
77
+ }
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload));
81
+ }
82
+ catch {
83
+ throw new CertificateError("invalid_input", "DSSE payload is not a statement");
84
+ }
85
+ const statement = readStatement(parsed);
86
+ if (statement === undefined) {
87
+ throw new CertificateError("invalid_input", "DSSE payload is not a MergeSeal receipt");
88
+ }
89
+ return statement;
90
+ }
91
+ function statementFrom(receipt) {
92
+ if (receipt.verified !== true) {
93
+ return undefined;
94
+ }
95
+ const timestamp = issuedAtRfc3339(receipt.timestamp);
96
+ if (timestamp === undefined || !fieldsOk(receipt)) {
97
+ return undefined;
17
98
  }
18
99
  return {
19
100
  _type: IN_TOTO_STATEMENT_TYPE,
@@ -31,22 +112,83 @@ export function toInTotoStatement(receipt) {
31
112
  humanCosigned: receipt.humanCosigned,
32
113
  issuerId: receipt.issuerId,
33
114
  keyId: receipt.keyId,
34
- timestamp: receipt.timestamp,
115
+ timestamp,
35
116
  compactBytes: receipt.compactBytes,
36
117
  token: receipt.token,
37
118
  },
38
119
  };
39
120
  }
40
- function timestampOk(value) {
41
- if (!/^\d+$/.test(value)) {
42
- return false;
121
+ function canonicalStatementJson(statement) {
122
+ const built = statementFrom({
123
+ verified: true,
124
+ name: statement.subject[0].name,
125
+ digestSha256: statement.subject[0].digest.sha256,
126
+ tier: statement.predicate.tier,
127
+ testCount: statement.predicate.testCount,
128
+ secretsClean: statement.predicate.secretsClean,
129
+ humanCosigned: statement.predicate.humanCosigned,
130
+ issuerId: statement.predicate.issuerId,
131
+ keyId: statement.predicate.keyId,
132
+ timestamp: statement.predicate.timestamp,
133
+ compactBytes: statement.predicate.compactBytes,
134
+ token: statement.predicate.token,
135
+ });
136
+ if (built === undefined ||
137
+ statement._type !== IN_TOTO_STATEMENT_TYPE ||
138
+ statement.predicateType !== MERGESEAL_PREDICATE_TYPE) {
139
+ throw new CertificateError("invalid_input", "DSSE payload is not a MergeSeal receipt");
43
140
  }
44
- if (value.length > 1 && value.startsWith("0")) {
45
- return false;
141
+ return JSON.stringify(built);
142
+ }
143
+ function readStatement(value) {
144
+ if (!isRecord(value)) {
145
+ return undefined;
46
146
  }
47
- return BigInt(value) < 2n ** 64n;
147
+ const subject = value.subject;
148
+ const predicate = value.predicate;
149
+ if (value._type !== IN_TOTO_STATEMENT_TYPE ||
150
+ value.predicateType !== MERGESEAL_PREDICATE_TYPE ||
151
+ !Array.isArray(subject) ||
152
+ subject.length !== 1 ||
153
+ !isRecord(predicate)) {
154
+ return undefined;
155
+ }
156
+ const one = subject[0];
157
+ if (!isRecord(one) || !isRecord(one.digest)) {
158
+ return undefined;
159
+ }
160
+ if (typeof one.name !== "string" ||
161
+ typeof one.digest.sha256 !== "string" ||
162
+ typeof predicate.tier !== "number" ||
163
+ typeof predicate.testCount !== "number" ||
164
+ typeof predicate.secretsClean !== "boolean" ||
165
+ typeof predicate.humanCosigned !== "boolean" ||
166
+ typeof predicate.issuerId !== "string" ||
167
+ typeof predicate.keyId !== "string" ||
168
+ typeof predicate.timestamp !== "string" ||
169
+ typeof predicate.compactBytes !== "number" ||
170
+ typeof predicate.token !== "string") {
171
+ return undefined;
172
+ }
173
+ if (!RFC3339.test(predicate.timestamp)) {
174
+ return undefined;
175
+ }
176
+ return statementFrom({
177
+ verified: true,
178
+ name: one.name,
179
+ digestSha256: one.digest.sha256,
180
+ tier: predicate.tier,
181
+ testCount: predicate.testCount,
182
+ secretsClean: predicate.secretsClean,
183
+ humanCosigned: predicate.humanCosigned,
184
+ issuerId: predicate.issuerId,
185
+ keyId: predicate.keyId,
186
+ timestamp: predicate.timestamp,
187
+ compactBytes: predicate.compactBytes,
188
+ token: predicate.token,
189
+ });
48
190
  }
49
- function validReceipt(receipt) {
191
+ function fieldsOk(receipt) {
50
192
  return (typeof receipt.name === "string" &&
51
193
  receipt.name.length > 0 &&
52
194
  typeof receipt.issuerId === "string" &&
@@ -63,9 +205,170 @@ function validReceipt(receipt) {
63
205
  receipt.testCount >= 0 &&
64
206
  typeof receipt.secretsClean === "boolean" &&
65
207
  typeof receipt.humanCosigned === "boolean" &&
66
- timestampOk(receipt.timestamp) &&
67
208
  Number.isInteger(receipt.compactBytes) &&
68
209
  receipt.compactBytes >= 1 &&
69
210
  receipt.compactBytes <= MAX_COMPACT_BYTES &&
70
211
  BigInt(receipt.testCount) <= MAX_SAFE);
71
212
  }
213
+ /** Decimal milliseconds, or the canonical `YYYY-MM-DDTHH:mm:ss.sssZ` form. */
214
+ function issuedAtRfc3339(value) {
215
+ if (decimalMillis(value)) {
216
+ const ms = Number(value);
217
+ if (!Number.isSafeInteger(ms) || ms < 0) {
218
+ return undefined;
219
+ }
220
+ const rendered = new Date(ms).toISOString();
221
+ return RFC3339.test(rendered) && Date.parse(rendered) === ms
222
+ ? rendered
223
+ : undefined;
224
+ }
225
+ if (!RFC3339.test(value)) {
226
+ return undefined;
227
+ }
228
+ const ms = Date.parse(value);
229
+ if (!Number.isSafeInteger(ms) || ms < 0) {
230
+ return undefined;
231
+ }
232
+ return new Date(ms).toISOString() === value ? value : undefined;
233
+ }
234
+ function decimalMillis(value) {
235
+ if (!/^\d+$/.test(value)) {
236
+ return false;
237
+ }
238
+ if (value.length > 1 && value.startsWith("0")) {
239
+ return false;
240
+ }
241
+ return BigInt(value) < 2n ** 64n;
242
+ }
243
+ function isRecord(value) {
244
+ return typeof value === "object" && value !== null && !Array.isArray(value);
245
+ }
246
+ function encodeBase64(bytes) {
247
+ let out = "";
248
+ let index = 0;
249
+ while (index + 3 <= bytes.length) {
250
+ const chunk = ((bytes[index] ?? 0) << 16) |
251
+ ((bytes[index + 1] ?? 0) << 8) |
252
+ (bytes[index + 2] ?? 0);
253
+ out += base64Char(chunk >> 18);
254
+ out += base64Char(chunk >> 12);
255
+ out += base64Char(chunk >> 6);
256
+ out += base64Char(chunk);
257
+ index += 3;
258
+ }
259
+ const rest = bytes.length - index;
260
+ if (rest === 1) {
261
+ const chunk = (bytes[index] ?? 0) << 16;
262
+ out += base64Char(chunk >> 18);
263
+ out += base64Char(chunk >> 12);
264
+ out += "==";
265
+ }
266
+ else if (rest === 2) {
267
+ const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8);
268
+ out += base64Char(chunk >> 18);
269
+ out += base64Char(chunk >> 12);
270
+ out += base64Char(chunk >> 6);
271
+ out += "=";
272
+ }
273
+ return out;
274
+ }
275
+ function decodeBase64(input) {
276
+ if (typeof input !== "string") {
277
+ return undefined;
278
+ }
279
+ if (input.length === 0) {
280
+ return new Uint8Array();
281
+ }
282
+ let padding = 0;
283
+ for (let index = input.length - 1; index >= 0; index -= 1) {
284
+ if (input[index] !== "=") {
285
+ break;
286
+ }
287
+ padding += 1;
288
+ }
289
+ if (padding > 2) {
290
+ return undefined;
291
+ }
292
+ const body = input.slice(0, input.length - padding);
293
+ if (body.includes("=")) {
294
+ return undefined;
295
+ }
296
+ let standard = "";
297
+ let sawUrl = false;
298
+ let sawStd = false;
299
+ for (let index = 0; index < body.length; index += 1) {
300
+ const symbol = body[index] ?? "";
301
+ if (symbol === "-" || symbol === "_") {
302
+ sawUrl = true;
303
+ standard += symbol === "-" ? "+" : "/";
304
+ continue;
305
+ }
306
+ if (symbol === "+" || symbol === "/") {
307
+ sawStd = true;
308
+ standard += symbol;
309
+ continue;
310
+ }
311
+ const code = symbol.charCodeAt(0);
312
+ if (code > 127 || (BASE64_DEC[code] ?? -1) < 0) {
313
+ return undefined;
314
+ }
315
+ standard += symbol;
316
+ }
317
+ if (sawUrl && sawStd) {
318
+ return undefined;
319
+ }
320
+ const mod = standard.length % 4;
321
+ if (mod === 1) {
322
+ return undefined;
323
+ }
324
+ const expectedPad = mod === 0 ? 0 : 4 - mod;
325
+ if (padding !== 0 && padding !== expectedPad) {
326
+ return undefined;
327
+ }
328
+ const values = new Uint8Array(standard.length);
329
+ for (let index = 0; index < standard.length; index += 1) {
330
+ const code = standard.charCodeAt(index);
331
+ const decoded = BASE64_DEC[code] ?? -1;
332
+ if (decoded < 0) {
333
+ return undefined;
334
+ }
335
+ values[index] = decoded;
336
+ }
337
+ if (expectedPad === 2 &&
338
+ ((values[values.length - 1] ?? 0) & 0b001111) !== 0) {
339
+ return undefined;
340
+ }
341
+ if (expectedPad === 1 &&
342
+ ((values[values.length - 1] ?? 0) & 0b000011) !== 0) {
343
+ return undefined;
344
+ }
345
+ const out = new Uint8Array(Math.floor((standard.length * 3) / 4));
346
+ let offset = 0;
347
+ let index = 0;
348
+ while (index + 4 <= standard.length) {
349
+ const chunk = ((values[index] ?? 0) << 18) |
350
+ ((values[index + 1] ?? 0) << 12) |
351
+ ((values[index + 2] ?? 0) << 6) |
352
+ (values[index + 3] ?? 0);
353
+ out[offset] = (chunk >> 16) & 0xff;
354
+ out[offset + 1] = (chunk >> 8) & 0xff;
355
+ out[offset + 2] = chunk & 0xff;
356
+ offset += 3;
357
+ index += 4;
358
+ }
359
+ if (mod === 2) {
360
+ const chunk = ((values[index] ?? 0) << 18) | ((values[index + 1] ?? 0) << 12);
361
+ out[offset] = (chunk >> 16) & 0xff;
362
+ }
363
+ else if (mod === 3) {
364
+ const chunk = ((values[index] ?? 0) << 18) |
365
+ ((values[index + 1] ?? 0) << 12) |
366
+ ((values[index + 2] ?? 0) << 6);
367
+ out[offset] = (chunk >> 16) & 0xff;
368
+ out[offset + 1] = (chunk >> 8) & 0xff;
369
+ }
370
+ return out;
371
+ }
372
+ function base64Char(value) {
373
+ return BASE64_STD[value & 63] ?? "";
374
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Minimal DER for the Ed25519 certificates Fulcio-style keyless signing uses.
3
+ * Lengths are definite and, on the way out, as short as DER allows.
4
+ *
5
+ * Copyright 2026 MergeSeal
6
+ * MergeSeal <team@mergeseal.dev>
7
+ */
8
+ export type DerNode = {
9
+ readonly tag: number;
10
+ readonly constructed: boolean;
11
+ readonly value: Uint8Array;
12
+ readonly children: readonly DerNode[];
13
+ };
14
+ export declare function tlv(tag: number, content: Uint8Array): Uint8Array;
15
+ export declare function sequence(parts: readonly Uint8Array[]): Uint8Array;
16
+ export declare function derOid(dotted: string): Uint8Array;
17
+ export declare function oidContent(dotted: string): Uint8Array;
18
+ export declare function derUtf8(text: string): Uint8Array;
19
+ export declare function derBoolean(value: boolean): Uint8Array;
20
+ export declare function derInteger(bytes: Uint8Array): Uint8Array;
21
+ export declare function derBitString(bytes: Uint8Array): Uint8Array;
22
+ export declare function parseDer(bytes: Uint8Array): DerNode;
23
+ export declare function encodeBase64(bytes: Uint8Array): string;
24
+ export declare function decodeBase64(input: string): Uint8Array | undefined;
25
+ export declare function encodePem(label: string, der: Uint8Array): string;
26
+ export declare function decodePemBody(pem: string): Uint8Array | undefined;
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Minimal DER for the Ed25519 certificates Fulcio-style keyless signing uses.
3
+ * Lengths are definite and, on the way out, as short as DER allows.
4
+ *
5
+ * Copyright 2026 MergeSeal
6
+ * MergeSeal <team@mergeseal.dev>
7
+ */
8
+ import { concat } from "../v1_1/bytes.js";
9
+ import { KeylessVerifyError } from "./errors.js";
10
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
11
+ const BASE64_DEC = new Int16Array(128).fill(-1);
12
+ for (let index = 0; index < BASE64.length; index += 1) {
13
+ BASE64_DEC[BASE64.charCodeAt(index)] = index;
14
+ }
15
+ export function tlv(tag, content) {
16
+ const length = derLength(content.length);
17
+ const out = new Uint8Array(1 + length.length + content.length);
18
+ out[0] = tag;
19
+ out.set(length, 1);
20
+ out.set(content, 1 + length.length);
21
+ return out;
22
+ }
23
+ export function sequence(parts) {
24
+ return tlv(0x30, concat(parts));
25
+ }
26
+ export function derOid(dotted) {
27
+ const arcs = dotted.split(".");
28
+ if (arcs.length < 2) {
29
+ throw new KeylessVerifyError("invalid_certificate");
30
+ }
31
+ const first = Number(arcs[0]);
32
+ const second = Number(arcs[1]);
33
+ if (!Number.isInteger(first) ||
34
+ !Number.isInteger(second) ||
35
+ first < 0 ||
36
+ second < 0) {
37
+ throw new KeylessVerifyError("invalid_certificate");
38
+ }
39
+ const body = [];
40
+ pushBase128(body, first * 40 + second);
41
+ for (let index = 2; index < arcs.length; index += 1) {
42
+ const arc = Number(arcs[index]);
43
+ if (!Number.isInteger(arc) || arc < 0) {
44
+ throw new KeylessVerifyError("invalid_certificate");
45
+ }
46
+ pushBase128(body, arc);
47
+ }
48
+ return tlv(0x06, Uint8Array.from(body));
49
+ }
50
+ export function oidContent(dotted) {
51
+ const encoded = derOid(dotted);
52
+ const length = encoded[1] ?? 0;
53
+ if (length >= 0x80) {
54
+ throw new KeylessVerifyError("invalid_certificate");
55
+ }
56
+ return encoded.subarray(2, 2 + length);
57
+ }
58
+ export function derUtf8(text) {
59
+ return tlv(0x0c, utf8(text));
60
+ }
61
+ export function derBoolean(value) {
62
+ return tlv(0x01, Uint8Array.of(value ? 0xff : 0x00));
63
+ }
64
+ export function derInteger(bytes) {
65
+ let start = 0;
66
+ while (start < bytes.length - 1 &&
67
+ bytes[start] === 0 &&
68
+ ((bytes[start + 1] ?? 0) & 0x80) === 0) {
69
+ start += 1;
70
+ }
71
+ let content = bytes.subarray(start);
72
+ if (content.length === 0) {
73
+ content = Uint8Array.of(0);
74
+ }
75
+ if (((content[0] ?? 0) & 0x80) !== 0) {
76
+ const padded = new Uint8Array(content.length + 1);
77
+ padded.set(content, 1);
78
+ content = padded;
79
+ }
80
+ return tlv(0x02, content);
81
+ }
82
+ export function derBitString(bytes) {
83
+ const content = new Uint8Array(bytes.length + 1);
84
+ content.set(bytes, 1);
85
+ return tlv(0x03, content);
86
+ }
87
+ export function parseDer(bytes) {
88
+ const read = readNode(bytes, 0);
89
+ if (read.next !== bytes.length) {
90
+ throw new KeylessVerifyError("invalid_certificate");
91
+ }
92
+ return read.node;
93
+ }
94
+ export function encodeBase64(bytes) {
95
+ let out = "";
96
+ let index = 0;
97
+ while (index + 3 <= bytes.length) {
98
+ const chunk = ((bytes[index] ?? 0) << 16) |
99
+ ((bytes[index + 1] ?? 0) << 8) |
100
+ (bytes[index + 2] ?? 0);
101
+ out += at(chunk >> 18);
102
+ out += at(chunk >> 12);
103
+ out += at(chunk >> 6);
104
+ out += at(chunk);
105
+ index += 3;
106
+ }
107
+ const rest = bytes.length - index;
108
+ if (rest === 1) {
109
+ const chunk = (bytes[index] ?? 0) << 16;
110
+ out += at(chunk >> 18);
111
+ out += at(chunk >> 12);
112
+ out += "==";
113
+ }
114
+ else if (rest === 2) {
115
+ const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8);
116
+ out += at(chunk >> 18);
117
+ out += at(chunk >> 12);
118
+ out += at(chunk >> 6);
119
+ out += "=";
120
+ }
121
+ return out;
122
+ }
123
+ export function decodeBase64(input) {
124
+ if (input.length === 0 || input.length % 4 !== 0) {
125
+ return undefined;
126
+ }
127
+ let padding = 0;
128
+ if (input.endsWith("==")) {
129
+ padding = 2;
130
+ }
131
+ else if (input.endsWith("=")) {
132
+ padding = 1;
133
+ }
134
+ const values = new Uint8Array(input.length);
135
+ for (let index = 0; index < input.length - padding; index += 1) {
136
+ const code = input.charCodeAt(index);
137
+ if (code > 127) {
138
+ return undefined;
139
+ }
140
+ const value = BASE64_DEC[code] ?? -1;
141
+ if (value < 0) {
142
+ return undefined;
143
+ }
144
+ values[index] = value;
145
+ }
146
+ if (padding === 1 && ((values[input.length - 2] ?? 0) & 0b0011) !== 0) {
147
+ return undefined;
148
+ }
149
+ if (padding === 2 && ((values[input.length - 3] ?? 0) & 0b001111) !== 0) {
150
+ return undefined;
151
+ }
152
+ const out = new Uint8Array((input.length / 4) * 3 - padding);
153
+ let offset = 0;
154
+ for (let index = 0; index < input.length; index += 4) {
155
+ const chunk = ((values[index] ?? 0) << 18) |
156
+ ((values[index + 1] ?? 0) << 12) |
157
+ ((values[index + 2] ?? 0) << 6) |
158
+ (values[index + 3] ?? 0);
159
+ if (offset < out.length) {
160
+ out[offset] = (chunk >> 16) & 0xff;
161
+ offset += 1;
162
+ }
163
+ if (offset < out.length) {
164
+ out[offset] = (chunk >> 8) & 0xff;
165
+ offset += 1;
166
+ }
167
+ if (offset < out.length) {
168
+ out[offset] = chunk & 0xff;
169
+ offset += 1;
170
+ }
171
+ }
172
+ return out;
173
+ }
174
+ export function encodePem(label, der) {
175
+ const body = encodeBase64(der);
176
+ const lines = [];
177
+ for (let index = 0; index < body.length; index += 64) {
178
+ lines.push(body.slice(index, index + 64));
179
+ }
180
+ return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
181
+ }
182
+ export function decodePemBody(pem) {
183
+ const lines = pem.replaceAll("\r\n", "\n").split("\n");
184
+ let body = "";
185
+ for (const line of lines) {
186
+ if (line.startsWith("-----") || line.length === 0) {
187
+ continue;
188
+ }
189
+ body += line.trim();
190
+ }
191
+ return decodeBase64(body);
192
+ }
193
+ function at(value) {
194
+ return BASE64[value & 63] ?? "";
195
+ }
196
+ function derLength(length) {
197
+ if (length < 0x80) {
198
+ return Uint8Array.of(length);
199
+ }
200
+ if (length <= 0xff) {
201
+ return Uint8Array.of(0x81, length);
202
+ }
203
+ if (length <= 0xffff) {
204
+ return Uint8Array.of(0x82, (length >> 8) & 0xff, length & 0xff);
205
+ }
206
+ throw new KeylessVerifyError("invalid_certificate");
207
+ }
208
+ function pushBase128(out, value) {
209
+ const stack = [value & 0x7f];
210
+ let rest = Math.floor(value / 128);
211
+ while (rest > 0) {
212
+ stack.push((rest & 0x7f) | 0x80);
213
+ rest = Math.floor(rest / 128);
214
+ }
215
+ for (let index = stack.length - 1; index >= 0; index -= 1) {
216
+ out.push(stack[index] ?? 0);
217
+ }
218
+ }
219
+ function readNode(bytes, offset) {
220
+ if (offset >= bytes.length) {
221
+ throw new KeylessVerifyError("invalid_certificate");
222
+ }
223
+ const tag = bytes[offset] ?? 0;
224
+ if ((tag & 0x1f) === 0x1f) {
225
+ throw new KeylessVerifyError("invalid_certificate");
226
+ }
227
+ let cursor = offset + 1;
228
+ if (cursor >= bytes.length) {
229
+ throw new KeylessVerifyError("invalid_certificate");
230
+ }
231
+ let length = bytes[cursor] ?? 0;
232
+ cursor += 1;
233
+ if ((length & 0x80) !== 0) {
234
+ const count = length & 0x7f;
235
+ if (count === 0 || count > 3) {
236
+ throw new KeylessVerifyError("invalid_certificate");
237
+ }
238
+ length = 0;
239
+ for (let index = 0; index < count; index += 1) {
240
+ if (cursor >= bytes.length) {
241
+ throw new KeylessVerifyError("invalid_certificate");
242
+ }
243
+ length = (length << 8) | (bytes[cursor] ?? 0);
244
+ cursor += 1;
245
+ }
246
+ }
247
+ const end = cursor + length;
248
+ if (end > bytes.length) {
249
+ throw new KeylessVerifyError("invalid_certificate");
250
+ }
251
+ const value = bytes.subarray(cursor, end);
252
+ const constructed = (tag & 0x20) !== 0;
253
+ const children = [];
254
+ if (constructed) {
255
+ let childAt = 0;
256
+ while (childAt < value.length) {
257
+ const child = readNode(value, childAt);
258
+ children.push(child.node);
259
+ childAt = child.next;
260
+ }
261
+ }
262
+ return {
263
+ node: { tag, constructed, value, children },
264
+ next: end,
265
+ };
266
+ }
267
+ function utf8(text) {
268
+ return new TextEncoder().encode(text);
269
+ }