cf-workers-native 0.1.5 → 0.1.7

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.
Files changed (197) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/documents/page-source.js +1 -1
  3. package/dist/browser/headers/index.d.ts +2 -0
  4. package/dist/browser/headers/index.js +5 -0
  5. package/dist/browser/response/index.d.ts +2 -0
  6. package/dist/browser/response/index.js +11 -3
  7. package/dist/browser/structured-clone/index.d.ts +3 -0
  8. package/dist/browser/structured-clone/index.js +75 -7
  9. package/dist/browser/websocket/attachment-size.d.ts +3 -0
  10. package/dist/browser/websocket/attachment-size.js +336 -0
  11. package/dist/browser/websocket/brand.d.ts +4 -0
  12. package/dist/browser/websocket/brand.js +16 -0
  13. package/dist/browser/websocket/close-event.d.ts +7 -0
  14. package/dist/browser/websocket/close-event.js +30 -0
  15. package/dist/browser/websocket/compression.d.ts +5 -0
  16. package/dist/browser/websocket/compression.js +124 -0
  17. package/dist/browser/websocket/conversion.d.ts +2 -0
  18. package/dist/browser/websocket/conversion.js +13 -0
  19. package/dist/browser/websocket/endpoint.d.ts +39 -0
  20. package/dist/browser/websocket/endpoint.js +379 -0
  21. package/dist/browser/websocket/frames.d.ts +21 -0
  22. package/dist/browser/websocket/frames.js +121 -0
  23. package/dist/browser/websocket/native.d.ts +14 -0
  24. package/dist/browser/websocket/native.js +226 -0
  25. package/dist/cloudflare/apis/cloudflare-node/index.js +11 -23
  26. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +20 -0
  27. package/dist/compat/crypto/LICENSE.boringssl +238 -0
  28. package/dist/compat/crypto/LICENSE.ncrypto +21 -0
  29. package/dist/compat/crypto/asymmetric.js +141 -68
  30. package/dist/compat/crypto/cipher-handle.d.ts +27 -0
  31. package/dist/compat/crypto/cipher-handle.js +239 -0
  32. package/dist/compat/crypto/cipher-info.d.ts +12 -0
  33. package/dist/compat/crypto/cipher-info.js +324 -0
  34. package/dist/compat/crypto/constants.d.ts +62 -0
  35. package/dist/compat/crypto/constants.js +68 -0
  36. package/dist/compat/crypto/dh-handle.d.ts +17 -0
  37. package/dist/compat/crypto/dh-handle.js +180 -0
  38. package/dist/compat/crypto/dh.d.ts +53 -0
  39. package/dist/compat/crypto/dh.js +138 -0
  40. package/dist/compat/crypto/digest-stream.d.ts +15 -0
  41. package/dist/compat/crypto/digest-stream.js +213 -0
  42. package/dist/compat/crypto/digests.d.ts +3 -0
  43. package/dist/compat/crypto/digests.js +32 -0
  44. package/dist/compat/crypto/ecdh.d.ts +16 -6
  45. package/dist/compat/crypto/hash-handle.d.ts +23 -0
  46. package/dist/compat/crypto/hash-handle.js +70 -0
  47. package/dist/compat/crypto/hash.d.ts +37 -0
  48. package/dist/compat/crypto/hash.js +218 -0
  49. package/dist/compat/crypto/hkdf.js +40 -14
  50. package/dist/compat/crypto/index.d.cts +168 -1
  51. package/dist/compat/crypto/index.d.ts +191 -8
  52. package/dist/compat/crypto/index.js +36 -23
  53. package/dist/compat/crypto/key-errors.d.ts +10 -0
  54. package/dist/compat/crypto/key-errors.js +17 -0
  55. package/dist/compat/crypto/key-export.d.ts +8 -0
  56. package/dist/compat/crypto/key-export.js +49 -0
  57. package/dist/compat/crypto/key-formats.d.ts +2 -1
  58. package/dist/compat/crypto/key-formats.js +162 -31
  59. package/dist/compat/crypto/key-options.d.ts +1 -0
  60. package/dist/compat/crypto/key-options.js +74 -0
  61. package/dist/compat/crypto/key-state.d.ts +1 -0
  62. package/dist/compat/crypto/keys.d.ts +20 -12
  63. package/dist/compat/crypto/keys.js +129 -59
  64. package/dist/compat/crypto/metadata.d.ts +9 -0
  65. package/dist/compat/crypto/metadata.js +89 -2
  66. package/dist/compat/crypto/native-cipher.d.ts +17 -0
  67. package/dist/compat/crypto/native-cipher.js +192 -0
  68. package/dist/compat/crypto/native-crypto.d.ts +14 -1
  69. package/dist/compat/crypto/native-crypto.js +182 -6
  70. package/dist/compat/crypto/pbkdf2-handle.d.ts +4 -0
  71. package/dist/compat/crypto/pbkdf2-handle.js +26 -0
  72. package/dist/compat/crypto/pbkdf2.d.ts +5 -0
  73. package/dist/compat/crypto/pbkdf2.js +60 -0
  74. package/dist/compat/crypto/prime.js +4 -4
  75. package/dist/compat/crypto/random.d.ts +11 -0
  76. package/dist/compat/crypto/random.js +86 -6
  77. package/dist/compat/crypto/rsa.d.ts +17 -1
  78. package/dist/compat/crypto/rsa.js +8 -4
  79. package/dist/compat/crypto/scrypt.d.ts +3 -3
  80. package/dist/compat/crypto/scrypt.js +25 -23
  81. package/dist/compat/crypto/sign-handle.d.ts +3 -3
  82. package/dist/compat/crypto/sign-handle.js +55 -11
  83. package/dist/compat/crypto/signatures.d.ts +17 -11
  84. package/dist/compat/crypto/subtle-digest.d.ts +1 -0
  85. package/dist/compat/crypto/subtle-digest.js +56 -0
  86. package/dist/compat/crypto/symmetric.d.ts +40 -24
  87. package/dist/compat/crypto/symmetric.js +229 -94
  88. package/dist/compat/crypto/validation.d.ts +4 -0
  89. package/dist/compat/crypto/validation.js +29 -2
  90. package/dist/compat/crypto/webcrypto.d.ts +13 -0
  91. package/dist/compat/crypto/webcrypto.js +51 -0
  92. package/dist/compat/crypto/x509.js +2 -1
  93. package/dist/compat/events/index.js +1 -1
  94. package/dist/compat/fs/LICENSE-3RD-PARTY.md +11 -0
  95. package/dist/compat/fs/LICENSE-APACHE +177 -0
  96. package/dist/compat/fs/directory-backend.d.ts +6 -0
  97. package/dist/compat/fs/directory-backend.js +51 -0
  98. package/dist/compat/fs/directory.d.ts +37 -0
  99. package/dist/compat/fs/directory.js +137 -0
  100. package/dist/compat/fs/embedded.d.ts +1 -1
  101. package/dist/compat/fs/embedded.js +7 -2
  102. package/dist/compat/fs/file-handle.d.ts +75 -0
  103. package/dist/compat/fs/file-handle.js +249 -0
  104. package/dist/compat/fs/glob-internal.d.ts +15 -0
  105. package/dist/compat/fs/glob-internal.js +417 -0
  106. package/dist/compat/fs/glob.d.ts +10 -0
  107. package/dist/compat/fs/glob.js +71 -0
  108. package/dist/compat/fs/index.d.ts +6 -3
  109. package/dist/compat/fs/index.js +596 -50
  110. package/dist/compat/fs/io-validation.d.ts +14 -0
  111. package/dist/compat/fs/io-validation.js +130 -0
  112. package/dist/compat/fs/io.d.ts +1 -0
  113. package/dist/compat/fs/io.js +283 -0
  114. package/dist/compat/fs/promises/index.d.ts +3 -1
  115. package/dist/compat/fs/public-types.d.ts +120 -0
  116. package/dist/compat/fs/public-types.js +1 -0
  117. package/dist/compat/fs/stream-errors.d.ts +6 -0
  118. package/dist/compat/fs/stream-errors.js +8 -0
  119. package/dist/compat/fs/stream-utils.d.ts +16 -0
  120. package/dist/compat/fs/stream-utils.js +29 -0
  121. package/dist/compat/fs/streams.d.ts +104 -0
  122. package/dist/compat/fs/streams.js +794 -0
  123. package/dist/compat/fs/writable.d.ts +8 -0
  124. package/dist/compat/fs/writable.js +412 -22
  125. package/dist/compat/http/index.d.ts +11 -28
  126. package/dist/compat/http/index.js +81 -125
  127. package/dist/compat/http/server-options.d.ts +1 -0
  128. package/dist/compat/http/server-options.js +87 -0
  129. package/dist/compat/http/unique-headers.d.ts +1 -0
  130. package/dist/compat/http/unique-headers.js +21 -0
  131. package/dist/compat/http-outgoing/index.d.ts +2 -1
  132. package/dist/compat/http-outgoing/index.js +2 -17
  133. package/dist/compat/http-server/index.d.ts +2 -2
  134. package/dist/compat/http-server/index.js +4 -85
  135. package/dist/compat/https/index.d.ts +4 -2
  136. package/dist/compat/net/sockets.js +98 -20
  137. package/dist/compat/net/validators.d.ts +1 -0
  138. package/dist/compat/net/validators.js +8 -0
  139. package/dist/compat/process/configuration.d.ts +113 -0
  140. package/dist/compat/process/configuration.js +115 -0
  141. package/dist/compat/process/directory.d.ts +4 -0
  142. package/dist/compat/process/directory.js +28 -0
  143. package/dist/compat/process/files.d.ts +3 -0
  144. package/dist/compat/process/files.js +10 -0
  145. package/dist/compat/process/index.d.ts +15 -13
  146. package/dist/compat/process/index.js +47 -74
  147. package/dist/compat/process/scheduling.d.ts +2 -0
  148. package/dist/compat/process/scheduling.js +60 -0
  149. package/dist/compat/process/state.js +1 -0
  150. package/dist/compat/process/stdio.d.ts +18 -0
  151. package/dist/compat/process/stdio.js +66 -0
  152. package/dist/compat/stream/destroy.d.ts +1 -0
  153. package/dist/compat/stream/destroy.js +21 -1
  154. package/dist/compat/stream/readable.js +10 -2
  155. package/dist/compat/tls/jsstream.js +16 -6
  156. package/dist/compat/tls/wrap.d.ts +1 -1
  157. package/dist/compat/tls/wrap.js +0 -3
  158. package/dist/compat/util/inspect.js +5 -1
  159. package/dist/compat/zlib/LICENSE-3RD-PARTY.md +11 -0
  160. package/dist/compat/zlib/LICENSE-APACHE +177 -0
  161. package/dist/compat/zlib/LICENSE.zlib +22 -0
  162. package/dist/compat/zlib/classic-base.cjs +600 -0
  163. package/dist/compat/zlib/classic-base.d.cts +39 -0
  164. package/dist/compat/zlib/classic-binding.d.ts +28 -0
  165. package/dist/compat/zlib/classic-binding.js +105 -0
  166. package/dist/compat/zlib/classic.d.ts +44 -0
  167. package/dist/compat/zlib/classic.js +199 -0
  168. package/dist/compat/zlib/codec-binding.d.ts +33 -0
  169. package/dist/compat/zlib/codec-binding.js +141 -0
  170. package/dist/compat/zlib/compression.d.ts +22 -51
  171. package/dist/compat/zlib/compression.js +129 -218
  172. package/dist/compat/zlib/errors.d.ts +21 -0
  173. package/dist/compat/zlib/errors.js +32 -0
  174. package/dist/compat/zlib/index.d.ts +367 -3
  175. package/dist/compat/zlib/index.js +28 -11
  176. package/dist/compat/zlib/input.d.ts +16 -0
  177. package/dist/compat/zlib/input.js +132 -0
  178. package/dist/compat/zlib/native-codecs.d.ts +7 -0
  179. package/dist/compat/zlib/native-codecs.js +22 -10
  180. package/dist/compat/zlib/native-zlib.d.ts +5 -0
  181. package/dist/compat/zlib/native-zlib.js +52 -0
  182. package/dist/compat/zlib/public-types.d.ts +48 -0
  183. package/dist/compat/zlib/public-types.js +1 -0
  184. package/dist/compat/zlib/validators.d.ts +3 -0
  185. package/dist/compat/zlib/validators.js +18 -0
  186. package/dist/shared/buffer-source.d.ts +5 -0
  187. package/dist/shared/buffer-source.js +70 -0
  188. package/dist/shared/globals/platform.d.ts +8 -0
  189. package/dist/shared/globals/platform.js +1 -0
  190. package/dist/shared/globals/web.js +5 -0
  191. package/dist/shared/request-context.d.ts +2 -0
  192. package/dist/shared/request-context.js +11 -0
  193. package/dist/shared/request-scope.js +4 -1
  194. package/dist/tooling/shared.js +6 -0
  195. package/dist/tooling/vite.js +4 -0
  196. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +38 -7
  197. package/package.json +2 -2
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ getPbkdf(password: ArrayBuffer | ArrayBufferView, salt: ArrayBuffer | ArrayBufferView, iterations: number, length: number, digest: string): Uint8Array<ArrayBufferLike>;
3
+ };
4
+ export default _default;
@@ -0,0 +1,26 @@
1
+ import { inputBytes, validateCryptoLength } from "./validation.js";
2
+ import { nativePbkdf2 } from "./native-crypto.js";
3
+ import { aliases } from "./hash-handle.js";
4
+ const sizes = {
5
+ md4: 16,
6
+ md5: 16,
7
+ sha1: 20,
8
+ sha224: 28,
9
+ sha256: 32,
10
+ sha384: 48,
11
+ sha512: 64,
12
+ "md5-sha1": 36,
13
+ };
14
+ export default {
15
+ getPbkdf(password, salt, iterations, length, digest) {
16
+ const passwordBytes = inputBytes(password, "getPbkdf", 1), saltBytes = inputBytes(salt, "getPbkdf", 2);
17
+ const normalized = aliases[digest.split("\0")[0].toLowerCase()];
18
+ if (!normalized)
19
+ throw new TypeError("Invalid Pbkdf2 digest: " + digest + ".");
20
+ validateCryptoLength(passwordBytes.byteLength, "Pbkdf2 failed: password is too large");
21
+ validateCryptoLength(saltBytes.byteLength, "Pbkdf2 failed: salt is too large");
22
+ if (length > 255 * sizes[normalized])
23
+ throw new RangeError("Pbkdf2 failed: derived key length exceeds maximum for this hash");
24
+ return nativePbkdf2(passwordBytes, saltBytes, iterations, length, normalized);
25
+ },
26
+ };
@@ -0,0 +1,5 @@
1
+ import { Buffer } from "node:buffer";
2
+ export type ArrayLike = string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView;
3
+ export declare function pbkdf2Sync(password: ArrayLike, salt: ArrayLike, iterations: number, keylen: number, digest: string): Buffer;
4
+ export type Pbkdf2Callback = (err?: Error | null, result?: Buffer) => void;
5
+ export declare function pbkdf2(password: ArrayLike, salt: ArrayLike, iterations: number, keylen: number, digest: string, callback: Pbkdf2Callback): void;
@@ -0,0 +1,60 @@
1
+ // @ts-nocheck
2
+ // Copyright (c) 2017-2023 Cloudflare, Inc.
3
+ // Licensed under the Apache 2.0 license found in the LICENSE file or at:
4
+ // https://opensource.org/licenses/Apache-2.0
5
+ //
6
+ // Copyright Joyent, Inc. and other Node contributors.
7
+ //
8
+ // Permission is hereby granted, free of charge, to any person obtaining a
9
+ // copy of this software and associated documentation files (the
10
+ // "Software"), to deal in the Software without restriction, including
11
+ // without limitation the rights to use, copy, modify, merge, publish,
12
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
13
+ // persons to whom the Software is furnished to do so, subject to the
14
+ // following conditions:
15
+ //
16
+ // The above copyright notice and this permission notice shall be included
17
+ // in all copies or substantial portions of the Software.
18
+ //
19
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+ import cryptoImpl from "./pbkdf2-handle.js";
27
+ import { Buffer } from "node:buffer";
28
+ import { validateInt32, validateFunction, validateString, } from "../net/validators.js";
29
+ import { arrayBufferOrView as getArrayBufferOrView } from "./validation.js";
30
+ export function pbkdf2Sync(password, salt, iterations, keylen, digest) {
31
+ ({ password, salt, iterations, keylen, digest } = check(password, salt, iterations, keylen, digest));
32
+ const result = cryptoImpl.getPbkdf(password, salt, iterations, keylen, digest);
33
+ return Buffer.from(result);
34
+ }
35
+ export function pbkdf2(password, salt, iterations, keylen, digest, callback) {
36
+ if (typeof digest === "function") {
37
+ // Appease node test cases
38
+ validateString(undefined, "digest");
39
+ }
40
+ validateFunction(callback, "callback");
41
+ ({ password, salt, iterations, keylen, digest } = check(password, salt, iterations, keylen, digest));
42
+ new Promise((res, rej) => {
43
+ try {
44
+ res(cryptoImpl.getPbkdf(password, salt, iterations, keylen, digest));
45
+ }
46
+ catch (err) {
47
+ rej(err);
48
+ }
49
+ }).then((val) => callback(null, Buffer.from(val)), (err) => callback(err));
50
+ }
51
+ function check(password, salt, iterations, keylen, digest) {
52
+ validateString(digest, "digest");
53
+ password = getArrayBufferOrView(password, "password");
54
+ salt = getArrayBufferOrView(salt, "salt");
55
+ // OpenSSL uses a signed int to represent these values, so we are restricted
56
+ // to the 31-bit range here (which is plenty).
57
+ validateInt32(iterations, "iterations", 1);
58
+ validateInt32(keylen, "keylen", 0);
59
+ return { password, salt, iterations, keylen, digest };
60
+ }
@@ -1,13 +1,13 @@
1
1
  // Adapted from pinned workerd crypto_random.ts (Apache-2.0 / Node MIT).
2
+ import { bufferBytes, viewBytes } from "../../shared/buffer-source.js";
2
3
  import { Buffer } from "node:buffer";
3
4
  import { validateObject, validateFunction, validateBoolean, validateInt32, } from "../net/validators.js";
4
5
  import { ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE } from "../net/errors.js";
5
- import { isAnyArrayBuffer, isArrayBufferView } from "../util/types/index.js";
6
+ import { isAnyBuffer as isAnyArrayBuffer } from "./validation.js";
7
+ const isArrayBufferView = ArrayBuffer.isView;
6
8
  import { nativePrimeCheck, nativePrimeGenerate } from "./native-crypto.js";
7
9
  function view(value) {
8
- return ArrayBuffer.isView(value)
9
- ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
10
- : new Uint8Array(value);
10
+ return ArrayBuffer.isView(value) ? viewBytes(value) : bufferBytes(value);
11
11
  }
12
12
  function arrayBufferToUnsignedBigInt(value) {
13
13
  const hex = Buffer.from(view(value)).toString("hex");
@@ -1,4 +1,15 @@
1
+ import { Buffer } from "node:buffer";
1
2
  import type { RandomUUIDOptions } from "node:crypto";
3
+ export type RandomBytesCallback = (err: Error | null, buffer: Buffer) => void;
4
+ export declare function randomBytes(size: number, callback: RandomBytesCallback): void;
5
+ export declare function randomBytes(size: number): Buffer;
6
+ export type RandomFillBuffer = NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer;
7
+ export type RandomFillResult<T extends RandomFillBuffer> = T extends ArrayBuffer | SharedArrayBuffer ? Buffer : T extends DataView ? Uint8Array : T;
8
+ export declare function randomFillSync<T extends RandomFillBuffer>(buffer: T, offset?: number, size?: number): RandomFillResult<T>;
9
+ export type RandomFillCallback<T extends RandomFillBuffer = RandomFillBuffer> = (err: Error | null, buf?: T) => void;
10
+ export declare function randomFill<T extends RandomFillBuffer>(buffer: T, callback: RandomFillCallback<T>): void;
11
+ export declare function randomFill<T extends RandomFillBuffer>(buffer: T, offset: number, callback: RandomFillCallback<T>): void;
12
+ export declare function randomFill<T extends RandomFillBuffer>(buffer: T, offset: number, size: number, callback: RandomFillCallback<T>): void;
2
13
  export type RandomIntCallback = (err: Error | null, n?: number) => void;
3
14
  export declare function randomInt(max: number): number;
4
15
  export declare function randomInt(min: number, max: number): number;
@@ -24,12 +24,92 @@
24
24
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
25
25
  // Adapted from workerd@5358e3d337336eaf696a48bc1563d808b10feba5.
26
26
  import { Buffer } from "node:buffer";
27
- import { validateInteger } from "./validation.js";
28
- import { validateBoolean, validateObject } from "../net/validators.js";
29
- import { ERR_OUT_OF_RANGE } from "../net/errors.js";
30
- // Cache size stays below the Web Crypto per-call limit.
31
- function randomFillSync(buffer) {
32
- return globalThis.crypto.getRandomValues(buffer);
27
+ import { validateInteger, isAnyBuffer as isAnyArrayBuffer, } from "./validation.js";
28
+ import { validateBoolean, validateObject, validateFunction, } from "../net/validators.js";
29
+ const isArrayBufferView = ArrayBuffer.isView;
30
+ const dataViewBuffer = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
31
+ function isDataView(value) {
32
+ try {
33
+ dataViewBuffer.call(value);
34
+ return true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ import { kMaxLength } from "../buffer/internal-buffer.js";
41
+ import { ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE } from "../net/errors.js";
42
+ export function randomBytes(size, callback) {
43
+ validateInteger(size, "size", 0, kMaxLength);
44
+ const buf = Buffer.alloc(size);
45
+ if (callback !== undefined) {
46
+ randomFill(buf, callback);
47
+ return undefined;
48
+ }
49
+ else {
50
+ randomFillSync(buf);
51
+ return buf;
52
+ }
53
+ }
54
+ export function randomFillSync(buffer, offset, size) {
55
+ if (!isAnyArrayBuffer(buffer) && !isArrayBufferView(buffer)) {
56
+ throw new ERR_INVALID_ARG_TYPE("buffer", ["TypedArray", "DataView", "ArrayBuffer", "SharedArrayBuffer"], buffer);
57
+ }
58
+ // Use byteLength, not length — DataView has no .length property and
59
+ // TypedArray .length is element count, not bytes.
60
+ const maxLength = buffer.byteLength;
61
+ if (offset !== undefined) {
62
+ validateInteger(offset, "offset", 0, kMaxLength);
63
+ }
64
+ else
65
+ offset = 0;
66
+ if (size !== undefined) {
67
+ validateInteger(size, "size", 0, maxLength - offset);
68
+ }
69
+ else
70
+ size = maxLength - offset;
71
+ if (isAnyArrayBuffer(buffer)) {
72
+ buffer = Buffer.from(buffer);
73
+ }
74
+ else if (isDataView(buffer)) {
75
+ buffer = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
76
+ }
77
+ buffer = buffer.subarray(offset, offset + size);
78
+ return crypto.getRandomValues(buffer);
79
+ }
80
+ export function randomFill(buffer, offsetOrCallback, sizeOrCallback, callback) {
81
+ if (!isAnyArrayBuffer(buffer) && !isArrayBufferView(buffer)) {
82
+ throw new ERR_INVALID_ARG_TYPE("buffer", ["TypedArray", "DataView", "ArrayBuffer", "SharedArrayBuffer"], buffer);
83
+ }
84
+ let offset = 0;
85
+ let size = 0;
86
+ // Use byteLength, not length — DataView has no .length property and
87
+ // TypedArray .length is element count, not bytes.
88
+ const maxLength = buffer.byteLength;
89
+ if (typeof callback === "function") {
90
+ validateInteger(offsetOrCallback, "offset", 0, maxLength);
91
+ offset = offsetOrCallback;
92
+ validateInteger(sizeOrCallback, "size", 0, maxLength - offset);
93
+ size = sizeOrCallback;
94
+ }
95
+ else if (typeof sizeOrCallback === "function") {
96
+ validateInteger(offsetOrCallback, "offset", 0, maxLength);
97
+ offset = offsetOrCallback;
98
+ size = maxLength - offset;
99
+ callback = sizeOrCallback;
100
+ }
101
+ else if (typeof offsetOrCallback === "function") {
102
+ offset = 0;
103
+ size = maxLength;
104
+ callback = offsetOrCallback;
105
+ }
106
+ validateFunction(callback, "callback");
107
+ // We're currently not actually implementing the fill itself asynchronously,
108
+ // so we defer to randomFillSync here, but we invoke the callback asynchronously.
109
+ new Promise((res) => {
110
+ randomFillSync(buffer, offset, size);
111
+ res();
112
+ }).then(() => callback(null, buffer), (err) => callback(err));
33
113
  }
34
114
  const RAND_MAX = 0xffff_ffff_ffff;
35
115
  // Cache random data to use in randomInt. The cache size must be evenly
@@ -1,5 +1,21 @@
1
1
  import { Buffer } from "node:buffer";
2
- export declare function privateEncrypt(privateKey: CreateAsymmetricKeyOptions | KeyObject | CryptoKey | undefined, buffer: string | ArrayBufferView | ArrayBuffer | undefined): Buffer;
2
+ import { KeyObject } from "./keys.js";
3
+ export type KeyData = string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | KeyObject | CryptoKey;
4
+ interface HashOptions {
5
+ padding?: number;
6
+ oaepHash?: string;
7
+ oaepLabel?: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView;
8
+ encoding?: BufferEncoding;
9
+ }
10
+ export interface RsaKeyOptions extends HashOptions {
11
+ key: KeyData;
12
+ format?: "pem" | "der" | "jwk";
13
+ type?: "pkcs1" | "pkcs8" | "sec1" | "spki";
14
+ passphrase?: string | ArrayBuffer | ArrayBufferView;
15
+ }
16
+ type CreateAsymmetricKeyOptions = RsaKeyOptions;
17
+ export declare function privateEncrypt(privateKey: CreateAsymmetricKeyOptions | KeyData | undefined, buffer: string | ArrayBufferView | ArrayBuffer | undefined): Buffer;
3
18
  export declare function privateDecrypt(privateKey: CreateAsymmetricKeyOptions | KeyData, buffer: string | ArrayBufferView | ArrayBuffer): Buffer;
4
19
  export declare function publicEncrypt(key: CreateAsymmetricKeyOptions | KeyData, buffer: string | ArrayBufferView | ArrayBuffer): Buffer;
5
20
  export declare function publicDecrypt(key: CreateAsymmetricKeyOptions | KeyData, buffer: string | ArrayBufferView | ArrayBuffer): Buffer;
21
+ export {};
@@ -4,7 +4,8 @@ import { Buffer } from "node:buffer";
4
4
  import { validateNumber, validateString } from "../net/validators.js";
5
5
  import { ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS } from "../net/errors.js";
6
6
  import { ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE } from "./sign-errors.js";
7
- import { isAnyArrayBuffer, isArrayBufferView } from "../util/types/index.js";
7
+ import { isAnyBuffer as isAnyArrayBuffer, bytes } from "./validation.js";
8
+ const isArrayBufferView = ArrayBuffer.isView;
8
9
  import { isKeyObject, getKeyObjectHandle } from "./keys.js";
9
10
  import { createPrivateKey, createPublicKey } from "./asymmetric.js";
10
11
  import { keyStates } from "./key-state.js";
@@ -13,9 +14,12 @@ function operate(operation, key, data, options) {
13
14
  const handle = keyStates.get(key)?.asymmetric;
14
15
  if (!handle)
15
16
  throw Object.assign(new Error("Synchronous access to opaque host key material is unavailable"), { code: "ERR_METHOD_NOT_IMPLEMENTED" });
16
- if (data instanceof ArrayBuffer)
17
- data = new Uint8Array(data);
18
- return handle.rsa(operation, data, options);
17
+ return handle.rsa(operation, bytes(data, "buffer"), {
18
+ ...options,
19
+ oaepLabel: options.oaepLabel === undefined
20
+ ? undefined
21
+ : bytes(options.oaepLabel, "oaepLabel"),
22
+ });
19
23
  }
20
24
  const cryptoImpl = {
21
25
  publicEncrypt: (...args) => operate(0, ...args),
@@ -1,8 +1,8 @@
1
1
  import { Buffer } from "node:buffer";
2
- type ArrayLike = any;
2
+ export type ArrayLike = ArrayBuffer | string | Buffer | ArrayBufferView;
3
3
  export interface ValidatedScryptOptions {
4
- password: ArrayLike;
5
- salt: ArrayLike;
4
+ password: ArrayBuffer | ArrayBufferView;
5
+ salt: ArrayBuffer | ArrayBufferView;
6
6
  keylen: number;
7
7
  N: number;
8
8
  r: number;
@@ -25,20 +25,30 @@
25
25
  // Validation/callback behavior from pinned workerd; algorithm from scrypt-js.
26
26
  import { syncScrypt } from "scrypt-js";
27
27
  import { Buffer } from "node:buffer";
28
- import { validateInteger, bytes as getArrayBufferOrView, } from "./validation.js";
28
+ import { validateInteger, arrayBufferOrView as getArrayBufferOrView, inputBytes, } from "./validation.js";
29
29
  import { validateFunction, validateUint32 } from "../net/validators.js";
30
30
  import { ERR_INVALID_ARG_VALUE } from "../net/errors.js";
31
31
  const kMaxLength = 2147483647;
32
32
  const cryptoImpl = {
33
33
  getScrypt(password, salt, N, r, p, maxmem, length) {
34
+ const passwordBytes = inputBytes(password, "getScrypt", 1), saltBytes = inputBytes(salt, "getScrypt", 2);
35
+ // JSG validates the uint32 binding argument before entering the backend.
36
+ if (maxmem > 0xffffffff)
37
+ throw new TypeError("Value out of range. Must be less than or equal to 4294967295.");
38
+ // Pinned workerd IsolateLimitEnforcer::checkScryptCost (2^20).
39
+ if (N > 1048576 || r > 1048576 || p > 1048576 || N * r * p > 1048576)
40
+ throw new RangeError("Scrypt failed: cost exceeds maximum (1048576).");
34
41
  if (N < 2 ||
35
42
  (N & (N - 1)) !== 0 ||
43
+ N >= 2 ** (16 * r) ||
44
+ r * p >= 2 ** 30 ||
36
45
  r < 1 ||
37
46
  p < 1 ||
38
47
  128 * N * r + 128 * r * p + 256 * r > maxmem) {
39
- throw new Error("Invalid scrypt params");
48
+ throw new Error("Scrypt failed");
40
49
  }
41
- return new Uint8Array(syncScrypt(password, salt, N, r, p, length)).buffer;
50
+ return new Uint8Array(syncScrypt(passwordBytes, saltBytes, N, r, p, length))
51
+ .buffer;
42
52
  },
43
53
  };
44
54
  const defaults = {
@@ -49,13 +59,13 @@ const defaults = {
49
59
  };
50
60
  function validateParameters(password, salt, keylen, options) {
51
61
  // TODO(soon): Add support for KeyObject input.
52
- password = getArrayBufferOrView(password, "password");
53
- salt = getArrayBufferOrView(salt, "salt");
54
- if (password.byteLength >= kMaxLength) {
55
- throw new ERR_INVALID_ARG_VALUE("password", password, "is too big");
62
+ const passwordBytes = getArrayBufferOrView(password, "password");
63
+ const saltBytes = getArrayBufferOrView(salt, "salt");
64
+ if (passwordBytes.byteLength >= kMaxLength) {
65
+ throw new ERR_INVALID_ARG_VALUE("password", passwordBytes, "is too big");
56
66
  }
57
- if (salt.byteLength >= kMaxLength) {
58
- throw new ERR_INVALID_ARG_VALUE("salt", salt, "is too big");
67
+ if (saltBytes.byteLength >= kMaxLength) {
68
+ throw new ERR_INVALID_ARG_VALUE("salt", saltBytes, "is too big");
59
69
  }
60
70
  validateInteger(keylen, "keylen", 0, kMaxLength);
61
71
  let { N, r, p, maxmem } = defaults;
@@ -107,8 +117,8 @@ function validateParameters(password, salt, keylen, options) {
107
117
  maxmem = defaults.maxmem;
108
118
  }
109
119
  return {
110
- password,
111
- salt,
120
+ password: passwordBytes,
121
+ salt: saltBytes,
112
122
  keylen,
113
123
  N: N,
114
124
  r: r,
@@ -121,15 +131,11 @@ export function scrypt(password, salt, keylen, options, callback = defaults) {
121
131
  callback = options;
122
132
  options = defaults;
123
133
  }
124
- let N;
125
- let r;
126
- let p;
127
- let maxmem;
128
- ({ password, salt, keylen, N, r, p, maxmem } = validateParameters(password, salt, keylen, options));
134
+ const { password: passwordBytes, salt: saltBytes, keylen: outputLength, N, r, p, maxmem, } = validateParameters(password, salt, keylen, options);
129
135
  validateFunction(callback, "callback");
130
136
  new Promise((res, rej) => {
131
137
  try {
132
- res(cryptoImpl.getScrypt(password, salt, N, r, p, maxmem, keylen));
138
+ res(cryptoImpl.getScrypt(passwordBytes, saltBytes, N, r, p, maxmem, outputLength));
133
139
  }
134
140
  catch (err) {
135
141
  rej(err);
@@ -141,10 +147,6 @@ export function scrypt(password, salt, keylen, options, callback = defaults) {
141
147
  });
142
148
  }
143
149
  export function scryptSync(password, salt, keylen, options) {
144
- let N;
145
- let r;
146
- let p;
147
- let maxmem;
148
- ({ password, salt, keylen, N, r, p, maxmem } = validateParameters(password, salt, keylen, options));
149
- return Buffer.from(cryptoImpl.getScrypt(password, salt, N, r, p, maxmem, keylen));
150
+ const { password: passwordBytes, salt: saltBytes, keylen: outputLength, N, r, p, maxmem, } = validateParameters(password, salt, keylen, options);
151
+ return Buffer.from(cryptoImpl.getScrypt(passwordBytes, saltBytes, N, r, p, maxmem, outputLength));
150
152
  }
@@ -1,17 +1,17 @@
1
1
  import { Buffer } from "node:buffer";
2
- declare class SignHandle {
2
+ export declare class SignHandle {
3
3
  private algorithm;
4
4
  private hash;
5
5
  constructor(algorithm: string);
6
6
  update(data: Uint8Array): void;
7
7
  sign(value: any, padding?: number, saltLength?: number, encoding?: number): Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>;
8
8
  }
9
- declare class VerifyHandle {
9
+ export declare class VerifyHandle {
10
10
  private algorithm;
11
11
  private hash;
12
12
  constructor(algorithm: string);
13
13
  update(data: Uint8Array): void;
14
- verify(value: any, signature: Uint8Array, padding?: number, saltLength?: number, encoding?: number): boolean;
14
+ verify(value: any, signature: ArrayBuffer | ArrayBufferView, padding?: number, saltLength?: number, encoding?: number): boolean;
15
15
  }
16
16
  declare const _default: {
17
17
  SignHandle: typeof SignHandle;
@@ -1,3 +1,6 @@
1
+ import { bufferBytes, viewBytes } from "../../shared/buffer-source.js";
2
+ import { isAnyBuffer } from "./validation.js";
3
+ import { signatureDigest } from "./digests.js";
1
4
  import { Buffer } from "node:buffer";
2
5
  import { NativeDigest } from "./native-crypto.js";
3
6
  import { keyStates } from "./key-state.js";
@@ -45,42 +48,83 @@ function rawSignature(data, width) {
45
48
  }
46
49
  return output;
47
50
  }
48
- class SignHandle {
51
+ function rsaParameters(type, padding, saltLength, verifying) {
52
+ if (type !== "rsa" && type !== "rsa-pss")
53
+ return;
54
+ const mode = padding ?? (type === "rsa-pss" ? 6 : 1);
55
+ if (![1, 3, 6].includes(mode) ||
56
+ (mode === 6 && saltLength !== undefined && saltLength < -2))
57
+ throw new Error("Failed to set RSA parameters for signature");
58
+ if (mode === 3)
59
+ throw new Error(verifying
60
+ ? "Failed to set digest context for signature verification"
61
+ : "Failed to set signature digest");
62
+ }
63
+ export class SignHandle {
49
64
  algorithm;
50
65
  hash;
51
66
  constructor(algorithm) {
52
67
  this.algorithm = algorithm;
53
- this.hash = new NativeDigest(algorithm);
68
+ this.algorithm = signatureDigest(algorithm);
69
+ this.hash = new NativeDigest(this.algorithm);
54
70
  }
55
71
  update(data) {
56
- this.hash.update(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
72
+ this.hash.update(viewBytes(data));
57
73
  }
58
74
  sign(value, padding, saltLength, encoding) {
59
- const native = key(value), signed = native.signHash(this.algorithm, this.hash.final(), padding, saltLength);
75
+ this.hash.assertActive();
76
+ const native = key(value), hash = this.hash.final();
77
+ if (native.type === "dsa")
78
+ throw new Error("Signing with DSA keys is not currently supported");
79
+ if (native.type === "ed25519")
80
+ throw new Error("Failed to set signature digest");
81
+ if (native.type === "x25519")
82
+ throw new Error("Failed to initialize signing context");
83
+ rsaParameters(native.type, padding, saltLength, false);
84
+ let signed;
85
+ try {
86
+ signed = native.signHash(this.algorithm, hash, native.type.startsWith("rsa") ? padding : undefined, saltLength ?? -1);
87
+ }
88
+ catch {
89
+ throw new Error("Failed to generate signature");
90
+ }
60
91
  return encoding === 1 && native.type === "ec"
61
92
  ? rawSignature(signed, Math.ceil(native.bits / 8))
62
93
  : signed;
63
94
  }
64
95
  }
65
- class VerifyHandle {
96
+ export class VerifyHandle {
66
97
  algorithm;
67
98
  hash;
68
99
  constructor(algorithm) {
69
100
  this.algorithm = algorithm;
70
- this.hash = new NativeDigest(algorithm, "Verification");
101
+ this.algorithm = signatureDigest(algorithm);
102
+ this.hash = new NativeDigest(this.algorithm, "Verification");
71
103
  }
72
104
  update(data) {
73
- this.hash.update(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
105
+ this.hash.update(viewBytes(data));
74
106
  }
75
107
  verify(value, signature, padding, saltLength, encoding) {
76
- const native = key(value), hash = this.hash.final();
108
+ if (!isAnyBuffer(signature) && !ArrayBuffer.isView(signature))
109
+ throw new TypeError("Failed to execute 'verify' on 'VerifyHandle': parameter 2 is not of type 'BufferSource'.");
110
+ this.hash.assertActive();
111
+ const native = key(value);
112
+ if (native.type === "ed25519" || native.type === "ed448")
113
+ throw new Error("Unsupported operation for this key");
114
+ let signatureBytes = Buffer.from(isAnyBuffer(signature) ? bufferBytes(signature) : viewBytes(signature));
115
+ const hash = this.hash.final();
116
+ if (native.type === "dsa")
117
+ throw new Error("Verifying with DSA keys is not currently supported");
118
+ if (native.type === "x25519")
119
+ throw new Error("Failed to initialize key for verification");
120
+ rsaParameters(native.type, padding, saltLength, true);
77
121
  if (encoding === 1 && native.type === "ec") {
78
122
  const width = Math.ceil(native.bits / 8);
79
- if (signature.length !== width * 2)
123
+ if (signatureBytes.length !== width * 2)
80
124
  return false;
81
- signature = der(48, integer(signature.subarray(0, width)), integer(signature.subarray(width)));
125
+ signatureBytes = der(48, integer(signatureBytes.subarray(0, width)), integer(signatureBytes.subarray(width)));
82
126
  }
83
- return native.verifyHash(this.algorithm, hash, signature, padding, saltLength);
127
+ return native.verifyHash(this.algorithm, hash, signatureBytes, native.type.startsWith("rsa") ? padding : undefined, saltLength ?? -1);
84
128
  }
85
129
  }
86
130
  export default {
@@ -1,28 +1,34 @@
1
1
  import { type SignHandle, type VerifyHandle } from "./sign-handle.js";
2
2
  import { Buffer } from "node:buffer";
3
- export interface SignOptions {
3
+ import type { Writable as WritableType, WritableOptions } from "node:stream";
4
+ export interface SignOptions extends WritableOptions {
4
5
  }
5
- export interface Sign extends Writable {
6
+ export interface Sign extends WritableType {
6
7
  [kHandle]: SignHandle;
7
- update(data: any): void;
8
- sign(privateKey: any): any;
8
+ update(data: string | ArrayBufferView, encoding?: BufferEncoding): this;
9
+ sign(privateKey: any, encoding?: undefined | "buffer"): Buffer;
10
+ sign(privateKey: any, encoding: BufferEncoding): string;
9
11
  }
10
- export interface Verify extends Writable {
12
+ export interface Verify extends WritableType {
11
13
  [kHandle]: VerifyHandle;
12
- update(data: any): void;
13
- verify(publicKey: any, signature: any): any;
14
+ update(data: string | ArrayBufferView, encoding?: BufferEncoding): this;
15
+ verify(publicKey: any, signature: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView, encoding?: BufferEncoding): boolean;
14
16
  }
15
17
  declare const kHandle: unique symbol;
16
18
  export declare const Sign: {
17
19
  new (algorithm: string, options?: SignOptions): Sign;
20
+ (algorithm: string, options?: SignOptions): Sign;
18
21
  };
19
22
  export declare const Verify: {
20
23
  new (algorithm: string, options?: SignOptions): Verify;
24
+ (algorithm: string, options?: SignOptions): Verify;
21
25
  };
22
- export declare function createSign(algorithm: string, options: any): Sign;
23
- export declare function createVerify(algorithm: string, options: any): Verify;
26
+ export declare function createSign(algorithm: string, options?: SignOptions): Sign;
27
+ export declare function createVerify(algorithm: string, options?: SignOptions): Verify;
24
28
  type SignCallback = (err: any, signature?: Buffer) => void;
25
29
  type VerifyCallback = (err: any, valid?: boolean) => void;
26
- export declare function sign(algorithm: string | null | undefined, data: BufferSource, options: any, callback?: SignCallback): Buffer | void;
27
- export declare function verify(algorithm: string | null | undefined, data: BufferSource, options: any, signature: BufferSource, callback?: VerifyCallback): boolean | undefined;
30
+ export declare function sign(algorithm: string | null | undefined, data: ArrayBufferView, options: any): Buffer;
31
+ export declare function sign(algorithm: string | null | undefined, data: ArrayBufferView, options: any, callback: SignCallback): void;
32
+ export declare function verify(algorithm: string | null | undefined, data: ArrayBufferView, options: any, signature: ArrayBufferView): boolean;
33
+ export declare function verify(algorithm: string | null | undefined, data: ArrayBufferView, options: any, signature: ArrayBufferView, callback: VerifyCallback): void;
28
34
  export {};
@@ -0,0 +1 @@
1
+ export declare function installDigest(subtle: SubtleCrypto): void;
@@ -0,0 +1,56 @@
1
+ import { NativeDigest } from "./native-crypto.js";
2
+ import { dictionaryString } from "./key-formats.js";
3
+ import { bufferBytes, viewBytes } from "../../shared/buffer-source.js";
4
+ const bufferLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
5
+ function isBuffer(value) {
6
+ try {
7
+ bufferLength.call(value);
8
+ return true;
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+ const names = Object.assign(Object.create(null), {
15
+ "sha-1": "sha1",
16
+ "sha-256": "sha256",
17
+ "sha-384": "sha384",
18
+ "sha-512": "sha512",
19
+ md5: "md5",
20
+ });
21
+ export function installDigest(subtle) {
22
+ const digest = {
23
+ digest(algorithm, data) {
24
+ if (this !== subtle)
25
+ throw new TypeError("Illegal invocation: function called with incorrect `this` reference. See https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors for details.");
26
+ return (async () => {
27
+ if (algorithm == null)
28
+ throw new TypeError("Cannot initialize N7workerd3api12SubtleCrypto13HashAlgorithmE with required members from an undefined or null value.");
29
+ const name = dictionaryString(typeof algorithm === "object" || typeof algorithm === "function"
30
+ ? algorithm.name
31
+ : algorithm);
32
+ if (!isBuffer(data) && !ArrayBuffer.isView(data))
33
+ throw new TypeError("Failed to execute 'digest' on 'SubtleCrypto': parameter 2 is not of type 'BufferSource'.");
34
+ const bytes = isBuffer(data) ? bufferBytes(data) : viewBytes(data);
35
+ const normalized = names[name.split("\0")[0].toLowerCase()];
36
+ if (!normalized)
37
+ throw new DOMException("Unrecognized or unimplemented digest algorithm requested.", "NotSupportedError");
38
+ const handle = new NativeDigest(normalized);
39
+ try {
40
+ handle.update(bytes);
41
+ return handle.final().buffer;
42
+ }
43
+ finally {
44
+ handle.dispose();
45
+ }
46
+ })();
47
+ },
48
+ }.digest;
49
+ Object.defineProperty(digest, "length", { value: 0 });
50
+ Object.defineProperty(Object.getPrototypeOf(subtle), "digest", {
51
+ value: digest,
52
+ writable: true,
53
+ enumerable: true,
54
+ configurable: true,
55
+ });
56
+ }