cf-workers-native 0.1.6 → 0.1.8-beta.pr103.shaa9df9497ef99
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/README.md +2 -2
- package/dist/browser/documents/service-worker.js +20 -3
- package/dist/compat/crypto/keys.js +4 -3
- package/dist/compat/crypto/native-crypto.js +64 -0
- package/dist/compat/fs/file-handle.js +28 -5
- package/dist/compat/fs/index.js +27 -4
- package/dist/compat/fs/io.js +33 -1
- 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
package/README.md
CHANGED
|
@@ -66,7 +66,7 @@ Install the package in your web project, then follow the
|
|
|
66
66
|
[complete mobile setup](docs/integration.md#workflow):
|
|
67
67
|
|
|
68
68
|
```sh
|
|
69
|
-
npm install --save-exact cf-workers-native@0.1.
|
|
69
|
+
npm install --save-exact cf-workers-native@0.1.7
|
|
70
70
|
```
|
|
71
71
|
|
|
72
72
|
Installation alone does not generate a mobile project. The guide covers adding
|
|
@@ -84,7 +84,7 @@ Open your application repository and give your assistant this prompt:
|
|
|
84
84
|
|
|
85
85
|
```text
|
|
86
86
|
Read https://github.com/rdlabo-dev/cf-workers-native/blob/main/docs/integration.md.
|
|
87
|
-
Add an iOS and Android version of this Workers web app using cf-workers-native@0.1.
|
|
87
|
+
Add an iOS and Android version of this Workers web app using cf-workers-native@0.1.7
|
|
88
88
|
and Capacitor. Preserve the existing pages, backend and Cloudflare deployment configuration.
|
|
89
89
|
Use an existing test Worker for cloud-backed requests; ask before any cloud deployment.
|
|
90
90
|
Start by verifying one page, navigation and a form or data action on a simulator/emulator.
|
|
@@ -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
|
};
|
|
@@ -254,11 +254,12 @@ export function secretMaterial(value) {
|
|
|
254
254
|
export function generateKeySync(type, options) {
|
|
255
255
|
validateOneOf(type, "type", ["hmac", "aes"]);
|
|
256
256
|
validateObject(options, "options");
|
|
257
|
+
const { length } = options;
|
|
257
258
|
if (type === "hmac")
|
|
258
|
-
validateInteger(
|
|
259
|
+
validateInteger(length, "options.length", 8, 65536);
|
|
259
260
|
else
|
|
260
|
-
validateOneOf(
|
|
261
|
-
const material = new Uint8Array(Math.floor(
|
|
261
|
+
validateOneOf(length, "options.length", [128, 192, 256]);
|
|
262
|
+
const material = new Uint8Array(Math.floor(length / 8));
|
|
262
263
|
globalThis.crypto.getRandomValues(material);
|
|
263
264
|
return createSecretKey(material);
|
|
264
265
|
}
|
|
@@ -47,6 +47,67 @@ var aliases = Object.assign(
|
|
|
47
47
|
)
|
|
48
48
|
);
|
|
49
49
|
|
|
50
|
+
// src/shared/buffer-source.ts
|
|
51
|
+
var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
52
|
+
var typedArrayBuffer = Object.getOwnPropertyDescriptor(
|
|
53
|
+
typedArrayPrototype,
|
|
54
|
+
"buffer"
|
|
55
|
+
).get;
|
|
56
|
+
var typedArrayOffset = Object.getOwnPropertyDescriptor(
|
|
57
|
+
typedArrayPrototype,
|
|
58
|
+
"byteOffset"
|
|
59
|
+
).get;
|
|
60
|
+
var typedArrayLength = Object.getOwnPropertyDescriptor(
|
|
61
|
+
typedArrayPrototype,
|
|
62
|
+
"byteLength"
|
|
63
|
+
).get;
|
|
64
|
+
var dataViewBuffer = Object.getOwnPropertyDescriptor(
|
|
65
|
+
DataView.prototype,
|
|
66
|
+
"buffer"
|
|
67
|
+
).get;
|
|
68
|
+
var dataViewOffset = Object.getOwnPropertyDescriptor(
|
|
69
|
+
DataView.prototype,
|
|
70
|
+
"byteOffset"
|
|
71
|
+
).get;
|
|
72
|
+
var dataViewLength = Object.getOwnPropertyDescriptor(
|
|
73
|
+
DataView.prototype,
|
|
74
|
+
"byteLength"
|
|
75
|
+
).get;
|
|
76
|
+
var sharedLength;
|
|
77
|
+
try {
|
|
78
|
+
const prototype = typeof SharedArrayBuffer === "function" ? SharedArrayBuffer.prototype : Object.getPrototypeOf(
|
|
79
|
+
new WebAssembly.Memory({ initial: 0, maximum: 1, shared: true }).buffer
|
|
80
|
+
);
|
|
81
|
+
sharedLength = Object.getOwnPropertyDescriptor(prototype, "byteLength")?.get;
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
function viewBytes(value) {
|
|
85
|
+
let buffer;
|
|
86
|
+
try {
|
|
87
|
+
buffer = typedArrayBuffer.call(value);
|
|
88
|
+
} catch {
|
|
89
|
+
buffer = dataViewBuffer.call(value);
|
|
90
|
+
try {
|
|
91
|
+
return new Uint8Array(
|
|
92
|
+
buffer,
|
|
93
|
+
dataViewOffset.call(value),
|
|
94
|
+
dataViewLength.call(value)
|
|
95
|
+
);
|
|
96
|
+
} catch {
|
|
97
|
+
return new Uint8Array(0);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return new Uint8Array(
|
|
102
|
+
buffer,
|
|
103
|
+
typedArrayOffset.call(value),
|
|
104
|
+
typedArrayLength.call(value)
|
|
105
|
+
);
|
|
106
|
+
} catch {
|
|
107
|
+
return new Uint8Array(0);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
50
111
|
// src/compat/crypto/native-crypto.ts
|
|
51
112
|
var instance;
|
|
52
113
|
var encoder = new TextEncoder();
|
|
@@ -469,12 +530,14 @@ var NativeECDH = class _NativeECDH {
|
|
|
469
530
|
return result(api);
|
|
470
531
|
}
|
|
471
532
|
setPrivateKey(data) {
|
|
533
|
+
data = viewBytes(data);
|
|
472
534
|
inputs([data], (api, [p]) => {
|
|
473
535
|
if (!api.wk_ec_set_private(this.pointer, p, data.byteLength))
|
|
474
536
|
throw new Error("Private key is not valid for specified curve.");
|
|
475
537
|
});
|
|
476
538
|
}
|
|
477
539
|
computeSecret(data) {
|
|
540
|
+
data = viewBytes(data);
|
|
478
541
|
return inputs([data], (api, [p]) => {
|
|
479
542
|
const status = api.wk_ec_secret(this.pointer, p, data.byteLength);
|
|
480
543
|
if (status !== 1)
|
|
@@ -485,6 +548,7 @@ var NativeECDH = class _NativeECDH {
|
|
|
485
548
|
});
|
|
486
549
|
}
|
|
487
550
|
static convertKey(data, curve, format) {
|
|
551
|
+
data = viewBytes(data);
|
|
488
552
|
if (!data.byteLength) return new Uint8Array();
|
|
489
553
|
const key = new _NativeECDH(curve);
|
|
490
554
|
try {
|
|
@@ -176,11 +176,17 @@ export class FileHandle extends EventEmitter {
|
|
|
176
176
|
validateBoolean(autoClose, "options.autoClose");
|
|
177
177
|
const handle = this;
|
|
178
178
|
const read = this.read.bind(this);
|
|
179
|
-
let controller, ended = false;
|
|
179
|
+
let controller, ended = false, failed = false, closingAtEof = false;
|
|
180
180
|
const finish = () => {
|
|
181
|
+
if (failed)
|
|
182
|
+
throw new TypeError("This ReadableStream is closed.");
|
|
183
|
+
if (ended && !closingAtEof)
|
|
184
|
+
throw new TypeError("This ReadableStream is closed.");
|
|
181
185
|
if (!ended) {
|
|
182
186
|
ended = true;
|
|
187
|
+
const request = controller.byobRequest;
|
|
183
188
|
controller.close();
|
|
189
|
+
request?.respond(0);
|
|
184
190
|
}
|
|
185
191
|
};
|
|
186
192
|
const stream = new ReadableStream({
|
|
@@ -191,13 +197,30 @@ export class FileHandle extends EventEmitter {
|
|
|
191
197
|
},
|
|
192
198
|
async pull(c) {
|
|
193
199
|
const request = c.byobRequest, view = request.view;
|
|
194
|
-
|
|
200
|
+
let bytesRead;
|
|
201
|
+
try {
|
|
202
|
+
({ bytesRead } = await read(view, view.byteOffset, view.byteLength));
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
failed = true;
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
if (ended)
|
|
209
|
+
return;
|
|
195
210
|
if (bytesRead === 0) {
|
|
196
211
|
finish();
|
|
197
|
-
if (autoClose)
|
|
198
|
-
|
|
212
|
+
if (autoClose) {
|
|
213
|
+
closingAtEof = true;
|
|
214
|
+
try {
|
|
215
|
+
await handle.close();
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
closingAtEof = false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
199
221
|
}
|
|
200
|
-
|
|
222
|
+
if (!ended)
|
|
223
|
+
request.respond(bytesRead);
|
|
201
224
|
},
|
|
202
225
|
async cancel() {
|
|
203
226
|
ended = true;
|
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";
|
|
@@ -28,6 +28,20 @@ const reads = new Set([
|
|
|
28
28
|
"existsSync",
|
|
29
29
|
]);
|
|
30
30
|
const api = { ...temporary };
|
|
31
|
+
// Stats values are produced by the filesystem; Workers forbids public construction.
|
|
32
|
+
api.Stats = new Proxy(api.Stats, {
|
|
33
|
+
construct() {
|
|
34
|
+
throw new TypeError("Illegal constructor");
|
|
35
|
+
},
|
|
36
|
+
apply() {
|
|
37
|
+
throw new TypeError("Class constructor Stats cannot be invoked without 'new'");
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
Object.defineProperty(api.Stats.prototype, "constructor", {
|
|
41
|
+
value: api.Stats,
|
|
42
|
+
configurable: true,
|
|
43
|
+
writable: true,
|
|
44
|
+
});
|
|
31
45
|
for (const name of Object.keys(api))
|
|
32
46
|
if (typeof api[name] === "function" && /^[a-z]/.test(name))
|
|
33
47
|
api[name] = (...args) => temporary[name](...args);
|
|
@@ -335,12 +349,21 @@ installOperation("copyFile", (source, destination, mode = 0) => {
|
|
|
335
349
|
throw Object.assign(new Error("The operation is not supported"), {
|
|
336
350
|
code: "ERR_UNSUPPORTED_OPERATION",
|
|
337
351
|
});
|
|
338
|
-
|
|
339
|
-
|
|
352
|
+
const sourcePath = pathOf(source);
|
|
353
|
+
const fromTemporary = temporaryPath(sourcePath);
|
|
340
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);
|
|
341
364
|
if (mode === 1 && api.existsSync(destination))
|
|
342
365
|
throw Object.assign(new Error("File already exists"), { code: "EEXIST" });
|
|
343
|
-
temporary.writeFileSync(destination, embedded.readFileSync(
|
|
366
|
+
temporary.writeFileSync(destination, embedded.readFileSync(sourcePath));
|
|
344
367
|
});
|
|
345
368
|
const copyTree = (source, destination, options) => {
|
|
346
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" &&
|
|
@@ -130,7 +161,8 @@ export function installIo(api, promises) {
|
|
|
130
161
|
}, (fd, buffers, position) => {
|
|
131
162
|
let count = 0;
|
|
132
163
|
for (const buffer of buffers) {
|
|
133
|
-
const
|
|
164
|
+
const bytes = viewBytes(buffer);
|
|
165
|
+
const size = api[name === "readv" ? "readSync" : "writeSync"](fd, bytes, 0, bytes.byteLength, position === null ? null : Number(position) + count);
|
|
134
166
|
count += size;
|
|
135
167
|
}
|
|
136
168
|
return count;
|
|
@@ -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.pr103.shaa9df9497ef99",
|
|
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": [
|