cf-workers-native 0.1.4 → 0.1.5

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 (161) hide show
  1. package/dist/browser/documents/page-source.js +1 -1
  2. package/dist/browser/fetch/host-call.js +6 -1
  3. package/dist/browser/fetch/native-network.d.ts +1 -1
  4. package/dist/browser/fetch/relay.js +2 -0
  5. package/dist/browser/isolated/transport.js +3 -2
  6. package/dist/browser/request/index.js +3 -2
  7. package/dist/cloudflare/workers/worker-runtime.js +2 -1
  8. package/dist/compat/console/index.d.ts +35 -0
  9. package/dist/compat/console/index.js +92 -0
  10. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +19 -0
  11. package/dist/compat/crypto/LICENSE-APACHE +177 -0
  12. package/dist/compat/crypto/LICENSE.emscripten +102 -0
  13. package/dist/compat/crypto/LICENSE.musl +193 -0
  14. package/dist/compat/crypto/LICENSE.openssl +177 -0
  15. package/dist/compat/crypto/asymmetric.d.ts +13 -0
  16. package/dist/compat/crypto/asymmetric.js +239 -0
  17. package/dist/compat/crypto/brorand.cjs +74 -0
  18. package/dist/compat/crypto/brorand.d.cts +6 -0
  19. package/dist/compat/crypto/certificate.d.ts +14 -0
  20. package/dist/compat/crypto/certificate.js +66 -0
  21. package/dist/compat/crypto/ecdh.d.ts +15 -0
  22. package/dist/compat/crypto/ecdh.js +109 -0
  23. package/dist/compat/crypto/hkdf.d.ts +2 -0
  24. package/dist/compat/crypto/hkdf.js +52 -0
  25. package/dist/compat/crypto/index.cjs +2 -0
  26. package/dist/compat/crypto/index.d.cts +2 -0
  27. package/dist/compat/crypto/index.d.ts +30 -0
  28. package/dist/compat/crypto/index.js +83 -0
  29. package/dist/compat/crypto/key-formats.d.ts +6 -0
  30. package/dist/compat/crypto/key-formats.js +120 -0
  31. package/dist/compat/crypto/key-state.d.ts +9 -0
  32. package/dist/compat/crypto/key-state.js +4 -0
  33. package/dist/compat/crypto/keys.d.ts +50 -0
  34. package/dist/compat/crypto/keys.js +209 -0
  35. package/dist/compat/crypto/metadata.d.ts +4 -0
  36. package/dist/compat/crypto/metadata.js +22 -0
  37. package/dist/compat/crypto/native-crypto.d.ts +68 -0
  38. package/dist/compat/crypto/native-crypto.js +569 -0
  39. package/dist/compat/crypto/prime.d.ts +19 -0
  40. package/dist/compat/crypto/prime.js +146 -0
  41. package/dist/compat/crypto/random.d.ts +7 -0
  42. package/dist/compat/crypto/random.js +123 -0
  43. package/dist/compat/crypto/rsa.d.ts +5 -0
  44. package/dist/compat/crypto/rsa.js +173 -0
  45. package/dist/compat/crypto/scrypt.d.ts +25 -0
  46. package/dist/compat/crypto/scrypt.js +150 -0
  47. package/dist/compat/crypto/sign-errors.d.ts +8 -0
  48. package/dist/compat/crypto/sign-errors.js +13 -0
  49. package/dist/compat/crypto/sign-handle.d.ts +22 -0
  50. package/dist/compat/crypto/sign-handle.js +105 -0
  51. package/dist/compat/crypto/signatures.d.ts +28 -0
  52. package/dist/compat/crypto/signatures.js +252 -0
  53. package/dist/compat/crypto/symmetric.d.ts +29 -0
  54. package/dist/compat/crypto/symmetric.js +104 -0
  55. package/dist/compat/crypto/validation.d.ts +3 -0
  56. package/dist/compat/crypto/validation.js +19 -0
  57. package/dist/compat/crypto/x509.d.ts +30 -0
  58. package/dist/compat/crypto/x509.js +406 -0
  59. package/dist/compat/events/errors.d.ts +8 -0
  60. package/dist/compat/events/errors.js +39 -0
  61. package/dist/compat/events/index.cjs +2 -0
  62. package/dist/compat/events/index.d.cts +2 -0
  63. package/dist/compat/events/index.d.ts +64 -0
  64. package/dist/compat/events/index.js +792 -0
  65. package/dist/compat/events/intrinsics.d.ts +1 -0
  66. package/dist/compat/events/intrinsics.js +2 -0
  67. package/dist/compat/fs/embedded.d.ts +85 -0
  68. package/dist/compat/fs/embedded.js +255 -0
  69. package/dist/compat/fs/index.d.ts +7 -84
  70. package/dist/compat/fs/index.js +218 -252
  71. package/dist/compat/fs/mode.d.ts +1 -0
  72. package/dist/compat/fs/mode.js +13 -0
  73. package/dist/compat/fs/promises/index.d.ts +1 -1
  74. package/dist/compat/fs/promises/index.js +1 -1
  75. package/dist/compat/fs/writable.d.ts +6 -0
  76. package/dist/compat/fs/writable.js +142 -0
  77. package/dist/compat/http/symbols.d.ts +5 -0
  78. package/dist/compat/http/symbols.js +9 -0
  79. package/dist/compat/http-common/index.d.ts +37 -0
  80. package/dist/compat/http-common/index.js +43 -0
  81. package/dist/compat/http-outgoing/index.d.ts +13 -0
  82. package/dist/compat/http-outgoing/index.js +32 -0
  83. package/dist/compat/http-server/index.d.ts +18 -0
  84. package/dist/compat/http-server/index.js +107 -0
  85. package/dist/compat/module/builtins.d.ts +1 -0
  86. package/dist/compat/module/builtins.js +101 -0
  87. package/dist/compat/module/index.d.ts +4 -2
  88. package/dist/compat/module/index.js +22 -17
  89. package/dist/compat/module/metadata.d.ts +44 -0
  90. package/dist/compat/module/metadata.js +127 -0
  91. package/dist/compat/net/internal-net.js +4 -0
  92. package/dist/compat/net/sockets.d.ts +5 -0
  93. package/dist/compat/net/sockets.js +74 -13
  94. package/dist/compat/process/index.cjs +2 -0
  95. package/dist/compat/process/index.d.cts +4 -0
  96. package/dist/compat/process/index.d.ts +18 -0
  97. package/dist/compat/process/index.js +140 -0
  98. package/dist/compat/process/metadata.d.ts +135 -0
  99. package/dist/compat/process/metadata.js +251 -0
  100. package/dist/compat/process/state.d.ts +4 -0
  101. package/dist/compat/process/state.js +4 -0
  102. package/dist/compat/stream-web/LICENSE +22 -0
  103. package/dist/compat/stream-web/ponyfill.d.ts +1 -1
  104. package/dist/compat/stream-web/ponyfill.js +2369 -1775
  105. package/dist/compat/stream-web/runtime.d.ts +1 -1
  106. package/dist/compat/stream-web/runtime.js +3 -2
  107. package/dist/compat/stream-wrap/LICENSE-3RD-PARTY.md +11 -0
  108. package/dist/compat/stream-wrap/LICENSE-APACHE +177 -0
  109. package/dist/compat/stream-wrap/index.d.ts +1 -0
  110. package/dist/compat/stream-wrap/index.js +1 -0
  111. package/dist/compat/tls/LICENSE-3RD-PARTY.md +11 -0
  112. package/dist/compat/tls/LICENSE-APACHE +177 -0
  113. package/dist/compat/tls/constants.d.ts +7 -0
  114. package/dist/compat/tls/constants.js +14 -0
  115. package/dist/compat/tls/errors.d.ts +35 -0
  116. package/dist/compat/tls/errors.js +68 -0
  117. package/dist/compat/tls/helpers.d.ts +9 -0
  118. package/dist/compat/tls/helpers.js +207 -0
  119. package/dist/compat/tls/index.d.ts +26 -0
  120. package/dist/compat/tls/index.js +50 -0
  121. package/dist/compat/tls/jsstream.d.ts +19 -0
  122. package/dist/compat/tls/jsstream.js +186 -0
  123. package/dist/compat/tls/native-session.d.ts +3 -0
  124. package/dist/compat/tls/native-session.js +187 -0
  125. package/dist/compat/tls/wrap.d.ts +65 -0
  126. package/dist/compat/tls/wrap.js +544 -0
  127. package/dist/compat/tls-wrap/LICENSE-3RD-PARTY.md +11 -0
  128. package/dist/compat/tls-wrap/LICENSE-APACHE +177 -0
  129. package/dist/compat/tls-wrap/index.d.ts +7 -0
  130. package/dist/compat/tls-wrap/index.js +3 -0
  131. package/dist/compat/util/index.js +43 -1
  132. package/dist/compat/util/types/index.d.ts +3 -0
  133. package/dist/compat/util/types/index.js +5 -0
  134. package/dist/compat/zlib/LICENSE.brotli +19 -0
  135. package/dist/compat/zlib/LICENSE.emscripten +102 -0
  136. package/dist/compat/zlib/LICENSE.musl +193 -0
  137. package/dist/compat/zlib/LICENSE.zstd +30 -0
  138. package/dist/compat/zlib/compression.d.ts +55 -0
  139. package/dist/compat/zlib/compression.js +259 -0
  140. package/dist/compat/zlib/constants.d.ts +172 -0
  141. package/dist/compat/zlib/constants.js +173 -0
  142. package/dist/compat/zlib/index.d.ts +180 -0
  143. package/dist/compat/zlib/index.js +177 -0
  144. package/dist/compat/zlib/native-codecs.d.ts +17 -0
  145. package/dist/compat/zlib/native-codecs.js +168 -0
  146. package/dist/shared/globals/inject.d.ts +2 -1
  147. package/dist/shared/globals/inject.js +2 -1
  148. package/dist/shared/globals/runtime.d.ts +1 -2
  149. package/dist/shared/globals/runtime.js +1 -2
  150. package/dist/shared/request-scope.d.ts +4 -0
  151. package/dist/shared/request-scope.js +11 -0
  152. package/dist/tooling/async.js +36 -14
  153. package/dist/tooling/shared.d.ts +1 -0
  154. package/dist/tooling/shared.js +20 -1
  155. package/dist/tooling/vite.js +4 -3
  156. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +56 -8
  157. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkersCapacitorPlugin.java +4 -2
  158. package/native/ios/NetworkBridge.swift +11 -1
  159. package/native/ios/SocketBridge.swift +37 -2
  160. package/native/ios/WorkersCapacitorPlugin.swift +4 -0
  161. package/package.json +3 -1
@@ -1,2 +1,3 @@
1
- export { process, global, setImmediate, clearImmediate } from "./runtime.js";
1
+ export { global, setImmediate, clearImmediate } from "./runtime.js";
2
+ export { default as process } from "node:process";
2
3
  export { Buffer } from "node:buffer";
@@ -1,3 +1,4 @@
1
1
  // esbuild injects these imports only where a Node global is referenced.
2
- export { process, global, setImmediate, clearImmediate } from "./runtime.js";
2
+ export { global, setImmediate, clearImmediate } from "./runtime.js";
3
+ export { default as process } from "node:process";
3
4
  export { Buffer } from "node:buffer";
@@ -1,6 +1,5 @@
1
- import process from "node:process";
2
1
  declare const nodeSetImmediate: typeof setImmediate;
3
2
  declare const nodeClearImmediate: typeof clearImmediate;
4
3
  declare const workerGlobal: typeof globalThis;
5
- export { process, workerGlobal as global };
4
+ export { workerGlobal as global };
6
5
  export { nodeSetImmediate as setImmediate, nodeClearImmediate as clearImmediate, };
@@ -1,8 +1,7 @@
1
1
  // Keep non-Buffer globals independent of Buffer's own dependencies.
2
- import process from "node:process";
3
2
  import { setImmediate as localSetImmediate, clearImmediate as localClearImmediate, } from "../../compat/immediate/index.js";
4
3
  const nodeSetImmediate = globalThis.setImmediate ?? localSetImmediate;
5
4
  const nodeClearImmediate = globalThis.clearImmediate ?? localClearImmediate;
6
5
  const workerGlobal = globalThis;
7
- export { process, workerGlobal as global };
6
+ export { workerGlobal as global };
8
7
  export { nodeSetImmediate as setImmediate, nodeClearImmediate as clearImmediate, };
@@ -0,0 +1,4 @@
1
+ type Scope = <T>(callback: () => T) => T;
2
+ export declare function registerRequestScope(scope: Scope): void;
3
+ export declare function runWithRequestScope<T>(callback: () => T): T;
4
+ export {};
@@ -0,0 +1,11 @@
1
+ const scopes = new Set();
2
+ export function registerRequestScope(scope) {
3
+ scopes.add(scope);
4
+ }
5
+ export function runWithRequestScope(callback) {
6
+ const entries = [...scopes];
7
+ const run = (index) => index === entries.length
8
+ ? callback()
9
+ : entries[index](() => run(index + 1));
10
+ return run(0);
11
+ }
@@ -30,21 +30,43 @@ export async function lowerAsync(code, filename, loader) {
30
30
  ],
31
31
  },
32
32
  plugins: [
33
- () => ({
34
- visitor: {
35
- Program(path) {
36
- // Type-only `this` parameters must not contribute to the wrapper
37
- // arity computed by Babel before esbuild strips TypeScript syntax.
38
- path.traverse({
39
- Function(path) {
40
- const first = path.node.params[0];
41
- if (first?.type === "Identifier" && first.name === "this")
42
- path.node.params.shift();
43
- },
44
- });
33
+ () => {
34
+ const intrinsicFunctions = [];
35
+ return {
36
+ visitor: {
37
+ Program(path) {
38
+ // Type-only `this` parameters must not contribute to the wrapper
39
+ // arity computed by Babel before esbuild strips TypeScript syntax.
40
+ path.traverse({
41
+ Function(path) {
42
+ const first = path.node.params[0];
43
+ if (first?.type === "Identifier" && first.name === "this")
44
+ path.node.params.shift();
45
+ // Empty anonymous async generators are used to discover native
46
+ // iterator intrinsics (including by workerd's events module).
47
+ // They have no continuation to instrument. Hide only this
48
+ // exact form from lowering, then restore its native syntax.
49
+ const node = path.node;
50
+ if (node.type === "FunctionExpression" &&
51
+ !node.id &&
52
+ node.async &&
53
+ node.generator &&
54
+ node.params.length === 0 &&
55
+ node.body.body.length === 0 &&
56
+ node.body.directives.length === 0) {
57
+ intrinsicFunctions.push(node);
58
+ node.async = false;
59
+ }
60
+ },
61
+ });
62
+ },
63
+ },
64
+ post() {
65
+ for (const node of intrinsicFunctions)
66
+ node.async = true;
45
67
  },
46
- },
47
- }),
68
+ };
69
+ },
48
70
  asyncGenerators,
49
71
  asyncFunctions,
50
72
  ],
@@ -4,6 +4,7 @@ export declare const globalsPath: string;
4
4
  export declare const networkRelayPath: string;
5
5
  export declare const globalsInstallPath: string;
6
6
  export declare const nodeGlobalsInstallPath: string;
7
+ export declare const processStatePath: string;
7
8
  export declare const nodeCompatPath: (name: string) => string;
8
9
  export declare function compatibilityAliases(): Record<string, string>;
9
10
  export declare function commonJSCompatibilityAliases(): Record<string, string>;
@@ -1,11 +1,13 @@
1
1
  import stdlib from "node-stdlib-browser";
2
2
  import { fileURLToPath } from "node:url";
3
+ import { createRequire } from "node:module";
3
4
  export const configuredPath = fileURLToPath(new URL("../configured.js", import.meta.url));
4
5
  export const transportPath = fileURLToPath(new URL("../browser/isolated/transport.js", import.meta.url));
5
6
  export const globalsPath = fileURLToPath(new URL("../shared/globals/index.js", import.meta.url));
6
7
  export const networkRelayPath = fileURLToPath(new URL("../browser/fetch/relay.js", import.meta.url));
7
8
  export const globalsInstallPath = fileURLToPath(new URL("../shared/globals/install.js", import.meta.url));
8
9
  export const nodeGlobalsInstallPath = fileURLToPath(new URL("../shared/globals/node-install.js", import.meta.url));
10
+ export const processStatePath = fileURLToPath(new URL("../compat/process/state.js", import.meta.url));
9
11
  export const nodeCompatPath = (name) => fileURLToPath(new URL(`../compat/${name}/index.js`, import.meta.url));
10
12
  const workersModulePath = (name) => fileURLToPath(new URL(`../cloudflare/apis/${name}/index.js`, import.meta.url));
11
13
  // A compat module reusing a CommonJS polyfill imports the concrete package
@@ -15,6 +17,16 @@ const polyfill = (specifier) => fileURLToPath(import.meta.resolve(specifier));
15
17
  // One entry per builtin; subpaths precede parent aliases when expanded.
16
18
  // The optional third path is the CommonJS constructor entry.
17
19
  const builtins = [
20
+ ["_http_common", "http-common/index.js"],
21
+ ["_http_outgoing", "http-outgoing/index.js"],
22
+ ["_http_server", "http-server/index.js"],
23
+ ["zlib", "zlib/index.js"],
24
+ ["crypto", "crypto/index.js", "crypto/index.cjs"],
25
+ ["console", "console/index.js"],
26
+ ["sys", "util/index.js"],
27
+ ["util/types", "util/types/index.js"],
28
+ ["events", "events/index.js", "events/index.cjs"],
29
+ ["process", "process/index.js", "process/index.cjs"],
18
30
  ["punycode", "punycode/index.js"],
19
31
  ["child_process", "child-process/index.js"],
20
32
  ["cluster", "cluster/index.js"],
@@ -46,6 +58,9 @@ const builtins = [
46
58
  ["tty", "tty/index.js"],
47
59
  ["url", "url/index.js"],
48
60
  ["diagnostics_channel", "diagnostics-channel/index.js"],
61
+ ["tls", "tls/index.js"],
62
+ ["_tls_wrap", "tls-wrap/index.js"],
63
+ ["_stream_wrap", "stream-wrap/index.js"],
49
64
  ["_tls_common", "tls-common/index.js"],
50
65
  ["async_hooks", "async-hooks/index.js"],
51
66
  ["timers/promises", "timers/promises.js", "timers/promises.cjs"],
@@ -95,7 +110,10 @@ function builtinAliases(commonJS = false) {
95
110
  }
96
111
  export function compatibilityAliases() {
97
112
  return {
98
- "process/": stdlib.process,
113
+ "process/": nodeCompatPath("process"),
114
+ // Preserve brorand's browser crypto:false branch across Vite aliases.
115
+ brorand: fileURLToPath(new URL("../compat/crypto/brorand.cjs", import.meta.url)),
116
+ "cf-workers-native:process-base": createRequire(import.meta.url).resolve(stdlib.process),
99
117
  "cloudflare:node": workersModulePath("cloudflare-node"),
100
118
  "cloudflare:workers": workersModulePath("cloudflare-workers"),
101
119
  "punycode/": polyfill("punycode/punycode.js"),
@@ -109,6 +127,7 @@ export function commonJSCompatibilityAliases() {
109
127
  }
110
128
  export function compatibilityDependencies() {
111
129
  return [
130
+ processStatePath,
112
131
  "cloudflare:node",
113
132
  "cloudflare:workers",
114
133
  ...Object.keys(builtinAliases()),
@@ -7,7 +7,7 @@ import { documentAssets, listAssets } from "./documents.js";
7
7
  import { serverModules } from "./server-modules.js";
8
8
  import { resolve, dirname, isAbsolute } from "node:path";
9
9
  import { existsSync } from "node:fs";
10
- import { configuredPath, compatibilityAliases, compatibilityDependencies, commonJSCompatibilityAliases, globalsInstallPath, nodeGlobalsInstallPath, globalsPath, globalsInjectPath, workerEntry, } from "./shared.js";
10
+ import { configuredPath, compatibilityAliases, compatibilityDependencies, processStatePath, commonJSCompatibilityAliases, globalsInstallPath, nodeGlobalsInstallPath, globalsPath, globalsInjectPath, workerEntry, } from "./shared.js";
11
11
  import { nodePolyfills } from "vite-plugin-node-polyfills";
12
12
  import inject from "@rollup/plugin-inject";
13
13
  import { normalizePath } from "vite";
@@ -130,8 +130,9 @@ function compatibilityPlugins(installGlobals = false) {
130
130
  ...inject({
131
131
  Buffer: [globalsInjectPath, "Buffer"],
132
132
  // util reads process during Buffer initialization. Keep this import
133
- // independent of the injector that also imports Buffer.
134
- process: [aliases["process/"], "default"],
133
+ // on the shared state leaf: importing the full process adapter here
134
+ // would cycle through events/util in optimized development chunks.
135
+ process: [processStatePath, "default"],
135
136
  global: [globalsRuntimePath, "global"],
136
137
  setImmediate: [globalsRuntimePath, "setImmediate"],
137
138
  clearImmediate: [globalsRuntimePath, "clearImmediate"],
@@ -33,13 +33,15 @@ final class WorkerSockets {
33
33
  final Result opening;
34
34
  final ArrayDeque<byte[]> chunks = new ArrayDeque<>();
35
35
  SocketChannel channel;
36
- Result reading, watching;
36
+ Result reading, watching, upgrading;
37
+ String host; int port;
37
38
  int count, offset;
38
39
  boolean ready, closed, eof, ended, writing, reset;
39
40
  Connection(String id, Result opening) { this.id=id; this.opening=opening; }
40
41
  void fail(String message) {
41
42
  if (closed) return;
42
43
  closed=true;
44
+ if(upgrading!=null) { Result pending=upgrading; upgrading=null; pending.reject(message); }
43
45
  if (!ready) { ready=true; opening.reject(message); }
44
46
  if (reading!=null) {
45
47
  Result pending=reading; reading=null;
@@ -85,7 +87,8 @@ final class WorkerSockets {
85
87
  fail("Socket failed: "+error.getMessage());
86
88
  }
87
89
  }
88
- synchronized void open(String id,String host,int port,boolean tls,Result result) {
90
+ synchronized void open(String id,String host,int port,boolean tls,Result result) { open(id,host,port,tls,null,result); }
91
+ synchronized void open(String id,String host,int port,boolean tls,String servername,Result result) {
89
92
  if(stopped || id==null || id.isEmpty() || connections.containsKey(id) || host==null || host.isEmpty() || port<1 || port>65535) { result.reject("Invalid socket open"); return; }
90
93
  try {
91
94
  final SSLEngine engine;
@@ -96,11 +99,11 @@ final class WorkerSockets {
96
99
  SSLContext context=SSLContext.getInstance("TLS");
97
100
  context.init(null,null,null); tlsContext=context;
98
101
  }
99
- engine=tlsContext.createSSLEngine(host,port); engine.setUseClientMode(true);
102
+ engine=tlsContext.createSSLEngine(servername==null || servername.isEmpty() ? host : servername,port); engine.setUseClientMode(true);
100
103
  SSLParameters parameters=engine.getSSLParameters(); parameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(parameters);
101
104
  } else engine=null;
102
105
  if(group==null) group=new NioEventLoopGroup(1);
103
- Connection connection=new Connection(id,result); connections.put(id,connection);
106
+ Connection connection=new Connection(id,result); connection.host=host; connection.port=port; connections.put(id,connection);
104
107
  ChannelFuture future=new Bootstrap().group(group).channel(NioSocketChannel.class)
105
108
  .option(ChannelOption.AUTO_READ,false).option(ChannelOption.ALLOW_HALF_CLOSURE,true)
106
109
  .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,30000)
@@ -130,6 +133,37 @@ final class WorkerSockets {
130
133
  });
131
134
  } catch(Exception error) { Connection connection=connections.remove(id); if(connection!=null) connection.fail(error.toString()); else result.reject(error.toString()); }
132
135
  }
136
+ void startTls(String id,String servername,Result result) {
137
+ perform(id,result,connection -> {
138
+ if(connection.ended || connection.eof || connection.writing || connection.upgrading!=null || connection.channel.pipeline().get(SslHandler.class)!=null) { result.reject("Socket cannot be upgraded"); return; }
139
+ try {
140
+ final SSLEngine engine;
141
+ synchronized(this) {
142
+ if(tlsContext==null) { tlsContext=SSLContext.getInstance("TLS"); tlsContext.init(null,null,null); }
143
+ engine=tlsContext.createSSLEngine(servername==null || servername.isEmpty()?connection.host:servername,connection.port);
144
+ }
145
+ engine.setUseClientMode(true);
146
+ SSLParameters parameters=engine.getSSLParameters(); parameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(parameters);
147
+ connection.upgrading=result;
148
+ JSObject moved=new JSObject(); moved.put("upgraded",true);
149
+ if(connection.reading!=null) { Result pending=connection.reading; connection.reading=null; pending.resolve(moved); }
150
+ if(connection.watching!=null) { Result pending=connection.watching; connection.watching=null; pending.resolve(moved); }
151
+ ArrayDeque<byte[]> buffered=new ArrayDeque<>(connection.chunks); connection.chunks.clear();
152
+ int firstOffset=connection.offset; connection.offset=0;
153
+ SslHandler handler=new SslHandler(engine);
154
+ connection.channel.pipeline().addFirst(handler);
155
+ for(byte[] chunk:buffered) {
156
+ connection.channel.pipeline().fireChannelRead(Unpooled.wrappedBuffer(chunk,firstOffset,chunk.length-firstOffset)); firstOffset=0;
157
+ }
158
+ handler.handshakeFuture().addListener(handshake -> {
159
+ if(connection.closed) return;
160
+ if(!handshake.isSuccess()) { connection.fail("TLS failed: "+handshake.cause()); return; }
161
+ Result pending=connection.upgrading; connection.upgrading=null; pending.resolve(null); connection.pump();
162
+ });
163
+ connection.channel.read();
164
+ } catch(Exception error) { result.reject(error.toString()); connection.fail(error.toString()); }
165
+ });
166
+ }
133
167
  private static String authority(java.net.InetSocketAddress address) {
134
168
  String host=address.getAddress().getHostAddress(); return (host.contains(":")?"["+host+"]":host)+":"+address.getPort();
135
169
  }
@@ -163,7 +197,7 @@ final class WorkerSockets {
163
197
  try { chunk=Base64.decode(encoded,Base64.DEFAULT); } catch(Exception error) { result.reject("Invalid socket chunk"); return; }
164
198
  if(chunk.length>65536) { result.reject("Socket chunk exceeds limit"); return; }
165
199
  perform(id,result,connection -> {
166
- if(connection.ended || connection.writing) { result.reject("Socket write unavailable"); return; }
200
+ if(connection.ended || connection.writing || connection.upgrading!=null) { result.reject("Socket write unavailable"); return; }
167
201
  connection.writing=true;
168
202
  connection.channel.writeAndFlush(Unpooled.wrappedBuffer(chunk)).addListener(future -> {
169
203
  connection.writing=false;
@@ -174,11 +208,25 @@ final class WorkerSockets {
174
208
  void end(String id,Result result) {
175
209
  perform(id,result,true,connection -> {
176
210
  if(connection.reset) { result.resolve(null); return; }
177
- if(connection.writing) { result.reject("Socket write still pending"); return; }
211
+ if(connection.writing || connection.upgrading!=null) { result.reject("Socket write still pending"); return; }
178
212
  if(connection.ended) { result.resolve(null); return; }
179
213
  connection.ended=true;
180
- connection.channel.shutdownOutput().addListener(future -> {
181
- if(future.isSuccess()) result.resolve(null); else { result.reject("Socket end failed"); connection.fail("Socket end failed"); }
214
+ Runnable shutdownOutput=() -> {
215
+ if(connection.eof && !connection.channel.isActive()) { result.resolve(null); return; }
216
+ connection.channel.shutdownOutput().addListener(future -> {
217
+ if(future.isSuccess() || connection.eof) result.resolve(null);
218
+ else { result.reject("Socket end failed"); connection.fail("Socket end failed"); }
219
+ });
220
+ };
221
+ SslHandler tls=connection.channel.pipeline().get(SslHandler.class);
222
+ if(tls==null) shutdownOutput.run();
223
+ else tls.closeOutbound().addListener(future -> {
224
+ // TLS close_notify half-closes the TLS write side. Do not send
225
+ // TCP FIN here: it can close a peer's raw transport before its
226
+ // encrypted response has flushed. The read side owns final close.
227
+ if(future.isSuccess()) result.resolve(null);
228
+ else if(connection.eof) result.resolve(null);
229
+ else { result.reject("TLS end failed"); connection.fail("TLS end failed"); }
182
230
  });
183
231
  });
184
232
  }
@@ -110,9 +110,10 @@ public class WorkersCapacitorPlugin extends Plugin {
110
110
  };
111
111
  }
112
112
 
113
+ @PluginMethod public void socketStartTls(PluginCall call) { network.startTls(call.getString("id"),call.getString("servername"),result(call)); }
113
114
  @PluginMethod public void socketWatch(PluginCall call) { network.watch(call.getString("id"),result(call)); }
114
115
  @PluginMethod public void socketOpen(PluginCall call) {
115
- network.open(call.getString("id"),call.getString("host"),call.getInt("port",0),call.getBoolean("tls",false),result(call));
116
+ network.open(call.getString("id"),call.getString("host"),call.getInt("port",0),call.getBoolean("tls",false),call.getString("servername"),result(call));
116
117
  }
117
118
  @PluginMethod public void socketWrite(PluginCall call) { network.write(call.getString("id"),call.getString("chunk"),result(call)); }
118
119
  @PluginMethod public void socketEnd(PluginCall call) { network.end(call.getString("id"),result(call)); }
@@ -246,8 +247,9 @@ public class WorkersCapacitorPlugin extends Plugin {
246
247
  }
247
248
  @JavascriptInterface public void cookiesGet(String callbackId,String url) { WorkersCapacitorPlugin.this.cookiesGet(url,hostResult(owner,callbackId)); }
248
249
  @JavascriptInterface public void cookiesSet(String callbackId,String url,String cookies) { WorkersCapacitorPlugin.this.cookiesSet(url,cookies,hostResult(owner,callbackId)); }
250
+ @JavascriptInterface public void socketStartTls(String callbackId,String id,String servername) { network.startTls(id,servername,hostResult(owner,callbackId)); }
249
251
  @JavascriptInterface public void socketWatch(String callbackId,String id) { network.watch(id,hostResult(owner,callbackId)); }
250
- @JavascriptInterface public void socketOpen(String callbackId,String id,String host,int port,boolean tls) { network.open(id,host,port,tls,hostResult(owner,callbackId)); }
252
+ @JavascriptInterface public void socketOpen(String callbackId,String id,String host,int port,boolean tls,String servername) { network.open(id,host,port,tls,servername,hostResult(owner,callbackId)); }
251
253
  @JavascriptInterface public void socketWrite(String callbackId,String id,String chunk) { network.write(id,chunk,hostResult(owner,callbackId)); }
252
254
  @JavascriptInterface public void socketEnd(String callbackId,String id) { network.end(id,hostResult(owner,callbackId)); }
253
255
  @JavascriptInterface public void socketRead(String callbackId,String id,int count) { network.read(id,count,hostResult(owner,callbackId)); }
@@ -22,13 +22,23 @@ final class NetworkBridge {
22
22
  }
23
23
  }
24
24
  }
25
+ func socketVerifyTls(_ call: CAPPluginCall) {
26
+ guard let id = call.getString("id"), let encoded = call.getArray("certificates", String.self), encoded.count <= 32 else { reject(call, "Invalid certificate chain"); return }
27
+ let certificates = encoded.compactMap { $0.utf8.count <= 1048576 ? Data(base64Encoded: $0) : nil }
28
+ guard certificates.count == encoded.count else { reject(call, "Invalid certificate chain"); return }
29
+ sockets.verifyTls(id: id, certificates: certificates, completion: socketResult(call))
30
+ }
31
+ func socketStartTls(_ call: CAPPluginCall) {
32
+ guard let id = call.getString("id") else { reject(call, "Missing socket"); return }
33
+ sockets.startTls(id: id, servername: call.getString("servername"), completion: socketResult(call))
34
+ }
25
35
  func socketWatch(_ call: CAPPluginCall) {
26
36
  guard let id = call.getString("id") else { reject(call, "Missing socket"); return }
27
37
  sockets.watch(id: id, completion: socketResult(call))
28
38
  }
29
39
  func socketOpen(_ call: CAPPluginCall) {
30
40
  guard let id = call.getString("id"), let host = call.getString("host"), let port = call.getInt("port") else { reject(call, "Invalid socket open"); return }
31
- sockets.open(id: id, host: host, port: port, tls: call.getBool("tls") ?? false, completion: socketResult(call))
41
+ sockets.open(id: id, host: host, port: port, tls: call.getBool("tls") ?? false, servername: call.getString("servername"), completion: socketResult(call))
32
42
  }
33
43
  func socketWrite(_ call: CAPPluginCall) {
34
44
  guard let id = call.getString("id"), let encoded = call.getString("chunk"), encoded.utf8.count <= 87384, let data = Data(base64Encoded: encoded) else { reject(call, "Invalid socket write"); return }
@@ -1,5 +1,6 @@
1
1
  import Foundation
2
2
  import Network
3
+ import Security
3
4
  import Capacitor
4
5
 
5
6
  /// TCP byte transport. All state and completions belong to one serial queue.
@@ -7,6 +8,8 @@ final class SocketBridge: @unchecked Sendable {
7
8
  private final class Connection: @unchecked Sendable {
8
9
  let id: String
9
10
  let transport: NWConnection
11
+ var encrypted = false
12
+ var host = ""
10
13
  var opening: ((Result<PluginCallResultData, Error>) -> Void)?
11
14
  var reading: ((Result<PluginCallResultData, Error>) -> Void)?
12
15
  var writing: ((Result<PluginCallResultData, Error>) -> Void)?
@@ -51,12 +54,19 @@ final class SocketBridge: @unchecked Sendable {
51
54
  let waiters = value.closeWaiters; value.closeWaiters.removeAll()
52
55
  for waiter in waiters { waiter() }
53
56
  }
54
- func open(id: String, host: String, port: Int, tls: Bool, completion: @escaping Completion) {
57
+ func open(id: String, host: String, port: Int, tls: Bool, servername: String? = nil, completion: @escaping Completion) {
55
58
  queue.async {
56
59
  guard !self.stopped, !id.isEmpty, !host.isEmpty, port > 0, port <= 65535,
57
60
  self.values[id] == nil, let endpointPort = NWEndpoint.Port(rawValue: UInt16(port)) else { completion(.failure(Failure.invalid)); return }
58
- let transport = NWConnection(host: NWEndpoint.Host(host), port: endpointPort, using: tls ? .tls : .tcp)
61
+ let parameters: NWParameters
62
+ if tls {
63
+ let options = NWProtocolTLS.Options()
64
+ sec_protocol_options_set_tls_server_name(options.securityProtocolOptions, servername ?? host)
65
+ parameters = NWParameters(tls: options, tcp: NWProtocolTCP.Options())
66
+ } else { parameters = .tcp }
67
+ let transport = NWConnection(host: NWEndpoint.Host(host), port: endpointPort, using: parameters)
59
68
  let value = Connection(id, transport)
69
+ value.host = host; value.encrypted = tls
60
70
  value.opening = completion
61
71
  self.values[id] = value
62
72
  transport.stateUpdateHandler = { [weak self, weak value] state in
@@ -89,6 +99,31 @@ final class SocketBridge: @unchecked Sendable {
89
99
  transport.start(queue: self.queue)
90
100
  }
91
101
  }
102
+ func startTls(id: String, servername: String?, completion: @escaping Completion) {
103
+ queue.async {
104
+ guard let value = self.values[id], value.ready, !value.closed, !value.eof, !value.ended, !value.encrypted, value.writing == nil,
105
+ let hostname = servername, !hostname.isEmpty, !hostname.utf8.contains(0) else { completion(.failure(Failure.invalid)); return }
106
+ value.encrypted = true; value.host = hostname
107
+ value.reading?(.success(["upgraded": true])); value.reading = nil
108
+ value.watching?(.success(["upgraded": true])); value.watching = nil
109
+ // JS encrypts records with OpenSSL memory BIOs on this same TCP stream.
110
+ // The successful JS open is withheld until verifyTls authenticates it.
111
+ completion(.success(["tlsEngine": "openssl-wasm"]))
112
+ }
113
+ }
114
+ func verifyTls(id: String, certificates: [Data], completion: @escaping Completion) {
115
+ queue.async {
116
+ guard let value = self.values[id], !value.closed, value.encrypted, !certificates.isEmpty else { completion(.failure(Failure.invalid)); return }
117
+ let chain = certificates.compactMap { SecCertificateCreateWithData(nil, $0 as CFData) }
118
+ guard chain.count == certificates.count else { completion(.failure(Failure.invalid)); return }
119
+ var trust: SecTrust?
120
+ let policy = SecPolicyCreateSSL(true, value.host as CFString)
121
+ guard SecTrustCreateWithCertificates(chain as CFArray, policy, &trust) == errSecSuccess, let trust else { completion(.failure(Failure.invalid)); return }
122
+ var error: CFError?
123
+ guard SecTrustEvaluateWithError(trust, &error) else { completion(.failure(error as Error? ?? Failure.invalid)); return }
124
+ completion(.success([:]))
125
+ }
126
+ }
92
127
  func watch(id: String, completion: @escaping Completion) {
93
128
  queue.async {
94
129
  if let value = self.values[id], value.reset { completion(.success(["reset": true])); return }
@@ -13,6 +13,8 @@ public final class WorkersCapacitorPlugin: CAPPlugin, CAPBridgedPlugin {
13
13
  CAPPluginMethod(name: "start", returnType: CAPPluginReturnPromise),
14
14
  CAPPluginMethod(name: "stop", returnType: CAPPluginReturnPromise),
15
15
  CAPPluginMethod(name: "socketWatch", returnType: CAPPluginReturnPromise),
16
+ CAPPluginMethod(name: "socketVerifyTls", returnType: CAPPluginReturnPromise),
17
+ CAPPluginMethod(name: "socketStartTls", returnType: CAPPluginReturnPromise),
16
18
  CAPPluginMethod(name: "socketOpen", returnType: CAPPluginReturnPromise),
17
19
  CAPPluginMethod(name: "socketWrite", returnType: CAPPluginReturnPromise),
18
20
  CAPPluginMethod(name: "socketEnd", returnType: CAPPluginReturnPromise),
@@ -69,6 +71,8 @@ public final class WorkersCapacitorPlugin: CAPPlugin, CAPBridgedPlugin {
69
71
  Task { await owner.closeAll(); call.resolve() }
70
72
  }
71
73
  }
74
+ @objc func socketVerifyTls(_ call: CAPPluginCall) { network.socketVerifyTls(call) }
75
+ @objc func socketStartTls(_ call: CAPPluginCall) { network.socketStartTls(call) }
72
76
  @objc func socketWatch(_ call: CAPPluginCall) { network.socketWatch(call) }
73
77
  @objc func socketOpen(_ call: CAPPluginCall) { network.socketOpen(call) }
74
78
  @objc func socketWrite(_ call: CAPPluginCall) { network.socketWrite(call) }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cf-workers-native",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "license": "MIT",
5
5
  "description": "Bring Cloudflare Workers apps to iOS and Android.",
6
6
  "repository": {
@@ -111,12 +111,14 @@
111
111
  "brotli-dec-wasm": "2.3.2",
112
112
  "esbuild": "^0.28.2",
113
113
  "jsonc-parser": "^3.3.1",
114
+ "memfs": "4.80.0",
114
115
  "node-stdlib-browser": "^1.3.1",
115
116
  "parse-srcset": "^1.0.2",
116
117
  "parse5": "^8.0.1",
117
118
  "punycode": "2.3.1",
118
119
  "readable-stream": "4.8.0",
119
120
  "rollup": "^4.64.9",
121
+ "scrypt-js": "3.0.1",
120
122
  "smol-toml": "^1.9.1",
121
123
  "string_decoder": "^1.3.0",
122
124
  "vite-plugin-node-polyfills": "^0.28.0",