All files / dingtalk-openclaw-connector/src onboarding.ts

0% Statements 0/328
0% Branches 0/1
0% Functions 0/1
0% Lines 0/328

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import type {
  ChannelOnboardingAdapter,
  ChannelOnboardingDmPolicy,
  ClawdbotConfig,
  DmPolicy,
  SecretInput,
  WizardPrompter,
} from "openclaw/plugin-sdk";
import {
  addWildcardAllowFrom,
  DEFAULT_ACCOUNT_ID,
  formatDocsLink,
  hasConfiguredSecretInput,
} from "./sdk/helpers.ts";
import { promptSingleChannelSecretInput } from "openclaw/plugin-sdk";
import { resolveDingtalkCredentials } from "./config/accounts.ts";
import { probeDingtalk } from "./probe.ts";
import type { DingtalkConfig } from "./types/index.ts";
 
const channel = "dingtalk-connector" as const;
 
function normalizeString(value: unknown): string | undefined {
  if (typeof value === "number") {
    return String(value);
  }
  if (typeof value !== "string") {
    return undefined;
  }
  const trimmed = value.trim();
  return trimmed || undefined;
}
 
function setDingtalkDmPolicy(cfg: ClawdbotConfig, dmPolicy: DmPolicy): ClawdbotConfig {
  const allowFrom =
    dmPolicy === "open"
      ? addWildcardAllowFrom(cfg.channels?.["dingtalk-connector"]?.allowFrom)?.map((entry) => String(entry))
      : undefined;
  return {
    ...cfg,
    channels: {
      ...cfg.channels,
      "dingtalk-connector": {
        ...cfg.channels?.["dingtalk-connector"],
        dmPolicy,
        ...(allowFrom ? { allowFrom } : {}),
      },
    },
  };
}
 
function setDingtalkAllowFrom(cfg: ClawdbotConfig, allowFrom: string[]): ClawdbotConfig {
  return {
    ...cfg,
    channels: {
      ...cfg.channels,
      "dingtalk-connector": {
        ...cfg.channels?.["dingtalk-connector"],
        allowFrom,
      },
    },
  };
}
 
function parseAllowFromInput(raw: string): string[] {
  return raw
    .split(/[\n,;]+/g)
    .map((entry) => entry.trim())
    .filter(Boolean);
}
 
async function promptDingtalkAllowFrom(params: {
  cfg: ClawdbotConfig;
  prompter: WizardPrompter;
}): Promise<ClawdbotConfig> {
  const existing = params.cfg.channels?.["dingtalk-connector"]?.allowFrom ?? [];
  await params.prompter.note(
    [
      "Allowlist DingTalk DMs by user ID.",
      "You can find user ID in DingTalk admin console or via API.",
      "Examples:",
      "- user123456",
      "- user789012",
    ].join("\n"),
    "DingTalk allowlist",
  );
 
  while (true) {
    const entry = await params.prompter.text({
      message: "DingTalk allowFrom (user IDs)",
      placeholder: "user123456, user789012",
      initialValue: existing[0] ? String(existing[0]) : undefined,
      validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
    });
    const parts = parseAllowFromInput(String(entry));
    if (parts.length === 0) {
      await params.prompter.note("Enter at least one user.", "DingTalk allowlist");
      continue;
    }
 
    const unique = [
      ...new Set([
        ...existing.map((v: string | number) => String(v).trim()).filter(Boolean),
        ...parts,
      ]),
    ];
    return setDingtalkAllowFrom(params.cfg, unique);
  }
}
 
async function noteDingtalkCredentialHelp(prompter: WizardPrompter): Promise<void> {
  await prompter.note(
    [
      "1) Go to DingTalk Open Platform (open-dev.dingtalk.com)",
      "2) Create an enterprise internal app",
      "3) Get App Key (Client ID) and App Secret (Client Secret) from Credentials page",
      "4) Enable required permissions: im:message, im:chat",
      "5) Publish the app or add it to a test group",
      "Tip: you can also set DINGTALK_CLIENT_ID / DINGTALK_CLIENT_SECRET env vars.",
      `Docs: ${formatDocsLink("/channels/dingtalk-connector", "dingtalk-connector")}`,
    ].join("\n"),
    "DingTalk credentials",
  );
}
 
async function promptDingtalkClientId(params: {
  prompter: WizardPrompter;
  initialValue?: string;
}): Promise<string> {
  const clientId = String(
    await params.prompter.text({
      message: "Enter DingTalk App Key (Client ID)",
      initialValue: params.initialValue,
      validate: (value) => (value?.trim() ? undefined : "Required"),
    }),
  ).trim();
  return clientId;
}
 
function setDingtalkGroupPolicy(
  cfg: ClawdbotConfig,
  groupPolicy: "open" | "allowlist" | "disabled",
): ClawdbotConfig {
  return {
    ...cfg,
    channels: {
      ...cfg.channels,
      "dingtalk-connector": {
        ...cfg.channels?.["dingtalk-connector"],
        enabled: true,
        groupPolicy,
      },
    },
  };
}
 
function setDingtalkGroupAllowFrom(cfg: ClawdbotConfig, groupAllowFrom: string[]): ClawdbotConfig {
  return {
    ...cfg,
    channels: {
      ...cfg.channels,
      "dingtalk-connector": {
        ...cfg.channels?.["dingtalk-connector"],
        groupAllowFrom,
      },
    },
  };
}
 
const dmPolicy: ChannelOnboardingDmPolicy = {
  label: "DingTalk",
  channel,
  policyKey: "channels.dingtalk-connector.dmPolicy",
  allowFromKey: "channels.dingtalk-connector.allowFrom",
  getCurrent: (cfg) => (cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined)?.dmPolicy ?? "open",
  setPolicy: (cfg, policy) => setDingtalkDmPolicy(cfg, policy),
  promptAllowFrom: promptDingtalkAllowFrom,
};
 
export const dingtalkOnboardingAdapter: ChannelOnboardingAdapter = {
  channel,
  getStatus: async ({ cfg }) => {
    const dingtalkCfg = cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined;
 
    const isClientIdConfigured = (value: unknown): boolean => {
      const asString = normalizeString(value);
      if (asString) {
        return true;
      }
      if (!value || typeof value !== "object") {
        return false;
      }
      const rec = value as Record<string, unknown>;
      const source = normalizeString(rec.source)?.toLowerCase();
      const id = normalizeString(rec.id);
      if (source === "env" && id) {
        return Boolean(normalizeString(process.env[id]));
      }
      return hasConfiguredSecretInput(value);
    };
 
    const topLevelConfigured = Boolean(
      isClientIdConfigured(dingtalkCfg?.clientId) && hasConfiguredSecretInput(dingtalkCfg?.clientSecret),
    );
 
    const accountConfigured = Object.values(dingtalkCfg?.accounts ?? {}).some((account) => {
      if (!account || typeof account !== "object") {
        return false;
      }
      const hasOwnClientId = Object.prototype.hasOwnProperty.call(account, "clientId");
      const hasOwnClientSecret = Object.prototype.hasOwnProperty.call(account, "clientSecret");
      const accountClientIdConfigured = hasOwnClientId
        ? isClientIdConfigured((account as Record<string, unknown>).clientId)
        : isClientIdConfigured(dingtalkCfg?.clientId);
      const accountSecretConfigured = hasOwnClientSecret
        ? hasConfiguredSecretInput((account as Record<string, unknown>).clientSecret)
        : hasConfiguredSecretInput(dingtalkCfg?.clientSecret);
      return Boolean(accountClientIdConfigured && accountSecretConfigured);
    });
 
    const configured = topLevelConfigured || accountConfigured;
    const resolvedCredentials = resolveDingtalkCredentials(dingtalkCfg, {
      allowUnresolvedSecretRef: true,
    });
 
    // Try to probe if configured
    let probeResult = null;
    if (configured && resolvedCredentials) {
      try {
        probeResult = await probeDingtalk(resolvedCredentials);
      } catch {
        // Ignore probe errors
      }
    }
 
    const statusLines: string[] = [];
    if (!configured) {
      statusLines.push("DingTalk: needs app credentials");
    } else if (probeResult?.ok) {
      statusLines.push(
        `DingTalk: connected as ${probeResult.botName ?? "bot"}`,
      );
    } else {
      statusLines.push("DingTalk: configured (connection not verified)");
    }
 
    return {
      channel,
      configured,
      statusLines,
      selectionHint: configured ? "configured" : "needs app creds",
      quickstartScore: configured ? 2 : 0,
    };
  },
 
  configure: async ({ cfg, prompter }) => {
    const dingtalkCfg = cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined;
    const resolved = resolveDingtalkCredentials(dingtalkCfg, {
      allowUnresolvedSecretRef: true,
    });
    const hasConfigSecret = hasConfiguredSecretInput(dingtalkCfg?.clientSecret);
    const hasConfigCreds = Boolean(
      typeof dingtalkCfg?.clientId === "string" && dingtalkCfg.clientId.trim() && hasConfigSecret,
    );
    const canUseEnv = Boolean(
      !hasConfigCreds && process.env.DINGTALK_CLIENT_ID?.trim() && process.env.DINGTALK_CLIENT_SECRET?.trim(),
    );
 
    let next = cfg;
    let clientId: string | null = null;
    let clientSecret: SecretInput | null = null;
    let clientSecretProbeValue: string | null = null;
 
    if (!resolved) {
      await noteDingtalkCredentialHelp(prompter);
    }
 
    const clientSecretResult = await promptSingleChannelSecretInput({
      cfg: next,
      prompter,
      providerHint: "dingtalk",
      credentialLabel: "App Secret (Client Secret)",
      accountConfigured: Boolean(resolved),
      canUseEnv,
      hasConfigToken: hasConfigSecret,
      envPrompt: "DINGTALK_CLIENT_ID + DINGTALK_CLIENT_SECRET detected. Use env vars?",
      keepPrompt: "DingTalk App Secret already configured. Keep it?",
      inputPrompt: "Enter DingTalk App Secret (Client Secret)",
      preferredEnvVar: "DINGTALK_CLIENT_SECRET",
    });
 
    if (clientSecretResult.action === "use-env") {
      next = {
        ...next,
        channels: {
          ...next.channels,
          "dingtalk-connector": { ...next.channels?.["dingtalk-connector"], enabled: true },
        },
      };
    } else if (clientSecretResult.action === "set") {
      clientSecret = clientSecretResult.value;
      clientSecretProbeValue = clientSecretResult.resolvedValue;
      clientId = await promptDingtalkClientId({
        prompter,
        initialValue:
          normalizeString(dingtalkCfg?.clientId) ?? normalizeString(process.env.DINGTALK_CLIENT_ID),
      });
    }
 
    if (clientId && clientSecret) {
      next = {
        ...next,
        channels: {
          ...next.channels,
          "dingtalk-connector": {
            ...next.channels?.["dingtalk-connector"],
            enabled: true,
            clientId,
            clientSecret,
          },
        },
      };
 
      // Test connection
      try {
        const probe = await probeDingtalk({
          clientId,
          clientSecret: clientSecretProbeValue ?? undefined,
        });
        if (probe.ok) {
          await prompter.note(
            `Connected as ${probe.botName ?? "bot"}`,
            "DingTalk connection test",
          );
        } else {
          await prompter.note(
            `Connection failed: ${probe.error ?? "unknown error"}`,
            "DingTalk connection test",
          );
        }
      } catch (err) {
        await prompter.note(`Connection test failed: ${String(err)}`, "DingTalk connection test");
      }
    }
 
    // Group policy
    const groupPolicy = await prompter.select({
      message: "Group chat policy",
      options: [
        { value: "allowlist", label: "Allowlist - only respond in specific groups" },
        { value: "open", label: "Open - respond in all groups (requires mention)" },
        { value: "disabled", label: "Disabled - don't respond in groups" },
      ],
      initialValue: (next.channels?.["dingtalk-connector"] as DingtalkConfig | undefined)?.groupPolicy ?? "open",
    });
    if (groupPolicy) {
      next = setDingtalkGroupPolicy(next, groupPolicy as "open" | "allowlist" | "disabled");
    }
 
    // Group allowlist if needed
    if (groupPolicy === "allowlist") {
      const existing = (next.channels?.["dingtalk-connector"] as DingtalkConfig | undefined)?.groupAllowFrom ?? [];
      const entry = await prompter.text({
        message: "Group chat allowlist (conversation IDs)",
        placeholder: "cidxxxx, cidyyyy",
        initialValue: existing.length > 0 ? existing.map(String).join(", ") : undefined,
      });
      if (entry) {
        const parts = parseAllowFromInput(String(entry));
        if (parts.length > 0) {
          next = setDingtalkGroupAllowFrom(next, parts);
        }
      }
    }
 
    return { cfg: next, accountId: DEFAULT_ACCOUNT_ID };
  },
 
  dmPolicy,
 
  disable: (cfg) => ({
    ...cfg,
    channels: {
      ...cfg.channels,
      "dingtalk-connector": { ...cfg.channels?.["dingtalk-connector"], enabled: false },
    },
  }),
};