cleanup: Remove server-side JS socket and HTTP request support. Not used/useful enough to justify keeping all this code around.
Some checks failed
Build Tilde Friends / Build-All (push) Failing after 5m6s

This commit is contained in:
2025-09-28 13:43:28 -04:00
parent 53261a6fbc
commit 0ead5ed967
12 changed files with 0 additions and 1637 deletions

View File

@@ -910,7 +910,6 @@ INPUT = README.md \
core/app.js \
core/client.js \
core/core.js \
core/http.js \
core/tfrpc.js \
docs/ \
src/

View File

@@ -195,18 +195,6 @@ Call a function after some delay.
* *Number* **timeout** Number of milliseconds to wait before calling the callback function.
`;
docs['parseHttpResponse()'] = `
Parses an HTTP response.
### Parameters
* *Uint8Array* **response** The response data. Maybe be partial or contain extra data. The return value will
indicate when and where it is complete.
* *Number* **last_length** The length of the data passed on a previous attempt for the same response, or 0 initially.
### Returns
* *Integer* **-2** if the response is incomplete.
* *Integer* **-1** if the response could not be parsed.
* *Object* An object with **bytes_parsed**, **minor_version**, **status**, **message**, and **headers** fields on successful parse.
`;
docs['exit()'] = `
Exits the app. But why would you want to do that?

View File

@@ -7,7 +7,6 @@
/** \cond */
import * as app from './app.js';
import * as http from './http.js';
export {invoke, getProcessBlob};
/** \endcond */
@@ -240,7 +239,6 @@ async function getProcessBlob(blobId, key, options) {
let settings = await loadSettings();
return settings?.permissions?.[user] ?? [];
},
getSockets: getSockets,
permissionTest: async function (permission) {
let user = process?.credentials?.session?.name;
let settings = await loadSettings();
@@ -556,10 +554,6 @@ async function getProcessBlob(blobId, key, options) {
imports.ssb.addEventListener = undefined;
imports.ssb.removeEventListener = undefined;
imports.ssb.getIdentityInfo = undefined;
imports.fetch = async function (url, options) {
let settings = await loadSettings();
return http.fetch(url, options, settings?.fetch_hosts);
};
if (
process.credentials &&

View File

@@ -1,121 +0,0 @@
/**
* \file
* \defgroup tfhttp Tilde Friends HTTP Client JS
* Tilde Friends server-side HTTP client.
* @{
*/
/**
* Parse a URL into protocol, host, path, and port parts.
* @param url
* @return An object of the URL parts.
*/
function parseUrl(url) {
// XXX: Hack.
let match = url.match(new RegExp('(\\w+)://([^/:]+)(?::(\\d+))?(.*)'));
return {
protocol: match[1],
host: match[2],
path: match[4],
port: match[3] ? parseInt(match[3]) : match[1] == 'http' ? 80 : 443,
};
}
/**
* Parse an HTTP response into headers and body content.
* @param data The response data, headers and body included.
* @return headers and body data.
*/
function parseResponse(data) {
let firstLine;
let headers = {};
while (true) {
let endLine = data.indexOf('\r\n');
let line = data.substring(0, endLine);
data = data.substring(endLine + 2);
if (!line.length) {
break;
} else if (!firstLine) {
firstLine = line;
} else {
let colon = line.indexOf(':');
headers[line.substring(colon)] = line.substring(colon + 1);
}
}
return {headers: headers, body: data};
}
/**
* Make an HTTP request.
* @param url The URL.
* @param options Request options.
* @param allowed_hosts List of allowed hosts.
* @return A promise resolved with the response headers and body.
*/
export function fetch(url, options, allowed_hosts) {
let parsed = parseUrl(url);
return new Promise(function (resolve, reject) {
if ((allowed_hosts ?? []).indexOf(parsed.host) == -1) {
throw new Error(`fetch() request to host ${parsed.host} is not allowed.`);
}
let socket = new Socket();
let buffer = new Uint8Array(0);
return socket
.connect(parsed.host, parsed.port)
.then(function () {
socket.read(function (data) {
if (data && data.length) {
let newBuffer = new Uint8Array(buffer.length + data.length);
newBuffer.set(buffer, 0);
newBuffer.set(data, buffer.length);
buffer = newBuffer;
} else {
let result = parseHttpResponse(buffer);
if (!result) {
reject(new Exception('Parse failed.'));
}
if (typeof result == 'number') {
if (result == -2) {
reject('Incomplete request.');
} else {
reject('Bad request.');
}
} else if (typeof result == 'object') {
resolve({
body: buffer.slice(result.bytes_parsed),
status: result.status,
message: result.message,
headers: result.headers,
});
} else {
reject(new Exception('Unexpected parse result.'));
}
resolve(parseResponse(utf8Decode(buffer)));
}
});
if (parsed.port == 443) {
return socket.startTls();
}
})
.then(function () {
let body =
typeof options?.body == 'string'
? utf8Encode(options.body)
: options.body || new Uint8Array(0);
let headers = utf8Encode(
`${options?.method ?? 'GET'} ${parsed.path} HTTP/1.0\r\nHost: ${parsed.host}\r\nConnection: close\r\nContent-Length: ${body.length}\r\n\r\n`
);
let fullRequest = new Uint8Array(headers.length + body.length);
fullRequest.set(headers, 0);
fullRequest.set(body, headers.length);
socket.write(fullRequest);
})
.catch(function (error) {
reject(error);
});
});
}
/** @} */

View File

@@ -45,7 +45,6 @@ options:
out_http_port_file (default: ""): File to which to write bound HTTP port.
blob_fetch_age_seconds (default: -1): Only blobs mentioned more recently than this age will be automatically fetched.
blob_expire_age_seconds (default: -1): Blobs older than this will be automatically deleted.
fetch_hosts (default: ""): Comma-separated list of host names to which HTTP fetch requests are allowed. None if empty.
http_redirect (default: ""): If connecting by HTTP and HTTPS is configured, Location header prefix (ie, "http://example.com")
index (default: "/~core/intro/"): Default path.
index_map (default: ""): Mappings from hostname to redirect path, one per line, as in: "www.tildefriends.net=/~core/index/"

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +0,0 @@
#pragma once
/**
** \defgroup socket_js Socket Interface
** Exposes network sockets to script.
** @{
*/
#include "quickjs.h"
/**
** Register the socket script interface.
** @param context The JS context.
** @return The Socket constructor.
*/
JSValue tf_socket_register(JSContext* context);
/**
** Get the number of active socket objects.
** @return The count.
*/
int tf_socket_get_count();
/**
** Get the number of connected socket objects.
** @return the count.
*/
int tf_socket_get_open_count();
/** @} */

View File

@@ -8,7 +8,6 @@
#include "mem.h"
#include "packetstream.h"
#include "serialize.h"
#include "socket.js.h"
#include "ssb.db.h"
#include "ssb.h"
#include "ssb.js.h"
@@ -826,9 +825,6 @@ static JSValue _tf_task_getStats(JSContext* context, JSValueConst this_val, int
JS_SetPropertyStr(context, result, "tls_malloc_percent", JS_NewFloat64(context, 100.0 * tf_mem_get_tls_malloc_size() / total_memory));
JS_SetPropertyStr(context, result, "tf_malloc_percent", JS_NewFloat64(context, 100.0 * tf_mem_get_tf_malloc_size() / total_memory));
JS_SetPropertyStr(context, result, "socket_count", JS_NewInt32(context, tf_socket_get_count()));
JS_SetPropertyStr(context, result, "socket_open_count", JS_NewInt32(context, tf_socket_get_open_count()));
if (task->_ssb)
{
tf_ssb_stats_t ssb_stats = { 0 };
@@ -1665,8 +1661,6 @@ void tf_task_activate(tf_task_t* task)
sqlite3_open(task->_db_path, &task->_db);
JS_SetPropertyStr(context, global, "Task", tf_taskstub_register(context));
JS_SetPropertyStr(context, global, "Socket", tf_socket_register(context));
JS_SetPropertyStr(context, global, "TlsContext", tf_tls_context_register(context));
tf_file_register(context);
tf_database_register(context);

View File

@@ -549,93 +549,6 @@ static void _test_float(const tf_test_options_t* options)
unlink("out/child.js");
}
static void _test_socket(const tf_test_options_t* options)
{
_write_file("out/test.js",
"'use strict';\n"
"\n"
"var s = new Socket();\n"
"print('connecting');\n"
"print('before connect', s.isConnected);\n"
"s.onError(function(e) {\n"
" print(e);\n"
"});\n"
"print('noDelay', s.noDelay);\n"
"s.noDelay = true;\n"
"s.connect('www.unprompted.com', 80).then(function() {\n"
" print('connected', 'www.unprompted.com', 80, s.isConnected);\n"
" print(s.peerName);\n"
" s.read(function(data) {\n"
" print('read', data ? data.length : null);\n"
" });\n"
" s.write('GET / HTTP/1.0\\r\\n\\r\\n');\n"
"}).then(function(e) {\n"
" print('closed 1');\n"
"});\n"
"\n"
"var s2 = new Socket();\n"
"print('connecting');\n"
"print('before connect', s2.isConnected);\n"
"s2.onError(function(e) {\n"
" print('error');\n"
" print(e);\n"
"});\n"
"print('noDelay', s2.noDelay);\n"
"s2.noDelay = true;\n"
"s2.connect('www.unprompted.com', 443).then(function() {\n"
" print('connected', 'www.unprompted.com', 443);\n"
" s2.read(function(data) {\n"
" print('read', data ? data.length : null);\n"
" });\n"
" return s2.startTls();\n"
"}).then(function() {\n"
" print('ready');\n"
" print(s2.peerName);\n"
" s2.write('GET / HTTP/1.0\\r\\nConnection: close\\r\\n\\r\\n').then(function() {\n"
" s2.shutdown();\n"
" });\n"
"}).catch(function(e) {\n"
" print('caught');\n"
" print(e);\n"
"});\n"
"var s3 = new Socket();\n"
"print('connecting s3');\n"
"print('before connect', s3.isConnected);\n"
"s3.onError(function(e) {\n"
" print('error');\n"
" print(e);\n"
"});\n"
"print('noDelay', s3.noDelay);\n"
"s3.noDelay = true;\n"
"s3.connect('0.0.0.0', 443).then(function() {\n"
" print('connected', '0.0.0.0', 443);\n"
" s3.read(function(data) {\n"
" print('read', data ? data.length : null);\n"
" });\n"
" return s3.startTls();\n"
"}).then(function() {\n"
" print('ready');\n"
" print(s3.peerName);\n"
" s3.write('GET / HTTP/1.0\\r\\nConnection: close\\r\\n\\r\\n').then(function() {\n"
" s3.shutdown();\n"
" });\n"
"}).catch(function(e) {\n"
" print('caught');\n"
" print(e);\n"
"});\n");
char command[256];
unlink("out/test_db0.sqlite");
snprintf(command, sizeof(command), "%s run --db-path=out/test_db0.sqlite -s out/test.js" TEST_ARGS, options->exe_path);
tf_printf("%s\n", command);
int result = system(command);
tf_printf("returned %d\n", WEXITSTATUS(result));
assert(WIFEXITED(result));
assert(WEXITSTATUS(result) == 0);
unlink("out/test.js");
}
static void _test_file(const tf_test_options_t* options)
{
_write_file("out/test.js",
@@ -1065,7 +978,6 @@ void tf_tests(const tf_test_options_t* options)
_tf_test_run(options, "icu", _test_icu, false);
_tf_test_run(options, "uint8array", _test_uint8array, false);
_tf_test_run(options, "float", _test_float, false);
_tf_test_run(options, "socket", _test_socket, false);
_tf_test_run(options, "file", _test_file, false);
_tf_test_run(options, "b64", _test_b64, false);
_tf_test_run(options, "rooms", tf_ssb_test_rooms, false);

View File

@@ -1,105 +0,0 @@
#include "tlscontext.js.h"
#include "log.h"
#include "mem.h"
#include "task.h"
#include "tls.h"
#include <stdlib.h>
#include <string.h>
static JSClassID _classId;
static int _count;
typedef struct _tf_tls_context_t
{
tf_tls_context_t* context;
tf_task_t* task;
JSValue object;
} tf_tls_context_t;
static JSValue _tls_context_create(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv);
static void _tls_context_finalizer(JSRuntime* runtime, JSValue value);
static JSValue _tls_context_set_certificate(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_tls_context_t* tls = JS_GetOpaque(this_val, _classId);
const char* value = JS_ToCString(context, argv[0]);
tf_tls_context_set_certificate(tls->context, value);
JS_FreeCString(context, value);
return JS_UNDEFINED;
}
static JSValue _tls_context_set_private_key(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_tls_context_t* tls = JS_GetOpaque(this_val, _classId);
const char* value = JS_ToCString(context, argv[0]);
tf_tls_context_set_private_key(tls->context, value);
JS_FreeCString(context, value);
return JS_UNDEFINED;
}
static JSValue _tls_context_add_trusted_certificate(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_tls_context_t* tls = JS_GetOpaque(this_val, _classId);
const char* value = JS_ToCString(context, argv[0]);
tf_tls_context_add_trusted_certificate(tls->context, value);
JS_FreeCString(context, value);
return JS_UNDEFINED;
}
JSValue tf_tls_context_register(JSContext* context)
{
JS_NewClassID(&_classId);
JSClassDef def = {
.class_name = "TlsContext",
.finalizer = _tls_context_finalizer,
};
if (JS_NewClass(JS_GetRuntime(context), _classId, &def) != 0)
{
fprintf(stderr, "Failed to register TlsContext.\n");
}
return JS_NewCFunction2(context, _tls_context_create, "TlsContext", 0, JS_CFUNC_constructor, 0);
}
tf_tls_context_t* tf_tls_context_get(JSValue value)
{
tf_tls_context_t* tls = JS_GetOpaque(value, _classId);
return tls ? tls->context : NULL;
}
int tf_tls_context_get_count()
{
return _count;
}
static JSValue _tls_context_create(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_tls_context_t* tls = tf_malloc(sizeof(tf_tls_context_t));
memset(tls, 0, sizeof(*tls));
++_count;
tls->object = JS_NewObjectClass(context, _classId);
JS_SetOpaque(tls->object, tls);
JS_SetPropertyStr(context, tls->object, "setCertificate", JS_NewCFunction(context, _tls_context_set_certificate, "setCertificate", 1));
JS_SetPropertyStr(context, tls->object, "setPrivateKey", JS_NewCFunction(context, _tls_context_set_private_key, "setPrivateKey", 1));
JS_SetPropertyStr(context, tls->object, "addTrustedCertificate", JS_NewCFunction(context, _tls_context_add_trusted_certificate, "addTrustedCertificate", 1));
tls->context = tf_tls_context_create();
tls->task = tf_task_get(context);
return tls->object;
}
static void _tls_context_finalizer(JSRuntime* runtime, JSValue value)
{
tf_tls_context_t* tls = JS_GetOpaque(value, _classId);
if (tls->context)
{
tf_tls_context_destroy(tls->context);
tls->context = NULL;
}
--_count;
tf_free(tls);
}

View File

@@ -1,37 +0,0 @@
#pragma once
/**
** \defgroup tls_js TLS Interface
** Exposes \ref tls to JS.
** @{
*/
#include "quickjs.h"
/**
** A TLS context instance.
*/
typedef struct _tf_tls_context_t tf_tls_context_t;
/**
** Register TLS script interface.
** @param context The TLS context.
** @return the TlsContext constructor.
*/
JSValue tf_tls_context_register(JSContext* context);
/**
** Get a TLS context instance from its JS object.
** @param value A TlsContext JS object.
** @return The corresponding instance.
*/
tf_tls_context_t* tf_tls_context_get(JSValue value);
/**
** Get the number of active TLS context instances.
** @return The number of TlsContext objects created that have not been
** finalized.
*/
int tf_tls_context_get_count();
/** @} */

View File

@@ -253,66 +253,6 @@ bool tf_util_report_error(JSContext* context, JSValue value)
return is_error;
}
static JSValue _util_parseHttpResponse(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
JSValue result = JS_UNDEFINED;
int status = 0;
int minor_version = 0;
const char* message = NULL;
size_t message_length = 0;
struct phr_header headers[100];
size_t header_count = sizeof(headers) / sizeof(*headers);
int previous_length = 0;
JS_ToInt32(context, &previous_length, argv[1]);
JSValue buffer = JS_UNDEFINED;
size_t length;
uint8_t* array = tf_util_try_get_array_buffer(context, &length, argv[0]);
if (!array)
{
size_t offset;
size_t element_size;
buffer = tf_util_try_get_typed_array_buffer(context, argv[0], &offset, &length, &element_size);
if (!JS_IsException(buffer))
{
array = tf_util_try_get_array_buffer(context, &length, buffer);
}
}
if (array)
{
int parse_result = phr_parse_response((const char*)array, length, &minor_version, &status, &message, &message_length, headers, &header_count, previous_length);
if (parse_result > 0)
{
result = JS_NewObject(context);
JS_SetPropertyStr(context, result, "bytes_parsed", JS_NewInt32(context, parse_result));
JS_SetPropertyStr(context, result, "minor_version", JS_NewInt32(context, minor_version));
JS_SetPropertyStr(context, result, "status", JS_NewInt32(context, status));
JS_SetPropertyStr(context, result, "message", JS_NewStringLen(context, message, message_length));
JSValue header_object = JS_NewObject(context);
for (int i = 0; i < (int)header_count; i++)
{
char name[256];
snprintf(name, sizeof(name), "%.*s", (int)headers[i].name_len, headers[i].name);
JS_SetPropertyStr(context, header_object, name, JS_NewStringLen(context, headers[i].value, headers[i].value_len));
}
JS_SetPropertyStr(context, result, "headers", header_object);
}
else
{
result = JS_NewInt32(context, parse_result);
}
}
else
{
result = JS_ThrowTypeError(context, "Could not convert argument to array.");
}
JS_FreeValue(context, buffer);
return result;
}
static const char* k_kind_name[] = {
[k_kind_bool] = "bool",
[k_kind_int] = "int",
@@ -359,10 +299,6 @@ static const setting_t k_settings[] = {
.type = "integer",
.description = "Blobs older than this will be automatically deleted.",
.default_value = { .kind = k_kind_int, .int_value = TF_IS_MOBILE ? (int)(1.0f * 365 * 24 * 60 * 60) : -1 } },
{ .name = "fetch_hosts",
.type = "string",
.description = "Comma-separated list of host names to which HTTP fetch requests are allowed. None if empty.",
.default_value = { .kind = k_kind_string, .string_value = NULL } },
{ .name = "http_redirect",
.type = "string",
.description = "If connecting by HTTP and HTTPS is configured, Location header prefix (ie, \"http://example.com\")",
@@ -523,7 +459,6 @@ void tf_util_register(JSContext* context)
JS_SetPropertyStr(context, global, "bip39Words", JS_NewCFunction(context, _util_bip39_words, "bip39Words", 1));
JS_SetPropertyStr(context, global, "bip39Bytes", JS_NewCFunction(context, _util_bip39_bytes, "bip39Bytes", 1));
JS_SetPropertyStr(context, global, "print", JS_NewCFunction(context, _util_print, "print", 1));
JS_SetPropertyStr(context, global, "parseHttpResponse", JS_NewCFunction(context, _util_parseHttpResponse, "parseHttpResponse", 2));
JS_SetPropertyStr(context, global, "defaultGlobalSettings", JS_NewCFunction(context, _util_defaultGlobalSettings, "defaultGlobalSettings", 2));
JS_FreeValue(context, global);
}