Skip to content

The open alternative to Salesforce, designed for AI.

feat(logic-function): give handlers an execution context, and a choice of whose access each call uses (#24493)

Félix Malfaite23d3c0a6043
diff --git a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
index d85ce69b2c0..10c651d8331 100644
--- a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
+++ b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
@@ -141,6 +141,7 @@ describe('Generated client wrapper auth behavior', () => {
beforeEach(() => {
delete process.env.TWENTY_APP_ACCESS_TOKEN;
+ delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
delete process.env.TWENTY_API_KEY;
delete (globalThis as Record<string, unknown>)
.frontComponentHostCommunicationApi;
@@ -152,6 +153,79 @@ describe('Generated client wrapper auth behavior', () => {
}
});
+ const runQueryCapturingAuthorization = async (
+ clientOptions: Record<string, unknown>,
+ ) => {
+ const capturedAuthorizationHeaders: string[] = [];
+ const fetchMock = vi.fn(
+ async (_url: string | URL | Request, requestInit?: RequestInit) => {
+ const authorizationHeaderValue =
+ getAuthorizationHeaderValue(requestInit);
+
+ if (authorizationHeaderValue) {
+ capturedAuthorizationHeaders.push(authorizationHeaderValue);
+ }
+
+ return createJsonResponse({
+ body: { data: { record: { id: 'record-id' } } },
+ });
+ },
+ );
+
+ const twentyClient = new TwentyClass({
+ url: 'https://example.com/graphql',
+ fetch: fetchMock as unknown as typeof globalThis.fetch,
+ ...clientOptions,
+ });
+
+ await twentyClient.query({ record: { id: true } });
+
+ return capturedAuthorizationHeaders;
+ };
+
+ it('should act as the triggering person by default', async () => {
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated-token';
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
+
+ expect(await runQueryCapturingAuthorization({})).toEqual([
+ 'Bearer delegated-token',
+ ]);
+ });
+
+ it('should act as the application when asked to', async () => {
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated-token';
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
+
+ expect(
+ await runQueryCapturingAuthorization({ runAs: 'application' }),
+ ).toEqual(['Bearer application-token']);
+ });
+
+ it('should act as the application when nobody triggered the run', async () => {
+ // The runtime points TWENTY_APP_ACCESS_TOKEN at the application in a cron
+ // schedule or install hook, so the default client keeps working there.
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'application-token';
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
+
+ expect(await runQueryCapturingAuthorization({})).toEqual([
+ 'Bearer application-token',
+ ]);
+ });
+
+ it('should still serve a run nobody triggered when asked for the application', async () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
+
+ expect(
+ await runQueryCapturingAuthorization({ runAs: 'application' }),
+ ).toEqual(['Bearer application-token']);
+ });
+
+ it('should build outside a logic function run', () => {
+ expect(
+ () => new TwentyClass({ url: 'https://example.com/graphql' }),
+ ).not.toThrow();
+ });
+
it('uses TWENTY_APP_ACCESS_TOKEN before TWENTY_API_KEY', async () => {
process.env.TWENTY_APP_ACCESS_TOKEN = 'application-token';
process.env.TWENTY_API_KEY = 'api-key-token';
diff --git a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
index 936157d9775..71463b25028 100644
--- a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
+++ b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
@@ -32,9 +32,18 @@ declare class GenqlError extends Error {
// __STRIPPED_DURING_INJECTION_END__
const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
+const APP_APPLICATION_ACCESS_TOKEN_ENV_KEY =
+ 'TWENTY_APP_APPLICATION_ACCESS_TOKEN';
const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
-type TwentyGeneratedClientOptions = ClientOptions;
+// The default acts as the person who triggered the run, limited to their role
+// intersected with the application's, and as the application alone when nobody
+// triggered it. 'application' asks for the application's access either way.
+type TwentyClientRunAs = 'user' | 'application';
+
+type TwentyGeneratedClientOptions = ClientOptions & {
+ runAs?: TwentyClientRunAs;
+};
type ProcessEnvironment = Record<string, string | undefined>;
@@ -158,6 +167,7 @@ export class TwentyGeneratedClient {
fetch: customFetchImplementation,
fetcher: _fetcher,
batch: _batch,
+ runAs,
...requestOptions
} = merged;
@@ -172,10 +182,15 @@ export class TwentyGeneratedClient {
typeof headers === 'function' ? undefined : headers,
);
- // Priority: explicit header > app access token > api key (legacy).
+ // Priority: explicit header > the token for the requested access > api key
+ // (legacy).
this.authorizationToken =
tokenFromHeaders ??
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
+ processEnvironment[
+ runAs === 'application'
+ ? APP_APPLICATION_ACCESS_TOKEN_ENV_KEY
+ : APP_ACCESS_TOKEN_ENV_KEY
+ ] ??
processEnvironment[API_KEY_ENV_KEY] ??
null;
diff --git a/packages/twenty-client-sdk/src/metadata/generated/index.ts b/packages/twenty-client-sdk/src/metadata/generated/index.ts
index 1551b4b313d..5d20283906f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/index.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/index.ts
@@ -71,9 +71,18 @@ function(options?: ClientOptions): Client {
// injected into. They enable full typecheck/lint on this file.
const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
+const APP_APPLICATION_ACCESS_TOKEN_ENV_KEY =
+ 'TWENTY_APP_APPLICATION_ACCESS_TOKEN';
const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
-type MetadataApiClientOptions = ClientOptions;
+// The default acts as the person who triggered the run, limited to their role
+// intersected with the application's, and as the application alone when nobody
+// triggered it. 'application' asks for the application's access either way.
+type TwentyClientRunAs = 'user' | 'application';
+
+type MetadataApiClientOptions = ClientOptions & {
+ runAs?: TwentyClientRunAs;
+};
type ProcessEnvironment = Record<string, string | undefined>;
@@ -197,6 +206,7 @@ export class MetadataApiClient {
fetch: customFetchImplementation,
fetcher: _fetcher,
batch: _batch,
+ runAs,
...requestOptions
} = merged;
@@ -211,10 +221,15 @@ export class MetadataApiClient {
typeof headers === 'function' ? undefined : headers,
);
- // Priority: explicit header > app access token > api key (legacy).
+ // Priority: explicit header > the token for the requested access > api key
+ // (legacy).
this.authorizationToken =
tokenFromHeaders ??
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
+ processEnvironment[
+ runAs === 'application'
+ ? APP_APPLICATION_ACCESS_TOKEN_ENV_KEY
+ : APP_ACCESS_TOKEN_ENV_KEY
+ ] ??
processEnvironment[API_KEY_ENV_KEY] ??
null;
diff --git a/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts b/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts
index bf1af913a46..9c89a436187 100644
--- a/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts
+++ b/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts
@@ -94,6 +94,55 @@ describe('RestApiClient', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ it('should act as the application when asked to', async () => {
+ (globalThis as Record<string, unknown>).process = {
+ env: {
+ TWENTY_API_URL: 'https://api.twenty.test',
+ TWENTY_APP_ACCESS_TOKEN: 'delegated-token',
+ TWENTY_APP_APPLICATION_ACCESS_TOKEN: 'application-token',
+ },
+ };
+ const fetchMock = vi.fn().mockResolvedValue(buildResponse('{}'));
+
+ await new RestApiClient({ fetch: fetchMock, runAs: 'application' }).get(
+ '/rest/people',
+ );
+
+ expect(
+ (fetchMock.mock.calls[0][1].headers as Headers).get('Authorization'),
+ ).toBe('Bearer application-token');
+ });
+
+ it('should act as the triggering person by default', async () => {
+ (globalThis as Record<string, unknown>).process = {
+ env: {
+ TWENTY_API_URL: 'https://api.twenty.test',
+ TWENTY_APP_ACCESS_TOKEN: 'delegated-token',
+ TWENTY_APP_APPLICATION_ACCESS_TOKEN: 'application-token',
+ },
+ };
+ const fetchMock = vi.fn().mockResolvedValue(buildResponse('{}'));
+
+ await new RestApiClient({ fetch: fetchMock }).get('/rest/people');
+
+ expect(
+ (fetchMock.mock.calls[0][1].headers as Headers).get('Authorization'),
+ ).toBe('Bearer delegated-token');
+ });
+
+ it('should name the application token when it is the one missing', async () => {
+ (globalThis as Record<string, unknown>).process = {
+ env: { TWENTY_API_URL: 'https://api.twenty.test' },
+ };
+
+ await expect(
+ new RestApiClient({
+ fetch: vi.fn(),
+ runAs: 'application',
+ }).get('/rest/people'),
+ ).rejects.toThrow(/TWENTY_APP_APPLICATION_ACCESS_TOKEN/);
+ });
+
it('should throw a RestApiClientError when the access token is missing', async () => {
(globalThis as Record<string, unknown>).process = {
env: { TWENTY_API_URL: 'https://api.twenty.test' },
diff --git a/packages/twenty-client-sdk/src/rest/index.ts b/packages/twenty-client-sdk/src/rest/index.ts
index 14cf614d16f..0133b585590 100644
--- a/packages/twenty-client-sdk/src/rest/index.ts
+++ b/packages/twenty-client-sdk/src/rest/index.ts
@@ -2,17 +2,24 @@ import {
DEFAULT_API_KEY_NAME,
DEFAULT_API_URL_NAME,
DEFAULT_APP_ACCESS_TOKEN_NAME,
+ DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
DEFAULT_FUNCTIONS_URL_NAME,
} from 'twenty-shared/application';
const isDefined = <T>(value: T): value is NonNullable<T> =>
value !== null && value !== undefined;
+// The default acts as the person who triggered the run, limited to their role
+// intersected with the application's, and as the application alone when nobody
+// triggered it. 'application' asks for the application's access either way.
+export type TwentyClientRunAs = 'user' | 'application';
+
export type RestApiClientOptions = {
baseUrl?: string;
token?: string;
fetch?: typeof globalThis.fetch;
defaultHeaders?: HeadersInit;
+ runAs?: TwentyClientRunAs;
};
export type RestApiRequestOptions = {
@@ -97,6 +104,7 @@ export class RestApiClient {
private defaultHeaders: HeadersInit | undefined;
private fetchImplementation: typeof globalThis.fetch | null;
private authorizationToken: string | null;
+ private runAs: TwentyClientRunAs | undefined;
private refreshAccessTokenPromise: Promise<string | null> | null = null;
constructor(options?: RestApiClientOptions) {
@@ -105,6 +113,7 @@ export class RestApiClient {
this.defaultHeaders = options?.defaultHeaders;
this.fetchImplementation = options?.fetch ?? globalThis.fetch ?? null;
this.authorizationToken = options?.token ?? null;
+ this.runAs = options?.runAs;
}
request<TResponse = unknown>(
@@ -195,12 +204,17 @@ export class RestApiClient {
}
private resolveToken(): string {
+ const tokenEnvironmentKey =
+ this.runAs === 'application'
+ ? DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME
+ : DEFAULT_APP_ACCESS_TOKEN_NAME;
+
if (!isDefined(this.authorizationToken)) {
const processEnvironment = getProcessEnvironment();
this.authorizationToken =
this.token ??
- processEnvironment[DEFAULT_APP_ACCESS_TOKEN_NAME] ??
+ processEnvironment[tokenEnvironmentKey] ??
processEnvironment[DEFAULT_API_KEY_NAME] ??
null;
}
@@ -210,7 +224,7 @@ export class RestApiClient {
this.authorizationToken.length === 0
) {
throw new RestApiClientError(
- `Missing application access token. Set the \`${DEFAULT_APP_ACCESS_TOKEN_NAME}\` environment variable or pass \`token\` to \`RestApiClient\`.`,
+ `Missing application access token. Set the \`${tokenEnvironmentKey}\` environment variable or pass \`token\` to \`RestApiClient\`.`,
);
}
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index 55cc62dde92..33278690981 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -96,7 +96,7 @@ The same applies to front components reading values via `getApplicationVariable(
The role declared with [`defineApplicationRole()`](/developers/extend/apps/config/roles) controls what the app's logic functions and front components can access:
-- The runtime token injected as `TWENTY_APP_ACCESS_TOKEN` is derived from this role.
+- The runtime tokens injected into your logic functions are derived from this role. A call acting as a person is further narrowed to what that person can do, so it can never exceed either one. See [Whose access a call uses](/developers/extend/apps/logic/logic-functions#whose-access-a-call-uses).
- The typed API client is restricted to the permissions granted to that role.
- Follow least-privilege: declare only the permissions your functions need.
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
index 8e89c6449f0..a99a5d3f10c 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
@@ -54,9 +54,9 @@ your-app/
## Sandboxing
-- **Logic functions** run in isolated Node.js processes on the server. They only access data through the typed API client, scoped to the app's role permissions.
+- **Logic functions** run in isolated Node.js processes on the server. They only access data through the typed API client, which acts either as the person who triggered the run or as the app itself. See [Whose access a call uses](/developers/extend/apps/logic/logic-functions#whose-access-a-call-uses).
- **Front components** run in Web Workers using Remote DOM — sandboxed from the main page but rendering native DOM elements (not iframes). They communicate with Twenty via a message-passing host API.
-- **Permissions** are enforced at the API level. The runtime token (`TWENTY_APP_ACCESS_TOKEN`) is derived from the role defined in `defineApplication()`.
+- **Permissions** are enforced at the API level. Two runtime tokens are injected, both derived from the role declared with `defineApplicationRole()`; the default one is narrowed further to what the triggering person can do whenever someone is behind the run.
## App lifecycle
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
index c70cde94226..1ff6febcbe5 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -333,6 +333,8 @@ export default defineLogicFunction({
To call app HTTP routes or read and write Twenty records from a front component, use `RestApiClient` from `twenty-client-sdk/rest`. It sends `/s/...` paths to your workspace's functions base URL and every other path, including `/rest/...`, to `TWENTY_API_URL`.
+It always acts as the person looking at the page. `runAs: 'application'` is a logic-function option only: a component never receives your application's own token, so asking for it here throws. Put work that needs the app's own access behind a logic function and call that instead.
+
| Method | Description |
|--------|-------------|
| `get(path, options?)` | Sends a `GET` request |
@@ -448,7 +450,7 @@ The following system variables are always available via `process.env`:
| Variable | Description |
|----------|-------------|
| `TWENTY_API_URL` | Base URL of the Twenty core API |
-| `TWENTY_APP_ACCESS_TOKEN` | Short-lived token scoped to your app's role |
+| `TWENTY_APP_ACCESS_TOKEN` | Short-lived token scoped to the signed-in person's role intersected with your app's, so a component can never do more than the person looking at it |
### `TWENTY_FUNCTIONS_URL`
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 4153f8ce3e5..b5c232f0598 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -447,6 +447,78 @@ const handler = async (event: PersonDestroyedEvent) => {
};
```
+#### Execution context
+
+Every handler receives a second argument describing the run itself, whatever triggered it. Where the first argument changes shape per trigger, this one does not:
+
+```ts
+import type { LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';
+
+const handler = async (
+ event: DatabaseEventPayload,
+ { workspaceId, workspaceMemberId }: LogicFunctionExecutionContext,
+) => {
+ if (workspaceMemberId === null) {
+ throw new Error('This function must be triggered by a person');
+ }
+
+ return { reviewedBy: workspaceMemberId, workspaceId };
+};
+```
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `workspaceId` | `string` | The workspace the run belongs to. |
+| `userWorkspaceId` | `string \| null` | The person who triggered the run, as their membership of this workspace. |
+| `workspaceMemberId` | `string \| null` | The same person as a workspace member record, which is what you link records to. |
+| `retryCount` | `number` | `0` on the first attempt. See [Background jobs](/developers/extend/apps/logic/background-jobs). |
+| `maxRetries` | `number` | Upper bound on application-requested retries. |
+
+`userWorkspaceId` and `workspaceMemberId` are `null` when nobody triggered the run: cron schedules, install hooks and unauthenticated webhooks have no person behind them. They are also `null` when the person has no workspace member record, or theirs has been deleted.
+
+<Note>
+**The context tells you who triggered the run.** What the run may *do* is a separate declaration, below.
+</Note>
+
+#### Whose access a call uses
+
+Every client — `CoreApiClient`, `MetadataApiClient` and `RestApiClient` — acts as the person who triggered the run: their role intersected with your application's, so the call can never do more than either of you. That is the default, and it means a person can never use your app to exceed their own permissions.
+
+When nobody triggered the run there is no person to act as, so the same client falls back to your application's own access: cron schedules, install hooks and unauthenticated webhooks need no special handling.
+
+Some calls legitimately need the application's own access even when a person *is* behind the run — reading your app's configuration records, or doing work that person could not do themselves. Build a second client for those:
+
+```ts
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+const asPerson = new CoreApiClient();
+const asApplication = new CoreApiClient({ runAs: 'application' });
+
+const handler = async (event: DatabaseEventPayload) => {
+ // config records only your app may read
+ const { slackUserLinks } = await asApplication.query({ ... });
+
+ // created as the person, so it is attributed and permission-checked
+ await asPerson.mutation({ createNote: { ... } });
+};
+```
+
+Build both once, at module scope, and every call site then says which access it uses by which client it calls. `RestApiClient` takes the same option:
+
+```ts
+import { RestApiClient } from 'twenty-client-sdk/rest';
+
+const asApplication = new RestApiClient({ runAs: 'application' });
+```
+
+<Note>
+**A run nobody triggered acts as your application.** Cron schedules, install hooks and unauthenticated webhooks have no person behind them, so the default client falls back to your application's own access and keeps working. `runAs: 'application'` is only needed when you want that access in a run a person *did* trigger.
+
+Check `context.workspaceMemberId` when a function behaves differently depending on whether someone is behind it, for instance to attribute a record.
+</Note>
+
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), `runAgent`, `getPublicAssetUrl` and credit charging.
+
#### Exposing a function as an AI tool or workflow action
Logic functions can be exposed on two surfaces, each with its own trigger:
@@ -722,7 +794,7 @@ setCompany(result.company);
</Accordion>
<Accordion title="MetadataApiClient" description="Workspace config, applications, and file uploads">
-`MetadataApiClient` ships pre-built with the SDK (no generation required). It queries the `/metadata` endpoint for workspace configuration, applications, and file uploads.
+`MetadataApiClient` ships pre-built with the SDK (no generation required). It queries the `/metadata` endpoint for workspace configuration, applications, and file uploads. It takes the same `runAs` option as `CoreApiClient` — see [Whose access a call uses](#whose-access-a-call-uses).
```ts
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
@@ -791,7 +863,8 @@ Key points:
When your code runs on Twenty (logic functions or front components), the platform injects credentials as environment variables:
- `TWENTY_API_URL` — Base URL of the Twenty API
- - `TWENTY_APP_ACCESS_TOKEN` — Short-lived key scoped to your application's default function role
+ - `TWENTY_APP_ACCESS_TOKEN` — Short-lived key for the default access: a person's role intersected with your application's when someone is behind the run, your application's own role when nobody is. The person is whoever triggered the run in a logic function, whoever is looking at the page in a front component.
+ - `TWENTY_APP_APPLICATION_ACCESS_TOKEN` — Short-lived key scoped to your application's own role alone. Logic functions only, always injected there, and what `runAs: 'application'` uses.
- You do **not** need to pass these to the clients — they read from `process.env` automatically. The API key's permissions are determined by the role declared with `defineApplicationRole()` (or referenced via `defaultRoleUniversalIdentifier` in `application-config.ts`).
+ You do **not** need to pass these to the clients — they read from `process.env` automatically, and [Whose access a call uses](#whose-access-a-call-uses) covers picking between them. Your application's own permissions are determined by the role declared with `defineApplicationRole()` (or referenced via `defaultRoleUniversalIdentifier` in `application-config.ts`); a run acting as a person can never exceed that role, nor theirs.
</Note>
diff --git a/packages/twenty-sdk/src/cli/utilities/client/twenty-client-template.ts b/packages/twenty-sdk/src/cli/utilities/client/twenty-client-template.ts
deleted file mode 100644
index 936157d9775..00000000000
--- a/packages/twenty-sdk/src/cli/utilities/client/twenty-client-template.ts
+++ /dev/null
@@ -1,434 +0,0 @@
-// Ambient type stubs for the genql-generated code this template gets
-// injected into. They enable full typecheck/lint on this file.
-// __STRIPPED_DURING_INJECTION_START__
-type QueryGenqlSelection = Record<string, unknown>;
-type MutationGenqlSelection = Record<string, unknown>;
-type GraphqlOperation = Record<string, unknown>;
-
-type ClientOptions = {
- url?: string;
- headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
- fetcher?: (
- operation: GraphqlOperation | GraphqlOperation[],
- ) => Promise<unknown>;
- fetch?: typeof globalThis.fetch;
- batch?: unknown;
-};
-
-type Client = {
- query: (
- request: QueryGenqlSelection & { __name?: string },
- ) => Promise<unknown>;
- mutation: (
- request: MutationGenqlSelection & { __name?: string },
- ) => Promise<unknown>;
-};
-
-declare function createClient(options: ClientOptions): Client;
-
-declare class GenqlError extends Error {
- constructor(errors: unknown, data: unknown);
-}
-// __STRIPPED_DURING_INJECTION_END__
-
-const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
-const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
-
-type TwentyGeneratedClientOptions = ClientOptions;
-
-type ProcessEnvironment = Record<string, string | undefined>;
-
-type GraphqlErrorPayloadEntry = {
- message?: string;
- extensions?: { code?: string };
-};
-
-type GraphqlResponsePayload = {
- data?: Record<string, unknown>;
- errors?: GraphqlErrorPayloadEntry[];
-};
-
-type GraphqlResponse = {
- status: number;
- statusText: string;
- payload: GraphqlResponsePayload | null;
- rawBody: string;
-};
-
-const getProcessEnvironment = (): ProcessEnvironment => {
- const processObject = (
- globalThis as { process?: { env?: ProcessEnvironment } }
- ).process;
-
- return processObject?.env ?? {};
-};
-
-const getTokenFromAuthorizationHeader = (
- authorizationHeader: string | undefined,
-): string | null => {
- if (typeof authorizationHeader !== 'string') {
- return null;
- }
-
- const trimmedAuthorizationHeader = authorizationHeader.trim();
-
- if (trimmedAuthorizationHeader.length === 0) {
- return null;
- }
-
- if (trimmedAuthorizationHeader === 'Bearer') {
- return null;
- }
-
- if (trimmedAuthorizationHeader.startsWith('Bearer ')) {
- return trimmedAuthorizationHeader.slice('Bearer '.length).trim();
- }
-
- return trimmedAuthorizationHeader;
-};
-
-const getTokenFromHeaders = (
- headers: HeadersInit | undefined,
-): string | null => {
- if (!headers) {
- return null;
- }
-
- if (headers instanceof Headers) {
- return getTokenFromAuthorizationHeader(
- headers.get('Authorization') ?? undefined,
- );
- }
-
- if (Array.isArray(headers)) {
- const matchedAuthorizationHeader = headers.find(
- ([headerName]) => headerName.toLowerCase() === 'authorization',
- );
-
- return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);
- }
-
- const headersRecord = headers as Record<string, string | undefined>;
-
- return getTokenFromAuthorizationHeader(
- headersRecord.Authorization ?? headersRecord.authorization,
- );
-};
-
-const hasAuthenticationErrorInGraphqlPayload = (
- payload: GraphqlResponsePayload | null,
-): boolean => {
- if (!payload?.errors) {
- return false;
- }
-
- return payload.errors.some((graphqlError) => {
- return (
- graphqlError.extensions?.code === 'UNAUTHENTICATED' ||
- graphqlError.message?.toLowerCase() === 'unauthorized'
- );
- });
-};
-
-const defaultOptions: TwentyGeneratedClientOptions = {
- url: '__TWENTY_DEFAULT_URL__',
- headers: {
- 'Content-Type': 'application/json',
- },
-};
-
-export class TwentyGeneratedClient {
- private client: Client;
- private url: string;
- private requestOptions: RequestInit;
- private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
- private fetchImplementation: typeof globalThis.fetch | null;
- private authorizationToken: string | null;
- private refreshAccessTokenPromise: Promise<string | null> | null = null;
-
- constructor(options?: TwentyGeneratedClientOptions) {
- const merged: TwentyGeneratedClientOptions = {
- ...defaultOptions,
- ...options,
- };
-
- const {
- url,
- headers,
- fetch: customFetchImplementation,
- fetcher: _fetcher,
- batch: _batch,
- ...requestOptions
- } = merged;
-
- this.url = url ?? '';
- this.requestOptions = requestOptions;
- this.headers = headers ?? {};
- this.fetchImplementation =
- customFetchImplementation ?? globalThis.fetch ?? null;
-
- const processEnvironment = getProcessEnvironment();
- const tokenFromHeaders = getTokenFromHeaders(
- typeof headers === 'function' ? undefined : headers,
- );
-
- // Priority: explicit header > app access token > api key (legacy).
- this.authorizationToken =
- tokenFromHeaders ??
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
- processEnvironment[API_KEY_ENV_KEY] ??
- null;
-
- this.client = createClient({
- ...merged,
- headers: undefined,
- fetcher: async (operation) =>
- this.executeGraphqlRequestWithOptionalRefresh({
- operation,
- }),
- });
- }
-
- query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {
- return this.client.query(request);
- }
-
- mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {
- return this.client.mutation(request);
- }
-
- // __UPLOAD_FILE_START__
- async uploadFile(
- fileBuffer: Buffer,
- filename: string,
- contentType: string = 'application/octet-stream',
- fieldMetadataUniversalIdentifier: string,
- ): Promise<{
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- }> {
- const form = new FormData();
-
- form.append(
- 'operations',
- JSON.stringify({
- query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {
- uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }
- }`,
- variables: {
- file: null,
- fieldMetadataUniversalIdentifier,
- },
- }),
- );
- form.append('map', JSON.stringify({ '0': ['variables.file'] }));
- form.append(
- '0',
- new Blob([fileBuffer as BlobPart], { type: contentType }),
- filename,
- );
-
- const result = await this.executeGraphqlRequestWithOptionalRefresh({
- operation: form,
- headers: {},
- requestInit: {
- method: 'POST',
- },
- });
-
- if (result.errors) {
- throw new GenqlError(result.errors, result.data);
- }
-
- const data = result.data as Record<string, unknown>;
-
- return data.uploadFilesFieldFileByUniversalIdentifier as {
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- };
- }
- // __UPLOAD_FILE_END__
-
- private async executeGraphqlRequestWithOptionalRefresh({
- operation,
- headers,
- requestInit,
- }: {
- operation: GraphqlOperation | GraphqlOperation[] | FormData;
- headers?: HeadersInit;
- requestInit?: RequestInit;
- }) {
- const firstResponse = await this.executeGraphqlRequest({
- operation,
- headers,
- requestInit,
- token: this.authorizationToken,
- });
-
- if (this.shouldRefreshToken(firstResponse)) {
- const refreshedAccessToken = await this.requestRefreshedAccessToken();
-
- if (refreshedAccessToken) {
- const retryResponse = await this.executeGraphqlRequest({
- operation,
- headers,
- requestInit,
- token: refreshedAccessToken,
- });
-
- return this.assertResponseIsSuccessful(retryResponse);
- }
- }
-
- return this.assertResponseIsSuccessful(firstResponse);
- }
-
- private async executeGraphqlRequest({
- operation,
- headers,
- requestInit,
- token,
- }: {
- operation: GraphqlOperation | GraphqlOperation[] | FormData;
- headers?: HeadersInit;
- requestInit?: RequestInit;
- token: string | null;
- }): Promise<GraphqlResponse> {
- if (!this.fetchImplementation) {
- throw new Error(
- 'Global `fetch` function is not available, ' +
- 'pass a fetch implementation to the Twenty client',
- );
- }
-
- const resolvedHeaders = await this.resolveHeaders();
- const requestHeaders = new Headers(resolvedHeaders);
-
- if (headers) {
- new Headers(headers).forEach((value, key) =>
- requestHeaders.set(key, value),
- );
- }
-
- if (operation instanceof FormData) {
- requestHeaders.delete('Content-Type');
- } else {
- requestHeaders.set('Content-Type', 'application/json');
- }
-
- if (token) {
- requestHeaders.set('Authorization', `Bearer ${token}`);
- } else {
- requestHeaders.delete('Authorization');
- }
-
- const response = await this.fetchImplementation.call(globalThis, this.url, {
- ...this.requestOptions,
- ...requestInit,
- method: requestInit?.method ?? 'POST',
- headers: requestHeaders,
- body:
- operation instanceof FormData ? operation : JSON.stringify(operation),
- });
-
- const rawBody = await response.text();
- let payload: GraphqlResponsePayload | null = null;
-
- if (rawBody.trim().length > 0) {
- try {
- payload = JSON.parse(rawBody) as GraphqlResponsePayload;
- } catch {
- payload = null;
- }
- }
-
- return {
- status: response.status,
- statusText: response.statusText,
- payload,
- rawBody,
- };
- }
-
- private async resolveHeaders(): Promise<HeadersInit> {
- if (typeof this.headers === 'function') {
- return (await this.headers()) ?? {};
- }
-
- return this.headers ?? {};
- }
-
- private shouldRefreshToken(response: GraphqlResponse): boolean {
- if (response.status === 401) {
- return true;
- }
-
- return hasAuthenticationErrorInGraphqlPayload(response.payload);
- }
-
- private assertResponseIsSuccessful(response: GraphqlResponse) {
- if (response.status < 200 || response.status >= 300) {
- throw new Error(`${response.statusText}: ${response.rawBody}`);
- }
-
- if (response.payload === null) {
- throw new Error('Invalid JSON response');
- }
-
- return response.payload;
- }
-
- private async requestRefreshedAccessToken(): Promise<string | null> {
- const refreshAccessTokenFunction = (
- globalThis as {
- frontComponentHostCommunicationApi?: {
- requestAccessTokenRefresh?: () => Promise<string>;
- };
- }
- ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;
-
- if (typeof refreshAccessTokenFunction !== 'function') {
- return null;
- }
-
- if (!this.refreshAccessTokenPromise) {
- this.refreshAccessTokenPromise = refreshAccessTokenFunction()
- .then((refreshedAccessToken) => {
- if (
- typeof refreshedAccessToken !== 'string' ||
- refreshedAccessToken.length === 0
- ) {
- return null;
- }
-
- this.setAuthorizationToken(refreshedAccessToken);
-
- return refreshedAccessToken;
- })
- .catch((refreshError: unknown) => {
- console.error('Twenty client: token refresh failed', refreshError);
-
- return null;
- })
- .finally(() => {
- this.refreshAccessTokenPromise = null;
- });
- }
-
- return this.refreshAccessTokenPromise;
- }
-
- private setAuthorizationToken(token: string) {
- this.authorizationToken = token;
-
- const processEnvironment = getProcessEnvironment();
-
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;
- }
-}
diff --git a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
index f9964a8dbdd..8706cd41127 100644
--- a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
+++ b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
@@ -1,7 +1,6 @@
-import {
- DEFAULT_API_URL_NAME,
- DEFAULT_APP_ACCESS_TOKEN_NAME,
-} from 'twenty-shared/application';
+import { DEFAULT_API_URL_NAME } from 'twenty-shared/application';
+
+import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
const BILLING_CHARGE_TIMEOUT_MS = 5_000;
@@ -13,8 +12,8 @@ export type ChargeCreditsParams = {
};
// Records credit usage against the running application via the Twenty
-// server's `/app/billing/charge` endpoint. Reads `TWENTY_API_URL` and
-// `TWENTY_APP_ACCESS_TOKEN` from the execution env (injected by the
+// server's `/app/billing/charge` endpoint. Reads `TWENTY_API_URL` and the
+// application access token from the execution env (injected by the
// logic-function runtime). No-ops silently when either is missing so
// local/test runs don't crash. Failures are non-fatal — a billing error
// never surfaces as a tool failure.
@@ -25,7 +24,7 @@ export const chargeCredits = async ({
resourceContext,
}: ChargeCreditsParams): Promise<void> => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
- const token = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
+ const token = getApplicationAccessToken();
if (!apiUrl || !token) {
return;
diff --git a/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts b/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
index 60ec7a8f36f..bb1f8327814 100644
--- a/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
+++ b/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
@@ -3,9 +3,15 @@ import {
type ServerRouteDispatchResult,
type ServerRouteTriggerSettings,
} from 'twenty-shared/application';
+import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
import { type LogicFunctionHttpResponse } from 'twenty-shared/types';
-export type LogicFunctionHandler = (...args: any[]) => any | Promise<any>;
+// TPayload defaults to any so handlers that declare a concrete payload type
+// stay assignable; the second parameter is what authors need to discover.
+export type LogicFunctionHandler<TPayload = any> = (
+ payload: TPayload,
+ context: LogicFunctionExecutionContext,
+) => any | Promise<any>;
// A resolver attached to `serverRouteTriggerSettings` runs in the owner workspace and is the single
// point of authorization: the URL only carries the resolver's universalIdentifier. Returning a
@@ -15,8 +21,9 @@ export type ServerRouteResolverResult =
| ServerRouteDispatchResult
| LogicFunctionHttpResponse;
-export type ServerRouteResolverHandler = (
- ...args: any[]
+export type ServerRouteResolverHandler<TPayload = any> = (
+ payload: TPayload,
+ context: LogicFunctionExecutionContext,
) => ServerRouteResolverResult | Promise<ServerRouteResolverResult>;
type LogicFunctionConfigBase = Omit<
diff --git a/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts b/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
index 34a20722865..f59e0469b00 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
@@ -1,8 +1,10 @@
import {
DEFAULT_API_URL_NAME,
- DEFAULT_APP_ACCESS_TOKEN_NAME,
+ DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
} from 'twenty-shared/application';
+import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
+
export const postGraphqlRequest = async <TVariables, TData>({
query,
variables,
@@ -13,12 +15,12 @@ export const postGraphqlRequest = async <TVariables, TData>({
caller: string;
}): Promise<TData> => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
- const accessToken = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
+ const accessToken = getApplicationAccessToken();
if (!apiUrl || !accessToken) {
throw new Error(
`${caller}() requires the app runtime env vars ` +
- `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_ACCESS_TOKEN_NAME}.`,
+ `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME}.`,
);
}
diff --git a/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts b/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts
new file mode 100644
index 00000000000..6540a3d87db
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
+
+describe('getApplicationAccessToken', () => {
+ const initialEnvironment = process.env;
+
+ beforeEach(() => {
+ process.env = { ...initialEnvironment };
+ delete process.env.TWENTY_APP_ACCESS_TOKEN;
+ delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
+ });
+
+ afterEach(() => {
+ process.env = initialEnvironment;
+ });
+
+ it('should prefer the application token over the delegated one', () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application';
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated';
+
+ expect(getApplicationAccessToken()).toBe('application');
+ });
+
+ it('should keep working in a run nobody triggered', () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application';
+
+ expect(getApplicationAccessToken()).toBe('application');
+ });
+
+ it('should fall back to the delegated token for front components', () => {
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated';
+
+ expect(getApplicationAccessToken()).toBe('delegated');
+ });
+
+ it('should return undefined outside the app runtime', () => {
+ expect(getApplicationAccessToken()).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
new file mode 100644
index 00000000000..bca34761fd0
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
@@ -0,0 +1,11 @@
+import {
+ DEFAULT_APP_ACCESS_TOKEN_NAME,
+ DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
+} from 'twenty-shared/application';
+
+// These calls reach the application's own resources rather than acting for
+// whoever triggered the run, so they take the application token whenever the
+// logic function runtime injects one. Front components only ever get the other.
+export const getApplicationAccessToken = (): string | undefined =>
+ process.env[DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME] ??
+ process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
diff --git a/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts b/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
index db9a8fc46af..86ab63703c0 100644
--- a/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
+++ b/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
@@ -1,7 +1,6 @@
-import {
- DEFAULT_API_URL_NAME,
- DEFAULT_APP_ACCESS_TOKEN_NAME,
-} from 'twenty-shared/application';
+import { DEFAULT_API_URL_NAME } from 'twenty-shared/application';
+
+import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
const decodeTokenPayload = (
token: string,
@@ -19,7 +18,7 @@ const decodeTokenPayload = (
// The path is relative to the public/ folder (e.g. "images/logo.png").
export const getPublicAssetUrl = (path: string): string => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
- const token = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
+ const token = getApplicationAccessToken();
if (!apiUrl || !token) {
throw new Error(
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts
index faa304e7734..10b44622348 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts
@@ -42,7 +42,13 @@ describe('LocalChildProcessRunnerService', () => {
runnerPath,
env: {},
payload: {},
- context: { retryCount: 2, maxRetries: 3 },
+ context: {
+ retryCount: 2,
+ maxRetries: 3,
+ workspaceId: 'workspace-1',
+ userWorkspaceId: null,
+ workspaceMemberId: null,
+ },
timeoutMs: 5_000,
});
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 0b484fbb585..27bd41fb104 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
@@ -116,10 +116,12 @@ export class LocalChildProcessRunnerService {
}
});
} else {
- // Fallback: read payload from argv[2] (JSON) and print to stdout
+ // Fallback for a runner started without IPC: the context travels as
+ // argv[3] because the script is written once, before any run exists.
const json = process.argv[2];
payload = json ? JSON.parse(json) : undefined;
- const out = await handlerFn(payload, { retryCount: 0, maxRetries: 0 });
+ const contextJson = process.argv[3];
+ const out = await handlerFn(payload, contextJson ? JSON.parse(contextJson) : undefined);
process.stdout.write(JSON.stringify({ ok: true, result: out }), () => process.exit(0));
}
} catch (error) {
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 52e263a191f..6eb88f3979b 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -5,9 +5,13 @@ import {
DEFAULT_API_KEY_NAME,
DEFAULT_API_URL_NAME,
DEFAULT_APP_ACCESS_TOKEN_NAME,
+ DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
DEFAULT_FUNCTIONS_URL_NAME,
} from 'twenty-shared/application';
-import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
+import {
+ type LogicFunctionExecutionContext,
+ type LogicFunctionRetryContext,
+} from 'twenty-shared/logic-function';
import { FeatureFlagKey } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
@@ -58,6 +62,7 @@ import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/eve
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
import { cleanServerUrl } from 'src/utils/clean-server-url';
export class LogicFunctionExecutionException extends Error {
@@ -110,7 +115,7 @@ export class LogicFunctionExecutorService {
userId,
userWorkspaceId,
executionMode,
- context = { retryCount: 0, maxRetries: 0 },
+ retry = { retryCount: 0, maxRetries: 0 },
}: {
logicFunctionId: string;
workspaceId: string;
@@ -118,7 +123,7 @@ export class LogicFunctionExecutorService {
userId?: string;
userWorkspaceId?: string;
executionMode?: LogicFunctionExecutionMode;
- context?: LogicFunctionExecutionContext;
+ retry?: LogicFunctionRetryContext;
}): Promise<LogicFunctionExecuteResult> {
const { flatApplication, flatLogicFunction, applicationVariableMaps } =
await this.getFlatEntitiesOrThrow({
@@ -140,6 +145,13 @@ export class LogicFunctionExecutorService {
userWorkspaceId,
});
+ const context = await this.buildExecutionContext({
+ workspaceId,
+ retry,
+ userId,
+ userWorkspaceId,
+ });
+
const driver = this.logicFunctionDriverFactory.getCurrentDriver();
const effectiveExecutionMode = await this.resolveEffectiveExecutionMode({
@@ -322,6 +334,42 @@ export class LogicFunctionExecutorService {
return { flatApplication, flatLogicFunction, applicationVariableMaps };
}
+ private async buildExecutionContext({
+ workspaceId,
+ retry,
+ userId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ retry: LogicFunctionRetryContext;
+ userId: string | undefined;
+ userWorkspaceId: string | undefined;
+ }): Promise<LogicFunctionExecutionContext> {
+ return {
+ ...retry,
+ workspaceId,
+ userWorkspaceId: userWorkspaceId ?? null,
+ workspaceMemberId: isDefined(userId)
+ ? await this.resolveWorkspaceMemberId({ workspaceId, userId })
+ : null,
+ };
+ }
+
+ private async resolveWorkspaceMemberId({
+ workspaceId,
+ userId,
+ }: {
+ workspaceId: string;
+ userId: string;
+ }): Promise<string | null> {
+ const { flatWorkspaceMemberMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatWorkspaceMemberMaps',
+ ]);
+
+ return resolveWorkspaceMemberIdForUser({ userId, flatWorkspaceMemberMaps });
+ }
+
private async getExecutionEnvVariables({
workspaceId,
flatApplication,
@@ -335,13 +383,24 @@ export class LogicFunctionExecutorService {
userId?: string;
userWorkspaceId?: string;
}) {
- const applicationAccessToken =
- await this.applicationTokenService.generateApplicationAccessToken({
+ // Two tokens so a handler can choose per call which access it acts with,
+ // rather than the whole run being locked to one of them.
+ const hasTriggeringPerson = isDefined(userId) && isDefined(userWorkspaceId);
+
+ const [applicationAccessToken, delegatedAccessToken] = await Promise.all([
+ this.applicationTokenService.generateApplicationAccessToken({
workspaceId,
applicationId: flatApplication.id,
- userId,
- userWorkspaceId,
- });
+ }),
+ hasTriggeringPerson
+ ? this.applicationTokenService.generateApplicationAccessToken({
+ workspaceId,
+ applicationId: flatApplication.id,
+ userId,
+ userWorkspaceId,
+ })
+ : null,
+ ]);
const baseUrl = cleanServerUrl(this.twentyConfigService.get('SERVER_URL'));
const functionsBaseUrl = await this.buildFunctionsBaseUrl({
@@ -361,7 +420,12 @@ export class LogicFunctionExecutorService {
return {
[DEFAULT_API_URL_NAME]: baseUrl ?? '',
- [DEFAULT_APP_ACCESS_TOKEN_NAME]: applicationAccessToken.token,
+ // Falls back to the application when nobody triggered the run, so a cron
+ // schedule or an install hook keeps working without asking for anything.
+ [DEFAULT_APP_ACCESS_TOKEN_NAME]: (
+ delegatedAccessToken ?? applicationAccessToken
+ ).token,
+ [DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME]: applicationAccessToken.token,
[DEFAULT_API_KEY_NAME]: applicationAccessToken.token,
[DEFAULT_FUNCTIONS_URL_NAME]: functionsBaseUrl ?? '',
APPLICATION_ID: flatApplication.id,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
new file mode 100644
index 00000000000..5e9f19b7e22
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
@@ -0,0 +1,37 @@
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
+
+const buildMaps = ({ deletedAt }: { deletedAt?: string } = {}) => ({
+ byId: { 'workspace-member-1': { deletedAt: deletedAt ?? null } },
+ idByUserId: { 'user-1': 'workspace-member-1' },
+});
+
+describe('resolveWorkspaceMemberIdForUser', () => {
+ it('should name the member the person holds in this workspace', () => {
+ expect(
+ resolveWorkspaceMemberIdForUser({
+ userId: 'user-1',
+ flatWorkspaceMemberMaps: buildMaps(),
+ }),
+ ).toBe('workspace-member-1');
+ });
+
+ it('should name no member for a person who has none', () => {
+ expect(
+ resolveWorkspaceMemberIdForUser({
+ userId: 'user-2',
+ flatWorkspaceMemberMaps: buildMaps(),
+ }),
+ ).toBeNull();
+ });
+
+ it('should name no member once theirs is soft deleted', () => {
+ expect(
+ resolveWorkspaceMemberIdForUser({
+ userId: 'user-1',
+ flatWorkspaceMemberMaps: buildMaps({
+ deletedAt: '2026-01-01T00:00:00.000Z',
+ }),
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util.ts
new file mode 100644
index 00000000000..c53524564a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util.ts
@@ -0,0 +1,25 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatWorkspaceMemberMaps } from 'src/engine/core-modules/user/types/flat-workspace-member-maps.type';
+import { type FlatWorkspaceMember } from 'src/engine/core-modules/user/types/flat-workspace-member.type';
+
+export const resolveWorkspaceMemberIdForUser = ({
+ userId,
+ flatWorkspaceMemberMaps,
+}: {
+ userId: string;
+ flatWorkspaceMemberMaps: {
+ byId: Partial<Record<string, Pick<FlatWorkspaceMember, 'deletedAt'>>>;
+ idByUserId: FlatWorkspaceMemberMaps['idByUserId'];
+ };
+}): string | null => {
+ const workspaceMemberId = flatWorkspaceMemberMaps.idByUserId[userId];
+
+ if (!isDefined(workspaceMemberId)) {
+ return null;
+ }
+
+ const workspaceMember = flatWorkspaceMemberMaps.byId[workspaceMemberId];
+
+ return isDefined(workspaceMember?.deletedAt) ? null : workspaceMemberId;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job.ts
index e89762a46da..ebcd34c5cd6 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job.ts
@@ -61,7 +61,7 @@ export class LogicFunctionTriggerJob {
payload: logicFunctionPayload.payload ?? {},
userId: logicFunctionPayload.userId,
userWorkspaceId: logicFunctionPayload.userWorkspaceId,
- context: { retryCount, maxRetries },
+ retry: { retryCount, maxRetries },
});
if (
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
index 483427c0781..cf10b7b2a18 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
@@ -42,6 +42,39 @@ const createMockWorkspaceEventBatch = (
});
describe('transformEventBatchToEventPayloads', () => {
+ describe('triggering person', () => {
+ it('should name the person whose mutation raised the event', () => {
+ const workspaceEventBatch = createMockWorkspaceEventBatch({
+ events: [
+ createMockEvent({
+ userId: 'user-1',
+ userWorkspaceId: 'user-workspace-1',
+ }),
+ ],
+ });
+
+ const [jobData] = transformEventBatchToEventPayloads({
+ workspaceEventBatch,
+ logicFunctions: [createMockLogicFunction()],
+ });
+
+ expect(jobData).toMatchObject({
+ userId: 'user-1',
+ userWorkspaceId: 'user-workspace-1',
+ });
+ });
+
+ it('should name nobody for a mutation with no user behind it', () => {
+ const [jobData] = transformEventBatchToEventPayloads({
+ workspaceEventBatch: createMockWorkspaceEventBatch(),
+ logicFunctions: [createMockLogicFunction()],
+ });
+
+ expect(jobData).not.toHaveProperty('userId');
+ expect(jobData).not.toHaveProperty('userWorkspaceId');
+ });
+ });
+
describe('basic transformation', () => {
it('should transform a single event batch with a single logic function', () => {
const workspaceEventBatch = createMockWorkspaceEventBatch();
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
index 62a39ac7ad9..3ecb04777f7 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
@@ -37,6 +37,10 @@ export const transformEventBatchToEventPayloads = ({
logicFunctionId: logicFunction.id,
workspaceId: logicFunction.workspaceId,
payload,
+ ...(isDefined(event.userId) ? { userId: event.userId } : {}),
+ ...(isDefined(event.userWorkspaceId)
+ ? { userWorkspaceId: event.userWorkspaceId }
+ : {}),
});
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
index 78b8b39fa03..6c8b76b1e0d 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
@@ -289,6 +289,8 @@ export class ToolExecutorService {
logicFunctionId: ref.logicFunctionId,
workspaceId: context.workspaceId,
payload: args,
+ userId: context.userId,
+ userWorkspaceId: context.userWorkspaceId,
});
if (result.error) {
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
index 91228c41004..676887afce4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
@@ -9,6 +9,9 @@ import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorato
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';
+import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { FeatureFlagGuard } from 'src/engine/guards/feature-flag.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
@@ -174,12 +177,16 @@ export class LogicFunctionResolver {
async executeOneLogicFunction(
@Args('input') { id, payload }: ExecuteOneLogicFunctionInput,
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthUser() { id: userId }: AuthContextUser,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
): Promise<LogicFunctionExecutionResultDTO> {
try {
return await this.logicFunctionFromSourceService.executeOneFromSource({
id,
payload,
workspaceId,
+ userId,
+ userWorkspaceId,
});
} catch (error) {
return logicFunctionGraphQLApiExceptionHandler(error);
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
index 6e1f0122bd1..6b553f599ef 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
@@ -348,10 +348,14 @@ export class LogicFunctionFromSourceService {
id,
payload,
workspaceId,
+ userId,
+ userWorkspaceId,
}: {
id: string;
payload: object;
workspaceId: string;
+ userId?: string;
+ userWorkspaceId?: string;
}): Promise<LogicFunctionExecutionResultDTO> {
const { flatLogicFunction } =
await this.helperService.findLogicFunctionAndApplicationOrThrow({
@@ -367,6 +371,8 @@ export class LogicFunctionFromSourceService {
logicFunctionId: id,
workspaceId,
payload,
+ userId,
+ userWorkspaceId,
executionMode: LogicFunctionExecutionMode.LIVE,
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/get-user-from-auth-context.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/get-user-from-auth-context.util.spec.ts
new file mode 100644
index 00000000000..9070e032acc
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/get-user-from-auth-context.util.spec.ts
@@ -0,0 +1,28 @@
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';
+
+describe('getUserFromAuthContext', () => {
+ it('should name the person a run acts on behalf of', () => {
+ expect(
+ getUserFromAuthContext({
+ type: 'user',
+ workspace: { id: 'workspace-1' },
+ user: { id: 'user-1' },
+ userWorkspaceId: 'user-workspace-1',
+ } as WorkspaceAuthContext),
+ ).toEqual({
+ userId: 'user-1',
+ userWorkspaceId: 'user-workspace-1',
+ });
+ });
+
+ it('should name nobody for a run the application owns', () => {
+ expect(
+ getUserFromAuthContext({
+ type: 'application',
+ workspace: { id: 'workspace-1' },
+ application: { id: 'app-1' },
+ } as WorkspaceAuthContext),
+ ).toEqual({});
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts
new file mode 100644
index 00000000000..9b0364f9670
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts
@@ -0,0 +1,14 @@
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+// Spread into a logic function execution call: a run started by the platform
+// rather than by a person contributes nothing rather than null fields.
+export const getUserFromAuthContext = (
+ authContext: WorkspaceAuthContext,
+): { userId?: string; userWorkspaceId?: string } =>
+ isUserAuthContext(authContext)
+ ? {
+ userId: authContext.user.id,
+ userWorkspaceId: authContext.userWorkspaceId,
+ }
+ : {};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
index aa6303056ef..55c0ab75360 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
@@ -1,12 +1,26 @@
import { Module } from '@nestjs/common';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { LogicFunctionModule } from 'src/engine/core-modules/logic-function/logic-function.module';
+import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
+import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
+import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
+import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { CodeWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@Module({
- imports: [LogicFunctionModule, WorkflowRunModule],
- providers: [CodeWorkflowAction],
+ imports: [
+ ApplicationModule,
+ LogicFunctionModule,
+ WorkflowRunModule,
+ UserWorkspaceModule,
+ UserRoleModule,
+ RoleModule,
+ WorkflowCommonModule,
+ ],
+ providers: [WorkflowExecutionContextService, CodeWorkflowAction],
exports: [CodeWorkflowAction],
})
export class CodeActionModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
index ebb67722967..fc96b5de8b9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
@@ -6,6 +6,8 @@ import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/inte
import { type LogicFunctionExecuteResult } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -24,6 +26,7 @@ export class CodeWorkflowAction implements WorkflowAction {
constructor(
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
+ private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,
) {}
@@ -52,10 +55,14 @@ export class CodeWorkflowAction implements WorkflowAction {
const { workspaceId } = runInfo;
+ const { authContext } =
+ await this.workflowExecutionContextService.getExecutionContext(runInfo);
+
const result = await this.logicFunctionExecutorService.execute({
logicFunctionId: workflowActionInput.logicFunctionId,
workspaceId,
payload: workflowActionInput.logicFunctionInput,
+ ...getUserFromAuthContext(authContext),
});
await this.persistStepLog({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module.ts
index 38cdf996d31..e850e1d42f0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module.ts
@@ -1,11 +1,28 @@
import { Module } from '@nestjs/common';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { LogicFunctionModule } from 'src/engine/core-modules/logic-function/logic-function.module';
+import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
+import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
+import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
+import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { LogicFunctionWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action';
+import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@Module({
- imports: [WorkspaceManyOrAllFlatEntityMapsCacheModule],
- providers: [LogicFunctionWorkflowAction],
+ imports: [
+ ApplicationModule,
+ LogicFunctionModule,
+ WorkspaceManyOrAllFlatEntityMapsCacheModule,
+ WorkflowRunModule,
+ UserWorkspaceModule,
+ UserRoleModule,
+ RoleModule,
+ WorkflowCommonModule,
+ ],
+ providers: [WorkflowExecutionContextService, LogicFunctionWorkflowAction],
exports: [LogicFunctionWorkflowAction],
})
export class LogicFunctionActionModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
index acf31b081a2..48abdb2c62b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
@@ -5,6 +5,8 @@ import { isDefined, resolveInput } from 'twenty-shared/utils';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import {
@@ -21,6 +23,7 @@ import { WorkflowLogicFunctionActionInput } from 'src/modules/workflow/workflow-
export class LogicFunctionWorkflowAction implements WorkflowAction {
constructor(
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
+ private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
) {}
@@ -76,10 +79,14 @@ export class LogicFunctionWorkflowAction implements WorkflowAction {
);
}
+ const { authContext } =
+ await this.workflowExecutionContextService.getExecutionContext(runInfo);
+
const result = await this.logicFunctionExecutorService.execute({
logicFunctionId: workflowActionInput.logicFunctionId,
workspaceId,
payload: workflowActionInput.logicFunctionInput,
+ ...getUserFromAuthContext(authContext),
});
if (result.error) {
diff --git a/packages/twenty-shared/src/application/constants/DefaultAppApplicationAccessTokenName.ts b/packages/twenty-shared/src/application/constants/DefaultAppApplicationAccessTokenName.ts
new file mode 100644
index 00000000000..1f2e06eb259
--- /dev/null
+++ b/packages/twenty-shared/src/application/constants/DefaultAppApplicationAccessTokenName.ts
@@ -0,0 +1,2 @@
+export const DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME =
+ 'TWENTY_APP_APPLICATION_ACCESS_TOKEN';
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 504a67fd233..3dd550c7054 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -35,6 +35,7 @@ export { ASSETS_DIR } from './constants/AssetDirectory';
export { DEFAULT_API_KEY_NAME } from './constants/DefaultApiKeyName';
export { DEFAULT_API_URL_NAME } from './constants/DefaultApiUrlName';
export { DEFAULT_APP_ACCESS_TOKEN_NAME } from './constants/DefaultAppAccessTokenName';
+export { DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME } from './constants/DefaultAppApplicationAccessTokenName';
export { DEFAULT_FUNCTIONS_URL_NAME } from './constants/DefaultFunctionsUrlName';
export { FRONT_COMPONENT_SHARED_DEPENDENCIES_BUILT_PATH } from './constants/FrontComponentSharedDependenciesBuiltPath';
export { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from './constants/FrontComponentSharedDependenciesImportSpecifier';
diff --git a/packages/twenty-shared/src/logic-function/index.ts b/packages/twenty-shared/src/logic-function/index.ts
index c0a499cc181..e0bef1ffb89 100644
--- a/packages/twenty-shared/src/logic-function/index.ts
+++ b/packages/twenty-shared/src/logic-function/index.ts
@@ -18,7 +18,10 @@ export { inputSchemaToOutputSchema } from './input-schema-to-output-schema';
export { isRecordArraySchema } from './is-record-array-schema';
export { isRecordObjectSchema } from './is-record-object-schema';
export { jsonSchemaToInputSchema } from './json-schema-to-input-schema';
-export type { LogicFunctionExecutionContext } from './logic-function-execution-context.type';
+export type {
+ LogicFunctionExecutionContext,
+ LogicFunctionRetryContext,
+} from './logic-function-execution-context.type';
export {
RETRYABLE_LOGIC_FUNCTION_ERROR_NAME,
RetryableLogicFunctionError,
diff --git a/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts b/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
index 19d20e1d9c9..7bcaae4727e 100644
--- a/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
+++ b/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
@@ -1,4 +1,14 @@
export type LogicFunctionExecutionContext = {
retryCount: number;
maxRetries: number;
+ workspaceId: string;
+ // Null when nobody triggered the run: cron, install hooks and
+ // unauthenticated webhooks have no person behind them.
+ userWorkspaceId: string | null;
+ workspaceMemberId: string | null;
};
+
+export type LogicFunctionRetryContext = Pick<
+ LogicFunctionExecutionContext,
+ 'retryCount' | 'maxRetries'
+>;