diff --git a/.env.example b/.env.example index dd93a424d8..aef487688a 100644 --- a/.env.example +++ b/.env.example @@ -36,6 +36,16 @@ MONGO_URI=mongodb://127.0.0.1:27017/LibreChat # CHANNEL_TENANT_ID=_ # Socket Mode app-level token; the bot token is entered through Agent Channel setup. # SLACK_APP_TOKEN= +# Shared workspace setup: add docker-compose.slack-workspaces.yml after the Channels overlay. +# Requires public HTTPS DOMAIN_SERVER/DOMAIN_CLIENT (replace the localhost defaults below) +# and transaction-capable MongoDB. For bundled MongoDB, +# also add docker-compose.mongo-replica.yml after following the existing-data guidance. +# This opt-in enables webhook Channels and stored background Responses; unrelated YAML policy stays intact. +# SLACK_WORKSPACES_ENABLED=true +# Host HTTPS proxies reach the shared gateway at 127.0.0.1:3081 by default. +# CHANNEL_GATEWAY_PORT=3081 +# Organization admins register Slack apps and install workspaces in the LibreChat UI. +# SLACK_GATEWAY_URL=https://slack.example.com #The maximum number of connections in the connection pool. */ MONGO_MAX_POOL_SIZE= #The minimum number of connections in the connection pool. */ diff --git a/.github/scripts/test-channel-compose.mjs b/.github/scripts/test-channel-compose.mjs index c5d54b032f..54e13306a2 100644 --- a/.github/scripts/test-channel-compose.mjs +++ b/.github/scripts/test-channel-compose.mjs @@ -10,6 +10,7 @@ const fixture = mkdtempSync(join(tmpdir(), 'channel-compose-')); for (const file of [ 'docker-compose.yml', 'docker-compose.channels.yml', + 'docker-compose.slack-workspaces.yml', 'docker-compose.channels-build.yml', 'docker-compose.mongo-replica.yml', '.env.example', @@ -19,8 +20,9 @@ for (const file of [ copyFileSync(join(root, '.env.example'), join(fixture, '.env')); process.on('exit', () => rmSync(fixture, { recursive: true, force: true })); -function configuration(tag, source = false) { +function configuration(tag, source = false, shared = false, gatewayPort) { const files = ['docker-compose.yml', 'docker-compose.channels.yml']; + if (shared) files.push('docker-compose.slack-workspaces.yml'); if (source) { files.push('docker-compose.channels-build.yml'); } @@ -42,7 +44,21 @@ function configuration(tag, source = false) { { cwd: fixture, encoding: 'utf8', - env: { ...process.env, UID: '1000', GID: '1000', LIBRECHAT_IMAGE_TAG: tag }, + env: { + ...process.env, + UID: '1000', + GID: '1000', + LIBRECHAT_IMAGE_TAG: tag, + SLACK_APP_ID: 'A123', + SLACK_CLIENT_ID: '123.456', + SLACK_CLIENT_SECRET: 'fixture-client-secret', + SLACK_SIGNING_SECRET: 'fixture-signature', + SLACK_GATEWAY_URL: 'https://slack.example.test', + CHANNEL_ID: 'legacy-connection', + CHANNEL_TENANT_ID: 'org.a', + SLACK_APP_TOKEN: 'xapp-fixture', + CHANNEL_GATEWAY_PORT: gatewayPort ?? '', + }, }, ), ).services; @@ -71,3 +87,37 @@ assert.equal(source['channel-gateway'].build.dockerfile, 'packages/channel-gatew assert.equal(source.api.pull_policy, 'build'); assert.equal(source['channel-gateway'].pull_policy, 'build'); console.log('PASS: release tags match, releases need no build, source builds remain explicit'); + +for (const source of [false, true]) { + const shared = configuration('v1.2.3-rc1', source, true); + assert.equal(shared.api.environment.SLACK_WORKSPACES_ENABLED, 'true'); + assert.equal(shared.api.environment.SLACK_GATEWAY_URL, 'https://slack.example.test'); + const gateway = shared['channel-gateway']; + for (const name of [ + 'SLACK_APP_ID', + 'SLACK_CLIENT_ID', + 'SLACK_CLIENT_SECRET', + 'SLACK_SIGNING_SECRET', + ]) { + assert.equal(shared.api.environment[name], undefined, `${name} is configured in the UI`); + assert.equal(gateway.environment[name], undefined, `${name} is configured in the UI`); + } + assert.equal(gateway.environment.CHANNEL_ID, ''); + assert.equal(gateway.environment.CHANNEL_TENANT_ID, '_'); + assert.equal(gateway.environment.SLACK_APP_TOKEN, ''); + assert.equal(gateway.depends_on.api.condition, 'service_healthy'); + assert.deepEqual(gateway.ports, [ + { + mode: 'ingress', + host_ip: '127.0.0.1', + target: 8080, + published: '3081', + protocol: 'tcp', + }, + ]); +} +assert.equal( + configuration('v1.2.3', false, true, '3999')['channel-gateway'].ports[0].published, + '3999', +); +console.log('PASS: shared Compose needs no app credentials and clears all bound-gateway settings'); diff --git a/.github/workflows/channel-gateway.yml b/.github/workflows/channel-gateway.yml index 45e792982a..774009fe83 100644 --- a/.github/workflows/channel-gateway.yml +++ b/.github/workflows/channel-gateway.yml @@ -11,6 +11,7 @@ on: - '.dockerignore' - 'docker-compose.yml' - 'docker-compose.channels.yml' + - 'docker-compose.slack-workspaces.yml' - 'docker-compose.channels-build.yml' - '.github/scripts/test-channel-compose.mjs' - '.github/scripts/test-channel-release.mjs' @@ -33,6 +34,7 @@ on: - '.dockerignore' - 'docker-compose.yml' - 'docker-compose.channels.yml' + - 'docker-compose.slack-workspaces.yml' - 'docker-compose.channels-build.yml' - '.github/scripts/test-channel-compose.mjs' - '.github/scripts/test-channel-release.mjs' diff --git a/api/server/services/Config/app.js b/api/server/services/Config/app.js index 4a56f6d61c..2b00e5b7e1 100644 --- a/api/server/services/Config/app.js +++ b/api/server/services/Config/app.js @@ -5,6 +5,7 @@ const { isEnabled, expandCustomEndpoint, createAppConfigService, + applySlackWorkspaceEnvironment, applyLoadedConfig, clearMcpConfigCache, createCodeEnvironmentRegistry, @@ -48,7 +49,12 @@ const loadBaseConfig = async (mode) => { adminIncluded: config.includedTools, directory: paths.structuredTools, }); - return AppService({ config, paths, systemTools, expandCustomEndpoint }); + return AppService({ + config: applySlackWorkspaceEnvironment(config, process.env), + paths, + systemTools, + expandCustomEndpoint, + }); }; const appConfigService = createAppConfigService({ diff --git a/docker-compose.slack-workspaces.yml b/docker-compose.slack-workspaces.yml new file mode 100644 index 0000000000..88b1f1ecc4 --- /dev/null +++ b/docker-compose.slack-workspaces.yml @@ -0,0 +1,19 @@ +# Add after docker-compose.channels.yml for UI-managed workspace installations. +# Requires public HTTPS DOMAIN_SERVER/DOMAIN_CLIENT, not the localhost defaults, +# and transaction-capable MongoDB. For bundled +# MongoDB, also add docker-compose.mongo-replica.yml; read the existing-data +# conversion instructions before applying it to an existing database. +# Slack app credentials are registered by organization admins in LibreChat, not in .env. +# Setup: https://www.librechat.ai/docs/features/agent_channels +services: + api: + environment: + SLACK_WORKSPACES_ENABLED: 'true' + SLACK_GATEWAY_URL: ${SLACK_GATEWAY_URL:-} + channel-gateway: + ports: + - '127.0.0.1:${CHANNEL_GATEWAY_PORT:-3081}:8080' + environment: + CHANNEL_ID: '' + CHANNEL_TENANT_ID: '_' + SLACK_APP_TOKEN: '' diff --git a/helm/librechat/Chart.yaml b/helm/librechat/Chart.yaml index 28a516ab8c..238221ff3d 100755 --- a/helm/librechat/Chart.yaml +++ b/helm/librechat/Chart.yaml @@ -15,7 +15,7 @@ type: application # This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 3.1.0 +version: 3.2.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to diff --git a/helm/librechat/templates/channel-gateway.yaml b/helm/librechat/templates/channel-gateway.yaml index 68da276402..1f707c80ef 100644 --- a/helm/librechat/templates/channel-gateway.yaml +++ b/helm/librechat/templates/channel-gateway.yaml @@ -7,6 +7,17 @@ {{- if and (eq $mode "shared") (or $gateway.channelId (ne $gateway.tenantId "_")) }} {{- fail "Shared gateway mode requires an empty channelId and the default tenantId _" }} {{- end }} +{{- $externalMongo := or (get (default dict .Values.librechat.configEnv) "MONGO_URI") (include "librechat.userEnvHas" (dict "root" . "name" "MONGO_URI")) (eq (toString (default dict .Values.librechat.injectBundledCredentials).mongodb) "false") }} +{{- if and (eq $mode "shared") .Values.mongodb.enabled (not $externalMongo) (ne (.Values.mongodb.architecture | default "standalone") "replicaset") }} +{{- fail "Shared Slack workspaces require transaction-capable MongoDB: set mongodb.architecture=replicaset, or configure an external transaction-capable MONGO_URI" }} +{{- end }} +{{- $replicas := $gateway.replicaCount | toString }} +{{- if not (regexMatch "^[1-9][0-9]*$" $replicas) }} +{{- fail "channelGateway.replicaCount must be a positive integer" }} +{{- end }} +{{- if and (eq $mode "single") (ne $replicas "1") }} +{{- fail "Single gateway mode requires channelGateway.replicaCount: 1" }} +{{- end }} {{- $tag := include "librechat.channelGateway.imageTag" . }} {{- $secret := required "channelGateway.existingSecretName or global.librechat.existingSecretName is required" ($gateway.existingSecretName | default .Values.global.librechat.existingSecretName) }} apiVersion: apps/v1 @@ -20,9 +31,16 @@ metadata: {{- toYaml . | nindent 4 }} {{- end }} spec: - replicas: 1 + replicas: {{ $replicas }} strategy: + {{- if eq $mode "shared" }} + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + {{- else }} type: Recreate + {{- end }} selector: matchLabels: {{- include "librechat.channelGateway.selectorLabels" . | nindent 6 }} diff --git a/helm/librechat/templates/configmap-env.yaml b/helm/librechat/templates/configmap-env.yaml index 2cd7b39b14..27ad664559 100755 --- a/helm/librechat/templates/configmap-env.yaml +++ b/helm/librechat/templates/configmap-env.yaml @@ -38,6 +38,14 @@ data: {{- end }} LANGFUSE_FANOUT_TENANT_DESTINATIONS: {{ join "," $tenantDestinations | quote }} {{- end }} + {{- if and .Values.channelGateway.enabled (eq .Values.channelGateway.mode "shared") }} + {{- if not (hasKey $configEnv "SLACK_WORKSPACES_ENABLED") }} + SLACK_WORKSPACES_ENABLED: "true" + {{- end }} + {{- if and .Values.channelGateway.ingress.enabled (not (hasKey $configEnv "SLACK_GATEWAY_URL")) }} + SLACK_GATEWAY_URL: {{ printf "https://%s" (required "channelGateway.ingress.host is required" .Values.channelGateway.ingress.host) | quote }} + {{- end }} + {{- end }} {{- if $configEnv }} {{- $renderedConfigEnv := $configEnv }} {{- if and $adminPanelUrl (hasKey $configEnv "ADMIN_PANEL_URL") (not $configAdminPanelUrl) }} diff --git a/helm/librechat/templates/deployment.yaml b/helm/librechat/templates/deployment.yaml index 5ea75670f4..77f73a1512 100755 --- a/helm/librechat/templates/deployment.yaml +++ b/helm/librechat/templates/deployment.yaml @@ -1,3 +1,4 @@ +{{- $sharedSlack := and .Values.channelGateway.enabled (eq .Values.channelGateway.mode "shared") -}} apiVersion: apps/v1 kind: Deployment metadata: @@ -86,11 +87,23 @@ spec: optional: false {{- end }} {{- include "librechat.validateBundledPasswords" . }} - {{- if or (include "librechat.bundledMongoAuth" .) (include "librechat.bundledRedisAuth" .) .Values.global.librechat.env }} + {{- if or (include "librechat.bundledMongoAuth" .) (include "librechat.bundledRedisAuth" .) .Values.global.librechat.env $sharedSlack }} env: {{- with .Values.global.librechat.env }} {{- toYaml . | nindent 12 }} {{- end }} + {{- if $sharedSlack }} + {{- $configEnv := default dict .Values.librechat.configEnv }} + {{- $key := "CHANNEL_SERVICE_TOKEN" }} + {{- if not (or (include "librechat.userEnvHas" (dict "root" $ "name" $key)) (hasKey $configEnv $key)) }} + {{- $secret := .Values.channelGateway.existingSecretName | default .Values.global.librechat.existingSecretName }} + - name: {{ $key }} + valueFrom: + secretKeyRef: + name: {{ required "Shared Slack setup requires a service token Secret or explicit API environment" $secret | quote }} + key: {{ $key }} + {{- end }} + {{- end }} {{- if include "librechat.bundledMongoAuth" . }} {{- if not (include "librechat.userEnvHas" (dict "root" . "name" "MONGODB_ROOT_PASSWORD")) }} - name: MONGODB_ROOT_PASSWORD diff --git a/helm/librechat/tests/channel_gateway_render_test.mjs b/helm/librechat/tests/channel_gateway_render_test.mjs index bf02cf014d..a243643bd4 100644 --- a/helm/librechat/tests/channel_gateway_render_test.mjs +++ b/helm/librechat/tests/channel_gateway_render_test.mjs @@ -12,6 +12,13 @@ const fixture = mkdtempSync(join(tmpdir(), 'channel-gateway-chart-')); try { // Render the real gateway and main Service without downloading unrelated subcharts. mkdirSync(join(fixture, 'templates')); + writeFileSync( + join(fixture, 'templates', '_mongodb.tpl'), + ` +{{- define "mongodb.secretName" -}}fixture-mongodb{{- end -}} +{{- define "mongodb.service.nameOverride" -}}fixture-mongodb{{- end -}} +`, + ); const metadata = yaml.load(readFileSync(resolve(chart, 'Chart.yaml'), 'utf8')); delete metadata.dependencies; writeFileSync(join(fixture, 'Chart.yaml'), yaml.dump(metadata)); @@ -83,6 +90,34 @@ try { 'channelGateway.mode': 'shared', 'channelGateway.channelId': '', }; + assert.throws( + () => render({ ...shared, 'mongodb.enabled': true }), + /transaction-capable MongoDB/, + ); + assert.throws( + () => render({ ...shared, 'mongodb.enabled': true, 'mongodb.architecture': 'standalone' }), + /transaction-capable MongoDB/, + ); + assert.doesNotThrow(() => + render({ ...shared, 'mongodb.enabled': true, 'mongodb.architecture': 'replicaset' }), + ); + for (const platform of [ + { librechat: { configEnv: { MONGO_URI: 'mongodb://external/LibreChat' } } }, + { + global: { + librechat: { + env: [ + { name: 'MONGO_URI', valueFrom: { secretKeyRef: { name: 'external-db', key: 'uri' } } }, + ], + }, + }, + }, + { + librechat: { injectBundledCredentials: { mongodb: false } }, + global: { librechat: { existingSecretName: 'external-db' } }, + }, + ]) + assert.doesNotThrow(() => render({ ...shared, 'mongodb.enabled': true }, platform)); assert.throws( () => render({ ...shared, 'channelGateway.tenantId': 'org.a' }), /default tenantId/, @@ -105,6 +140,78 @@ try { 'shared', 'rendered shared pods must select the actual shared runtime', ); + assert.equal(sharedDeployment.spec.strategy.type, 'RollingUpdate'); + for (const count of ['0', '-1', '1.5', 'invalid']) + assert.throws( + () => render({ ...shared, 'channelGateway.replicaCount': count }), + /positive integer/, + ); + assert.throws( + () => render({ ...enabled, 'channelGateway.replicaCount': '2' }), + /Single gateway mode/, + ); + const sharedDocs = render( + { ...shared, 'channelGateway.replicaCount': '2' }, + { + channelGateway: { + existingSecretName: 'service-credentials', + ingress: { enabled: true, host: 'slack.example.test' }, + }, + }, + ); + const gatewayPod = sharedDocs.find( + (doc) => doc.kind === 'Deployment' && doc.metadata.name === sharedDeployment.metadata.name, + ); + assert.equal(gatewayPod.spec.replicas, 2); + assert.deepEqual(gatewayPod.spec.strategy.rollingUpdate, { maxSurge: 1, maxUnavailable: 0 }); + const apiPod = sharedDocs.find((doc) => doc.kind === 'Deployment' && doc !== gatewayPod); + const apiEnv = Object.fromEntries( + apiPod.spec.template.spec.containers[0].env.map((entry) => [entry.name, entry]), + ); + assert.equal(apiEnv.CHANNEL_SERVICE_TOKEN.valueFrom.secretKeyRef.name, 'service-credentials'); + for (const key of [ + 'SLACK_APP_ID', + 'SLACK_CLIENT_ID', + 'SLACK_CLIENT_SECRET', + 'SLACK_SIGNING_SECRET', + ]) + assert.equal( + apiEnv[key], + undefined, + 'organization app credentials must not be injected by the chart', + ); + const appDefaults = sharedDocs.find( + (doc) => doc.kind === 'ConfigMap' && doc.metadata.name.endsWith('-configenv'), + ).data; + assert.equal(appDefaults.SLACK_WORKSPACES_ENABLED, 'true'); + assert.equal(appDefaults.SLACK_GATEWAY_URL, 'https://slack.example.test'); + const gatewaySecrets = gatewayPod.spec.template.spec.containers[0].env.filter( + (entry) => entry.valueFrom, + ); + assert.deepEqual( + gatewaySecrets.map((entry) => entry.name), + ['CHANNEL_SERVICE_TOKEN'], + ); + const explicit = render(shared, { + global: { + librechat: { + env: [ + { + name: 'CHANNEL_SERVICE_TOKEN', + valueFrom: { secretKeyRef: { name: 'explicit', key: 'service' } }, + }, + ], + }, + }, + }).find( + (doc) => doc.kind === 'Deployment' && doc.metadata.name !== sharedDeployment.metadata.name, + ); + const explicitEnv = explicit.spec.template.spec.containers[0].env; + assert.equal(explicitEnv.filter((entry) => entry.name === 'CHANNEL_SERVICE_TOKEN').length, 1); + assert.equal( + explicitEnv.find((entry) => entry.name === 'CHANNEL_SERVICE_TOKEN').valueFrom.secretKeyRef.name, + 'explicit', + ); assert.throws( () => render({ ...enabled, 'global.librechat.existingSecretName': '' }), /existingSecretName/, diff --git a/helm/librechat/values.yaml b/helm/librechat/values.yaml index 18855ca4a6..501e7633eb 100755 --- a/helm/librechat/values.yaml +++ b/helm/librechat/values.yaml @@ -298,8 +298,10 @@ updateStrategy: channelGateway: enabled: false # single binds a manually configured connection; shared serves installed workspaces. - # Shared mode requires webhook transport and slackApp configuration in librechat.yaml. + # Shared mode enables webhook transport; organization admins register apps in the UI. mode: single + # Shared workers use durable leases and may run across replicas; single mode requires 1. + replicaCount: 1 image: repository: ghcr.io/librechat-ai/librechat-channel-gateway # Defaults to image.tag, which must explicitly select a release containing Channels. diff --git a/packages/api/src/channels/deployment.spec.ts b/packages/api/src/channels/deployment.spec.ts new file mode 100644 index 0000000000..fe459650c5 --- /dev/null +++ b/packages/api/src/channels/deployment.spec.ts @@ -0,0 +1,143 @@ +import '~/mcp/registry/__tests__/helpers/setupCredsEnv'; +import mongoose from 'mongoose'; +import { resolve } from 'node:path'; +import { parseEnv } from 'node:util'; +import { readFileSync } from 'node:fs'; +import { agentsEndpointSchema } from 'librechat-data-provider'; +import { AppService, createSlackWorkspaceStorage } from '@librechat/data-schemas'; +import type { TCustomConfig } from 'librechat-data-provider'; +import { createSlackWorkspaceSettingsReader } from './workspaceRuntime'; +import { applySlackWorkspaceEnvironment } from './deployment'; + +const environment = { + SLACK_WORKSPACES_ENABLED: 'true', + SLACK_GATEWAY_URL: 'https://slack.example.com', + DOMAIN_SERVER: 'https://chat.example.com/librechat', + DOMAIN_CLIENT: 'https://client.example.com/librechat', +}; + +describe('shared Slack deployment setup', () => { + it('rejects the active localhost defaults shipped in .env.example', () => { + const defaults = parseEnv(readFileSync(resolve(__dirname, '../../../../.env.example'), 'utf8')); + expect(() => + applySlackWorkspaceEnvironment( + {}, + { + ...environment, + DOMAIN_SERVER: defaults.DOMAIN_SERVER, + DOMAIN_CLIENT: defaults.DOMAIN_CLIENT, + }, + ), + ).toThrow('public HTTPS'); + const ordinary = {}; + expect(applySlackWorkspaceEnvironment(ordinary, defaults)).toBe(ordinary); + }); + + it('accepts a public hostname starting with an IP-range prefix', () => { + expect(() => + applySlackWorkspaceEnvironment( + {}, + { + ...environment, + DOMAIN_SERVER: 'https://fc.example.com/librechat', + }, + ), + ).not.toThrow(); + }); + + describe.each(['DOMAIN_SERVER', 'DOMAIN_CLIENT', 'SLACK_GATEWAY_URL'] as const)('%s', (field) => { + it.each([ + 'http://chat.example.com', + 'https://localhost', + 'https://localhost.', + 'https://chat.localhost', + 'https://127.1', + 'https://2130706433', + 'https://[::1]', + 'https://[::ffff:127.0.0.1]', + 'https://10.0.0.1', + ' https://chat.example.com', + 'https://chat.example.com ', + 'https://chat.example.com\n', + ])('rejects a nonpublic installation URL: %s', (value) => { + expect(() => applySlackWorkspaceEnvironment({}, { ...environment, [field]: value })).toThrow( + 'public HTTPS', + ); + }); + }); + + it.each([undefined, '', 'false'])( + 'leaves ordinary and manual setup unchanged when %s', + (enabled) => { + const config = { endpoints: { agents: agentsEndpointSchema.parse({}) } }; + expect( + applySlackWorkspaceEnvironment(config, { + ...environment, + SLACK_WORKSPACES_ENABLED: enabled, + }), + ).toBe(config); + }, + ); + + it('feeds the real base configuration and settings reader while preserving other policy', async () => { + const config: Partial = { + secureImageLinks: false, + endpoints: { + agents: agentsEndpointSchema.parse({ + channels: { maxMetadataPageSize: 17, slackApp: { gateway: { workerConcurrency: 2 } } }, + remoteApi: { + auth: { apiKey: { enabled: false } }, + background: { acknowledgementTimeoutMs: 7000 }, + }, + }), + }, + }; + const configured = applySlackWorkspaceEnvironment(config, environment); + const appConfig = await AppService({ config: configured }); + expect(configured.secureImageLinks).toBe(false); + expect(config.endpoints?.agents?.channels?.enabled).toBe(false); + expect(appConfig.endpoints?.agents?.remoteApi).toEqual({ + auth: { apiKey: { enabled: false } }, + background: { enabled: true, acknowledgementTimeoutMs: 7000 }, + }); + const read = createSlackWorkspaceSettingsReader({ + storage: createSlackWorkspaceStorage(new mongoose.Mongoose()), + readAppConfig: async () => appConfig, + publicBaseUrl: environment.DOMAIN_SERVER, + clientBaseUrl: 'https://client.example.com/librechat', + }); + const settings = await read(); + expect(settings.channels.maxMetadataPageSize).toBe(17); + expect(settings.channels.slackApp?.gateway.workerConcurrency).toBe(2); + expect(settings.app).toBeUndefined(); + expect(settings.channels.slackApp).not.toHaveProperty('clientSecret'); + expect(settings.channels.slackApp).not.toHaveProperty('signingSecret'); + }); + + it('preserves YAML runtime policy without requiring app credentials', () => { + const first = applySlackWorkspaceEnvironment({}, environment); + const second = applySlackWorkspaceEnvironment(first, { + SLACK_WORKSPACES_ENABLED: 'true', + DOMAIN_SERVER: environment.DOMAIN_SERVER, + DOMAIN_CLIENT: environment.DOMAIN_CLIENT, + }); + expect(second.endpoints?.agents?.channels?.slackApp).toEqual( + first.endpoints?.agents?.channels?.slackApp, + ); + expect(second.endpoints?.agents?.channels?.gatewayUrl).toBe(environment.SLACK_GATEWAY_URL); + }); + + it.each([ + { DOMAIN_SERVER: undefined }, + { DOMAIN_SERVER: '' }, + { DOMAIN_SERVER: ' ' }, + { DOMAIN_CLIENT: undefined }, + { DOMAIN_CLIENT: '' }, + { DOMAIN_SERVER: 'https://user:sensitive-secret@chat.example.com' }, + { SLACK_GATEWAY_URL: 'https://user:sensitive-secret@slack.example.com' }, + ])('rejects incomplete or invalid setup without echoing values', (override) => { + const run = () => applySlackWorkspaceEnvironment({}, { ...environment, ...override }); + expect(run).toThrow('Invalid shared Slack setup'); + expect(run).not.toThrow('sensitive-secret'); + }); +}); diff --git a/packages/api/src/channels/deployment.ts b/packages/api/src/channels/deployment.ts new file mode 100644 index 0000000000..934544f9af --- /dev/null +++ b/packages/api/src/channels/deployment.ts @@ -0,0 +1,73 @@ +import { isIP } from 'node:net'; +import { agentsEndpointSchema, channelConfigSchema } from 'librechat-data-provider'; +import type { TCustomConfig } from 'librechat-data-provider'; +import { slackPublicURL } from './workspaces'; +import { isPrivateIP } from '~/auth/ip'; +import { isEnabled } from '~/utils'; + +type DeploymentEnvironment = Partial< + Record< + 'SLACK_WORKSPACES_ENABLED' | 'SLACK_GATEWAY_URL' | 'DOMAIN_SERVER' | 'DOMAIN_CLIENT', + string + > +>; + +/** Explicit deployment opt-in supplies shared-app settings without replacing librechat.yaml. */ +export function applySlackWorkspaceEnvironment( + config: Partial, + env: DeploymentEnvironment, +): Partial { + if (!isEnabled(env.SLACK_WORKSPACES_ENABLED)) return config; + const agents = config.endpoints?.agents; + const previous = agents?.channels; + try { + const publicServer = env.DOMAIN_SERVER; + const publicClient = env.DOMAIN_CLIENT; + if (!publicServer || !publicClient) throw new Error('Missing public application URLs'); + const gatewayUrl = env.SLACK_GATEWAY_URL || previous?.gatewayUrl; + for (const value of [publicServer, publicClient, gatewayUrl]) { + if (!value) continue; + if (value !== value.trim()) + throw new Error('Public URLs must not contain surrounding whitespace'); + const url = slackPublicURL(value); + const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, ''); + if ( + url.protocol !== 'https:' || + host === 'localhost' || + host === 'localhost.localdomain' || + host.endsWith('.localhost') || + (isIP(host) && isPrivateIP(host)) + ) + throw new Error('Shared deployment requires public HTTPS URLs'); + } + const channels = channelConfigSchema.parse({ + ...previous, + enabled: true, + transport: 'webhook', + gatewayUrl, + slackApp: { + ...previous?.slackApp, + enabled: true, + }, + }); + return { + ...config, + endpoints: { + ...config.endpoints, + agents: agentsEndpointSchema.parse({ + ...agents, + channels, + remoteApi: { + ...agents?.remoteApi, + background: { ...agents?.remoteApi?.background, enabled: true }, + }, + }), + }, + }; + } catch { + // Schema diagnostics can contain submitted configuration values. + throw new Error( + 'Invalid shared Slack setup. Configure public HTTPS DOMAIN_SERVER and DOMAIN_CLIENT without surrounding whitespace. SLACK_GATEWAY_URL must also use public HTTPS when set. Replace the localhost defaults.', + ); + } +} diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index b90893b5bf..69419260b5 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -162,6 +162,7 @@ export * from './channels/workspaces'; export * from './channels/workspaceHttp'; export * from './channels/workspaceRuntime'; export * from './channels/workspaceBindings'; +export { applySlackWorkspaceEnvironment } from './channels/deployment'; export * from './channels/slackDispatch'; export * from './channels/applicationPolicy'; export * from './channels/applicationAuthority';