Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1fdaefe
fix: close p1-p7 security gaps across org membership, auth linking, a…
ludomikula Nov 23, 2026
731662a
test: add an e2e scenario proving two chat sessions exchange messages…
ludomikula Nov 23, 2026
7b8e5c3
fix: pin redis-server and redis-tools to the available 8.12.0 build
ludomikula Nov 23, 2026
e938e9a
fix: close security gaps across org membership, auth, data access and…
ludomikula Nov 24, 2026
a7ea9c9
test: add node-service data source harness and catalogue scenario
ludomikula Nov 24, 2026
cb8aed9
test: add DuckDB node-service data source scenarios
ludomikula Nov 24, 2026
3d1845e
test: add Turso and Slack node-service data source scenarios
ludomikula Nov 24, 2026
c933f91
test: add GitLab and Shopify GraphQL node-service data source scenarios
ludomikula Nov 24, 2026
46b0256
test: add generic OpenAPI node-service data source scenarios
ludomikula Nov 24, 2026
a353234
test: add CouchDB, Jira, Datadog, WooCommerce and Supabase API scenarios
ludomikula Nov 24, 2026
eda7134
test: add Lowcoder, OpenAI, APITemplate, Carbone and UiPath scenarios
ludomikula Nov 24, 2026
a3019f5
test: add DynamoDB and S3 node-service data source scenarios
ludomikula Nov 24, 2026
d90c660
test: add Supabase Storage node-service data source scenarios
ludomikula Nov 24, 2026
84e3c53
test: add an opt-in sidecar mechanism and Firebird node-service scena…
ludomikula Nov 24, 2026
b40740a
test: add an opt-in libSQL server sidecar and Turso scenarios against it
ludomikula Nov 24, 2026
6472758
test: add an opt-in CouchDB server sidecar and CouchDB scenarios agai…
ludomikula Nov 24, 2026
905745f
test: add an opt-in DynamoDB Local sidecar and DynamoDB scenarios aga…
ludomikula Nov 25, 2026
721a61f
test: stop the run script leaking anonymous Docker volumes
ludomikula Nov 25, 2026
b285b2c
test: add an opt-in S3-compatible server sidecar and S3 scenarios aga…
ludomikula Nov 25, 2026
7783e2d
test: number the node-service defect findings in the shared D-series
ludomikula Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 110 additions & 18 deletions client/packages/lowcoder/hocuspocus-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,122 @@
* Hocuspocus awareness on the client side.
*
* Env vars:
* PORT - HTTP/WebSocket port (default 3006)
* HOST - Bind address (default 0.0.0.0)
* HOCUSPOCUS_SECRET - Optional shared secret for token auth
* PORT - HTTP/WebSocket port (default 3006)
* HOST - Bind address (default 0.0.0.0)
* HOCUSPOCUS_SECRET - Optional shared secret for token auth, checked before room authorization
* API_SERVICE_URL - Base URL of the api-service, used to authorize signal_* rooms (default http://localhost:8080)
* LOWCODER_API_SERVICE_URL - Same as API_SERVICE_URL, read if API_SERVICE_URL is unset
*
* A room named signal_<appId>[:<sub>] is authorized by re-checking the connecting
* browser's own cookie against GET <API_SERVICE_URL>/api/applications/<appId>/view -- the same READ rule the app
* editor/viewer itself uses (a public app is open to anonymous visitors, a private app only to a reader). Rooms
* named typeform_*, googleform_*, website_* (the proxy-service bridges) keep today's behaviour: only the shared
* secret, if one is configured, gates them (left open deliberately for now). Any other room name is refused.
*
* Usage: node hocuspocus-server.js
*/

import { Server } from "@hocuspocus/server";
import { pathToFileURL } from "node:url";

const PORT = parseInt(process.env.PORT || "3006", 10);
const HOST = process.env.HOST || "0.0.0.0";
const SECRET = process.env.HOCUSPOCUS_SECRET || "";
const API_SERVICE_URL = process.env.API_SERVICE_URL || process.env.LOWCODER_API_SERVICE_URL || "http://localhost:8080";
const FETCH_TIMEOUT_MS = 5000;

/** A signal_<appId> room's own id, matching SlugUtils.validate exactly -- no numeric length cap. */
const APP_ID_PATTERN = /^[A-Za-z0-9_-]*$/;
const BRIDGE_PREFIXES = ["typeform_", "googleform_", "website_"];
const SIGNAL_PREFIX = "signal_";

function writeJson(response, statusCode, payload) {
response.writeHead(statusCode, { "Content-Type": "application/json" });
response.end(JSON.stringify(payload));
}

/**
* The `Cookie` header of the upgrade request, whatever shape `requestHeaders` has. Different `@hocuspocus/server`
* versions expose it differently: a plain Node `IncomingHttpHeaders` object (property access), confirmed against
* the locally installed 3.4.4; or, NOT VERIFIED locally, a Fetch-API-style `Headers` instance (a `.get` method) in
* the deployed 4.3.0. Support both rather than assume one.
*/
export function cookieOf(requestHeaders) {
if (!requestHeaders) {
return undefined;
}
if (typeof requestHeaders.get === "function") {
return requestHeaders.get("cookie") ?? requestHeaders.get("Cookie") ?? undefined;
}
return requestHeaders.cookie ?? requestHeaders["Cookie"] ?? undefined;
}

/**
* Authorizes a Hocuspocus room by name. `fetchImpl` and `apiServiceUrl` are injectable for tests;
* production calls pass the real `fetch` and `API_SERVICE_URL`.
*/
export async function authorizeDocument({ documentName, cookie, fetchImpl = fetch, apiServiceUrl = API_SERVICE_URL }) {
if (typeof documentName !== "string") {
throw new Error("Unauthorized");
}

if (BRIDGE_PREFIXES.some((prefix) => documentName.startsWith(prefix))) {
return;
}

if (!documentName.startsWith(SIGNAL_PREFIX)) {
throw new Error("Unauthorized");
}

const afterPrefix = documentName.slice(SIGNAL_PREFIX.length);
const colonIndex = afterPrefix.indexOf(":");
const appId = colonIndex === -1 ? afterPrefix : afterPrefix.slice(0, colonIndex);

if (!APP_ID_PATTERN.test(appId)) {
throw new Error("Unauthorized");
}

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const response = await fetchImpl(`${apiServiceUrl}/api/applications/${appId}/view`, {
method: "GET",
headers: cookie ? { Cookie: cookie } : {},
signal: controller.signal,
});
if (!response.ok) {
throw new Error("Unauthorized");
}
const body = await response.json();
if (body?.success !== true) {
throw new Error("Unauthorized");
}
} catch {
throw new Error("Unauthorized");
} finally {
clearTimeout(timeout);
}
}

/**
* The secret check (when `SECRET` is set) runs first, before any room authorization -- a wrong token must refuse
* without ever calling `authorizeDocument` (and so without any fetch). Exported, not only the inline Server hook,
* so the gate order itself is directly testable.
*/
export async function onAuthenticate({ token, documentName, requestHeaders }, secret = SECRET, authorize = authorizeDocument) {
if (secret && token !== secret) {
console.warn(`[hocuspocus] rejected connection for ${documentName}: invalid token`);
throw new Error("Unauthorized");
}

try {
await authorize({ documentName, cookie: cookieOf(requestHeaders) });
} catch (error) {
console.warn(`[hocuspocus] rejected connection for ${documentName}: ${error?.message || "Unauthorized"}`);
throw error;
}
}

const server = new Server({
name: "lowcoder-hocuspocus",
quiet: true,
Expand All @@ -46,6 +144,7 @@ const server = new Server({
host: HOST,
port: PORT,
auth: SECRET ? "enabled" : "disabled",
rooms: "app-read-check",
});
throw null;
}
Expand All @@ -60,16 +159,7 @@ const server = new Server({
}
},

async onAuthenticate({ token, documentName }) {
if (!SECRET) {
return;
}

if (token !== SECRET) {
console.warn(`[hocuspocus] rejected connection for ${documentName}: invalid token`);
throw new Error("Unauthorized");
}
},
onAuthenticate,

async onConnect({ documentName, socketId }) {
console.log(`[hocuspocus] connect socket=${socketId} document=${documentName}`);
Expand All @@ -80,9 +170,11 @@ const server = new Server({
},
});

try {
await server.listen();
} catch (error) {
console.error("[hocuspocus] failed to start", error);
process.exit(1);
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
try {
await server.listen();
} catch (error) {
console.error("[hocuspocus] failed to start", error);
process.exit(1);
}
}
181 changes: 181 additions & 0 deletions client/packages/lowcoder/hocuspocus-server.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Unit tests of hocuspocus-server.js's room authorization. Run with `node --test`.
// Not copied into any image -- this file is test-only.

import test from "node:test";
import assert from "node:assert/strict";
import { authorizeDocument, onAuthenticate, cookieOf } from "./hocuspocus-server.js";

const COOKIE = "lowcoder.sid=abc123";

function fetchReturning(status, body) {
const calls = [];
const impl = async (url, options) => {
calls.push({ url, options });
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
};
};
impl.calls = calls;
return impl;
}

function fetchThrowing(error) {
return async () => {
throw error;
};
}

function fetchNeverCalled() {
return async () => {
throw new Error("fetchImpl must not be called");
};
}

// ----------------------------------------------------------------- authorizeDocument: signal_* rooms

test("signal_<id>: a 200 with success:true is accepted", async () => {
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" });
assert.equal(fetchImpl.calls.length, 1);
assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/app-1/view");
});

test("signal_<id>: a 200 with success:false is refused", async () => {
const fetchImpl = fetchReturning(200, { success: false });
await assert.rejects(
authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }),
/Unauthorized/
);
});

test("signal_<id>: a 401 is refused", async () => {
const fetchImpl = fetchReturning(401, {});
await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

test("signal_<id>: a 403 is refused", async () => {
const fetchImpl = fetchReturning(403, {});
await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

test("signal_<id>: a fetch failure (timeout/network error) is refused", async () => {
const fetchImpl = fetchThrowing(new Error("network error"));
await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

test("signal_<id>: a bad app id is refused before any fetch", async () => {
const fetchImpl = fetchNeverCalled();
await assert.rejects(authorizeDocument({ documentName: "signal_app one!", cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

test("signal_<id>:sub checks <id>, not the sub-room suffix", async () => {
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: "signal_app-1:app-2", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" });
assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/app-1/view");
});

test("the cookie is forwarded and nothing else is sent as a header", async () => {
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl });
assert.deepEqual(fetchImpl.calls[0].options.headers, { Cookie: COOKIE });
});

test("an id containing an underscore is accepted (the SDK-slug case)", async () => {
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: "signal_my_app_slug", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" });
assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/my_app_slug/view");
});

test("a deliberately long id (500+ chars) of only valid characters is accepted -- no numeric length cap", async () => {
const longId = "a".repeat(500) + "-" + "b".repeat(50);
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: `signal_${longId}`, cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" });
assert.equal(fetchImpl.calls[0].url, `http://api/api/applications/${longId}/view`);
});

test("an id containing a character outside [A-Za-z0-9_-] is refused before any fetch, regardless of length", async () => {
const fetchImpl = fetchNeverCalled();
const longInvalidId = "a".repeat(500) + "/evil";
await assert.rejects(authorizeDocument({ documentName: `signal_${longInvalidId}`, cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

test("an empty app id (signal_ alone) is accepted by the regex (matches SlugUtils.validate's *)", async () => {
const fetchImpl = fetchReturning(200, { success: true });
await authorizeDocument({ documentName: "signal_", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" });
assert.equal(fetchImpl.calls[0].url, "http://api/api/applications//view");
});

// ----------------------------------------------------------------- authorizeDocument: other rooms

test("bridge-prefixed rooms (typeform_/googleform_/website_) pass without any fetch", async () => {
const fetchImpl = fetchNeverCalled();
await authorizeDocument({ documentName: "typeform_abc", cookie: COOKIE, fetchImpl });
await authorizeDocument({ documentName: "googleform_abc", cookie: COOKIE, fetchImpl });
await authorizeDocument({ documentName: "website_abc", cookie: COOKIE, fetchImpl });
});

test("an unknown room prefix is refused", async () => {
const fetchImpl = fetchNeverCalled();
await assert.rejects(authorizeDocument({ documentName: "unknown_room", cookie: COOKIE, fetchImpl }), /Unauthorized/);
});

// ----------------------------------------------------------------- onAuthenticate (secret gate + wiring)
// onAuthenticate itself is exported (not only authorizeDocument), with injectable secret/authorize parameters
// for tests; production calls it with one argument, so those parameters default to the module's real SECRET and
// authorizeDocument -- these tests inject different ones to prove the gate order without touching real state.

test("onAuthenticate: a wrong secret token short-circuits before authorizeDocument runs (never calls fetchImpl)", async () => {
const fetchImpl = fetchNeverCalled();
const authorize = (args) => authorizeDocument({ ...args, fetchImpl });

await assert.rejects(
onAuthenticate({ token: "wrong", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize),
/Unauthorized/
);
await assert.rejects(
onAuthenticate({ token: "wrong", documentName: "typeform_abc", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize),
/Unauthorized/
);
});

test("onAuthenticate: a correct token proceeds to authorizeDocument", async () => {
const fetchImpl = fetchReturning(200, { success: true });
const authorize = (args) => authorizeDocument({ ...args, fetchImpl });

await onAuthenticate({ token: "the-secret", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize);

assert.equal(fetchImpl.calls.length, 1);
});

test("onAuthenticate: no secret configured proceeds straight to authorizeDocument", async () => {
const fetchImpl = fetchReturning(200, { success: true });
const authorize = (args) => authorizeDocument({ ...args, fetchImpl });

await onAuthenticate({ token: "anything-or-nothing", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "", authorize);

assert.equal(fetchImpl.calls.length, 1);
});

test("onAuthenticate: a refused authorizeDocument (e.g. a bad app id) still refuses the connection", async () => {
const fetchImpl = fetchNeverCalled();
const authorize = (args) => authorizeDocument({ ...args, fetchImpl });

await assert.rejects(
onAuthenticate({ token: "", documentName: "signal_app one!", requestHeaders: { cookie: COOKIE } }, "", authorize),
/Unauthorized/
);
});

// ----------------------------------------------------------------- requestHeaders shape (plain object vs Headers)

test("cookie extraction: a plain-object requestHeaders (Node IncomingHttpHeaders) works", async () => {
assert.equal(cookieOf({ cookie: COOKIE }), COOKIE);
});

test("cookie extraction: a Fetch-API-style Headers instance (.get method) works", async () => {
const headers = new Headers();
headers.set("cookie", COOKIE);
assert.equal(cookieOf(headers), COOKIE);
});
12 changes: 10 additions & 2 deletions client/packages/lowcoder/src/comps/comps/moduleComp/moduleComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { API_STATUS_CODES } from "constants/apiConstants";
import { AppTypeEnum } from "constants/applicationConstants";
import { GreyTextColor } from "constants/style";
import { ScrollBar, Section, sectionNames } from "lowcoder-design";
import { ReactNode, useEffect, useMemo } from "react";
import { ReactNode, useContext, useEffect, useMemo } from "react";
import styled from "styled-components";
import {
ExternalEditorContext,
Expand Down Expand Up @@ -513,14 +513,22 @@ const ModuleCompWithView = withViewFn(ModuleTmpComp, (comp) => {
const error = comp.children.error.getView();
const scrollbars = comp.children.scrollbars.getView();

// Read the ENCLOSING context before this component's own Provider (below) replaces
// it, so a nested chat controller can reach the outermost, actually READ-checked host app id rather than this
// module's own (moduleComp.tsx's Provider overrides `applicationId` with `appId`, which may not itself be
// directly READ-checked for a viewer who only has READ on the host -- see ExternalEditorContext.ts).
const enclosingContext = useContext(ExternalEditorContext);
const hostApplicationId = enclosingContext.hostApplicationId ?? enclosingContext.applicationId;

const moduleExternalState: ExternalEditorContextState = useMemo(
() => ({
readOnly: true,
hideHeader: true,
applicationId: appId,
hostApplicationId,
appType: AppTypeEnum.Module,
}),
[appId]
[appId, hostApplicationId]
);

useEffect(() => {
Expand Down
Loading
Loading