cf-workers-native 0.1.7 → 0.1.8-beta.pr86.sha3d2780a410ab

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.
@@ -83,7 +83,7 @@ self.addEventListener("fetch", (event) => {
83
83
  url.pathname.startsWith("/_capacitor_")
84
84
  )
85
85
  return fetch(event.request);
86
- return dispatch(event.request);
86
+ return dispatch(event.request, event.clientId);
87
87
  })(),
88
88
  );
89
89
  });
@@ -112,7 +112,7 @@ function hostReady(host, signal) {
112
112
  }
113
113
  });
114
114
  }
115
- async function dispatch(request) {
115
+ async function dispatch(request, clientId) {
116
116
  const deadline = Date.now() + 10000;
117
117
  let host = (
118
118
  await self.clients.matchAll({ type: "window", includeUncontrolled: true })
@@ -143,11 +143,28 @@ async function dispatch(request) {
143
143
  ? undefined
144
144
  : await readUpload(request);
145
145
  request.signal.throwIfAborted();
146
+ const requestHeaders = Object.fromEntries(request.headers);
147
+ // For an explicit same-origin fetch, Chromium can omit Origin from the
148
+ // FetchEvent. Clients.get only exposes same-origin clients to this worker.
149
+ if (
150
+ clientId &&
151
+ request.mode === "same-origin" &&
152
+ !["GET", "HEAD", "OPTIONS"].includes(request.method) &&
153
+ !request.headers.has("Origin")
154
+ ) {
155
+ const client = await self.clients.get(clientId);
156
+ if (
157
+ client?.type === "window" &&
158
+ client.frameType === "top-level" &&
159
+ new URL(client.url).origin === self.location.origin
160
+ )
161
+ requestHeaders.origin = self.location.origin;
162
+ }
146
163
  const message = {
147
164
  id: crypto.randomUUID(),
148
165
  url: request.url,
149
166
  method: request.method,
150
- headers: Object.fromEntries(request.headers),
167
+ headers: requestHeaders,
151
168
  body,
152
169
  stream: true,
153
170
  };
@@ -16,20 +16,23 @@ export function connect(address, options = {}) {
16
16
  if (!call)
17
17
  throw new Error("TCP sockets require the Capacitor native transport");
18
18
  const separator = address.lastIndexOf(":");
19
- const hostname = address.slice(0, separator).replace(/^\[|\]$/g, "");
19
+ const authority = address.slice(0, separator);
20
20
  const portText = address.slice(separator + 1);
21
- if (separator < 1 || !/^\d+$/.test(portText))
21
+ const port = Number(portText);
22
+ if (separator < 1 || !/^\d+$/.test(portText) || port < 1 || port > 65535)
22
23
  throw new TypeError("Invalid TCP address");
23
- const url = new URL(`tcp://${hostname.includes(":") ? `[${hostname}]` : hostname}:${portText}`);
24
- const port = Number(url.port);
25
- if (!url.hostname ||
26
- !port ||
27
- url.username ||
28
- url.password ||
29
- (url.pathname && url.pathname !== "/"))
24
+ let host = authority;
25
+ if (authority.includes(":")) {
26
+ // Special URL schemes parse IPv6 consistently even on older WebViews.
27
+ const literal = authority.startsWith("[") ? authority : `[${authority}]`;
28
+ if (!/^\[[0-9a-f:.]+\]$/i.test(literal))
29
+ throw new TypeError("Invalid TCP address");
30
+ host = new URL(`http://${literal}/`).hostname.slice(1, -1);
31
+ }
32
+ else if (/[\s/\\@?#<>^|\[\]\u0000]/u.test(host)) {
30
33
  throw new TypeError("Invalid TCP address");
34
+ }
31
35
  const id = crypto.randomUUID();
32
- const host = url.hostname.replace(/^\[|\]$/g, "");
33
36
  const directTls = options.secureTransport === "on";
34
37
  let secureCall = call;
35
38
  return transport((...args) => {
@@ -35,13 +35,14 @@ final class WorkerSockets {
35
35
  final ArrayDeque<byte[]> chunks = new ArrayDeque<>();
36
36
  SocketChannel channel;
37
37
  Result reading, watching, upgrading;
38
- String host; int port;
38
+ String host, terminalError; int port;
39
39
  int count, offset;
40
40
  boolean ready, closed, eof, ended, writing, reset, encrypted, closeNotify, inboundEndQueued;
41
41
  Connection(String id, Result opening) { this.id=id; this.opening=opening; }
42
42
  void fail(String message) {
43
43
  if (closed) return;
44
44
  closed=true;
45
+ terminalError=message;
45
46
  if(upgrading!=null) { Result pending=upgrading; upgrading=null; pending.reject(message); }
46
47
  if (!ready) { ready=true; opening.reject(message); }
47
48
  if (reading!=null) {
@@ -110,6 +111,7 @@ final class WorkerSockets {
110
111
  }
111
112
  }
112
113
  @Override public void exceptionCaught(ChannelHandlerContext context,Throwable error) {
114
+ if(closed) return;
113
115
  boolean peerReset = error instanceof java.io.IOException && String.valueOf(error.getMessage()).toLowerCase(java.util.Locale.ROOT).contains("reset");
114
116
  // Workers' plain TCP reset-as-EOF behavior must not turn a truncated
115
117
  // authenticated TLS stream into a successful end.
@@ -204,7 +206,9 @@ final class WorkerSockets {
204
206
  Connection connection=connections.get(id);
205
207
  if(connection==null) { result.reject("Unknown socket handle"); return; }
206
208
  connection.channel.eventLoop().execute(() -> {
207
- if((connection.closed && !(allowReset && connection.reset)) || !connection.ready) result.reject("Socket is not connected"); else action.accept(connection);
209
+ if(connection.closed && !(allowReset && connection.reset)) result.reject(connection.terminalError);
210
+ else if(!connection.ready) result.reject("Socket is not connected");
211
+ else action.accept(connection);
208
212
  });
209
213
  }
210
214
  void watch(String id,Result result) {
@@ -241,6 +241,17 @@ final class DocumentSchemeHandler: NSObject, WKURLSchemeHandler, WKScriptMessage
241
241
  }
242
242
  let id = UUID().uuidString
243
243
  request["id"] = id
244
+ // Script-message fetches bypass WebKit's network header generation.
245
+ // Derive Origin from the sending frame for state-changing requests.
246
+ if let method = request["method"] as? String,
247
+ !["GET", "HEAD", "OPTIONS"].contains(method.uppercased()) {
248
+ var headers = request["headers"] as? [String: String] ?? [:]
249
+ if !headers.keys.contains(where: { $0.caseInsensitiveCompare("Origin") == .orderedSame }),
250
+ let origin = localInitiator(message.frameInfo) {
251
+ headers["Origin"] = origin
252
+ request["headers"] = headers
253
+ }
254
+ }
244
255
  let streamId = request["streamId"] as? String ?? id
245
256
  fetchReplies[id] = replyHandler
246
257
  fetchRequests[id] = request
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cf-workers-native",
3
- "version": "0.1.7",
3
+ "version": "0.1.8-beta.pr86.sha3d2780a410ab",
4
4
  "license": "MIT",
5
5
  "description": "Bring Cloudflare Workers apps to iOS and Android.",
6
6
  "repository": {
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "publishConfig": {
25
25
  "access": "public",
26
- "tag": "latest"
26
+ "tag": "beta"
27
27
  },
28
28
  "type": "module",
29
29
  "files": [