@cogover/sdk 0.12.1 → 0.12.2

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/crypto.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CogoverApiError, ValidationError } from "./errors.js";
2
- import { decodeBase64, encodeBase64 } from "./internal/base64.js";
2
+ import { decodeBase64, encodeBase64, encodeHex } from "./internal/base64.js";
3
3
  import { callBridge } from "./internal/bridge.js";
4
- import { encodeUtf8, utf8ByteLength } from "./internal/utf8.js";
4
+ import { utf8ByteLength } from "./internal/utf8.js";
5
5
  import { requireSecretName } from "./internal/validation.js";
6
6
  import { isRecord } from "./internal/values.js";
7
7
  const MAX_DATA_BYTES = 256 * 1024;
@@ -220,23 +220,19 @@ export const crypto = Object.freeze({
220
220
  return bytes;
221
221
  },
222
222
  async randomUUID() {
223
- const bytes = await crypto.randomBytes(16);
223
+ const bytes = await uuidBytes();
224
224
  bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; // version 4
225
225
  bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant
226
- const hex = toHex(bytes);
226
+ const hex = encodeHex(bytes);
227
227
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
228
228
  },
229
229
  timingSafeEqual(a, b) {
230
- const left = toBytes(a, "timingSafeEqual() first value");
231
- const right = toBytes(b, "timingSafeEqual() second value");
232
- // Every byte of the longer value is visited, so the time depends only on the lengths, never on
233
- // where the first difference is.
234
- let mismatch = left.length ^ right.length;
235
- const length = Math.max(left.length, right.length);
236
- for (let index = 0; index < length; index++) {
237
- mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);
238
- }
239
- return mismatch === 0;
230
+ const left = comparable(a, "timingSafeEqual() first value");
231
+ const right = comparable(b, "timingSafeEqual() second value");
232
+ // Well-formed strings are equal exactly when their UTF-8 encodings are, so two strings need no encoding.
233
+ return typeof left === "string" && typeof right === "string"
234
+ ? constantTimeEqual(wellFormed(left), wellFormed(right))
235
+ : constantTimeEqual(binaryString(left), binaryString(right));
240
236
  },
241
237
  aesEncrypt,
242
238
  aesDecrypt: aesDecrypt,
@@ -443,18 +439,92 @@ function digest(payload) {
443
439
  }
444
440
  return payload.digest;
445
441
  }
446
- function toBytes(value, label) {
447
- if (typeof value === "string")
448
- return encodeUtf8(value);
449
- if (value instanceof Uint8Array)
442
+ /** Random bytes for UUIDs, fetched MAX_RANDOM_BYTES at a time: one capability call covers 64 UUIDs. */
443
+ let uuidPool = new Uint8Array(0);
444
+ let uuidPoolOffset = 0;
445
+ let uuidPoolRefill;
446
+ async function uuidBytes() {
447
+ while (uuidPoolOffset + 16 > uuidPool.length) {
448
+ // Concurrent calls share one refill; a failed refill is retried by the next call.
449
+ uuidPoolRefill ??= crypto.randomBytes(MAX_RANDOM_BYTES)
450
+ .then(bytes => {
451
+ uuidPool = bytes;
452
+ uuidPoolOffset = 0;
453
+ })
454
+ .finally(() => {
455
+ uuidPoolRefill = undefined;
456
+ });
457
+ await uuidPoolRefill;
458
+ }
459
+ const bytes = uuidPool.slice(uuidPoolOffset, uuidPoolOffset + 16);
460
+ uuidPool.fill(0, uuidPoolOffset, uuidPoolOffset + 16);
461
+ uuidPoolOffset += 16;
462
+ return bytes;
463
+ }
464
+ /** A timingSafeEqual argument after its type and size checks. */
465
+ function comparable(value, label) {
466
+ if (typeof value === "string") {
467
+ if (utf8ByteLength(value) > MAX_DATA_BYTES)
468
+ throw tooLarge(label);
469
+ return value;
470
+ }
471
+ if (value instanceof Uint8Array) {
472
+ if (value.length > MAX_DATA_BYTES)
473
+ throw tooLarge(label);
450
474
  return value;
475
+ }
451
476
  throw new ValidationError(`${label} must be a string or a Uint8Array`);
452
477
  }
453
- function toHex(bytes) {
454
- let hex = "";
455
- for (const byte of bytes)
456
- hex += (byte < 16 ? "0" : "") + byte.toString(16);
457
- return hex;
478
+ const LONE_SURROGATES = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
479
+ const BINARY_CHUNK = 8192;
480
+ /** The string with each lone surrogate replaced by U+FFFD, as its UTF-8 encoding does. */
481
+ function wellFormed(value) {
482
+ const toWellFormed = String.prototype.toWellFormed;
483
+ return typeof toWellFormed === "function" ? toWellFormed.call(value) : value.replace(LONE_SURROGATES, "\ufffd");
484
+ }
485
+ /**
486
+ * One character per byte: the UTF-8 encoding of a string, or the bytes themselves. Both conversions run as engine
487
+ * code; encodeURIComponent leaves only ASCII characters unescaped, and unescape turns each %XX back into one byte.
488
+ */
489
+ function binaryString(value) {
490
+ if (typeof value === "string")
491
+ return unescape(encodeURIComponent(wellFormed(value)));
492
+ const parts = [];
493
+ for (let index = 0; index < value.length; index += BINARY_CHUNK) {
494
+ parts[parts.length] = String.fromCharCode.apply(null, value.subarray(index, index + BINARY_CHUNK));
495
+ }
496
+ return parts.join("");
497
+ }
498
+ /**
499
+ * Visits every code unit of the longer string, so the time depends only on the lengths, never on where the first
500
+ * difference is. Each loop turn compares 32 code units in one expression to stay within the statement budget; past
501
+ * the end of the shorter string charCodeAt returns NaN, which a bitwise operator reads as 0.
502
+ */
503
+ function constantTimeEqual(left, right) {
504
+ let mismatch = left.length ^ right.length;
505
+ const length = Math.max(left.length, right.length);
506
+ let index = 0;
507
+ for (; index + 32 <= length; index += 32) {
508
+ mismatch |= (left.charCodeAt(index) ^ right.charCodeAt(index)) | (left.charCodeAt(index + 1) ^ right.charCodeAt(index + 1))
509
+ | (left.charCodeAt(index + 2) ^ right.charCodeAt(index + 2)) | (left.charCodeAt(index + 3) ^ right.charCodeAt(index + 3))
510
+ | (left.charCodeAt(index + 4) ^ right.charCodeAt(index + 4)) | (left.charCodeAt(index + 5) ^ right.charCodeAt(index + 5))
511
+ | (left.charCodeAt(index + 6) ^ right.charCodeAt(index + 6)) | (left.charCodeAt(index + 7) ^ right.charCodeAt(index + 7))
512
+ | (left.charCodeAt(index + 8) ^ right.charCodeAt(index + 8)) | (left.charCodeAt(index + 9) ^ right.charCodeAt(index + 9))
513
+ | (left.charCodeAt(index + 10) ^ right.charCodeAt(index + 10)) | (left.charCodeAt(index + 11) ^ right.charCodeAt(index + 11))
514
+ | (left.charCodeAt(index + 12) ^ right.charCodeAt(index + 12)) | (left.charCodeAt(index + 13) ^ right.charCodeAt(index + 13))
515
+ | (left.charCodeAt(index + 14) ^ right.charCodeAt(index + 14)) | (left.charCodeAt(index + 15) ^ right.charCodeAt(index + 15))
516
+ | (left.charCodeAt(index + 16) ^ right.charCodeAt(index + 16)) | (left.charCodeAt(index + 17) ^ right.charCodeAt(index + 17))
517
+ | (left.charCodeAt(index + 18) ^ right.charCodeAt(index + 18)) | (left.charCodeAt(index + 19) ^ right.charCodeAt(index + 19))
518
+ | (left.charCodeAt(index + 20) ^ right.charCodeAt(index + 20)) | (left.charCodeAt(index + 21) ^ right.charCodeAt(index + 21))
519
+ | (left.charCodeAt(index + 22) ^ right.charCodeAt(index + 22)) | (left.charCodeAt(index + 23) ^ right.charCodeAt(index + 23))
520
+ | (left.charCodeAt(index + 24) ^ right.charCodeAt(index + 24)) | (left.charCodeAt(index + 25) ^ right.charCodeAt(index + 25))
521
+ | (left.charCodeAt(index + 26) ^ right.charCodeAt(index + 26)) | (left.charCodeAt(index + 27) ^ right.charCodeAt(index + 27))
522
+ | (left.charCodeAt(index + 28) ^ right.charCodeAt(index + 28)) | (left.charCodeAt(index + 29) ^ right.charCodeAt(index + 29))
523
+ | (left.charCodeAt(index + 30) ^ right.charCodeAt(index + 30)) | (left.charCodeAt(index + 31) ^ right.charCodeAt(index + 31));
524
+ }
525
+ for (; index < length; index++)
526
+ mismatch |= left.charCodeAt(index) ^ right.charCodeAt(index);
527
+ return mismatch === 0;
458
528
  }
459
529
  function tooLarge(label) {
460
530
  return new ValidationError(`${label} must not exceed ${MAX_DATA_BYTES} bytes`);
@@ -1,9 +1,5 @@
1
1
  const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2
2
  const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
3
- // Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
4
- // The sandbox caps the statements one execution may run and every loop turn costs about three of them, so each
5
- // turn handles 24 bytes in a single expression: 256 KiB costs about 33,000 statements instead of several hundred
6
- // thousand.
7
3
  let digits;
8
4
  /** 6-bit value of each base64 character code; "=" reads as 0 once the text has been validated. */
9
5
  function digitTable() {
@@ -17,6 +13,20 @@ function digitTable() {
17
13
  }
18
14
  /** Standard base64 with padding (RFC 4648 section 4). */
19
15
  export function encodeBase64(bytes) {
16
+ const toBase64 = Uint8Array.prototype.toBase64;
17
+ return typeof toBase64 === "function" ? toBase64.call(bytes) : encodeBase64InGuest(bytes);
18
+ }
19
+ /** Lowercase hexadecimal, two digits per byte. */
20
+ export function encodeHex(bytes) {
21
+ const toHex = Uint8Array.prototype.toHex;
22
+ if (typeof toHex === "function")
23
+ return toHex.call(bytes);
24
+ let hex = "";
25
+ for (const byte of bytes)
26
+ hex += (byte < 16 ? "0" : "") + byte.toString(16);
27
+ return hex;
28
+ }
29
+ function encodeBase64InGuest(bytes) {
20
30
  const length = bytes.length;
21
31
  const whole = length - (length % 3);
22
32
  const parts = [];
@@ -54,8 +64,13 @@ export function encodeBase64(bytes) {
54
64
  }
55
65
  /** Decodes padded standard base64; returns null for text that is not canonical base64. */
56
66
  export function decodeBase64(text) {
67
+ // The built-in also accepts whitespace and missing padding, so the text is validated first either way.
57
68
  if (typeof text !== "string" || !BASE64.test(text))
58
69
  return null;
70
+ const fromBase64 = Uint8Array.fromBase64;
71
+ return typeof fromBase64 === "function" ? fromBase64.call(Uint8Array, text) : decodeBase64InGuest(text);
72
+ }
73
+ function decodeBase64InGuest(text) {
59
74
  const table = digitTable();
60
75
  const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
61
76
  const groups = text.length / 4;
@@ -18,39 +18,3 @@ export function utf8ByteLength(value) {
18
18
  return value.length + matchedUnits(TWO_BYTE_UNITS) + 2 * matchedUnits(THREE_BYTE_UNITS)
19
19
  + pairedUnits + 2 * (surrogateUnits - pairedUnits);
20
20
  }
21
- /** UTF-8 encoding without TextEncoder, which the sandbox does not provide; a lone surrogate becomes U+FFFD. */
22
- export function encodeUtf8(value) {
23
- const bytes = new Uint8Array(utf8ByteLength(value));
24
- let position = 0;
25
- for (let index = 0; index < value.length; index++) {
26
- let code = value.charCodeAt(index);
27
- if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
28
- const low = value.charCodeAt(index + 1);
29
- if (low >= 0xdc00 && low <= 0xdfff) {
30
- code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00);
31
- index++;
32
- }
33
- }
34
- if (code >= 0xd800 && code <= 0xdfff)
35
- code = 0xfffd;
36
- if (code < 0x80) {
37
- bytes[position++] = code;
38
- }
39
- else if (code < 0x800) {
40
- bytes[position++] = 0xc0 | (code >> 6);
41
- bytes[position++] = 0x80 | (code & 63);
42
- }
43
- else if (code < 0x10000) {
44
- bytes[position++] = 0xe0 | (code >> 12);
45
- bytes[position++] = 0x80 | ((code >> 6) & 63);
46
- bytes[position++] = 0x80 | (code & 63);
47
- }
48
- else {
49
- bytes[position++] = 0xf0 | (code >> 18);
50
- bytes[position++] = 0x80 | ((code >> 12) & 63);
51
- bytes[position++] = 0x80 | ((code >> 6) & 63);
52
- bytes[position++] = 0x80 | (code & 63);
53
- }
54
- }
55
- return bytes;
56
- }
@@ -91,10 +91,13 @@ const token = await crypto.randomUUID();
91
91
  - `randomBytes(length)` returns `length` cryptographically secure random bytes;
92
92
  `length` is an integer from 1 through 1024.
93
93
  - `randomUUID()` returns a random version 4 UUID such as
94
- `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
94
+ `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`. Random bytes are fetched 1,024 at a
95
+ time, so one capability call covers 64 UUIDs.
95
96
  - `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
96
- returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
97
- it for every comparison of a signature, token, or key.
97
+ returns `false` for different lengths. Strings are compared as UTF-8 bytes. Each
98
+ value is limited to 256 KiB, a string measured in UTF-8 bytes; a larger one
99
+ throws `ValidationError`. Use it for every comparison of a signature, token, or
100
+ key.
98
101
 
99
102
  ### Keys
100
103
 
@@ -308,7 +311,8 @@ close to 256 KiB together with other arguments, therefore throws `ValidationErro
308
311
  before the call even though each value is within its own limit. The key, algorithm, and option errors that
309
312
  Cogover detects, such as a key of the wrong size or type, also throw
310
313
  `ValidationError`. Every operation except `timingSafeEqual` is a capability call
311
- and counts towards the invocation's limits.
314
+ and counts towards the invocation's limits; `randomUUID` makes one call for every
315
+ 64 UUIDs.
312
316
 
313
317
  The operations work in every context, including before-change triggers, with a key
314
318
  given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,