cf-workers-native 0.1.7 → 0.1.8-beta.pr100.sha30ed95ef6e6b
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/browser/documents/service-worker.js +20 -3
- package/dist/compat/fs/index.js +13 -4
- package/dist/compat/fs/io.js +31 -0
- package/dist/compat/fs/writable.d.ts +1 -0
- package/dist/compat/fs/writable.js +40 -0
- package/dist/compat/net/sockets.js +13 -10
- package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +6 -2
- package/native/ios/DocumentBridge.swift +11 -0
- package/native/ios/SocketBridge.swift +9 -5
- package/package.json +2 -2
|
@@ -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:
|
|
167
|
+
headers: requestHeaders,
|
|
151
168
|
body,
|
|
152
169
|
stream: true,
|
|
153
170
|
};
|
package/dist/compat/fs/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { globSync as workersGlob } from "./glob.js";
|
|
|
7
7
|
import { fileMode } from "./mode.js";
|
|
8
8
|
import { validateInteger } from "../crypto/validation.js";
|
|
9
9
|
import * as embedded from "./embedded.js";
|
|
10
|
-
import { temporary, retainTemporaryFiles, temporaryPath, clearTemporaryFiles, writablePath, pathOf, readonlyFile, embeddedStat, } from "./writable.js";
|
|
10
|
+
import { temporary, retainTemporaryFiles, replaceTemporaryFile, temporaryPath, clearTemporaryFiles, writablePath, pathOf, readonlyFile, embeddedStat, } from "./writable.js";
|
|
11
11
|
import { Buffer } from "node:buffer";
|
|
12
12
|
import { validateFunction, validateObject, validateBoolean, validateUint32, } from "../net/validators.js";
|
|
13
13
|
import { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE } from "../net/errors.js";
|
|
@@ -349,12 +349,21 @@ installOperation("copyFile", (source, destination, mode = 0) => {
|
|
|
349
349
|
throw Object.assign(new Error("The operation is not supported"), {
|
|
350
350
|
code: "ERR_UNSUPPORTED_OPERATION",
|
|
351
351
|
});
|
|
352
|
-
|
|
353
|
-
|
|
352
|
+
const sourcePath = pathOf(source);
|
|
353
|
+
const fromTemporary = temporaryPath(sourcePath);
|
|
354
354
|
writablePath(destination, "copyFile");
|
|
355
|
+
const entry = api.lstatSync(destination, { throwIfNoEntry: false });
|
|
356
|
+
if ((entry?.isFile() || entry?.isSymbolicLink()) &&
|
|
357
|
+
(mode !== 1 || !api.existsSync(destination)) &&
|
|
358
|
+
api.statSync(sourcePath, { throwIfNoEntry: false })?.isFile()) {
|
|
359
|
+
replaceTemporaryFile(pathOf(destination), api.readFileSync(sourcePath));
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (fromTemporary)
|
|
363
|
+
return temporaryCopyFile(sourcePath, destination, mode);
|
|
355
364
|
if (mode === 1 && api.existsSync(destination))
|
|
356
365
|
throw Object.assign(new Error("File already exists"), { code: "EEXIST" });
|
|
357
|
-
temporary.writeFileSync(destination, embedded.readFileSync(
|
|
366
|
+
temporary.writeFileSync(destination, embedded.readFileSync(sourcePath));
|
|
358
367
|
});
|
|
359
368
|
const copyTree = (source, destination, options) => {
|
|
360
369
|
const fail = (code) => {
|
package/dist/compat/fs/io.js
CHANGED
|
@@ -111,6 +111,37 @@ export function installIo(api, promises) {
|
|
|
111
111
|
return 0;
|
|
112
112
|
return perform(() => raw[name + "Sync"](fd, buffers[0], 0, buffers[0].byteLength, position));
|
|
113
113
|
}, (args) => [args[1]]);
|
|
114
|
+
const readCallback = api.read;
|
|
115
|
+
api.read = (fd, ...args) => {
|
|
116
|
+
const callbackOnly = typeof args[0] === "function";
|
|
117
|
+
const options = callbackOnly ? {} : args[0];
|
|
118
|
+
if (options &&
|
|
119
|
+
typeof options === "object" &&
|
|
120
|
+
!ArrayBuffer.isView(options)) {
|
|
121
|
+
const callback = callbackOnly ? args[0] : args[1];
|
|
122
|
+
const { buffer = Buffer.alloc(16384), offset = 0, length = buffer.byteLength - offset, position = null, } = options;
|
|
123
|
+
if (!ArrayBuffer.isView(buffer))
|
|
124
|
+
throw new ERR_INVALID_ARG_TYPE("options.buffer", ["Buffer", "TypedArray", "DataView"], buffer);
|
|
125
|
+
validateUint32(offset, "options.offset");
|
|
126
|
+
validateUint32(length, "options.length");
|
|
127
|
+
validatePosition(position, "options.position");
|
|
128
|
+
validateFunction(callback, "callback");
|
|
129
|
+
if (length !== 0 && offset + length > buffer.byteLength)
|
|
130
|
+
throw new ERR_INVALID_ARG_VALUE("offset", "must be >= 0 and <= buffer.length");
|
|
131
|
+
let count;
|
|
132
|
+
try {
|
|
133
|
+
count =
|
|
134
|
+
length === 0 ? 0 : api.readSync(fd, buffer, offset, length, position);
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
queueMicrotask(() => callback(error));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
queueMicrotask(() => callback(null, count, buffer));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
return readCallback(fd, ...args);
|
|
144
|
+
};
|
|
114
145
|
const writeCallback = api.write;
|
|
115
146
|
api.write = (...args) => {
|
|
116
147
|
if (typeof args[1] === "string" &&
|
|
@@ -11,4 +11,5 @@ export declare function retainTemporaryFiles(): <T>(operation: () => T) => T;
|
|
|
11
11
|
export declare function readonlyFile(value: any, follow?: boolean): boolean;
|
|
12
12
|
export declare function embeddedStat(path: any, options?: any): any;
|
|
13
13
|
export declare function readDescriptor(fd: number): Buffer;
|
|
14
|
+
export declare function replaceTemporaryFile(path: string, data: Uint8Array): void;
|
|
14
15
|
export declare function descriptorFlags(fd: number): number;
|
|
@@ -312,6 +312,24 @@ function createTemporary() {
|
|
|
312
312
|
args[0] = pathOf(args[0]);
|
|
313
313
|
mount(args[0]);
|
|
314
314
|
args[1] = mutable(args[1], base, base !== "link");
|
|
315
|
+
// memfs may truncate or unlink an existing destination before discovering
|
|
316
|
+
// that the source cannot be copied. Workers preserves it on failure.
|
|
317
|
+
if (base === "copyFile" &&
|
|
318
|
+
fs.lstatSync(args[1], { throwIfNoEntry: false })) {
|
|
319
|
+
if (args[2] === fs.constants.COPYFILE_EXCL &&
|
|
320
|
+
fs.existsSync(args[1]))
|
|
321
|
+
throw Object.assign(new Error(`file already exists, copyFile '${args[1]}'`), {
|
|
322
|
+
code: "EEXIST",
|
|
323
|
+
errno: -17,
|
|
324
|
+
syscall: "copyFile",
|
|
325
|
+
path: args[1],
|
|
326
|
+
});
|
|
327
|
+
if (fs.statSync(args[0], { throwIfNoEntry: false })?.isDirectory())
|
|
328
|
+
throw Object.assign(new Error("illegal operation on a directory"), {
|
|
329
|
+
code: "EISDIR",
|
|
330
|
+
syscall: "copy",
|
|
331
|
+
});
|
|
332
|
+
}
|
|
315
333
|
}
|
|
316
334
|
else if (base === "rename") {
|
|
317
335
|
args[0] = mutable(args[0], base, false);
|
|
@@ -446,6 +464,25 @@ function createTemporary() {
|
|
|
446
464
|
])
|
|
447
465
|
api.promises[name] = (...args) => new Promise((resolve, reject) => api[name](...args, (error, value) => error ? reject(error) : resolve(value)));
|
|
448
466
|
return {
|
|
467
|
+
replaceFile(path, data) {
|
|
468
|
+
const target = mutable(path, "copyFile", false);
|
|
469
|
+
const parent = core.getResolvedLinkOrThrow(posix.dirname(target), "copyFile");
|
|
470
|
+
const entry = parent.getChild(posix.basename(target));
|
|
471
|
+
const previous = entry.getNode();
|
|
472
|
+
const replacement = core.createNode(fs.constants.S_IFREG | 0o666);
|
|
473
|
+
try {
|
|
474
|
+
replacement.setBuffer(data);
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
core.deleteNode(replacement);
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
// Retarget this entry only. Its parent keeps the same child count, while
|
|
481
|
+
// other links and open descriptions retain their original node.
|
|
482
|
+
entry.setNode(replacement);
|
|
483
|
+
if (--previous.nlink === 0)
|
|
484
|
+
core.deleteNode(previous);
|
|
485
|
+
},
|
|
449
486
|
descriptorFlags(fd) {
|
|
450
487
|
return core.getFileByFdOrThrow(fd, "write").flags;
|
|
451
488
|
},
|
|
@@ -527,6 +564,9 @@ registerDirectoryValidator((path) => {
|
|
|
527
564
|
export function readDescriptor(fd) {
|
|
528
565
|
return active().readDescriptor(fd);
|
|
529
566
|
}
|
|
567
|
+
export function replaceTemporaryFile(path, data) {
|
|
568
|
+
active().replaceFile(path, data);
|
|
569
|
+
}
|
|
530
570
|
export function descriptorFlags(fd) {
|
|
531
571
|
return active().descriptorFlags(fd);
|
|
532
572
|
}
|
|
@@ -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
|
|
19
|
+
const authority = address.slice(0, separator);
|
|
20
20
|
const portText = address.slice(separator + 1);
|
|
21
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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(
|
|
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
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
import Network
|
|
3
3
|
import Security
|
|
4
|
-
import Capacitor
|
|
5
4
|
|
|
6
5
|
/// TCP byte transport. All state and completions belong to one serial queue.
|
|
7
6
|
final class SocketBridge: @unchecked Sendable {
|
|
@@ -10,9 +9,9 @@ final class SocketBridge: @unchecked Sendable {
|
|
|
10
9
|
let transport: NWConnection
|
|
11
10
|
var encrypted = false
|
|
12
11
|
var host = ""
|
|
13
|
-
var opening:
|
|
14
|
-
var reading:
|
|
15
|
-
var writing:
|
|
12
|
+
var opening: Completion?
|
|
13
|
+
var reading: Completion?
|
|
14
|
+
var writing: Completion?
|
|
16
15
|
var closeWaiters: [() -> Void] = []
|
|
17
16
|
var cancelled = false
|
|
18
17
|
var reset = false
|
|
@@ -31,7 +30,7 @@ final class SocketBridge: @unchecked Sendable {
|
|
|
31
30
|
private let queue = DispatchQueue(label: "jp.rdlabo.workerscapacitor.sockets")
|
|
32
31
|
private var values: [String: Connection] = [:]
|
|
33
32
|
private var stopped = false
|
|
34
|
-
typealias Completion = (Result<
|
|
33
|
+
typealias Completion = (Result<[String: Any], Error>) -> Void
|
|
35
34
|
private func close(_ value: Connection, error: Error = Failure.closed, completion: (() -> Void)? = nil) {
|
|
36
35
|
if let completion {
|
|
37
36
|
value.releaseRequested = true
|
|
@@ -88,6 +87,11 @@ final class SocketBridge: @unchecked Sendable {
|
|
|
88
87
|
let remote = host.contains(":") ? "[\(host)]:\(port)" : "\(host):\(port)"
|
|
89
88
|
value.opening?(.success(["remoteAddress": remote])); value.opening = nil
|
|
90
89
|
self.pump(value)
|
|
90
|
+
case .failed(.posix(.ENETDOWN)) where value.ready && value.ended && !value.encrypted && !value.eof:
|
|
91
|
+
// Network.framework can report ENETDOWN after both peers
|
|
92
|
+
// send FIN, before the queued receive delivers the final
|
|
93
|
+
// bytes and EOF. Let receive report the inbound outcome.
|
|
94
|
+
self.pump(value)
|
|
91
95
|
case .waiting(let error), .failed(let error):
|
|
92
96
|
// Once EOF and the final send have completed, a late
|
|
93
97
|
// NW failure must not erase the EOF waiting for JS.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cf-workers-native",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8-beta.pr100.sha30ed95ef6e6b",
|
|
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": "
|
|
26
|
+
"tag": "beta"
|
|
27
27
|
},
|
|
28
28
|
"type": "module",
|
|
29
29
|
"files": [
|