mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 05:20:46 +08:00
feat: add unified IM access policies
This commit is contained in:
parent
075d2713c1
commit
840e5aa857
89 changed files with 5573 additions and 1676 deletions
137
plugin-src/host/channels/shared/access-policy-production.mjs
Normal file
137
plugin-src/host/channels/shared/access-policy-production.mjs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import {
|
||||
createAccessPolicy,
|
||||
createAccessPolicyScope,
|
||||
} from '../../../../src/channels/shared/access-policy.mjs';
|
||||
|
||||
function policyUsers(users) {
|
||||
return users.map((id) => ({ id, canExecuteCommands: true }));
|
||||
}
|
||||
|
||||
function openScope(allowlistUsers = []) {
|
||||
return createAccessPolicyScope({
|
||||
mode: 'open',
|
||||
open: {
|
||||
defaultCanExecuteCommands: true,
|
||||
commandPermissionOverrides: [],
|
||||
},
|
||||
allowlist: { users: policyUsers(allowlistUsers) },
|
||||
});
|
||||
}
|
||||
|
||||
function allowlistScope(users = []) {
|
||||
return createAccessPolicyScope({
|
||||
mode: 'allowlist',
|
||||
open: {
|
||||
defaultCanExecuteCommands: false,
|
||||
commandPermissionOverrides: [],
|
||||
},
|
||||
allowlist: { users: policyUsers(users) },
|
||||
});
|
||||
}
|
||||
|
||||
function cleanIds(values) {
|
||||
return [...new Set((Array.isArray(values) ? values : [values])
|
||||
.filter((value) => typeof value === 'string' || typeof value === 'number'
|
||||
|| typeof value === 'bigint')
|
||||
.map((value) => String(value).trim())
|
||||
.filter(Boolean))];
|
||||
}
|
||||
|
||||
function whatsappNumberJids(values) {
|
||||
return cleanIds(values).map((value) => `${value.replace(/^\+/, '')}@s.whatsapp.net`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the one-time, backwards-compatible seed for a bot whose workspace
|
||||
* document does not yet contain an access policy.
|
||||
*/
|
||||
export function initialAccessPolicyFor(channel, config = {}) {
|
||||
const key = String(channel ?? '').trim().toLowerCase();
|
||||
if (key === 'weixin') {
|
||||
return createAccessPolicy({
|
||||
direct: allowlistScope(),
|
||||
group: allowlistScope(),
|
||||
});
|
||||
}
|
||||
if (key === 'feishu') {
|
||||
const owners = cleanIds(config.ownerOpenIds ?? config.ownerOpenId);
|
||||
const scope = owners.includes('*') ? openScope() : allowlistScope();
|
||||
return createAccessPolicy({ direct: scope, group: scope });
|
||||
}
|
||||
if (key === 'qq') {
|
||||
const owners = cleanIds(config.ownerUserOpenid);
|
||||
return createAccessPolicy({
|
||||
direct: owners.includes('*') ? openScope() : allowlistScope(),
|
||||
group: openScope(),
|
||||
});
|
||||
}
|
||||
if (key === 'telegram') {
|
||||
const users = cleanIds(config.allowedUsers);
|
||||
if ((config.accessMode ?? 'compatible') === 'private-allowlist') {
|
||||
return createAccessPolicy({
|
||||
direct: allowlistScope(users),
|
||||
group: allowlistScope(),
|
||||
});
|
||||
}
|
||||
return createAccessPolicy({
|
||||
direct: openScope(users),
|
||||
group: openScope(),
|
||||
});
|
||||
}
|
||||
if (key === 'whatsapp') {
|
||||
const mode = config.accessMode ?? 'self-only';
|
||||
const allowed = whatsappNumberJids(config.allowedNumbers);
|
||||
if (mode === 'open') {
|
||||
return createAccessPolicy({ direct: openScope(allowed), group: openScope() });
|
||||
}
|
||||
return createAccessPolicy({
|
||||
direct: allowlistScope(mode === 'private-allowlist'
|
||||
? allowed
|
||||
: []),
|
||||
group: allowlistScope(),
|
||||
});
|
||||
}
|
||||
if (['dingtalk', 'wecom', 'slack', 'discord'].includes(key)) {
|
||||
return createAccessPolicy({ direct: openScope(), group: openScope() });
|
||||
}
|
||||
throw new TypeError(`Unsupported access-policy channel: ${channel}`);
|
||||
}
|
||||
|
||||
export function privilegedSenderIdsFor(channel, config = {}) {
|
||||
const key = String(channel ?? '').trim().toLowerCase();
|
||||
if (key === 'weixin') return cleanIds(config.ownerUserId);
|
||||
if (key === 'feishu') {
|
||||
return cleanIds(config.ownerOpenIds ?? config.ownerOpenId).filter((id) => id !== '*');
|
||||
}
|
||||
if (key === 'dingtalk') {
|
||||
const approved = Array.isArray(config.approvedSenders) ? config.approvedSenders : [];
|
||||
return cleanIds(approved.map((entry) => entry?.staffId));
|
||||
}
|
||||
if (key === 'qq') return cleanIds(config.ownerUserOpenid).filter((id) => id !== '*');
|
||||
if (key === 'whatsapp') return cleanIds(config.accountJid);
|
||||
return [];
|
||||
}
|
||||
|
||||
export function accessPolicyProvider(workspaces, botId, { channel, config, equals } = {}) {
|
||||
if (!workspaces || typeof workspaces.accessPolicyFor !== 'function') {
|
||||
throw new TypeError('A workspace store with access policies is required');
|
||||
}
|
||||
const privilegedSenderIds = new Set(privilegedSenderIdsFor(channel, config));
|
||||
const sameSender = typeof equals === 'function' ? equals : (left, right) => left === right;
|
||||
return Object.freeze({
|
||||
botId,
|
||||
getSettings: () => workspaces.accessPolicyFor(botId),
|
||||
isPrivileged(senderIds, conversationType) {
|
||||
if (!['direct', 'group'].includes(conversationType)) return false;
|
||||
const candidates = Array.isArray(senderIds) ? senderIds : [senderIds];
|
||||
try {
|
||||
return candidates.some((senderId) => typeof senderId === 'string'
|
||||
&& [...privilegedSenderIds].some((privilegedId) => (
|
||||
sameSender(senderId.trim(), privilegedId) === true
|
||||
)));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
17
plugin-src/host/channels/shared/access-policy-rpc.mjs
Normal file
17
plugin-src/host/channels/shared/access-policy-rpc.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { validateAccessPolicy } from '../../../../src/channels/shared/access-policy.mjs';
|
||||
|
||||
export const SET_ACCESS_POLICY_ENDPOINT = 'bot.access-policy.set';
|
||||
|
||||
export function validAccessPolicyPayload(payload) {
|
||||
try {
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)
|
||||
|| Reflect.ownKeys(payload).length !== 2
|
||||
|| !Object.hasOwn(payload, 'botId') || !Object.hasOwn(payload, 'policy')
|
||||
|| typeof payload.botId !== 'string'
|
||||
|| !/^[A-Za-z0-9_-]{1,128}$/.test(payload.botId)) return false;
|
||||
validateAccessPolicy(payload.policy);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,10 @@ import {
|
|||
createDeliveryAdapter,
|
||||
supportsDeliveryChannel,
|
||||
} from '../../delivery-adapter.mjs';
|
||||
import {
|
||||
accessPolicyProvider,
|
||||
initialAccessPolicyFor,
|
||||
} from './access-policy-production.mjs';
|
||||
|
||||
export function pluginPaths(config, channel) {
|
||||
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
||||
|
|
@ -46,6 +50,11 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
throw new TypeError(`dsh-im ${channel} runtimeOptions must return an object`);
|
||||
}
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
|
||||
const seedAccessPolicy = typeof definitions.initialAccessPolicyForBot === 'function'
|
||||
? definitions.initialAccessPolicyForBot
|
||||
// Telegram is the only token channel with a legacy access model. Other
|
||||
// current token channels preserve their fully-open baseline.
|
||||
: (bot) => initialAccessPolicyFor(channel === 'telegram' ? 'telegram' : 'discord', bot);
|
||||
const logger = typeof ctx.logger === 'function'
|
||||
? ctx.logger(`dsh-im:${channel}`) : (ctx.logger ?? console);
|
||||
const agentPresetCatalog = () => listAgentPresetCatalog(ctx);
|
||||
|
|
@ -59,6 +68,7 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
|
||||
await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
|
||||
defaultAgentPreset: config.agentPreset,
|
||||
initialAccessPolicy: seedAccessPolicy(bot),
|
||||
})));
|
||||
const observedConfigStore = typeof configStore.remove === 'function'
|
||||
? observeBotWorkspaceRemovals(configStore, { workspaces })
|
||||
|
|
@ -96,7 +106,10 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
...(internals.inspectToken ? { inspectToken: internals.inspectToken } : {}),
|
||||
createRuntime: async ({ botId, config: botConfig, token }) => {
|
||||
const state = await stateFor(botId);
|
||||
await workspaces.ensure(botId, { defaultAgentPreset: config.agentPreset });
|
||||
await workspaces.ensure(botId, {
|
||||
defaultAgentPreset: config.agentPreset,
|
||||
initialAccessPolicy: seedAccessPolicy(botConfig),
|
||||
});
|
||||
const workspaceScope = createBotWorkspaceScope(harness, {
|
||||
botId, workspaces, state, agentPresetCatalog,
|
||||
});
|
||||
|
|
@ -107,6 +120,7 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
harness: workspaceScope.harness,
|
||||
state: workspaceScope.state,
|
||||
contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
|
||||
accessPolicy: accessPolicyProvider(workspaces, botId, { channel, config: botConfig }),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
logger: {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from './context-enhancement-rpc.mjs';
|
||||
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from './access-policy-rpc.mjs';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
import { publicConnectionTestResult } from '../../../../src/channels/shared/connection-test.mjs';
|
||||
import {
|
||||
|
|
@ -19,6 +20,7 @@ export const TOKEN_BOT_ENDPOINTS = Object.freeze({
|
|||
setWorkspace: SET_WORKSPACE_ENDPOINT,
|
||||
setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
|
||||
setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
|
||||
setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
|
||||
});
|
||||
|
||||
const ENDPOINTS = Object.freeze(Object.values(TOKEN_BOT_ENDPOINTS));
|
||||
|
|
@ -77,6 +79,10 @@ function payloadFailure(endpoint, payload) {
|
|||
return validContextEnhancementPayload(payload)
|
||||
? null : '请提交有效的上下文增强设置。';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.setAccessPolicy) {
|
||||
return validAccessPolicyPayload(payload)
|
||||
? null : '请提交有效的访问设置。';
|
||||
}
|
||||
return 'Unknown bot endpoint.';
|
||||
}
|
||||
|
||||
|
|
@ -161,6 +167,9 @@ export function createTokenBotRpcHandler(controller, { channel }) {
|
|||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.setContextEnhancement) {
|
||||
if (typeof controller.updateContextEnhancement !== 'function') throw new Error('Context enhancement update is unavailable');
|
||||
value = await controller.updateContextEnhancement(payload.botId, payload.config);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.setAccessPolicy) {
|
||||
if (typeof controller.updateAccessPolicy !== 'function') throw new Error('Access policy update is unavailable');
|
||||
value = await controller.updateAccessPolicy(payload.botId, payload.policy);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.setAgentPreset) {
|
||||
if (typeof controller.updateAgentPreset !== 'function') throw new Error('Agent preset update is unavailable');
|
||||
value = await controller.updateAgentPreset(payload.botId, payload.agentPreset);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue