Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix(connectors): separate Feishu user authorization from access issues
BlueSkyID66624622c74e891
diff --git a/bin/local-cli-auth.cjs b/bin/local-cli-auth.cjsindex f2466710..f385c6a1 100644--- a/bin/local-cli-auth.cjs+++ b/bin/local-cli-auth.cjs@@ -331,20 +331,17 @@ async function authorizeLark(node, npxCli, manifest, env, dependencies = {}) {const existingScopes = authorizationScopes();if (ready && !existingScopes) throw new Error('current user permissions could not be verified');const requestedScopes = [...new Set([...(existingScopes || []), ...pendingPermissions.scopes])].sort();- // A permission failure requires a real interactive login, including when the- // current token is valid or the provider supplied no missing scope list.+ // An explicit authorization attempt preserves existing grants. Access+ // advisories are independent of the verified user-consent result.await execute(pendingPermissions.scopes.length? ['auth', 'login', '--profile', env.ORKAS_LOCAL_CLI_PROFILE, '--scope', requestedScopes.join(' ')]: [...commands[1], ...(requestedScopes.length ? ['--scope', requestedScopes.join(' ')] : [])]);if (!authorizationReady(requestedScopes)) {throw new Error('requested permissions are still unavailable');}- // Verified user scopes cannot establish bot visibility or unknown resource- // access. Keep that advisory, just as a read-only scope check does.- if (pendingPermissions.unresolved_access || !pendingPermissions.scopes.length) {- throw new Error('requested permissions could not be verified');- }- permissions.clearPermissionRequest(env, pendingPermissions);+ // Verification establishes these user scopes, not bot/resource access.+ // Keep unrelated advisories and any denial newer than this attempt.+ permissions.recordUserScopeCheck(env, requestedScopes, pendingPermissions, []);return;}diff --git a/bin/local-cli-permissions.cjs b/bin/local-cli-permissions.cjsindex 39d96bad..afc641fc 100644--- a/bin/local-cli-permissions.cjs+++ b/bin/local-cli-permissions.cjs@@ -13,6 +13,64 @@ function isScopeName(value) {// Preserve the legacy filename/profile reader; empty scope lists require an// explicit reauthorize marker. Business calls never log in or replay themselves.const MAX_PENDING_SCOPES = 50;+const LARK_ACCESS_RECOVERIES = new Set(['check_bot_availability', 'check_app_permissions', 'check_resource_access']);+const LARK_IDENTITIES = new Set(['user', 'bot', 'unknown']);+const LARK_PERMISSION_SUBTYPES = new Set(['missing_scope', 'token_scope_insufficient', 'app_scope_not_applied', 'access_denied']);++// One latest reason per identity/recovery pair bounds the advisory ledger to+// nine entries. No resource identifiers or provider prose are persisted.+function larkAccessIssues(pending) {+ if (!pending) return [];+ const issues = new Map();+ let unknown = !Array.isArray(pending.access_issues)+ && (pending.unresolved_access === true || !pending.scopes.length);+ if (Array.isArray(pending.access_issues)) {+ for (const issue of pending.access_issues) {+ if (!LARK_IDENTITIES.has(issue?.identity) || !LARK_ACCESS_RECOVERIES.has(issue?.recovery)) {+ unknown = true;+ continue;+ }+ const safe = { identity: issue.identity, recovery: issue.recovery,+ ...(Number.isSafeInteger(issue.code) ? { code: issue.code } : {}),+ ...(LARK_PERMISSION_SUBTYPES.has(issue.subtype) ? { subtype: issue.subtype } : {}) };+ issues.set(`${safe.identity}:${safe.recovery}`, safe);+ }+ if (!issues.size && pending.unresolved_access) unknown = true;+ }+ if (unknown) issues.set('unknown:check_resource_access', { identity: 'unknown', recovery: 'check_resource_access' });+ return [...issues.values()];+}++function rememberLarkPermissionRequest(error, env, file, prior) {+ const failure = error.provider_error || {};+ const identity = LARK_IDENTITIES.has(failure.identity) ? failure.identity : 'unknown';+ const scopes = Array.isArray(failure.missing_scopes) ? failure.missing_scopes.filter(isScopeName) : [];+ const recovery = failure.code === 230013 ? 'check_bot_availability'+ : failure.subtype === 'app_scope_not_applied' || (identity === 'bot' && scopes.length)+ ? 'check_app_permissions'+ : identity === 'user' && scopes.length && failure.subtype !== 'access_denied'+ ? 'reauthorize' : 'check_resource_access';+ const value = { profile: env.ORKAS_LOCAL_CLI_PROFILE, reauthorize: true, revision: randomUUID(),+ scopes: [...new Set([...(prior?.scopes || []), ...(recovery === 'reauthorize' ? scopes : [])])].sort(),+ access_issues: larkAccessIssues(prior), unresolved_access: false };+ if (recovery !== 'reauthorize') {+ value.access_issues = larkAccessIssues({ ...value, access_issues: [...value.access_issues, {+ identity, recovery, code: failure.code, subtype: failure.subtype,+ }] });+ }+ if (value.scopes.length > MAX_PENDING_SCOPES) {+ value.scopes = [];+ value.access_issues = larkAccessIssues({ ...value, access_issues: [...value.access_issues,+ { identity: 'unknown', recovery: 'check_resource_access' }] });+ }+ // Retain the legacy fields for old readers; new readers separate this advisory+ // from user consent. Do not clear either state from a business success.+ value.unresolved_access = value.access_issues.length > 0;+ if (writePermissionRequest(file, value) && error.provider_error) {+ error.provider_error.recovery = value.scopes.length || recovery !== 'reauthorize'+ ? recovery : 'check_resource_access';+ }+}function permissionRequestPath(env) {return path.isAbsolute(env.ORKAS_LOCAL_CLI_RUNTIME_DIR || '') && env.ORKAS_LOCAL_CLI_PROFILE? path.join(env.ORKAS_LOCAL_CLI_RUNTIME_DIR, '.orkas-user-permissions.json') : null;@@ -45,6 +103,10 @@ function rememberPermissionRequest(error, env) {const file = permissionRequestPath(env);if (!file) return;const prior = readPermissionRequest(env);+ if (env.ORKAS_LOCAL_CLI_PROVIDER === 'lark') {+ rememberLarkPermissionRequest(error, env, file, prior);+ return;+ }const value = { profile: env.ORKAS_LOCAL_CLI_PROFILE, reauthorize: true, revision: randomUUID(), scopes: [...new Set([...(prior?.scopes || []), ...scopes])].sort(),unresolved_access: prior?.unresolved_access === true || (scopes.length === 0 && patScopes.length === 0) };if (patScopes.length || prior?.pat_scopes?.length) value.pat_scopes = [...new Set([...(prior?.pat_scopes || []), ...patScopes])].sort();@@ -78,6 +140,22 @@ function recordUserScopeCheck(env, granted, expected, required) {if (!Array.isArray(granted) || !granted.every(isScopeName)) return;if (JSON.stringify(readPermissionRequest(env)) !== JSON.stringify(expected)) return;const scopes = [...new Set([...(expected?.scopes || []), ...required])].filter(scope => !granted.includes(scope)).sort();+ if (env.ORKAS_LOCAL_CLI_PROVIDER === 'lark') {+ let issues = larkAccessIssues(expected);+ if (scopes.length > MAX_PENDING_SCOPES) issues = larkAccessIssues({ scopes: [], unresolved_access: true,+ access_issues: [...issues, { identity: 'unknown', recovery: 'check_resource_access' }] });+ if (!scopes.length && !issues.length) {+ clearPermissionRequest(env, expected);+ return;+ }+ const file = permissionRequestPath(env);+ const remaining = scopes.length > MAX_PENDING_SCOPES ? [] : scopes;+ if (!file || (JSON.stringify(expected?.scopes) === JSON.stringify(remaining)+ && JSON.stringify(expected?.access_issues) === JSON.stringify(issues))) return;+ writePermissionRequest(file, { profile: env.ORKAS_LOCAL_CLI_PROFILE, reauthorize: true,+ revision: randomUUID(), scopes: remaining, access_issues: issues, unresolved_access: issues.length > 0 });+ return;+ }const unresolved = expected?.unresolved_access === true || (expected && !expected.scopes.length);if (!scopes.length && !unresolved) {clearPermissionRequest(env, expected);@@ -148,9 +226,11 @@ function structuredPermissionFailure(result, provider) {if (!found && provider === 'xero' && result.status !== 0) {found = /^(?:\s*Error:\s*)?Xero API error \(403\)(?::|\s*$)/m.test(result.stderr || '');}- return found ? Object.assign(new Error('connector permission is insufficient; reauthorize this connector'), {+ return found ? Object.assign(new Error(provider === 'lark'+ ? 'connector permission is insufficient; check access to the affected resource'+ : 'connector permission is insufficient; reauthorize this connector'), {code: 'connector_permission_denied', provider_error: { type: 'authorization', ...detail },}) : null;}-module.exports = { isScopeName, readPermissionRequest, rememberPermissionRequest, clearPermissionRequest, recordUserScopeCheck, recordPatScopeGrant, structuredPermissionFailure };+module.exports = { isScopeName, readPermissionRequest, rememberPermissionRequest, clearPermissionRequest, recordUserScopeCheck, recordPatScopeGrant, structuredPermissionFailure, larkAccessIssues };diff --git a/docs/test/connectors-regression.md b/docs/test/connectors-regression.mdindex 49af0556..e647e7a0 100644--- a/docs/test/connectors-regression.md+++ b/docs/test/connectors-regression.md@@ -45,12 +45,12 @@ a successful login or a green transport. Exercise these journeys independently:| First connection, verified identity with partial business access | Keep Use and Reauthorize together; an unverified/expired identity cannot establish a new connection. | `manager.test.ts`, `local-cli-files.test.ts`, `connectors-degraded-card.test.ts` || Connected account, one operation denied | Preserve the failed operation's error, expose only validated scope identifiers, then complete a different granted read on the same connection; no login or replay. Cover Feishu user/bot, DingTalk OAuth/PAT/admin, WeCom and Xero. | `local-cli-files.test.ts`, `manager.test.ts`, `local-cli_e2e_permissions.test.ts`, `local-cli_e2e_attachment.test.ts` || Error-shaped business data or unavailable provider | Success payloads, nested permission text, local-file errors, malformed JSON and timeouts must not manufacture a permission request. | `local-cli-files.test.ts` |-| Lark incremental consent | Request old grants plus missing user scopes; cancellation, absent grant, unknown resource/bot access and a newer denial retain recovery. A successful scope check clears only proven scope deficiencies. | `local-cli-files.test.ts` |+| Lark incremental consent | Request old grants plus missing user scopes; cancellation and absent grants remain failures. Verified user consent succeeds even with bot/resource advisories or legacy unresolved state; preserve those advisories and newer denials, without replay. A successful scope check clears only proven scope deficiencies. | `local-cli-files.test.ts` || DingTalk PAT incremental consent | Cover new/already-granted receipts, partial grants followed by retry, malformed/failed receipts, case-sensitive identifiers, mixed OAuth/PAT and changed administrator policy. Only acknowledged PAT scopes disappear. | `local-cli-files.test.ts` || WeCom or DingTalk identity-only login | Do not equate identity success with business access. Preserve the existing connection and permission notice after cancellation or unverifiable recovery. | `local-cli-files.test.ts`, `manager.test.ts` || Concurrent recovery and device-local persistence | An old check/grant cannot clear a newer denial, including the same scope denied again; profiles and providers remain isolated. Malformed/oversized/symlink state and failed writes do not leak or replace provider errors. | `local-cli-files.test.ts`, `local-cli.test.ts` || Page entry, refresh, account switch | Listing is read-only; page checks coalesce for one minute; explicit refresh/consent completion rechecks. Switching accounts/disconnecting aborts pending checks. No startup/timer login. | `local-cli.test.ts`, `ipc/connectors.test.ts`, `connectors-render-cache.test.ts` |-| Card action and recovery | Use stays available, Reauthorize is explicit, known names are localized, unknown identifiers render as text, and the notice disappears only after verified recovery. Preserve selected tools. | `connectors-degraded-card.test.ts`, `manager.test.ts` |+| Card action and recovery | Use stays available. Missing user scopes offer Reauthorize; Feishu/Lark business-only advisories show localized configuration/resource guidance without OAuth. Mixed cases show both. Unknown identifiers render as text, and only verified scope recovery removes the scope notice. Preserve selected tools. | `connectors-degraded-card.test.ts`, `manager.test.ts` |Real-account canaries (macOS and Windows) remain required for each provider:start with verified identity plus one denied capability; perform one allowed read,@@ -72,6 +72,6 @@ verification likewise needs provider evidence beyond `identity whoami`.| Confirm a high-impact/destructive operation | The existing title is retained; the visible body shows the connector and operation identifier. First-party CLI/direct API execution lanes use the singular `action` parameter; other tools use their actual tool name. Only redacted parameters appear in the expandable details, collapsed by default; account, risk, tool metadata and explanatory notes are omitted. Allow once affects only that call. Allow for this task covers every action for the same connector account, including deletion, without changing global permissions; other tasks/accounts/connectors still ask. Concurrent prompts covered by the grant close as approved. Completion, stop, account switch and connector replacement/removal revoke the grant. | `action-confirm.test.ts`, `registry.test.ts`, `bash-permission.test.ts`, `bus-integration.test.ts`, `connectors_e2e_validation.spec.ts` |-6. Feishu/Lark authorization opens only structurally validated HTTPS URLs on exact official hosts and authorization routes; provider prose does not determine success. A successful automatic browser launch keeps the interactive terminal hidden; show manual recovery only if opening fails, the CLI requests input, or authorization fails. Fixed domains must remain a subset accepted by the pinned CLI auth login command. Reuse a pending attempt for the same account and catalog id. Any confirmed permission failure from an official CLI offers **Reauthorize**, regardless of business operation, identity or availability of scope metadata. Structured failure envelopes and pinned provider status protocols drive this state; successful business data, arbitrary prose and transport failures do not. Clicking starts the applicable authorization flow even with a valid old login. DingTalk retains structured missing OAuth and PAT scope identifiers. PAT recovery grants only the missing scopes and requires a structured granted/already-granted receipt; plain login success never clears PAT, unknown-access or administrator denials. WeCom identity-only reauthorization also retains the permission notice; it must not imply that business access was restored. Known DingTalk PAT scopes may be retried after an administrator changes policy; cached policy denials must not permanently block recovery. The pinned DWS 1.0.61 login does not implement incremental OAuth scope requests, so those deficiencies remain visible after login. Lark requests confirmed missing user scopes explicitly and retains existing granted scopes (including unprefixed OAuth scopes); unknown or bot scopes use the normal provider flow without inventing user scopes. Selected tools remain unchanged. On Connectors-page entry, inspect verified Lark user scopes for message sending and previously reported missing scopes, even when its transport is live. Repeated opens within one minute reuse the check; explicit refresh and completed authorization check again. There is no startup or timer scan. For Feishu/Lark, DingTalk and WeCom, a failed business operation or a cancelled/failed reauthorization leaves other authorized operations usable without replaying the failure. A missing scope adds a concise advisory card notice (localized names for known scopes, identifiers for other reported scopes, a generic notice if absent) and Reauthorize alongside Use; it never disables the whole connector. Unavailable checks retain prior evidence, confirmed grants clear only scope deficiencies, and resource/admin denials remain unresolved. Disconnect or account switch cancels an in-flight check. Cancellation or failed grant verification retains recovery; success clears only the request handled by that attempt. Newer denials remain recoverable. Bot visibility and administrator-owned permission failures also offer reauthorization, without claiming user consent can grant administrator access. No failed business action is replayed automatically.+6. Feishu/Lark authorization opens only structurally validated HTTPS URLs on exact official hosts and authorization routes; provider prose does not determine success. A successful automatic browser launch keeps the interactive terminal hidden; show manual recovery only if opening fails, the CLI requests input, or authorization fails. Fixed domains must remain a subset accepted by the pinned CLI auth login command. Reuse a pending attempt for the same account and catalog id. Feishu/Lark offers **Reauthorize** for confirmed missing user scopes. Bot availability, app-permission and unknown resource denials remain separate access advisories; they do not offer OAuth as their remedy. Other official CLI providers retain their existing reauthorization entry. Structured failure envelopes and pinned provider status protocols drive this state; successful business data, arbitrary prose and transport failures do not. Clicking starts the applicable authorization flow even with a valid old login. DingTalk retains structured missing OAuth and PAT scope identifiers. PAT recovery grants only the missing scopes and requires a structured granted/already-granted receipt; plain login success never clears PAT, unknown-access or administrator denials. WeCom identity-only reauthorization also retains the permission notice; it must not imply that business access was restored. Known DingTalk PAT scopes may be retried after an administrator changes policy; cached policy denials must not permanently block recovery. The pinned DWS 1.0.61 login does not implement incremental OAuth scope requests, so those deficiencies remain visible after login. Lark requests confirmed missing user scopes explicitly and retains existing granted scopes (including unprefixed OAuth scopes). After verified consent it reports authorization success and clears only confirmed user scope deficiencies, while preserving bot/resource advisories. Legacy unresolved records become unknown-access advisories, without guessing an identity or claiming access was restored. Selected tools remain unchanged. On Connectors-page entry, inspect verified Lark user scopes for message sending and previously reported missing scopes, even when its transport is live. Repeated opens within one minute reuse the check; explicit refresh and completed authorization check again. There is no startup or timer scan. For Feishu/Lark, DingTalk and WeCom, a failed business operation or a cancelled/failed reauthorization leaves other authorized operations usable without replaying the failure. A missing scope adds a concise advisory card notice (localized names for known scopes, identifiers for other reported scopes, a generic notice if absent) and Reauthorize alongside Use; it never disables the whole connector. Unavailable checks retain prior evidence, confirmed grants clear only scope deficiencies, and resource/admin denials remain unresolved. Disconnect or account switch cancels an in-flight check. Cancellation or failed grant verification retains recovery; success clears only the request handled by that attempt. Newer denials remain recoverable. Feishu/Lark bot visibility and application-owned permission failures show administrator configuration guidance alongside Use; unknown access shows resource-access guidance. A mixed user-scope and access denial shows both the consent action and the independent advisory. Advisories describe historical failures and are not proof of current resource access. No failed business action is replayed automatically.11. Reject credentials, config/profile overrides, output paths, raw flags, excess parameters, outside files and symlink escapes. Approved local inputs must exist as absolute paths with a realpath inside Orkas-approved roots. Identify file carriers from the pinned provider parameter contract, preserving literal text and file arrays. Prepare private, per-call copies for CLI uploads and declared @file inputs, preserving bytes and filenames; serialize Lark native binary carriers as key=value and preserve WeCom media_id objects. Clean staging after success, failure or cancellation, and reject changed/non-regular sources before sending. Preserve Xero full-JSON destructive-status inspection. Use 60s execution deadlines for ordinary commands and 10min for transfers including staging; only active transfers emit periodic progress to extend the 90s MCP inactivity window, with a 13min total bound. Cancellation must stop descendant processes and must not replay an operation. Network file inputs require HTTPS; bound and sanitize provider output.diff --git a/src/main/features/connectors/local-cli.ts b/src/main/features/connectors/local-cli.tsindex a04ddec9..48d2f5c7 100644--- a/src/main/features/connectors/local-cli.ts+++ b/src/main/features/connectors/local-cli.ts@@ -116,15 +116,30 @@ export function localCliReauthorizationRequired(uid: string, catalogId: string):/** Only missing scope identifiers may cross IPC; never return granted scopes or identities. */export function localCliMissingPermissions(uid: string, catalogId: string): string[] | null {- if (!uid || !['feishu', 'lark', 'dingtalk', 'wecom', 'xero'].includes(catalogId)) return null;+ return localCliPermissionRecovery(uid, catalogId).missingPermissions;+}++/** One bounded local read for both consent and advisory state. Only closed+ * recovery kinds and missing user scopes cross IPC, never provider details. */+export function localCliPermissionRecovery(uid: string, catalogId: string): {+ missingPermissions: string[] | null; accessAdvisories: string[];+} {+ const empty = { missingPermissions: null, accessAdvisories: [] };+ if (!uid || !['feishu', 'lark', 'dingtalk', 'wecom', 'xero'].includes(catalogId)) return empty;const contract = require(path.join(pcDirForChild(), 'bin/local-cli-permissions.cjs')) as {readPermissionRequest: (env: Record<string, string>) => { scopes: string[]; pat_scopes?: string[] } | null;+ larkAccessIssues: (pending: unknown) => Array<{ recovery: string }>;};const pending = contract.readPermissionRequest({ORKAS_LOCAL_CLI_RUNTIME_DIR: localCliRuntimeDir(uid, catalogId),ORKAS_LOCAL_CLI_PROFILE: localCliProfileName(uid, catalogId),});- return pending ? [...new Set([...pending.scopes, ...(pending.pat_scopes || [])])].sort() : null;+ if (!pending) return empty;+ if (catalogId === 'feishu' || catalogId === 'lark') return {+ missingPermissions: pending.scopes.length ? pending.scopes : null,+ accessAdvisories: [...new Set(contract.larkAccessIssues(pending).map(issue => issue.recovery))],+ };+ return { missingPermissions: [...new Set([...pending.scopes, ...(pending.pat_scopes || [])])].sort(), accessAdvisories: [] };}const permissionChecks = new Map<string, { checkedAt: number; running?: Promise<void>; abort: AbortController }>();diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.tsindex bf647320..dd10c981 100644--- a/src/main/ipc/connectors.ts+++ b/src/main/ipc/connectors.ts@@ -24,7 +24,7 @@ import type { ConnectorInstance, ConnectorStatus, ToolSchema } from '../featuresimport { isConnectorEnabled, setConnectorEnabled } from '../features/component_enabled';import { catalogWithAvailability, isConnectorRuntimeEnabled } from '../features/connectors/availability';import { requireConnectorApiKey } from '../features/connectors/api-key';-import { checkLocalCliPermissions, localCliMissingPermissions } from '../features/connectors/local-cli';+import { checkLocalCliPermissions, localCliPermissionRecovery } from '../features/connectors/local-cli';/*** Renderer-safe view of a connector instance. The hydrated `ConnectorInstance`@@ -54,6 +54,7 @@ interface ClientConnectorInstance {enabled?: boolean;reauthorization_required?: boolean;missing_permissions?: string[];+ access_advisories?: string[];}function _safeTransportSummary(inst: ConnectorInstance): ClientConnectorInstance['transport'] | undefined {@@ -101,11 +102,12 @@ function toClientInstance(inst: ConnectorInstance, enabled?: boolean, uid?: stri}if (typeof enabled === 'boolean') out.enabled = enabled;if (uid && inst.origin !== 'custom') {- const missing = localCliMissingPermissions(uid, inst.id);- if (missing !== null) {+ const recovery = localCliPermissionRecovery(uid, inst.id);+ if (recovery.missingPermissions !== null) {out.reauthorization_required = true;- out.missing_permissions = missing;+ out.missing_permissions = recovery.missingPermissions;}+ if (recovery.accessAdvisories.length) out.access_advisories = recovery.accessAdvisories;}return out;}diff --git a/src/renderer/locales/de.json b/src/renderer/locales/de.jsonindex ba6cf5e0..e5aaf314 100644--- a/src/renderer/locales/de.json+++ b/src/renderer/locales/de.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Nachrichten senden","connectors.permissions.missing": "Fehlende Berechtigung: {permissions}","connectors.permissions.limited": "Einige Berechtigungen fehlen",+ "connectors.permissions.check_bot_availability": "Der Bot konnte einen Benutzer nicht erreichen. Bitten Sie den App-Administrator, den Verfügbarkeitsbereich in Feishu/Lark zu prüfen. Eine erneute Benutzerautorisierung behebt dies nicht.",+ "connectors.permissions.check_app_permissions": "Einige App-Berechtigungen wurden verweigert. Bitten Sie den App-Administrator, die Berechtigungen in Feishu/Lark zu prüfen.",+ "connectors.permissions.check_resource_access": "Die Behebung eines früheren Zugriffsproblems wurde noch nicht bestätigt. Prüfen Sie den Zugriff auf die betroffene Ressource. Andere autorisierte Funktionen bleiben verfügbar.","connectors.permissions.send_mail": "E-Mails senden","connectors.action.connect": "Verbinden","connectors.action.connecting": "Verbindung wird hergestellt…",diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 48f1b1ca..572a6878 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Send messages","connectors.permissions.missing": "Missing permission: {permissions}","connectors.permissions.limited": "Some permissions are missing",+ "connectors.permissions.check_bot_availability": "The bot could not reach a user. Ask the app administrator to check its availability scope in Feishu/Lark. User reauthorization cannot resolve this.",+ "connectors.permissions.check_app_permissions": "Some app permissions were denied. Ask the app administrator to check permissions in Feishu/Lark.",+ "connectors.permissions.check_resource_access": "A previous access issue has not been verified as resolved. Check access to the affected resource. Other authorized features remain available.","connectors.permissions.send_mail": "Send mail","connectors.action.connect": "Connect","connectors.action.connecting": "Connecting…",diff --git a/src/renderer/locales/es.json b/src/renderer/locales/es.jsonindex 2ed7c726..fa94de9a 100644--- a/src/renderer/locales/es.json+++ b/src/renderer/locales/es.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Enviar mensajes","connectors.permissions.missing": "Permiso faltante: {permissions}","connectors.permissions.limited": "Faltan algunos permisos",+ "connectors.permissions.check_bot_availability": "El bot no pudo acceder a un usuario. Pide al administrador de la aplicación que revise su ámbito de disponibilidad en Feishu/Lark. Volver a autorizar al usuario no resuelve este problema.",+ "connectors.permissions.check_app_permissions": "Se denegaron algunos permisos de la aplicación. Pide al administrador que revise los permisos en Feishu/Lark.",+ "connectors.permissions.check_resource_access": "No se ha confirmado la resolución de un problema de acceso anterior. Revisa el acceso al recurso afectado. Las demás funciones autorizadas siguen disponibles.","connectors.permissions.send_mail": "Enviar correo","connectors.action.connect": "Conectar","connectors.action.connecting": "Conectando…",diff --git a/src/renderer/locales/fr.json b/src/renderer/locales/fr.jsonindex f29b33a5..fe87b271 100644--- a/src/renderer/locales/fr.json+++ b/src/renderer/locales/fr.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Envoyer des messages","connectors.permissions.missing": "Autorisation manquante : {permissions}","connectors.permissions.limited": "Certaines autorisations sont manquantes",+ "connectors.permissions.check_bot_availability": "Le bot n’a pas pu accéder à un utilisateur. Demandez à l’administrateur de vérifier le périmètre de disponibilité de l’application dans Feishu/Lark. Réautoriser l’utilisateur ne résout pas ce problème.",+ "connectors.permissions.check_app_permissions": "Certaines autorisations de l’application ont été refusées. Demandez à l’administrateur de vérifier les autorisations dans Feishu/Lark.",+ "connectors.permissions.check_resource_access": "La résolution d’un problème d’accès précédent n’a pas été confirmée. Vérifiez l’accès à la ressource concernée. Les autres fonctions autorisées restent disponibles.","connectors.permissions.send_mail": "Envoyer des e-mails","connectors.action.connect": "Connecter","connectors.action.connecting": "Connexion…",diff --git a/src/renderer/locales/it.json b/src/renderer/locales/it.jsonindex 05060863..e449065e 100644--- a/src/renderer/locales/it.json+++ b/src/renderer/locales/it.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Inviare messaggi","connectors.permissions.missing": "Permesso mancante: {permissions}","connectors.permissions.limited": "Mancano alcuni permessi",+ "connectors.permissions.check_bot_availability": "Il bot non ha potuto raggiungere un utente. Chiedi all’amministratore dell’app di verificarne l’ambito di disponibilità in Feishu/Lark. Autorizzare di nuovo l’utente non risolve il problema.",+ "connectors.permissions.check_app_permissions": "Alcune autorizzazioni dell’app sono state negate. Chiedi all’amministratore di verificare le autorizzazioni in Feishu/Lark.",+ "connectors.permissions.check_resource_access": "La risoluzione di un precedente problema di accesso non è stata verificata. Controlla l’accesso alla risorsa interessata. Le altre funzioni autorizzate restano disponibili.","connectors.permissions.send_mail": "Inviare email","connectors.action.connect": "Connetti","connectors.action.connecting": "Connessione…",diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex e56593e6..b6e3e434 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "メッセージ送信","connectors.permissions.missing": "未許可:{permissions}","connectors.permissions.limited": "一部の権限が不足しています",+ "connectors.permissions.check_bot_availability": "ボットがユーザーにアクセスできませんでした。アプリ管理者に Feishu/Lark の利用可能範囲の確認を依頼してください。ユーザーの再認証では解決しません。",+ "connectors.permissions.check_app_permissions": "一部のアプリ権限が拒否されました。アプリ管理者に Feishu/Lark の権限設定の確認を依頼してください。",+ "connectors.permissions.check_resource_access": "以前のアクセス問題の解決は未確認です。対象リソースへのアクセス権を確認してください。他の認証済み機能は引き続き利用できます。","connectors.permissions.send_mail": "メール送信","connectors.action.connect": "接続","connectors.action.connecting": "接続中…",diff --git a/src/renderer/locales/ko.json b/src/renderer/locales/ko.jsonindex b7b9e933..34b60baf 100644--- a/src/renderer/locales/ko.json+++ b/src/renderer/locales/ko.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "메시지 전송","connectors.permissions.missing": "누락된 권한: {permissions}","connectors.permissions.limited": "일부 권한이 없습니다",+ "connectors.permissions.check_bot_availability": "봇이 사용자에게 접근하지 못했습니다. 앱 관리자에게 Feishu/Lark의 앱 사용 가능 범위를 확인해 달라고 요청하세요. 사용자 재인증으로는 해결되지 않습니다.",+ "connectors.permissions.check_app_permissions": "일부 앱 권한이 거부되었습니다. 앱 관리자에게 Feishu/Lark의 권한 설정을 확인해 달라고 요청하세요.",+ "connectors.permissions.check_resource_access": "이전 접근 문제가 해결되었는지 아직 확인되지 않았습니다. 해당 리소스의 접근 권한을 확인하세요. 다른 인증된 기능은 계속 사용할 수 있습니다.","connectors.permissions.send_mail": "메일 전송","connectors.action.connect": "연결","connectors.action.connecting": "연결 중…",diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.jsonindex 594859cf..3bda51a4 100644--- a/src/renderer/locales/pt.json+++ b/src/renderer/locales/pt.json@@ -144,6 +144,9 @@"connectors.permissions.send_as_user": "Enviar mensagens","connectors.permissions.missing": "Permissão ausente: {permissions}","connectors.permissions.limited": "Algumas permissões estão ausentes",+ "connectors.permissions.check_bot_availability": "O bot não conseguiu acessar um usuário. Peça ao administrador do aplicativo para verificar o escopo de disponibilidade no Feishu/Lark. Autorizar o usuário novamente não resolve isso.",+ "connectors.permissions.check_app_permissions": "Algumas permissões do aplicativo foram negadas. Peça ao administrador para verificar as permissões no Feishu/Lark.",+ "connectors.permissions.check_resource_access": "A resolução de um problema de acesso anterior ainda não foi confirmada. Verifique o acesso ao recurso afetado. Outros recursos autorizados continuam disponíveis.","connectors.permissions.send_mail": "Enviar e-mail","connectors.action.connect": "Conectar","connectors.action.connecting": "Conectando…",diff --git a/src/renderer/locales/ru.json b/src/renderer/locales/ru.jsonindex 12f9fe7b..41eb581c 100644--- a/src/renderer/locales/ru.json+++ b/src/renderer/locales/ru.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "Отправка сообщений","connectors.permissions.missing": "Нет разрешения: {permissions}","connectors.permissions.limited": "Отсутствуют некоторые разрешения",+ "connectors.permissions.check_bot_availability": "Бот не смог получить доступ к пользователю. Попросите администратора приложения проверить область доступности в Feishu/Lark. Повторная авторизация пользователя не решит эту проблему.",+ "connectors.permissions.check_app_permissions": "Некоторые разрешения приложения были отклонены. Попросите администратора проверить разрешения в Feishu/Lark.",+ "connectors.permissions.check_resource_access": "Устранение предыдущей проблемы доступа ещё не подтверждено. Проверьте доступ к соответствующему ресурсу. Остальные авторизованные функции по-прежнему доступны.","connectors.permissions.send_mail": "Отправка почты","connectors.action.connect": "Подключить","connectors.action.connecting": "Подключение…",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 04c6f107..66191f9c 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -149,6 +149,9 @@"connectors.permissions.send_as_user": "发送消息","connectors.permissions.missing": "缺少权限:{permissions}","connectors.permissions.limited": "部分权限不足",+ "connectors.permissions.check_bot_availability": "机器人此前无法访问目标用户。请联系应用管理员检查飞书/Lark 的应用可用范围,重新授权用户账号无法解决此问题。",+ "connectors.permissions.check_app_permissions": "部分应用权限此前被拒绝。请联系应用管理员检查飞书/Lark 的权限配置。",+ "connectors.permissions.check_resource_access": "历史访问问题尚未确认解决。请检查目标资源的访问权限,其他已获授权的功能仍可使用。","connectors.permissions.send_mail": "发送邮件","connectors.action.connect": "连接","connectors.action.connecting": "连接中…",diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex 7b1e7287..728f9ef8 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -1147,6 +1147,9 @@ function _renderCatalogCard(entry, instance) {const installPhase = _localCliInstallPhases.get(e.id) || '';const installError = _localCliInstallErrors.get(e.id) || null;const permissionNotice = e.auth_mode === 'local_cli' && instance?.reauthorization_required;+ const accessAdvisories = e.auth_mode === 'local_cli' && Array.isArray(instance?.access_advisories)+ ? [...new Set(instance.access_advisories)].filter(kind =>+ ['check_bot_availability', 'check_app_permissions', 'check_resource_access'].includes(kind)) : [];// The ⋯ menu lives on installed cards — it hosts the destructive disconnect action so it stays// one click away from accidental triggers. Un-connected / errored cards still surface the@@ -1236,10 +1239,15 @@ function _renderCatalogCard(entry, instance) {</div><div class="connector-card-desc muted"></div>${permissionNotice ? '<div class="connector-card-unverified" data-role="permission-notice"></div>' : ''}+ ${accessAdvisories.length ? '<div class="connector-card-unverified" data-role="access-notice"></div>' : ''}<div class="connector-card-foot">${cardBadgesHtml}${action}</div>`;card.querySelector('.connector-card-name').textContent = displayName;card.querySelector('.connector-card-desc').textContent = desc;+ if (accessAdvisories.length) {+ card.querySelector('[data-role="access-notice"]').textContent = accessAdvisories+ .map(kind => t('connectors.permissions.' + kind)).join(' ');+ }if (permissionNotice) {const scopes = Array.isArray(instance.missing_permissions) ? instance.missing_permissions : [];const permissionLabels = {diff --git a/test/main/features/connectors/local-cli-files.test.ts b/test/main/features/connectors/local-cli-files.test.tsindex f0cc1fd0..28e2b357 100644--- a/test/main/features/connectors/local-cli-files.test.ts+++ b/test/main/features/connectors/local-cli-files.test.ts@@ -482,9 +482,12 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strinconst env = envFor(provider as string);const runner = vi.fn(() => ({ status: 1, stdout: JSON.stringify(payload), stderr: '' }));await expect(adapter.inspectAction(provider === 'xero' ? 'contacts.list' : provider === 'dingtalk' ? 'doc.get' : provider === 'wecom' ? 'contact.get-user' : 'docs.+fetch', { runner }, env))- .rejects.toMatchObject({ code: 'connector_permission_denied', provider_error: { recovery: 'reauthorize' } });+ .rejects.toMatchObject({ code: 'connector_permission_denied', provider_error: {+ recovery: provider === 'lark' ? 'check_resource_access' : 'reauthorize',+ } });expect(runner).toHaveBeenCalledOnce();expect(permissions.readPermissionRequest(env)).toMatchObject({ reauthorize: true, scopes: [] });+ if (provider === 'lark') expect(permissions.structuredPermissionFailure(runner(), provider).message).not.toContain('reauthorize');});it.each([@@ -526,19 +529,21 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strin},);- it('still offers reauthorization when the accumulated scope list exceeds the bounded explicit request', () => {+ it('retains an access advisory when the accumulated Lark scope list exceeds the bounded explicit request', () => {const env = envFor('lark');permissions.rememberPermissionRequest({ provider_error: { type: 'authorization', identity: 'user',missing_scopes: Array.from({ length: 51 }, (_, index) => `resource:scope${index}`),} }, env);- expect(permissions.readPermissionRequest(env)).toMatchObject({ reauthorize: true, scopes: [] });+ expect(permissions.readPermissionRequest(env)).toMatchObject({ reauthorize: true, scopes: [],+ access_issues: [{ recovery: 'check_resource_access' }] });});- it.each([230013, 99991679])('retains Lark API permission code %s and offers reauthorization', code => {+ it.each([230013, 99991679])('retains Lark API permission code %s with the applicable access recovery', code => {const env = envFor('lark');const error = lark.structuredFailure({ status: 1, stdout: JSON.stringify({ ok: false, error: { type: 'api', code } }), stderr: '' });permissions.rememberPermissionRequest(error, env);- expect(error).toMatchObject({ code: 'connector_permission_denied', provider_error: { type: 'api', code, recovery: 'reauthorize' } });+ expect(error).toMatchObject({ code: 'connector_permission_denied', provider_error: { type: 'api', code,+ recovery: code === 230013 ? 'check_bot_availability' : 'check_resource_access' } });expect(permissions.readPermissionRequest(env)).toMatchObject({ reauthorize: true, scopes: [] });});@@ -698,7 +703,7 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strinexpect(execute.mock.calls).toEqual(Array(3).fill([['auth', 'init', '--noninteractive', '--no-browser']]));});- it('forces Lark authorization without missing scope names and preserves old grants through cancellation and retry', async () => {+ it('preserves cancellation and old grants without mistaking unknown Lark access for an authorization failure', async () => {const env = envFor('lark');permissions.rememberPermissionRequest({ code: 'connector_permission_denied' }, env);const oldScopes = ['im:message.send_as_user', 'offline_access'];@@ -708,7 +713,7 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strinawait expect(auth.authorizeLark('', '', auth.MANIFESTS.lark, env, deps)).rejects.toThrow('cancelled');expect(permissions.readPermissionRequest(env)).not.toBeNull();execute.mockImplementation(async () => undefined);- await expect(auth.authorizeLark('', '', auth.MANIFESTS.lark, env, deps)).rejects.toThrow('permissions could not be verified');+ await expect(auth.authorizeLark('', '', auth.MANIFESTS.lark, env, deps)).resolves.toBeUndefined();expect(execute).toHaveBeenCalledTimes(2);expect(execute).toHaveBeenLastCalledWith([...auth.MANIFESTS.lark.login(env)[1], '--scope', oldScopes.join(' ')]);expect(authorizationReady).toHaveBeenLastCalledWith(oldScopes);@@ -722,23 +727,41 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strin}) });}- it('keeps a Lark bot visibility denial after confirming the requested user scope', async () => {+ it('completes Lark user authorization while retaining the separate bot access advisory', async () => {const env = envFor('lark');lark.rememberPermissionRequest(permissionError('bot'), env);lark.rememberPermissionRequest(permissionError('user'), env);const execute = vi.fn(async () => undefined);await expect(auth.authorizeLark('', '', auth.MANIFESTS.lark, env, {execute, authorizationReady: () => true, authorizationScopes: () => ['offline_access'],- })).rejects.toThrow('permissions could not be verified');+ })).resolves.toBeUndefined();expect(execute).toHaveBeenCalledExactlyOnceWith(['auth', 'login', '--profile', 'file-contract', '--scope', 'im:message.send_as_user offline_access',]);+ expect(permissions.readPermissionRequest(env)).toMatchObject({ scopes: [], unresolved_access: true,+ access_issues: [{ identity: 'bot', recovery: 'check_app_permissions' }] });auth.checkLarkPermissions('', '', auth.MANIFESTS.lark, env, () => ok({ identities: { user: {available: true, verified: true, scope: 'im:message.send_as_user offline_access',} } }));expect(permissions.readPermissionRequest(env)).toMatchObject({ scopes: [], unresolved_access: true });});+ it('recovers a legacy stuck Lark record without treating unknown access as restored', async () => {+ const env = envFor('lark');+ fs.writeFileSync(path.join(env.ORKAS_LOCAL_CLI_RUNTIME_DIR, '.orkas-user-permissions.json'), JSON.stringify({+ profile: env.ORKAS_LOCAL_CLI_PROFILE, reauthorize: true, scopes: [], unresolved_access: true,+ }));+ const execute = vi.fn(async () => undefined);+ const deps = { execute, authorizationReady: () => true,+ authorizationScopes: () => ['im:message.send_as_user', 'offline_access'] };+ for (let attempt = 0; attempt < 2; attempt++) {+ await expect(auth.authorizeLark('', '', auth.MANIFESTS.lark, env, deps)).resolves.toBeUndefined();+ expect(permissions.readPermissionRequest(env)).toMatchObject({ scopes: [], unresolved_access: true,+ access_issues: [{ identity: 'unknown', recovery: 'check_resource_access' }] });+ }+ expect(execute.mock.calls.every(([args]: any) => args[0] === 'auth' && args[1] === 'login')).toBe(true);+ });+it.each(['missing_scope', 'token_scope_insufficient'])('recovers %s across document, spreadsheet and API operations without replaying them', async (subtype) => {const env = envFor('lark');@@ -829,24 +852,58 @@ process.stdout.write(process.env.FIXTURE_MODE === 'malformed' ? '{' : JSON.strinexpect(lark.readPermissionRequest(env)?.scopes).toEqual(['im:message.send_as_user']);});- it('offers reauthorization without inventing scopes when the provider supplies no scope list', () => {+ it('retains an unknown access advisory without inventing scopes when the provider supplies no scope list', () => {const env = envFor('lark');const error = permissionError();delete error.provider_error.missing_scopes;lark.rememberPermissionRequest(error, env);expect(lark.readPermissionRequest(env)?.scopes).toEqual([]);+ expect(error.provider_error.recovery).toBe('check_resource_access');});it.each([['bot', 'missing_scope'], ['bot', 'token_scope_insufficient'], ['', 'missing_scope'],['user', 'app_scope_not_applied'], ['user', 'access_denied']])(- 'offers reauthorization for %s/%s without requiring IM scope metadata', (identity, subtype) => {+ 'separates business access recovery for %s/%s from user consent', (identity, subtype) => {const env = envFor('lark');- lark.rememberPermissionRequest(permissionError(identity, subtype), env);- expect(lark.readPermissionRequest(env)?.reauthorize).toBe(true);- if (identity !== 'user') expect(lark.readPermissionRequest(env)?.scopes).toEqual([]);+ const error = permissionError(identity, subtype);+ lark.rememberPermissionRequest(error, env);+ const recovery = identity === 'bot' || subtype === 'app_scope_not_applied'+ ? 'check_app_permissions' : 'check_resource_access';+ expect(error.provider_error.recovery).toBe(recovery);+ expect(lark.readPermissionRequest(env)).toMatchObject({ scopes: [], access_issues: [{ recovery }] });},);+ it.each(['same-scope', 'bot-access'])('preserves a newer %s denial arriving during successful Lark authorization', async variant => {+ const env = envFor('lark');+ permissions.rememberPermissionRequest(permissionError(), env);+ let newer;+ const execute = vi.fn(async () => {+ permissions.rememberPermissionRequest(permissionError(variant === 'same-scope' ? 'user' : 'bot'), env);+ newer = permissions.readPermissionRequest(env);+ });+ await auth.authorizeLark('', '', auth.MANIFESTS.lark, env, {+ execute, authorizationReady: () => true, authorizationScopes: () => ['offline_access'],+ });+ expect(permissions.readPermissionRequest(env)).toEqual(newer);+ expect(execute).toHaveBeenCalledOnce();+ });++ it('bounds repeated bot denials and retains their structured reason without provider prose', () => {+ const env = envFor('lark');+ for (let index = 0; index < 100; index++) {+ const error = lark.structuredFailure({ status: 1, stderr: '', stdout: JSON.stringify({+ ok: false, identity: 'bot', error: { type: 'api', code: 230013, message: `private-recipient-${index}` },+ }) });+ permissions.rememberPermissionRequest(error, env);+ expect(error.provider_error.recovery).toBe('check_bot_availability');+ }+ const pending = permissions.readPermissionRequest(env);+ expect(pending.access_issues).toEqual([{ identity: 'bot', recovery: 'check_bot_availability', code: 230013 }]);+ expect(JSON.stringify(pending)).not.toContain('private-recipient');+ expect(Buffer.byteLength(JSON.stringify(pending))).toBeLessThan(1024);+ });+it('verifies requested scope membership as well as the user identity', () => {const env = envFor('lark');const runner = vi.fn(() => ({ status: 0, stdout: JSON.stringify({ identities: { user: {diff --git a/test/main/features/connectors/local-cli_e2e_permissions.test.ts b/test/main/features/connectors/local-cli_e2e_permissions.test.tsindex afb16ae1..275a4ce5 100644--- a/test/main/features/connectors/local-cli_e2e_permissions.test.ts+++ b/test/main/features/connectors/local-cli_e2e_permissions.test.ts@@ -2,6 +2,7 @@ import { createRequire } from 'node:module';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { spawnSync } from 'node:child_process';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';import { expect, it } from 'vitest';@@ -10,6 +11,92 @@ const require = createRequire(import.meta.url);const adapter = require('../../../../bin/local-cli-mcp-server.cjs');const permissions = require('../../../../bin/local-cli-permissions.cjs');+it('completes real Lark authorization after bot denial without replaying a message or clearing the bot advisory', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-lark-recovery-e2e-'));+ const work = path.join(root, 'work');+ fs.mkdirSync(work);+ const cli = path.join(root, 'npx-cli.cjs');+ const trace = path.join(root, 'calls.jsonl');+ const grants = path.join(root, 'grants.json');+ const marker = path.join(root, 'integrity.json');+ const manifest = adapter.MANIFESTS.lark;+ const samples = require('./fixtures/lark-cli-1.0.93.json').samples;+ fs.writeFileSync(marker, JSON.stringify(manifest));+ fs.writeFileSync(grants, JSON.stringify(['offline_access']));+ fs.writeFileSync(cli, [+ "const fs = require('node:fs');",+ `const samples = ${JSON.stringify(samples)};`,+ `const trace = ${JSON.stringify(trace)}, grants = ${JSON.stringify(grants)};`,+ 'const args = process.argv.slice(5);',+ "fs.appendFileSync(trace, JSON.stringify(args) + '\\n');",+ "const scope = JSON.parse(fs.readFileSync(grants, 'utf8'));",+ "if (args[0] === 'auth' && args[1] === 'status') {",+ " process.stdout.write(JSON.stringify({identities:{user:{available:true,verified:true,scope:scope.join(' ')}}}));",+ "} else if (args[0] === 'auth' && args[1] === 'login') {",+ " fs.writeFileSync(grants, JSON.stringify(args[args.indexOf('--scope') + 1].split(' ')));",+ "} else if (args[0] === 'im' && args[1] === '+messages-send' && !args.includes('--help')) {",+ " const identity = args[args.indexOf('--as') + 1];",+ " if (identity === 'bot' || !scope.includes('im:message.send_as_user')) {",+ " process.stderr.write(JSON.stringify({ok:false,identity, error: identity === 'bot' ? {type:'api',code:230013} : {type:'authorization',subtype:'missing_scope',missing_scopes:['im:message.send_as_user']}}));",+ ' process.exitCode = 2;',+ " } else process.stdout.write(JSON.stringify({ok:true,data:{message_id:'explicit-retry'}}));",+ '} else {',+ ' const sample = samples.find(s => JSON.stringify(s.args) === JSON.stringify(args));',+ ' if (!sample) process.exit(9);',+ ' process.stdout.write(sample.stdout); process.stderr.write(sample.stderr); process.exitCode = sample.status;',+ '}',+ ].join('\n'));+ const node = process.env.ORKAS_TEST_NODE || process.execPath;+ const env = {+ ORKAS_LOCAL_CLI_PROVIDER: 'lark', ORKAS_LOCAL_CLI_BRAND: 'feishu',+ ORKAS_LOCAL_CLI_PACKAGE: manifest.package, ORKAS_LOCAL_CLI_PACKAGE_INTEGRITY: manifest.integrity,+ ORKAS_LOCAL_CLI_EXECUTABLE: manifest.executable, ORKAS_LOCAL_CLI_ALLOWED_DOMAINS_JSON: JSON.stringify(manifest.domains),+ ORKAS_LOCAL_CLI_RUNTIME_DIR: root, ORKAS_LOCAL_CLI_WORK_DIR: work,+ ORKAS_LOCAL_CLI_PROFILE: 'recovery-e2e', ORKAS_LOCAL_CLI_SKIP_AUTH_CHECK: '1',+ ORKAS_LOCAL_CLI_NPX_CLI: cli, ORKAS_LOCAL_CLI_INTEGRITY_MARKER: marker, ORKAS_NODE: node,+ };+ const transport = new StdioClientTransport({ command: node,+ args: [path.resolve('bin/local-cli-mcp-server.cjs')], env, stderr: 'pipe' });+ let diagnostics = '';+ transport.stderr?.on('data', data => { diagnostics += String(data); });+ const client = new Client({ name: 'lark-recovery-regression', version: '1.0.0' });+ const send = (identity: string) => client.callTool({ name: 'execute_high_impact', arguments: {+ action: 'im.+messages-send', parameters: { user_id: 'fixture-recipient', text: 'fixture', as: identity },+ } });+ const parse = (value: any) => JSON.parse(value.content[0].text);+ try {+ await client.connect(transport);+ for (const identity of ['bot', 'user']) {+ const denied = await send(identity);+ expect(denied.isError).toBe(true);+ expect(parse(denied).provider_error.recovery).toBe(identity === 'bot' ? 'check_bot_availability' : 'reauthorize');+ }+ const authorized = spawnSync(node, [path.resolve('bin/local-cli-auth.cjs')], {+ env, encoding: 'utf8', timeout: 10_000,+ });+ expect(authorized.error).toBeUndefined();+ expect(authorized.status).toBe(0);+ expect(authorized.stderr).toBe('');+ expect(authorized.stdout).toBe('[Orkas] Authorization complete. You can close this terminal.\n');+ const pending = permissions.readPermissionRequest(env);+ expect(pending).toMatchObject({ scopes: [], access_issues: [+ { identity: 'bot', code: 230013, recovery: 'check_bot_availability' },+ ] });+ expect(JSON.parse(fs.readFileSync(grants, 'utf8'))).toEqual(['im:message.send_as_user', 'offline_access']);+ const callsBeforeRetry = fs.readFileSync(trace, 'utf8').trim().split('\n').map(line => JSON.parse(line));+ expect(callsBeforeRetry.filter(args => args[0] === 'im' && !args.includes('--help'))).toHaveLength(2);+ expect(callsBeforeRetry.filter(args => args[0] === 'auth' && args[1] === 'login')).toHaveLength(1);+ const retried = await send('user');+ expect(retried.isError).not.toBe(true);+ expect(parse(retried).result.data.message_id).toBe('explicit-retry');+ expect(permissions.readPermissionRequest(env)).toEqual(pending);+ } finally {+ await client.close();+ fs.rmSync(root, { recursive: true, force: true });+ expect(diagnostics).toBe('');+ }+});+// Real adapter/stdio/process lifecycle with synthetic provider protocol fixtures.// This proves operation isolation, not live provider consent or schema compatibility.it.each(['dingtalk', 'wecom'])('keeps %s reads usable across a business denial and adapter restart without login or replay', async provider => {diff --git a/test/main/ipc/connectors.test.ts b/test/main/ipc/connectors.test.tsindex cec3d64f..0c3ecfbd 100644--- a/test/main/ipc/connectors.test.ts+++ b/test/main/ipc/connectors.test.ts@@ -84,7 +84,9 @@ describe('ipc/connectors renderer DTO', () => {const entry = { id: 'feishu', auth_mode: 'local_cli' };const check = vi.fn(async () => undefined);vi.doMock('../../../src/main/features/connectors/local-cli', () => ({- checkLocalCliPermissions: check, localCliMissingPermissions: () => ['im:message.send_as_user'],+ checkLocalCliPermissions: check, localCliPermissionRecovery: () => ({+ missingPermissions: ['im:message.send_as_user'], accessAdvisories: [],+ }),}));vi.doMock('../../../src/main/features/connectors', () => ({connectorCatalog: () => [entry], listInstances: () => [instance],@@ -121,6 +123,28 @@ describe('ipc/connectors renderer DTO', () => {expect(_toClientInstanceForTest({ ...instance, origin: 'custom' }, true, 'u-ipc').reauthorization_required).toBeUndefined();});+ it.each(['legacy', 'bot', 'mixed'])('projects %s Lark access issues separately from user reauthorization', async variant => {+ const runtime = await import('../../../src/main/features/connectors/local-cli');+ const { _toClientInstanceForTest } = await import('../../../src/main/ipc/connectors');+ const directory = runtime.localCliRuntimeDir('u-access', 'feishu');+ fs.mkdirSync(directory, { recursive: true });+ const issue = { identity: 'bot', recovery: 'check_bot_availability', code: 230013, private_detail: 'must-not-cross-ipc' };+ fs.writeFileSync(path.join(directory, '.orkas-user-permissions.json'), JSON.stringify({+ profile: runtime.localCliProfileName('u-access', 'feishu'), reauthorize: true, unresolved_access: true,+ scopes: variant === 'mixed' ? ['im:message.send_as_user'] : [],+ ...(variant === 'legacy' ? {} : { access_issues: [issue] }),+ }));+ const instance = { ...baseInstance({ kind: 'stdio' }), id: 'feishu', origin: undefined };+ const dto = _toClientInstanceForTest(instance, true, 'u-access');+ expect(dto.status.kind).toBe('connected');+ expect(dto.reauthorization_required).toBe(variant === 'mixed' ? true : undefined);+ expect(dto.access_advisories).toEqual([variant === 'legacy' ? 'check_resource_access' : 'check_bot_availability']);+ expect(JSON.stringify(dto)).not.toMatch(/must-not-cross-ipc|230013|orkas-/);+ expect(runtime.localCliMissingPermissions('u-access', 'feishu'))+ .toEqual(variant === 'mixed' ? ['im:message.send_as_user'] : null);+ expect(_toClientInstanceForTest(instance, true, 'other-account').access_advisories).toBeUndefined();+ });+it('accepts OAuth start without waiting for the browser callback', async () => {const beginOAuthConnect = vi.fn(() => ({ attempt_id: 'attempt-1' }));vi.doMock('../../../src/main/features/connectors', () => ({diff --git a/test/renderer/connectors-degraded-card.test.ts b/test/renderer/connectors-degraded-card.test.tsindex 090dc156..ac0362a7 100644--- a/test/renderer/connectors-degraded-card.test.ts+++ b/test/renderer/connectors-degraded-card.test.ts@@ -117,6 +117,23 @@ describe('connector setup assistance', () => {expect(ordinary.innerHTML).not.toContain('permission-notice');});+ it.each(['check_bot_availability', 'check_app_permissions', 'check_resource_access'])(+ 'shows %s guidance without offering OAuth for a business-only advisory', recovery => {+ const ctx = loadConnectorsRenderer();+ const entry = { id: 'feishu', display_name: 'Feishu', auth_mode: 'local_cli' };+ const instance = { id: 'feishu', status: { kind: 'connected' }, access_advisories: [recovery, '<untrusted>'] };+ const card = ctx._renderCatalogCard(entry, instance);+ expect(card.innerHTML).toContain('data-act="use-connector"');+ expect(card.innerHTML).not.toContain('connectors.action.authorize_permissions');+ expect(card.querySelector('[data-role="access-notice"]').textContent).toBe('connectors.permissions.' + recovery);+ const mixed = ctx._renderCatalogCard(entry, { ...instance, reauthorization_required: true,+ missing_permissions: ['im:message.send_as_user'] });+ expect(mixed.innerHTML).toContain('connectors.action.authorize_permissions');+ expect(mixed.innerHTML).toContain('data-role="permission-notice"');+ expect(mixed.querySelector('[data-role="access-notice"]').textContent).toBe('connectors.permissions.' + recovery);+ },+ );+it('names DingTalk message permission and preserves unknown identifiers as text', () => {const ctx = loadConnectorsRenderer();ctx.t = (key: string, args: any = {}) => `${key} ${args.permissions || ''}`.trim();