Skip to content

The open alternative to Salesforce, designed for AI.

Align local logic function runtime with Lambda (#28599)

Félix Malfait00117f64ef1a
diff --git a/.github/actions/yarn-install/action.yaml b/.github/actions/yarn-install/action.yaml
index b516a60f0ef..7913d72a950 100644
--- a/.github/actions/yarn-install/action.yaml
+++ b/.github/actions/yarn-install/action.yaml
@@ -2,7 +2,7 @@ name: Yarn Install
inputs:
node-version:
required: false
- default: '24'
+ default: '26'
runs:
using: 'composite'
diff --git a/.github/oss-scanner/Dockerfile b/.github/oss-scanner/Dockerfile
index e2bfa7202ab..2bf702b5dea 100644
--- a/.github/oss-scanner/Dockerfile
+++ b/.github/oss-scanner/Dockerfile
@@ -1,7 +1,7 @@
# Builds Twenty for Anthropic's OSS Scanner (https://github.com/anthropics/oss-scanner).
# Mirrors .github/workflows/ci-server.yaml: Yarn 4 install, twenty-shared/twenty-emails/twenty-server builds,
# then a local Postgres + Redis initialized and seeded so the server and integration tests run offline.
-FROM node:24-bookworm
+FROM node:26-bookworm
ENV DEBIAN_FRONTEND=noninteractive \
CI=true \
NX_NO_CLOUD=true \
@@ -18,7 +18,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& apt-get update && apt-get install -y --no-install-recommends postgresql-18 \
&& rm -rf /var/lib/apt/lists/*
-RUN corepack enable
+# Node 26 images no longer bundle Corepack.
+RUN npm install -g corepack && corepack enable
# scanner contract: the checkout lives inside the image, at /src
COPY . /src
diff --git a/.github/workflows/publish-npm-packages.yaml b/.github/workflows/publish-npm-packages.yaml
index a82946954b9..568cbe36887 100644
--- a/.github/workflows/publish-npm-packages.yaml
+++ b/.github/workflows/publish-npm-packages.yaml
@@ -132,11 +132,12 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
- node-version: "24"
+ node-version-file: .nvmrc
package-manager-cache: false
- name: Build and inspect packages
run: |
+ npm install -g corepack
corepack enable
yarn install --immutable
projects=$(jq -rn --arg packages "$PACKAGES" \
diff --git a/.nvmrc b/.nvmrc
index ce62013c39a..63f87c20ef9 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-24.22.1
+26.12.1
diff --git a/package.json b/package.json
index 7377b78941b..4bc8a13343f 100644
--- a/package.json
+++ b/package.json
@@ -20,7 +20,7 @@
"verdaccio": "^6.10.7"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
diff --git a/packages/create-twenty-app/package.json b/packages/create-twenty-app/package.json
index 820cca69893..0febe18535a 100644
--- a/packages/create-twenty-app/package.json
+++ b/packages/create-twenty-app/package.json
@@ -36,7 +36,7 @@
"vite": "^8.0.0"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^24.5.0 || ^26.5.1",
"yarn": "^4.0.2"
}
}
diff --git a/packages/twenty-cli/app-template/package.json b/packages/twenty-cli/app-template/package.json
index f5ea2a79cb5..1b27aef049a 100644
--- a/packages/twenty-cli/app-template/package.json
+++ b/packages/twenty-cli/app-template/package.json
@@ -3,7 +3,7 @@
"version": "0.1.0",
"license": "MIT",
"engines": {
- "node": "^24.5.0",
+ "node": "^24.5.0 || ^26.5.1",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
diff --git a/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts b/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts
index 48731734745..5a972102395 100644
--- a/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts
+++ b/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path';
export const writeTestSourceSdk = async ({
appPath,
version = '9.9.9',
- requiredNode = '^24.5.0',
+ requiredNode = '^24.5.0 || ^26.5.1',
hasSourceExports = true,
}: {
appPath: string;
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
index 4373728a39a..7075f6dee16 100644
--- a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
@@ -106,7 +106,7 @@ describe('app init', () => {
expect(await readPackageJson(appDirectory)).toMatchObject({
name: 'my-app',
engines: {
- node: '^24.5.0',
+ node: '^24.5.0 || ^26.5.1',
npm: 'please-use-yarn',
twenty: `>=${semver.major(APP_TEMPLATE_PACKAGE_VERSION)}.${semver.minor(APP_TEMPLATE_PACKAGE_VERSION)}.0`,
yarn: '>=4.0.2',
diff --git a/packages/twenty-client-sdk/package.json b/packages/twenty-client-sdk/package.json
index 6bb8255a9c2..e9de5e0f080 100644
--- a/packages/twenty-client-sdk/package.json
+++ b/packages/twenty-client-sdk/package.json
@@ -70,7 +70,7 @@
"vitest": "^4.1.12"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^24.5.0 || ^26.5.1",
"yarn": "^4.0.2"
}
}
diff --git a/packages/twenty-docker/twenty/Dockerfile b/packages/twenty-docker/twenty/Dockerfile
index 9f20c77e8ee..e54dd3e8cb8 100644
--- a/packages/twenty-docker/twenty/Dockerfile
+++ b/packages/twenty-docker/twenty/Dockerfile
@@ -2,7 +2,12 @@
# Base image
# ===========================================================================
-FROM node:24.22.1-alpine3.23@sha256:0468540aa58203ff9e40c2aab3907c52644ab818af6176b1c70a026137dc92a2 AS node-base
+FROM node:26.12.1-alpine3.23@sha256:bc2b334006f15c7167bbeb2f08f28c2df883f7594a0470e04454ebe7560cfe68 AS node-base
+
+# Node 26 images no longer bundle Yarn; run the release pinned in .yarnrc.yml.
+RUN printf '%s\n' '#!/bin/sh' 'exec node "/app/$(sed -n "s/^yarnPath: //p" /app/.yarnrc.yml)" "$@"' \
+ > /usr/local/bin/yarn && \
+ chmod +x /usr/local/bin/yarn
# ===========================================================================
# Dependency stages
@@ -143,7 +148,7 @@ LABEL org.opencontainers.image.description="Twenty server image (no frontend)."
# Remove unused, unpatchable components the scanner flags (none are executed at
# runtime, and none can be fixed by upgrading our deps or Node):
-# - the bundled npm CLI: the app uses yarn via corepack and never invokes npm,
+# - the bundled npm CLI: the app uses yarn (see node-base) and never invokes npm,
# and npm's bundled ip-address has no patched release;
# - example/ apps vendored inside dependencies, e.g. passport-microsoft's
# example/login ships a package-lock.json for an old Express demo
@@ -151,11 +156,6 @@ LABEL org.opencontainers.image.description="Twenty server image (no frontend)."
# - the Node dev headers: only node-gyp needs them and native addons are
# compiled in the build stages; their vendored openssl/opensslv.h is what
# scanners fingerprint whenever OpenSSL patches ahead of Node releases.
-# The pinned node:24.22.1-alpine base carries the October 2026 security fixes.
-# Do not pin below 24.18.0: 24.17.0's http.Agent keep-alive regression
-# (nodejs/node#64004) flooded prod with false "Premature close" fetch failures.
-# Keep the base current when Node ships 24.x security releases; the scanner
-# flags the statically-linked node binary itself.
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx \
/usr/local/include/node && \
find /app/node_modules -type d -name example -prune -exec rm -rf {} +
diff --git a/packages/twenty-docs/developers/contribute/capabilities/local-setup.mdx b/packages/twenty-docs/developers/contribute/capabilities/local-setup.mdx
index c66c0f758b6..e4db285c179 100644
--- a/packages/twenty-docs/developers/contribute/capabilities/local-setup.mdx
+++ b/packages/twenty-docs/developers/contribute/capabilities/local-setup.mdx
@@ -12,13 +12,12 @@ import { PageBanner } from "/snippets/page-banner.mdx"
Before you can install and use Twenty, make sure you install the following on your computer:
- [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
-- [Node v24.5.0](https://nodejs.org/en/download)
+- [Node v26](https://nodejs.org/en/download)
- [yarn v4](https://yarnpkg.com/getting-started/install)
- [nvm](https://github.com/nvm-sh/nvm/blob/master/README.md)
<Warning>
-`npm` won't work, you should use `yarn` instead. Yarn is now shipped with Node.js, so you don't need to install it separately.
-You only have to run `corepack enable` to enable Yarn if you haven't done it yet.
+`npm` won't work, you should use `yarn` instead. Node 26 no longer ships Corepack, so install it once with `npm install -g corepack`, then run `corepack enable` to enable Yarn.
</Warning>
</Tab>
@@ -64,6 +63,7 @@ nvm install # installs recommended node version
nvm use # use recommended node version
+npm install -g corepack
corepack enable
```
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
index 718edae9c7b..aef02945cec 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
@@ -8,7 +8,7 @@ import { CardTitle } from "/snippets/card-title.mdx"
## Before you start
-Use Node.js 24.5+ and Yarn 4. Install the CLI globally; your app keeps its own SDK dependencies.
+Use Node.js 24.5+ or 26.5+ and Yarn 4 (via Corepack: `corepack enable`; on Node 26, install it first with `npm install -g corepack`). Install the CLI globally; your app keeps its own SDK dependencies.
<Note>
Building Twenty apps is officially supported on Unix systems (macOS and Linux) only. On Windows, work inside WSL 2.
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
index 9e37d260919..0c53b42837c 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
@@ -8,8 +8,8 @@ import { PageBanner } from "/snippets/page-banner.mdx"
## Common issues
- **Local server errors**, check your Docker or repository development environment. The standalone CLI does not manage containers.
-- **Wrong Node version** — Need 24.5+ (`engines.node: ^24.5.0`). Check with `node -v`.
-- **Yarn 4 missing** — Run `corepack enable`.
+- **Wrong Node version** — Need 24.5+ or 26.5+ (`engines.node: ^24.5.0 || ^26.5.1`). Check with `node -v`.
+- **Yarn 4 missing** — Run `corepack enable` (on Node 26, first `npm install -g corepack`).
- **Dependencies broken** — `rm -rf node_modules && yarn install`.
- **Empty `yarn.lock`** — The build fails with "yarn.lock is empty" when the lockfile exists but has no content; run `yarn install` to regenerate it.
- **`twenty-sdk` errors after upgrading to v2.8.0** — It moved from `dependencies` to `devDependencies` in v2.8.0. See [Project Structure → Dependencies](/developers/extend/apps/getting-started/project-structure#dependencies).
diff --git a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
index ce31c9ae3fb..68fb5d97b6b 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
@@ -7,7 +7,7 @@ import { PageBanner } from "/snippets/page-banner.mdx"
## Running the CLI
-The `twenty` CLI connects to Twenty workspaces from your terminal. Use it to inspect metadata, read records, send API requests, and create, sync and debug apps. It needs **Node.js 24.5 or later**.
+The `twenty` CLI connects to Twenty workspaces from your terminal. Use it to inspect metadata, read records, send API requests, and create, sync and debug apps. It needs **Node.js 24.5+ or 26.5+**.
Run any command through `npx`, without installing anything:
diff --git a/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx b/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
index 21472f3ce75..f20574b44e4 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
@@ -104,7 +104,7 @@ If your app uses a feature introduced in a specific Twenty server version (for e
"name": "twenty-my-app",
"version": "1.0.0",
"engines": {
- "node": "^24.5.0",
+ "node": "^24.5.0 || ^26.5.1",
"twenty": ">=2.3.0"
}
}
diff --git a/packages/twenty-emails/package.json b/packages/twenty-emails/package.json
index c4af8cc4c53..4b22c0e4c5f 100644
--- a/packages/twenty-emails/package.json
+++ b/packages/twenty-emails/package.json
@@ -39,7 +39,7 @@
}
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"npm": "please-use-yarn",
"yarn": "^4.0.2"
}
diff --git a/packages/twenty-front-component-renderer/package.json b/packages/twenty-front-component-renderer/package.json
index 913097802ae..b3a0b8fede0 100644
--- a/packages/twenty-front-component-renderer/package.json
+++ b/packages/twenty-front-component-renderer/package.json
@@ -58,7 +58,7 @@
"twenty-ui": "workspace:*"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"yarn": "^4.0.2"
}
}
diff --git a/packages/twenty-front/package.json b/packages/twenty-front/package.json
index 6a475891718..b325534ac8b 100644
--- a/packages/twenty-front/package.json
+++ b/packages/twenty-front/package.json
@@ -9,7 +9,7 @@
"tsup": "npx tsup"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"npm": "please-use-yarn",
"yarn": "^4.0.2"
},
diff --git a/packages/twenty-sdk/package.json b/packages/twenty-sdk/package.json
index 20988c2d5c4..bc0093f23f7 100644
--- a/packages/twenty-sdk/package.json
+++ b/packages/twenty-sdk/package.json
@@ -86,7 +86,7 @@
"vite-plugin-dts": "^4.5.4"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^24.5.0 || ^26.5.1",
"yarn": "^4.0.2",
"twenty": ">=2.49.0"
},
diff --git a/packages/twenty-server/package.json b/packages/twenty-server/package.json
index 390caac2530..90dca38d954 100644
--- a/packages/twenty-server/package.json
+++ b/packages/twenty-server/package.json
@@ -234,7 +234,7 @@
"twenty-shared": "workspace:*"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"npm": "please-use-yarn",
"yarn": "^4.0.2"
}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-executor-tmpdir-folder.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-executor-tmpdir-folder.ts
index 728e8177e60..cd63f2bd390 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-executor-tmpdir-folder.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-executor-tmpdir-folder.ts
@@ -1,7 +1,17 @@
+import { realpathSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
+// Resolved because the local driver's Node permission flags only match real paths.
+const resolveTemporaryDirectory = (): string => {
+ try {
+ return realpathSync(tmpdir());
+ } catch {
+ return tmpdir();
+ }
+};
+
export const LOGIC_FUNCTION_EXECUTOR_TMPDIR_FOLDER = join(
- tmpdir(),
+ resolveTemporaryDirectory(),
'logic-function-executor-tmpdir',
);
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
index 2ab284d4006..43ec77ed4c9 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
@@ -202,6 +202,9 @@ export class LocalDriver implements LogicFunctionDriver {
const { ok, result, errorType, error, stack, stdout, stderr } =
await this.childProcessRunner.runChildWithEnv({
runnerPath,
+ executionDirectory: sourceTemporaryDir,
+ flatApplication,
+ applicationUniversalIdentifier,
env: env ?? {},
payload,
context,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/constants/local-driver.constant.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/constants/local-driver.constant.ts
index 80e8e39409b..e2aaab25aa9 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/constants/local-driver.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/constants/local-driver.constant.ts
@@ -10,3 +10,25 @@ export const PREBUILT_CHECKSUM_FILE_NAME = 'prebuilt-bundle.checksum';
export const PREBUILT_INSTALL_LOCK_TTL_MS = 180_000;
export const PREBUILT_INSTALL_LOCK_RETRY_MS = 1_000;
export const PREBUILT_INSTALL_LOCK_MAX_RETRIES = 180;
+
+export const LOCAL_CHILD_PROCESS_INHERITED_ENV_VARIABLE_NAMES = [
+ 'PATH',
+ 'HOME',
+ 'LANG',
+ 'LC_ALL',
+ 'LC_CTYPE',
+ 'TZ',
+ 'NODE_ENV',
+ 'NODE_EXTRA_CA_CERTS',
+ 'NODE_USE_SYSTEM_CA',
+ 'NODE_USE_ENV_PROXY',
+ 'NODE_TLS_REJECT_UNAUTHORIZED',
+ 'SSL_CERT_FILE',
+ 'SSL_CERT_DIR',
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'NO_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ 'no_proxy',
+] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
index 18dedbcc64d..89f82a3f6bd 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
@@ -5,6 +5,8 @@ import { join } from 'path';
import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { buildLocalChildProcessEnv } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-env.util';
+import { buildLocalChildProcessNodeFlags } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-node-flags.util';
import { getLocalDepsLayerPath } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/get-local-deps-layer-path.util';
import { getLocalSdkLayerPath } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/get-local-sdk-layer-path.util';
import { HANDLER_NAME_REGEX } from 'src/engine/metadata-modules/logic-function/constants/handler.contant';
@@ -20,17 +22,12 @@ export class LocalChildProcessRunnerService {
flatApplication: FlatApplication;
applicationUniversalIdentifier: string;
}): Promise<void> {
- const depsNodeModules = join(
- getLocalDepsLayerPath(flatApplication),
- 'node_modules',
- );
- const sdkNodeModules = join(
- getLocalSdkLayerPath({
- workspaceId: flatApplication.workspaceId,
- applicationUniversalIdentifier,
- }),
- 'node_modules',
- );
+ const { depsLayerDirectory, sdkLayerDirectory } = this.getLayerDirectories({
+ flatApplication,
+ applicationUniversalIdentifier,
+ });
+ const depsNodeModules = join(depsLayerDirectory, 'node_modules');
+ const sdkNodeModules = join(sdkLayerDirectory, 'node_modules');
const execNodeModules = join(sourceTemporaryDir, 'node_modules');
await fs.mkdir(execNodeModules, { recursive: true });
@@ -144,14 +141,52 @@ export class LocalChildProcessRunnerService {
return runnerPath;
}
- runChildWithEnv(options: {
+ async runChildWithEnv(options: {
runnerPath: string;
+ executionDirectory: string;
+ flatApplication: FlatApplication;
+ applicationUniversalIdentifier: string;
env: Record<string, string>;
payload: unknown;
context: LogicFunctionExecutionContext;
timeoutMs: number;
}) {
- const { runnerPath, env, payload, context, timeoutMs } = options;
+ const {
+ runnerPath,
+ executionDirectory,
+ flatApplication,
+ applicationUniversalIdentifier,
+ env,
+ payload,
+ context,
+ timeoutMs,
+ } = options;
+
+ const temporaryDirectory = join(executionDirectory, 'tmp');
+
+ await fs.mkdir(temporaryDirectory, { recursive: true });
+
+ const nodeFlags = buildLocalChildProcessNodeFlags({
+ readableDirectories: [
+ executionDirectory,
+ ...Object.values(
+ this.getLayerDirectories({
+ flatApplication,
+ applicationUniversalIdentifier,
+ }),
+ ),
+ ],
+ writableDirectory: temporaryDirectory,
+ // Node 25+ denies network access under --permission unless --allow-net is passed.
+ shouldAllowNetwork:
+ process.allowedNodeEnvironmentFlags.has('--allow-net'),
+ });
+
+ const childEnv = buildLocalChildProcessEnv({
+ hostEnv: process.env,
+ functionEnv: env,
+ temporaryDirectory,
+ });
return new Promise<{
ok: boolean;
@@ -162,12 +197,9 @@ export class LocalChildProcessRunnerService {
stdout: string;
stderr: string;
}>((resolve) => {
- // Strip NODE_OPTIONS to prevent tsx loader from being inherited
- const { NODE_OPTIONS: _n1, ...cleanProcessEnv } = process.env;
- const { NODE_OPTIONS: _n2, ...cleanUserEnv } = env;
-
- const child = spawn(process.execPath, [runnerPath], {
- env: { ...cleanProcessEnv, ...cleanUserEnv },
+ const child = spawn(process.execPath, [...nodeFlags, runnerPath], {
+ cwd: executionDirectory,
+ env: childEnv,
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
});
@@ -235,4 +267,20 @@ export class LocalChildProcessRunnerService {
child.on('close', () => clearTimeout(t));
});
}
+
+ private getLayerDirectories({
+ flatApplication,
+ applicationUniversalIdentifier,
+ }: {
+ flatApplication: FlatApplication;
+ applicationUniversalIdentifier: string;
+ }) {
+ return {
+ depsLayerDirectory: getLocalDepsLayerPath(flatApplication),
+ sdkLayerDirectory: getLocalSdkLayerPath({
+ workspaceId: flatApplication.workspaceId,
+ applicationUniversalIdentifier,
+ }),
+ };
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-env.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-env.util.spec.ts
new file mode 100644
index 00000000000..648f0f8a605
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-env.util.spec.ts
@@ -0,0 +1,50 @@
+import { buildLocalChildProcessEnv } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-env.util';
+
+describe('buildLocalChildProcessEnv', () => {
+ it('keeps runtime settings from the host and drops everything else', () => {
+ expect(
+ buildLocalChildProcessEnv({
+ hostEnv: {
+ PATH: '/usr/bin',
+ TZ: 'UTC',
+ NODE_EXTRA_CA_CERTS: '/certs/ca.pem',
+ HTTPS_PROXY: 'http://proxy:3128',
+ APP_SECRET: 'app-secret',
+ PG_DATABASE_URL: 'postgres://user:password@db:5432/default',
+ },
+ functionEnv: {},
+ temporaryDirectory: '/execution/tmp',
+ }),
+ ).toEqual({
+ PATH: '/usr/bin',
+ TZ: 'UTC',
+ NODE_EXTRA_CA_CERTS: '/certs/ca.pem',
+ HTTPS_PROXY: 'http://proxy:3128',
+ TMPDIR: '/execution/tmp',
+ });
+ });
+
+ it('lets function variables override host settings', () => {
+ expect(
+ buildLocalChildProcessEnv({
+ hostEnv: { TZ: 'UTC' },
+ functionEnv: { TZ: 'Europe/Paris', TWENTY_API_URL: 'http://api' },
+ temporaryDirectory: '/execution/tmp',
+ }),
+ ).toEqual({
+ TZ: 'Europe/Paris',
+ TWENTY_API_URL: 'http://api',
+ TMPDIR: '/execution/tmp',
+ });
+ });
+
+ it('ignores NODE_OPTIONS and TMPDIR from function variables', () => {
+ expect(
+ buildLocalChildProcessEnv({
+ hostEnv: { NODE_OPTIONS: '--import tsx' },
+ functionEnv: { NODE_OPTIONS: '--inspect', TMPDIR: '/tmp' },
+ temporaryDirectory: '/execution/tmp',
+ }),
+ ).toEqual({ TMPDIR: '/execution/tmp' });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-node-flags.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-node-flags.util.spec.ts
new file mode 100644
index 00000000000..cbaa0779635
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/__tests__/build-local-child-process-node-flags.util.spec.ts
@@ -0,0 +1,31 @@
+import { buildLocalChildProcessNodeFlags } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-node-flags.util';
+
+describe('buildLocalChildProcessNodeFlags', () => {
+ it('grants read access to each directory and write access to the temporary directory only', () => {
+ expect(
+ buildLocalChildProcessNodeFlags({
+ readableDirectories: ['/execution', '/layers/deps', '/layers/sdk'],
+ writableDirectory: '/execution/tmp',
+ shouldAllowNetwork: false,
+ }),
+ ).toEqual([
+ '--permission',
+ '--allow-addons',
+ '--disable-warning=SecurityWarning',
+ '--allow-fs-read=/execution',
+ '--allow-fs-read=/layers/deps',
+ '--allow-fs-read=/layers/sdk',
+ '--allow-fs-write=/execution/tmp',
+ ]);
+ });
+
+ it('keeps network access when requested', () => {
+ expect(
+ buildLocalChildProcessNodeFlags({
+ readableDirectories: ['/execution'],
+ writableDirectory: '/execution/tmp',
+ shouldAllowNetwork: true,
+ }),
+ ).toContain('--allow-net');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-env.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-env.util.ts
new file mode 100644
index 00000000000..39b2c17351f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-env.util.ts
@@ -0,0 +1,33 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { LOCAL_CHILD_PROCESS_INHERITED_ENV_VARIABLE_NAMES } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/constants/local-driver.constant';
+
+export const buildLocalChildProcessEnv = ({
+ hostEnv,
+ functionEnv,
+ temporaryDirectory,
+}: {
+ hostEnv: NodeJS.ProcessEnv;
+ functionEnv: Record<string, string>;
+ temporaryDirectory: string;
+}): Record<string, string> => {
+ const inheritedEnv: Record<string, string> = {};
+
+ for (const name of LOCAL_CHILD_PROCESS_INHERITED_ENV_VARIABLE_NAMES) {
+ const value = hostEnv[name];
+
+ if (isDefined(value)) {
+ inheritedEnv[name] = value;
+ }
+ }
+
+ // NODE_OPTIONS could load the server's tsx loader into the handler process.
+ const { NODE_OPTIONS: _nodeOptions, ...functionEnvWithoutNodeOptions } =
+ functionEnv;
+
+ return {
+ ...inheritedEnv,
+ ...functionEnvWithoutNodeOptions,
+ TMPDIR: temporaryDirectory,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-node-flags.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-node-flags.util.ts
new file mode 100644
index 00000000000..bab93522bde
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/utils/build-local-child-process-node-flags.util.ts
@@ -0,0 +1,21 @@
+export const buildLocalChildProcessNodeFlags = ({
+ readableDirectories,
+ writableDirectory,
+ shouldAllowNetwork,
+}: {
+ readableDirectories: string[];
+ writableDirectory: string;
+ shouldAllowNetwork: boolean;
+}): string[] => [
+ '--permission',
+ // Published apps ship prebuilt native addons (e.g. sharp); addons are not covered by the permission model.
+ '--allow-addons',
+ '--disable-warning=SecurityWarning',
+ ...(shouldAllowNetwork
+ ? ['--allow-net', '--disable-warning=ExperimentalWarning']
+ : []),
+ ...readableDirectories.map(
+ (readableDirectory) => `--allow-fs-read=${readableDirectory}`,
+ ),
+ `--allow-fs-write=${writableDirectory}`,
+];
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts
index 21129996fff..a1628d0842f 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts
@@ -1,7 +1,3 @@
-import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-
import { randomUUID } from 'crypto';
import gql from 'graphql-tag';
@@ -19,6 +15,8 @@ import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/m
import { expectEventually } from 'test/integration/utils/expect-eventually.util';
import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { type MarkerServer } from 'test/integration/types/marker-server.type';
+import { startMarkerServer } from 'test/integration/utils/start-marker-server.util';
import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
import { isDefined } from 'twenty-shared/utils';
import { v4 as uuidv4 } from 'uuid';
@@ -27,28 +25,22 @@ import { WORKSPACE_CUSTOM_APPLICATION_NAME } from 'src/engine/core-modules/appli
import { AUTH_PRINCIPAL_REFUSED_MESSAGE } from 'src/engine/guards/constants/auth-principal-refused-message.constant';
import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
-const MARKER_DIRECTORY = join(tmpdir(), `enqueue-job-${uuidv4()}`);
-
-const TARGET_SOURCE_CODE = `import { writeFileSync } from 'node:fs';
+let markerServer: MarkerServer;
-export const main = async (params: { markerPath: string }): Promise<object> => {
- writeFileSync(params.markerPath, 'ran', 'utf-8');
+const TARGET_SOURCE_CODE = `export const main = async (params: { markerUrl: string }): Promise<object> => {
+ await fetch(params.markerUrl, { method: 'POST', body: 'ran' });
return { ok: true };
};`;
-const APPENDING_TARGET_SOURCE_CODE = `import { appendFileSync } from 'node:fs';
-
-export const main = async (params: { markerPath: string }): Promise<object> => {
- appendFileSync(params.markerPath, 'ran\\n', 'utf-8');
+const APPENDING_TARGET_SOURCE_CODE = `export const main = async (params: { markerUrl: string }): Promise<object> => {
+ await fetch(params.markerUrl, { method: 'POST', body: 'ran\\n' });
return { ok: true };
};`;
-const RETRYABLE_TARGET_SOURCE_CODE = `import { appendFileSync } from 'node:fs';
-
-type RetryableTargetParams = {
- markerPath: string;
+const RETRYABLE_TARGET_SOURCE_CODE = `type RetryableTargetParams = {
+ markerUrl: string;
shouldRetry: boolean;
};
@@ -61,11 +53,10 @@ export const main = async (
params: RetryableTargetParams,
context: RetryContext,
): Promise<object> => {
- appendFileSync(
- params.markerPath,
- context.retryCount + '/' + context.maxRetries + '\\n',
- 'utf-8',
- );
+ await fetch(params.markerUrl, {
+ method: 'POST',
+ body: context.retryCount + '/' + context.maxRetries + '\\n',
+ });
if (params.shouldRetry) {
const retryableError = new Error('Dependency is temporarily unavailable');
@@ -183,7 +174,7 @@ describe('enqueueJob (e2e)', () => {
};
beforeAll(async () => {
- mkdirSync(MARKER_DIRECTORY, { recursive: true });
+ markerServer = await startMarkerServer();
const { data } = await findManyApplications({ expectToFail: false });
@@ -265,7 +256,7 @@ describe('enqueueJob (e2e)', () => {
input: {
id: retryableLogicFunctionId,
payload: {
- markerPath: join(MARKER_DIRECTORY, 'retryable-build.txt'),
+ markerUrl: markerServer.markerUrl('retryable-build'),
shouldRetry: false,
},
},
@@ -278,7 +269,7 @@ describe('enqueueJob (e2e)', () => {
input: {
id: appendingLogicFunctionId,
payload: {
- markerPath: join(MARKER_DIRECTORY, 'appending-build.txt'),
+ markerUrl: markerServer.markerUrl('appending-build'),
},
},
expectToFail: false,
@@ -310,7 +301,7 @@ describe('enqueueJob (e2e)', () => {
await deleteUser({ accessToken: otherWorkspaceUserAccessToken });
}
- rmSync(MARKER_DIRECTORY, { recursive: true, force: true });
+ await markerServer.close();
});
it('rejects requests that do not carry an APPLICATION_ACCESS token', async () => {
@@ -327,7 +318,7 @@ describe('enqueueJob (e2e)', () => {
});
it('enqueues a logic function owned by the calling application and the worker runs it', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'enqueued.txt');
+ const markerUrl = markerServer.markerUrl('enqueued');
await updateLogicFunctionSource({
input: {
@@ -340,7 +331,7 @@ describe('enqueueJob (e2e)', () => {
const { data: buildData } = await executeLogicFunction({
input: {
id: logicFunctionId,
- payload: { markerPath: join(MARKER_DIRECTORY, 'build.txt') },
+ payload: { markerUrl: markerServer.markerUrl('build') },
},
expectToFail: false,
});
@@ -351,7 +342,7 @@ describe('enqueueJob (e2e)', () => {
{
query: ENQUEUE_JOB,
variables: {
- input: { logicFunctionUniversalIdentifier, payload: { markerPath } },
+ input: { logicFunctionUniversalIdentifier, payload: { markerUrl } },
},
},
customApplicationToken,
@@ -367,12 +358,12 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
await expectEventually(() => {
- expect(existsSync(markerPath)).toBe(true);
+ expect(markerServer.hasMarker(markerUrl)).toBe(true);
});
});
it('caps application-requested retries independently from the overall queue budget', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'application-retry-cap.txt');
+ const markerUrl = markerServer.markerUrl('application-retry-cap');
const response = await makeMetadataApiRequest(
{
@@ -381,7 +372,7 @@ describe('enqueueJob (e2e)', () => {
input: {
logicFunctionUniversalIdentifier:
retryableLogicFunctionUniversalIdentifier,
- payload: { markerPath, shouldRetry: true },
+ payload: { markerUrl, shouldRetry: true },
retryLimit: 10,
},
},
@@ -394,7 +385,7 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
- expect(readFileSync(markerPath, 'utf-8').trim().split('\n')).toEqual([
+ expect(markerServer.readMarker(markerUrl).trim().split('\n')).toEqual([
'0/3',
'1/3',
'2/3',
@@ -403,7 +394,7 @@ describe('enqueueJob (e2e)', () => {
}, 60_000);
it('uses a smaller overall queue budget as the application retry maximum', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'queue-retry-cap.txt');
+ const markerUrl = markerServer.markerUrl('queue-retry-cap');
const response = await makeMetadataApiRequest(
{
@@ -412,7 +403,7 @@ describe('enqueueJob (e2e)', () => {
input: {
logicFunctionUniversalIdentifier:
retryableLogicFunctionUniversalIdentifier,
- payload: { markerPath, shouldRetry: true },
+ payload: { markerUrl, shouldRetry: true },
retryLimit: 1,
},
},
@@ -425,7 +416,7 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
- expect(readFileSync(markerPath, 'utf-8').trim().split('\n')).toEqual([
+ expect(markerServer.readMarker(markerUrl).trim().split('\n')).toEqual([
'0/1',
'1/1',
]);
@@ -462,9 +453,9 @@ describe('enqueueJob (e2e)', () => {
});
it('enqueues a batch of payloads in a single call and the worker runs them all', async () => {
- const markerPaths = [
- join(MARKER_DIRECTORY, 'batch-0.txt'),
- join(MARKER_DIRECTORY, 'batch-1.txt'),
+ const markerUrls = [
+ markerServer.markerUrl('batch-0'),
+ markerServer.markerUrl('batch-1'),
];
const response = await makeMetadataApiRequest(
@@ -473,7 +464,7 @@ describe('enqueueJob (e2e)', () => {
variables: {
input: {
logicFunctionUniversalIdentifier,
- payloads: markerPaths.map((markerPath) => ({ markerPath })),
+ payloads: markerUrls.map((markerUrl) => ({ markerUrl })),
},
},
},
@@ -484,15 +475,15 @@ describe('enqueueJob (e2e)', () => {
expect(response.body.data.enqueueJobs).toEqual({
enqueued: true,
logicFunctionUniversalIdentifier,
- enqueuedJobsCount: markerPaths.length,
- jobIds: markerPaths.map(() => expect.any(String)),
+ enqueuedJobsCount: markerUrls.length,
+ jobIds: markerUrls.map(() => expect.any(String)),
});
await waitForAllJobsToFinish();
await expectEventually(() => {
- for (const markerPath of markerPaths) {
- expect(existsSync(markerPath)).toBe(true);
+ for (const markerUrl of markerUrls) {
+ expect(markerServer.hasMarker(markerUrl)).toBe(true);
}
});
});
@@ -531,7 +522,7 @@ describe('enqueueJob (e2e)', () => {
});
it('reports a caller-supplied job id as completed once the worker ran it', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'job-status.txt');
+ const markerUrl = markerServer.markerUrl('job-status');
const jobId = `job-status-${uuidv4()}`;
const enqueueResponse = await makeMetadataApiRequest(
@@ -540,7 +531,7 @@ describe('enqueueJob (e2e)', () => {
variables: {
input: {
logicFunctionUniversalIdentifier,
- jobs: [{ payload: { markerPath }, jobId }],
+ jobs: [{ payload: { markerUrl }, jobId }],
},
},
},
@@ -576,13 +567,13 @@ describe('enqueueJob (e2e)', () => {
});
it('does not run a caller-supplied job id a second time', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'idempotent.txt');
+ const markerUrl = markerServer.markerUrl('idempotent');
const jobId = `idempotent-${uuidv4()}`;
const variables = {
input: {
logicFunctionUniversalIdentifier:
appendingLogicFunctionUniversalIdentifier,
- jobs: [{ payload: { markerPath }, jobId }],
+ jobs: [{ payload: { markerUrl }, jobId }],
},
};
@@ -597,7 +588,7 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
await expectEventually(() => {
- expect(existsSync(markerPath)).toBe(true);
+ expect(markerServer.hasMarker(markerUrl)).toBe(true);
});
const secondResponse = await makeMetadataApiRequest(
@@ -610,13 +601,13 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
- expect(readFileSync(markerPath, 'utf-8').trim().split('\n')).toEqual([
+ expect(markerServer.readMarker(markerUrl).trim().split('\n')).toEqual([
'ran',
]);
}, 60_000);
it('does not expose a job to another workspace', async () => {
- const markerPath = join(MARKER_DIRECTORY, 'cross-workspace.txt');
+ const markerUrl = markerServer.markerUrl('cross-workspace');
const jobId = `cross-workspace-${uuidv4()}`;
const enqueueResponse = await makeMetadataApiRequest(
@@ -625,7 +616,7 @@ describe('enqueueJob (e2e)', () => {
variables: {
input: {
logicFunctionUniversalIdentifier,
- jobs: [{ payload: { markerPath }, jobId }],
+ jobs: [{ payload: { markerUrl }, jobId }],
},
},
},
@@ -637,7 +628,7 @@ describe('enqueueJob (e2e)', () => {
await waitForAllJobsToFinish();
await expectEventually(() => {
- expect(existsSync(markerPath)).toBe(true);
+ expect(markerServer.hasMarker(markerUrl)).toBe(true);
});
const ownWorkspaceResponse = await makeMetadataApiRequest(
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts
index 1ab6416c5fb..7765e995d8b 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts
@@ -1,7 +1,4 @@
import { createHash, createHmac } from 'crypto';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
import request from 'supertest';
import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
@@ -11,6 +8,8 @@ import { syncApplication } from 'test/integration/metadata/suites/application/ut
import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
import { generateTransientTokenResponse } from 'test/integration/utils/generate-transient-token.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type MarkerServer } from 'test/integration/types/marker-server.type';
+import { startMarkerServer } from 'test/integration/utils/start-marker-server.util';
import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
import { type Manifest } from 'twenty-shared/application';
import { assertIsDefinedOrThrow } from 'twenty-shared/utils';
@@ -52,12 +51,12 @@ export const handler = ({ httpMethod, headers, body, rawBody }) => {
describe('app connection custom flow', () => {
let provider: ConnectionProviderEntity;
let logicFunctionManifests: Manifest['logicFunctions'];
- let fixtureDirectory: string;
- let onConnectExecutionsPath: string;
+ let markerServer: MarkerServer;
+ let onConnectExecutionsUrl: string;
const readOnConnectExecutions = (): string[] =>
- existsSync(onConnectExecutionsPath)
- ? readFileSync(onConnectExecutionsPath, 'utf8').trim().split('\n')
+ markerServer.hasMarker(onConnectExecutionsUrl)
+ ? markerServer.readMarker(onConnectExecutionsUrl).trim().split('\n')
: [];
const readAccounts = (): Promise<ConnectedAccountEntity[]> =>
@@ -129,8 +128,8 @@ describe('app connection custom flow', () => {
};
beforeAll(async () => {
- fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-connection-custom-'));
- onConnectExecutionsPath = join(fixtureDirectory, 'on-connect-executions');
+ markerServer = await startMarkerServer();
+ onConnectExecutionsUrl = markerServer.markerUrl('on-connect-executions');
await setupApplicationForSync({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
@@ -154,9 +153,8 @@ describe('app connection custom flow', () => {
{
universalIdentifier: ON_CONNECT_IDENTIFIER,
name: 'on-connect',
- source: `import { appendFileSync } from 'node:fs';
-export const handler = ({ connectedAccountId }) => {
- appendFileSync(${JSON.stringify(onConnectExecutionsPath)}, connectedAccountId + '\\n');
+ source: `export const handler = async ({ connectedAccountId }) => {
+ await fetch(${JSON.stringify(onConnectExecutionsUrl)}, { method: 'POST', body: connectedAccountId + '\\n' });
};`,
},
];
@@ -224,7 +222,7 @@ export const handler = ({ connectedAccountId }) => {
}, 120000);
beforeEach(() => {
- rmSync(onConnectExecutionsPath, { force: true });
+ markerServer.clearMarker(onConnectExecutionsUrl);
});
afterEach(async () => {
@@ -238,7 +236,7 @@ export const handler = ({ connectedAccountId }) => {
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
});
- rmSync(fixtureDirectory, { recursive: true, force: true });
+ await markerServer.close();
});
it('stores the provider and sends the member to the URL the authorize function returns', async () => {
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
index d5fbaa0e93e..46be1fef77b 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
@@ -1,7 +1,4 @@
import { createHash } from 'crypto';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
import { http, HttpResponse } from 'msw';
import request from 'supertest';
@@ -13,6 +10,8 @@ import { uploadApplicationFile } from 'test/integration/metadata/suites/applicat
import { generateTransientTokenResponse } from 'test/integration/utils/generate-transient-token.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { setupHttpMock } from 'test/integration/utils/http-mock.util';
+import { type MarkerServer } from 'test/integration/types/marker-server.type';
+import { startMarkerServer } from 'test/integration/utils/start-marker-server.util';
import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
import {
type LogicFunctionManifest,
@@ -47,8 +46,8 @@ const IDENTIFY_ACCOUNT_SOURCE = `export const handler = ({ accessToken }) => {
describe('app connection OAuth callback', () => {
let provider: ConnectionProviderEntity;
- let fixtureDirectory: string;
- let onConnectExecutionsPath: string;
+ let markerServer: MarkerServer;
+ let onConnectExecutionsUrl: string;
let tokenExchanges: string[];
setupHttpMock(
@@ -75,8 +74,10 @@ describe('app connection OAuth callback', () => {
}),
);
- const readExecutions = (path: string): string[] =>
- existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n') : [];
+ const readExecutions = (markerUrl: string): string[] =>
+ markerServer.hasMarker(markerUrl)
+ ? markerServer.readMarker(markerUrl).trim().split('\n')
+ : [];
const readAccounts = (): Promise<ConnectedAccountEntity[]> =>
globalThis.testDataSource.query(
@@ -156,8 +157,8 @@ describe('app connection OAuth callback', () => {
};
beforeAll(async () => {
- fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-connection-callback-'));
- onConnectExecutionsPath = join(fixtureDirectory, 'on-connect-executions');
+ markerServer = await startMarkerServer();
+ onConnectExecutionsUrl = markerServer.markerUrl('on-connect-executions');
await setupApplicationForSync({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
@@ -176,9 +177,8 @@ describe('app connection OAuth callback', () => {
{
universalIdentifier: ON_CONNECT_IDENTIFIER,
name: 'on-connect',
- source: `import { appendFileSync } from 'node:fs';
-export const handler = ({ connectedAccountId }) => {
- appendFileSync(${JSON.stringify(onConnectExecutionsPath)}, connectedAccountId + '\\n');
+ source: `export const handler = async ({ connectedAccountId }) => {
+ await fetch(${JSON.stringify(onConnectExecutionsUrl)}, { method: 'POST', body: connectedAccountId + '\\n' });
};`,
},
];
@@ -265,7 +265,7 @@ export const handler = ({ connectedAccountId }) => {
beforeEach(() => {
tokenExchanges = [];
- rmSync(onConnectExecutionsPath, { force: true });
+ markerServer.clearMarker(onConnectExecutionsUrl);
});
afterEach(async () => {
@@ -279,7 +279,7 @@ export const handler = ({ connectedAccountId }) => {
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
});
- rmSync(fixtureDirectory, { recursive: true, force: true });
+ await markerServer.close();
});
it('stores the identified account on first connect and runs onConnect for it', async () => {
@@ -291,7 +291,7 @@ export const handler = ({ connectedAccountId }) => {
externalAccountId: 'team-a',
handle: 'Handle team-a',
});
- expect(readExecutions(onConnectExecutionsPath)).toEqual([connection.id]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([connection.id]);
});
it('replaces credentials on the same connection when the reconnect resolves to the same account', async () => {
@@ -311,7 +311,7 @@ export const handler = ({ connectedAccountId }) => {
externalAccountId: 'team-a',
});
expect(decryptAccessToken(connections[0])).toBe('team-a:second');
- expect(readExecutions(onConnectExecutionsPath)).toEqual([
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([
original.id,
original.id,
]);
@@ -364,7 +364,7 @@ export const handler = ({ connectedAccountId }) => {
handle: 'Handle team-a',
});
expect(decryptAccessToken(connections[0])).toBe('team-a:first');
- expect(readExecutions(onConnectExecutionsPath)).toEqual([original.id]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([original.id]);
});
it('pins the identified account on a reconnect target that predates identification', async () => {
@@ -395,7 +395,7 @@ export const handler = ({ connectedAccountId }) => {
expect(redirect.searchParams.has('errorMessage')).toBe(false);
expect(connection.externalAccountId).toBeNull();
- expect(readExecutions(onConnectExecutionsPath)).toEqual([connection.id]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([connection.id]);
});
it('clears the stored account when a reconnect opts out', async () => {
@@ -424,7 +424,7 @@ export const handler = ({ connectedAccountId }) => {
'invalid result',
);
expect(await readAccounts()).toEqual([]);
- expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([]);
});
it('saves nothing and skips onConnect when the identify function fails', async () => {
@@ -437,7 +437,7 @@ export const handler = ({ connectedAccountId }) => {
'broken:first',
);
expect(await readAccounts()).toEqual([]);
- expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([]);
});
it('returns to where the flow started with a short message when the token exchange fails', async () => {
@@ -537,7 +537,7 @@ export const handler = ({ connectedAccountId }) => {
);
expect(redirect.pathname).toBe('/settings/accounts');
expect(tokenExchanges).toEqual([]);
- expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([]);
expect(await readAccounts()).toEqual([]);
});
@@ -545,7 +545,7 @@ export const handler = ({ connectedAccountId }) => {
const OTHER_APPLICATION_IDENTIFIER = v4();
const OTHER_IDENTIFY_ACCOUNT_IDENTIFIER = v4();
const OTHER_ROLE_IDENTIFIER = v4();
- let otherIdentifyExecutionsPath: string;
+ let otherIdentifyExecutionsUrl: string;
let otherLogicFunctionManifest: LogicFunctionManifest;
const buildOtherApplicationManifest = (
@@ -567,14 +567,12 @@ export const handler = ({ connectedAccountId }) => {
});
beforeAll(async () => {
- otherIdentifyExecutionsPath = join(
- fixtureDirectory,
+ otherIdentifyExecutionsUrl = markerServer.markerUrl(
'other-identify-executions',
);
- const source = `import { appendFileSync } from 'node:fs';
-export const handler = () => {
- appendFileSync(${JSON.stringify(otherIdentifyExecutionsPath)}, 'executed\\n');
+ const source = `export const handler = async () => {
+ await fetch(${JSON.stringify(otherIdentifyExecutionsUrl)}, { method: 'POST', body: 'executed\\n' });
return { externalAccountId: 'other-application' };
};`;
@@ -616,7 +614,7 @@ export const handler = () => {
}, 120000);
beforeEach(() => {
- rmSync(otherIdentifyExecutionsPath, { force: true });
+ markerServer.clearMarker(otherIdentifyExecutionsUrl);
});
afterAll(async () => {
@@ -680,8 +678,8 @@ export const handler = () => {
'not found in its application',
);
expect(await readAccounts()).toEqual([]);
- expect(readExecutions(otherIdentifyExecutionsPath)).toEqual([]);
- expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ expect(readExecutions(otherIdentifyExecutionsUrl)).toEqual([]);
+ expect(readExecutions(onConnectExecutionsUrl)).toEqual([]);
} finally {
await globalThis.testDataSource.query(
'UPDATE core."connectionProvider" SET "identifyAccountLogicFunctionUniversalIdentifier" = $1 WHERE id = $2',
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/logic-function-execution.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/logic-function/logic-function-execution.integration-spec.ts
index 003be3b4c52..5ca1bc12e77 100644
--- a/packages/twenty-server/test/integration/metadata/suites/logic-function/logic-function-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/logic-function-execution.integration-spec.ts
@@ -27,6 +27,33 @@ const ERROR_FUNCTION_CODE = `export const main = async (params: { shouldFail: bo
return { success: true };
};`;
+const RUNTIME_FUNCTION_CODE = `import { execSync } from 'node:child_process';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const attempt = (operation: () => unknown): string => {
+ try {
+ operation();
+
+ return 'allowed';
+ } catch (error) {
+ return error instanceof Error && 'code' in error
+ ? String(error.code)
+ : 'failed';
+ }
+};
+
+export const main = async (): Promise<object> => ({
+ hasServerVariables: 'PG_DATABASE_URL' in process.env,
+ hasApplicationId: 'APPLICATION_ID' in process.env,
+ writeTemporaryFile: attempt(() =>
+ writeFileSync(join(tmpdir(), 'file.txt'), 'content'),
+ ),
+ readServerFile: attempt(() => readFileSync('/etc/hosts')),
+ spawnProcess: attempt(() => execSync('true')),
+});`;
+
describe('Logic Function Execution', () => {
const createdFunctionIds: string[] = [];
@@ -153,6 +180,43 @@ describe('Logic Function Execution', () => {
);
});
+ it('should run with the function variables and its own temporary directory', async () => {
+ const { data: createData } = await createOneLogicFunction({
+ input: {
+ name: 'Runtime Test Function',
+ source: {
+ sourceHandlerCode: RUNTIME_FUNCTION_CODE,
+ handlerName: 'main',
+ },
+ },
+ expectToFail: false,
+ });
+
+ const functionId = createData?.createOneLogicFunction?.id;
+
+ expect(functionId).toBeDefined();
+ createdFunctionIds.push(functionId);
+
+ const { data: executeData } = await executeLogicFunction({
+ input: { id: functionId, payload: {} },
+ expectToFail: false,
+ });
+
+ const result = executeData?.executeOneLogicFunction;
+
+ if (result?.status !== LogicFunctionExecutionStatus.SUCCESS) {
+ throw new Error(JSON.stringify(result?.error, null, 2));
+ }
+
+ expect(result?.data).toEqual({
+ hasServerVariables: false,
+ hasApplicationId: true,
+ writeTemporaryFile: 'allowed',
+ readServerFile: 'ERR_ACCESS_DENIED',
+ spawnProcess: 'ERR_ACCESS_DENIED',
+ });
+ });
+
it('should create logic function without source', async () => {
const { data: createData } = await createOneLogicFunction({
input: {
diff --git a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts
index 160173ba6d0..004c4eb5c65 100644
--- a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts
@@ -1,7 +1,4 @@
import { createHash } from 'crypto';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
import { gql } from 'graphql-tag';
import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
@@ -11,7 +8,9 @@ import { syncApplication } from 'test/integration/metadata/suites/application/ut
import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
import { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type MarkerServer } from 'test/integration/types/marker-server.type';
import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { startMarkerServer } from 'test/integration/utils/start-marker-server.util';
import { type SendAppMessagePayload } from 'twenty-shared/application';
import {
ConnectedAccountProvider,
@@ -75,19 +74,20 @@ const SEND_MESSAGE_MUTATION = gql`
`;
describe('sendAppChannelMessage (e2e)', () => {
- let fixtureDirectory: string;
- let sendExecutionsPath: string;
+ let markerServer: MarkerServer;
+ let sendExecutionsUrl: string;
let applicationToken: string;
let applicationDbId: string;
let sendingConnectionId: string;
let silentConnectionId: string;
const readSendExecutions = (): SendAppMessagePayload[] => {
- if (!existsSync(sendExecutionsPath)) {
+ if (!markerServer.hasMarker(sendExecutionsUrl)) {
return [];
}
- return readFileSync(sendExecutionsPath, 'utf8')
+ return markerServer
+ .readMarker(sendExecutionsUrl)
.trim()
.split('\n')
.map((line) => JSON.parse(line));
@@ -222,8 +222,8 @@ describe('sendAppChannelMessage (e2e)', () => {
};
beforeAll(async () => {
- fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-channel-send-'));
- sendExecutionsPath = join(fixtureDirectory, 'send-executions');
+ markerServer = await startMarkerServer();
+ sendExecutionsUrl = markerServer.markerUrl('send-executions');
await setupApplicationForSync({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
@@ -233,9 +233,8 @@ describe('sendAppChannelMessage (e2e)', () => {
});
jest.useRealTimers();
- const sendMessageSource = `import { appendFileSync } from 'node:fs';
-export const handler = (payload) => {
- appendFileSync(${JSON.stringify(sendExecutionsPath)}, JSON.stringify(payload) + '\\n');
+ const sendMessageSource = `export const handler = async (payload) => {
+ await fetch(${JSON.stringify(sendExecutionsUrl)}, { method: 'POST', body: JSON.stringify(payload) + '\\n' });
if (payload.text === 'refused') throw new Error('provider refused the message');
return { externalId: 'sent:' + payload.text, sentAt: '2026-10-21T10:00:00.000Z' };
};`;
@@ -339,7 +338,7 @@ export const handler = (payload) => {
}, 180000);
beforeEach(() => {
- rmSync(sendExecutionsPath, { force: true });
+ markerServer.clearMarker(sendExecutionsUrl);
});
afterEach(async () => {
@@ -391,7 +390,7 @@ export const handler = (payload) => {
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
});
- rmSync(fixtureDirectory, { recursive: true, force: true });
+ await markerServer.close();
}, 120000);
it('sends through the app and records the reply in the same thread', async () => {
diff --git a/packages/twenty-server/test/integration/types/marker-server.type.ts b/packages/twenty-server/test/integration/types/marker-server.type.ts
new file mode 100644
index 00000000000..b038865809d
--- /dev/null
+++ b/packages/twenty-server/test/integration/types/marker-server.type.ts
@@ -0,0 +1,7 @@
+export type MarkerServer = {
+ markerUrl: (name: string) => string;
+ hasMarker: (markerUrl: string) => boolean;
+ readMarker: (markerUrl: string) => string;
+ clearMarker: (markerUrl: string) => void;
+ close: () => Promise<void>;
+};
diff --git a/packages/twenty-server/test/integration/utils/start-marker-server.util.ts b/packages/twenty-server/test/integration/utils/start-marker-server.util.ts
new file mode 100644
index 00000000000..31428096a5d
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/start-marker-server.util.ts
@@ -0,0 +1,53 @@
+import { createServer } from 'node:http';
+
+import { type MarkerServer } from 'test/integration/types/marker-server.type';
+import { isDefined } from 'twenty-shared/utils';
+
+// Logic functions cannot write outside their execution directory, so tests observe them over HTTP.
+export const startMarkerServer = async (): Promise<MarkerServer> => {
+ const markers = new Map<string, string>();
+
+ const server = createServer((request, response) => {
+ const chunks: Buffer[] = [];
+
+ request.on('data', (chunk: Buffer) => chunks.push(chunk));
+ request.on('end', () => {
+ const name = request.url ?? '/';
+
+ markers.set(
+ name,
+ (markers.get(name) ?? '') + Buffer.concat(chunks).toString(),
+ );
+ response.end();
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+
+ const address = server.address();
+
+ if (!isDefined(address) || typeof address === 'string') {
+ throw new Error('Marker server is not listening on a TCP port');
+ }
+
+ const baseUrl = `http://127.0.0.1:${address.port}`;
+ const toName = (markerUrl: string) => new URL(markerUrl).pathname;
+
+ return {
+ markerUrl: (name) => `${baseUrl}/${name}`,
+ hasMarker: (markerUrl) => markers.has(toName(markerUrl)),
+ readMarker: (markerUrl) => {
+ const marker = markers.get(toName(markerUrl));
+
+ if (!isDefined(marker)) {
+ throw new Error(`No request was received for marker ${markerUrl}`);
+ }
+
+ return marker;
+ },
+ clearMarker: (markerUrl) => {
+ markers.delete(toName(markerUrl));
+ },
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ };
+};
diff --git a/packages/twenty-shared/package.json b/packages/twenty-shared/package.json
index 30e3223a80d..d656658c2e3 100644
--- a/packages/twenty-shared/package.json
+++ b/packages/twenty-shared/package.json
@@ -10,7 +10,7 @@
"build": "npx vite build"
},
"engines": {
- "node": "^24.5.0",
+ "node": "^26.5.1",
"npm": "please-use-yarn",
"yarn": "^4.0.2"
},