diff --git a/changes/refactor-shared-account-remove.md b/changes/refactor-shared-account-remove.md new file mode 100644 index 0000000..c966a7f --- /dev/null +++ b/changes/refactor-shared-account-remove.md @@ -0,0 +1,13 @@ +### Changed — may break callers + +- **`account remove --delete-data` refuses with `account-remove.account-shared`, detail `account`.** It was + `account-remove.portal-shared` with detail `portal`. The command is now cli-core's shared CRM one (`@wirecat/cli-core` + 0.722.0). It still refuses while another profile here reads the same portal, even one whose session ended. Under + `--dry-run` it now warns and lists what would go, where it used to fail. +- **`account remove --delete-data` refuses when b24 cannot tell which portal another profile holds** + (`account-remove.account-unknown`, detail `profile`): a profile whose saved webhook is unreadable and that + `session start` never remembered. `--keep-data` still removes. +- **`session start` refuses a second sign-in to the same portal and user with the shared words.** The reason stays + `session.duplicate`; its detail `portal` is now `account`, and the message says to end the other profile with + `b24 session end`. A webhook sign-in to a profile named `files` or `foreign-contacts`, folders every + portal shares, is refused with `profile.reserved`. diff --git a/contracts/help.snap b/contracts/help.snap index b62fe3c..243f567 100644 --- a/contracts/help.snap +++ b/contracts/help.snap @@ -27,6 +27,7 @@ Works with: notion Notion pages and databases as local text, searchable with your other WireCat data ydisk Yandex Disk folders as local text, searchable with your other WireCat data wordpress WordPress posts and pages, searchable with your other WireCat data + linear Linear issues and projects, searchable with your other WireCat data Start here: b24 work session start (any profile name works) Next: b24 commands every command, by section diff --git a/contracts/wirecat.json b/contracts/wirecat.json index ef1a50d..67b31c9 100644 --- a/contracts/wirecat.json +++ b/contracts/wirecat.json @@ -71,19 +71,6 @@ "local": "read" } }, - { - "path": [ - "account", - "remove" - ], - "summary": "sign this profile out and forget it, keeping or deleting its data", - "effects": { - "remote": "none", - "local": "write" - }, - "permission": "account.remove", - "entity": "account_removal" - }, { "path": [ "sync" @@ -721,6 +708,19 @@ "permission": "search.all", "entity": "hit" }, + { + "path": [ + "account", + "remove" + ], + "summary": "sign this profile out and forget it, keeping or deleting its data", + "effects": { + "remote": "none", + "local": "write" + }, + "permission": "account.remove", + "entity": "account_removal" + }, { "path": [ "products", diff --git a/docs/commands.md b/docs/commands.md index a377681..e2b67b7 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -118,30 +118,6 @@ b24 session list **Example:** `b24 session list`, `b24 session list --json` -## `b24 account` - -this profile on this computer - -### `b24 account remove` - -sign the profile out, then forget it on this computer: its settings, its saved sign-in and its files; --keep-data leaves its messages in the store, where search still finds them, --delete-data deletes them; asks first, or --yes - -**Changes something on this computer only.** - -```sh -b24 account remove [options] -``` - -| Option | What it does | -|---|---| -| `--keep-data` | leave what the store holds of this account, still searchable. | -| `--delete-data` | delete what the store and the tool's own files hold of this account. | -| `--dry-run` | list what it would remove and keep, and change nothing. | - -**Returns:** account removal — profile, data, dry_run, account, revoked, config_file, removed, kept; every field: b24 commands info account remove - -**Example:** `b24 personal account remove --keep-data --dry-run`, `b24 personal account remove --delete-data --yes` - ## `b24 sync` bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that changed since the last sync, or everything with --rescan; a run stops before its deadline or --max-pages and the next one goes on from there @@ -1146,6 +1122,30 @@ b24 search all [options] **Example:** `b24 work search all Example LLC`, `b24 work search all website --only crm --json` +## `b24 account` + +this profile on this computer + +### `b24 account remove` + +sign the profile out, then forget it on this computer: its settings, its saved sign-in and its files; --keep-data leaves its messages in the store, where search still finds them, --delete-data deletes them; asks first, or --yes + +**Changes something on this computer only.** + +```sh +b24 account remove [options] +``` + +| Option | What it does | +|---|---| +| `--keep-data` | leave what the store holds of this account, still searchable. | +| `--delete-data` | delete what the store and the tool's own files hold of this account. | +| `--dry-run` | list what it would remove and keep, and change nothing. | + +**Returns:** account removal — profile, data, dry_run, account, revoked, config_file, removed, kept; every field: b24 commands info account remove + +**Example:** `b24 personal account remove --keep-data --dry-run`, `b24 personal account remove --delete-data --yes` + ## `b24 products` read the portal's product catalog diff --git a/docs/dev/test-matrix.md b/docs/dev/test-matrix.md index fe85aaa..9f5ae34 100644 --- a/docs/dev/test-matrix.md +++ b/docs/dev/test-matrix.md @@ -21,10 +21,6 @@ Measured from the test run (`coverage/argv.jsonl`), not searched for — see | `session status` | `--check` | ✅ | | | `session end` | | ✅ | | | `session list` | | ✅ | | -| `account remove` | | ✅ | | -| `account remove` | `--keep-data` | ✅ | | -| `account remove` | `--delete-data` | ✅ | | -| `account remove` | `--dry-run` | ✅ | | | `sync` | | ✅ | | | `sync` | `--rescan` | ✅ | | | `sync` | `--max-pages` | ✅ | | @@ -176,6 +172,10 @@ Measured from the test run (`coverage/argv.jsonl`), not searched for — see | `search all` | `--page` | ✅ | | | `search all` | `--exact` | ✅ | | | `search all` | `--timezone` | ✅ | | +| `account remove` | | ✅ | | +| `account remove` | `--keep-data` | ✅ | | +| `account remove` | `--delete-data` | ✅ | | +| `account remove` | `--dry-run` | ✅ | | | `products list` | | ✅ | | | `products list` | `--limit` | ✅ | | | `products list` | `--page` | ✅ | | diff --git a/package.json b/package.json index fc213c2..f0a6a44 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "docs:spell": "cspell lint --config cspell.json --no-progress --no-summary README.md SECURITY.md CHANGELOG.md AGENTS.md CLAUDE.md 'docs/*.md' 'skills/**/*.md'" }, "dependencies": { - "@wirecat/cli-core": "0.710.0", + "@wirecat/cli-core": "0.722.0", "commander": "15.0.0", "valibot": "1.5.0" }, @@ -71,7 +71,7 @@ "@cspell/dict-ru_ru": "2.3.4", "@types/node": "22.20.5", "@vitest/coverage-v8": "5.0.5", - "@wirecat/cli-base": "0.124.0", + "@wirecat/cli-base": "0.127.0", "@wirecat/cli-testing": "0.7.0", "cspell": "10.4.0", "esbuild": "0.28.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a1ce390..7ada9be 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,8 +13,8 @@ importers: .: dependencies: '@wirecat/cli-core': - specifier: 0.710.0 - version: 0.710.0(@wirecat/cli-base@0.124.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) + specifier: 0.722.0 + version: 0.722.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) commander: specifier: 15.0.0 version: 15.0.0 @@ -41,8 +41,8 @@ importers: specifier: 5.0.5 version: 5.0.5(vitest@5.0.5) '@wirecat/cli-base': - specifier: 0.124.0 - version: 0.124.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) + specifier: 0.127.0 + version: 0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-testing': specifier: 0.7.0 version: 0.7.0 @@ -1161,8 +1161,8 @@ packages: '@wasm-audio-decoders/opus-ml@0.0.3': resolution: {integrity: sha512-SEeTmk0eb3q5etJA/NHCRWW6BivTx9tqvNTmG0kg2ynuATEQRUZnwQE6Ibvl1BBvqIGHqI57+qyJMWmJBwb5XQ==} - '@wirecat/cli-base@0.124.0': - resolution: {integrity: sha512-kl/6+PqN7sWkWqYvI2ujvoDK6PaUBvY7NTB5oDYk0CQdqWDV2MqYxgR1BXxwWDB88SzUA5GpN7x0ykVHksjfaQ==} + '@wirecat/cli-base@0.127.0': + resolution: {integrity: sha512-w7LkZhICv4d08N/vEWT4BnxeWt9tPpkVEOFBIUL7sR+JX5PNTHJj3vVTTT/pWhqtmVBFvsFA1xtdoHEX2GfZwQ==} engines: {node: '>=22'} hasBin: true peerDependencies: @@ -1189,13 +1189,13 @@ packages: '@wirecat/cli-core-sqlite@1.1.0': resolution: {integrity: sha512-GpGlh/dAIX/nblBYCdT6DfWSLFxav9mxxeELQAfEuw+QZdT9unKxbi5xa02s/s4JS1P7n0PQx2sCABj4FlMRNw==} - '@wirecat/cli-core@0.710.0': - resolution: {integrity: sha512-cZ/eLpANwnL6JyDa/YmmRDCpNEKwbMLjE2OhGKLW8U6itxRCRjF64xYl6C30R9OpqFz/ZvkTLmNuzb+Iqrszwg==} + '@wirecat/cli-core@0.722.0': + resolution: {integrity: sha512-nJM/EA3qpHRi+g7OWLhogNH1ZKVhbu6LdAQP+rNW7Fha6tcdmBCYCoSI9T0V+yb9FkxnOPPj7qNWOsEkAsJGfQ==} engines: {node: ^22.16.0 || >=24} hasBin: true peerDependencies: '@napi-rs/canvas': '>=0.1.69 <2' - '@wirecat/cli-base': '>=0.120.0 <1.0.0' + '@wirecat/cli-base': '>=0.125.0 <1.0.0' commander: '>=15' mysql2: ^3.24.6 pg: ^8.23.1 @@ -3282,12 +3282,13 @@ snapshots: dependencies: '@wasm-audio-decoders/common': 9.0.7 - '@wirecat/cli-base@0.124.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5)': + '@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5)': dependencies: '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) cli-table3: 0.6.5 cross-spawn: 7.0.6 valibot: 1.5.0(typescript@7.0.2) + yaml: 2.9.1 optionalDependencies: '@napi-rs/keyring': 2.1.2 commander: 15.0.0 @@ -3302,7 +3303,7 @@ snapshots: '@wirecat/cli-core-sqlite@1.1.0': {} - '@wirecat/cli-core@0.710.0(@wirecat/cli-base@0.124.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': + '@wirecat/cli-core@0.722.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 1.3.0(zod@4.6.7) '@bomb.sh/tab': 0.0.22(commander@15.0.0) @@ -3312,7 +3313,7 @@ snapshots: '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) '@wasm-audio-decoders/flac': 0.2.11 '@wasm-audio-decoders/ogg-vorbis': 0.1.20 - '@wirecat/cli-base': 0.124.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) + '@wirecat/cli-base': 0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-core-onnx': 1.2.0 '@wirecat/cli-core-sqlite': 1.1.0 '@xmldom/xmldom': 0.9.12 diff --git a/src/commands/account.test.ts b/src/commands/account.test.ts index 74e2c2a..7b794cf 100644 --- a/src/commands/account.test.ts +++ b/src/commands/account.test.ts @@ -86,13 +86,57 @@ describe("account remove", () => { ) const refused = await b24(["work", "account", "remove", "--delete-data", "--yes", "--json"], { keyring }) expect(refused.code).not.toBe(0) - expect(refused.json().error).toMatchObject({ code: "conflict", reason: "account-remove.portal-shared" }) + expect(refused.json().error).toMatchObject({ + code: "conflict", + reason: "account-remove.account-shared", + details: { profiles: ["home"], account: "example.bitrix24.test" }, + }) expect(keyring.get("bitrix24-cli", "token:work")).toBe(FAKE_HOOK) const kept = await b24(["work", "account", "remove", "--keep-data", "--yes", "--json"], { keyring }) expect(kept.code).toBe(0) expect(keyring.get("bitrix24-cli", "token:home")).toBe(COLLEAGUE_HOOK) }) + it("--delete-data --dry-run warns that another profile reads the same portal, and changes nothing", async () => { + const { keyring } = await syncedWork() + const colleague = fakePortal({ "user.current": ok({ ID: "9" }), "user.admin": ok(false), "department.get": ok([]) }) + expect((await b24(["home", "session", "start"], { keyring, portal: colleague, stdin: COLLEAGUE_HOOK })).code).toBe( + 0, + ) + const ran = await b24(["work", "account", "remove", "--delete-data", "--dry-run", "--json"], { keyring }) + expect(ran.code).toBe(0) + expect(ran.err).toContain("without --dry-run this refuses: home also reads Bitrix24 account example.bitrix24.test") + expect(await storedAccounts()).toContain("bitrix24:example.bitrix24.test") + }) + + it("--delete-data still refuses when the other profile's webhook is unreadable, from what session start kept", async () => { + const { keyring } = await syncedWork() + const colleague = fakePortal({ "user.current": ok({ ID: "9" }), "user.admin": ok(false), "department.get": ok([]) }) + expect((await b24(["home", "session", "start"], { keyring, portal: colleague, stdin: COLLEAGUE_HOOK })).code).toBe( + 0, + ) + keyring.set("bitrix24-cli", "token:home", "not a webhook") + const refused = await b24(["work", "account", "remove", "--delete-data", "--yes", "--json"], { keyring }) + expect(refused.json().error).toMatchObject({ code: "conflict", reason: "account-remove.account-shared" }) + expect(await storedAccounts()).toContain("bitrix24:example.bitrix24.test") + }) + + it("--delete-data refuses when nothing tells which portal another profile holds", async () => { + const { keyring } = await syncedWork() + const accounts = join(process.env.B24_STATE_DIR ?? "", "accounts") + writeFileSync(join(accounts, "home.json"), `${JSON.stringify({ account: "unknown" })}\n`) + keyring.set("bitrix24-cli", "token:home", "not a webhook") + const refused = await b24(["work", "account", "remove", "--delete-data", "--yes", "--json"], { keyring }) + expect(refused.json().error).toMatchObject({ + code: "conflict", + reason: "account-remove.account-unknown", + details: { profile: "home" }, + }) + expect(keyring.get("bitrix24-cli", "token:work")).toBe(FAKE_HOOK) + expect(await storedAccounts()).toContain("bitrix24:example.bitrix24.test") + expect((await b24(["work", "account", "remove", "--keep-data", "--yes", "--json"], { keyring })).code).toBe(0) + }) + it("asks what happens to the data, and refuses without --yes when it cannot ask", async () => { const { keyring } = await syncedWork() const unchosen = await b24(["work", "account", "remove", "--json"], { keyring }) diff --git a/src/commands/account.ts b/src/commands/account.ts index 0fceff5..ea17c4f 100644 --- a/src/commands/account.ts +++ b/src/commands/account.ts @@ -1,122 +1,43 @@ -import { readFileSync } from "node:fs" -import { join } from "node:path" -import { CliError, type KeyringStore, resolvePaths } from "@wirecat/cli-base" -import { annotate } from "@wirecat/cli-base/commands" -import { - type AccountRemoval, - accountRemoveCommand, - LOCAL_READ, - LOCAL_WRITE, - ProfileTokenStore, - profilesHere, -} from "@wirecat/cli-core/cli" -import { oauthAccount } from "@wirecat/cli-core/oauth" -import type { AccountKey } from "@wirecat/cli-core/store" -import { Command } from "commander" +import type { KeyringStore } from "@wirecat/cli-base" +import { ProfileTokenStore, recalledAccount } from "@wirecat/cli-core/cli" +import type { CrmAccountOptions } from "@wirecat/cli-core/crm/cli" import { parseWebhook } from "../bitrix/webhook.js" import { configuration } from "../config.js" import { IDENTITY } from "../identity.js" -import { contextOf } from "../portal.js" import { PROVIDER } from "../store.js" -const stateOf = (env: NodeJS.ProcessEnv) => - resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env }).state - /** What `session start` remembered: `:`, which outlives `session end`. */ -const rememberedOf = (env: NodeJS.ProcessEnv, profile: string): { portal: string; userId: string } | undefined => { - try { - const { account } = JSON.parse(readFileSync(join(stateOf(env), "accounts", `${profile}.json`), "utf8")) - const parts = typeof account === "string" ? /^(.+):(\d+)$/.exec(account) : null - return parts?.[1] && parts[2] ? { portal: parts[1], userId: parts[2] } : undefined - } catch { - return undefined - } -} - -const tokensOf = (env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined) => - new ProfileTokenStore({ app: IDENTITY, env, ...(keyring ? { keyring } : {}) }) - -/** The portal a profile's saved webhook reaches; one from `B24_TOKEN` is no profile's own. */ -const savedPortalOf = (tokens: ProfileTokenStore, profile: string) => { - try { - const stored = tokens.read(profile) - if (!stored || stored.source === "environment") return undefined - const webhook = parseWebhook(stored.secret) - return { portal: new URL(webhook.origin).host, userId: webhook.userId } - } catch { - return undefined - } -} - -/** The portal and webhook user of each profile here, from its saved webhook, else from what `session start` kept. */ -export const portalsHere = (env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined, { savedOnly = false } = {}) => { - // biome-ignore lint/plugin/no-own-settings: this local read names no profile, so baseContext cannot give it - const { configuredProfiles } = configuration.resolveSettings({}, { env, needsProfile: false }) - const tokens = tokensOf(env, keyring) - return profilesHere(IDENTITY, configuredProfiles, env).flatMap((profile) => { - const saved = savedPortalOf(tokens, profile) - const found = saved ?? (savedOnly ? undefined : rememberedOf(env, profile)) - return found ? [{ profile, ...found }] : [] - }) +const rememberedOf = (profile: string, env: NodeJS.ProcessEnv) => { + const parts = /^(.+):(\d+)$/.exec(recalledAccount(IDENTITY, PROVIDER.name, profile, env)?.account ?? "") + return parts?.[1] && parts[2] ? { account: parts[1], user: parts[2] } : undefined } -const accountOf = ( - profile: string, - env: NodeJS.ProcessEnv, - keyring: KeyringStore | undefined, -): AccountKey | undefined => { - const portal = (savedPortalOf(tokensOf(env, keyring), profile) ?? rememberedOf(env, profile))?.portal - return portal ? { provider: PROVIDER.name, account: portal } : undefined -} - -const removal: AccountRemoval = { - // Neither an incoming webhook nor a local application's token can be revoked over REST; only the portal deletes them. - signOut: async (profile) => ({ - revoked: null, - removed: [ - `the webhook address or application sign-in of ${profile} (the webhook or application itself stays in Bitrix24)`, - ], - }), - account: (profile, { env, keyring }) => accountOf(profile, env, keyring), - secrets: (profile, { env, keyring }) => [ - { - credentials: { - configDir: resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env }).config, - service: IDENTITY.appName, - envVar: `${IDENTITY.envPrefix}_TOKEN`, - env, - ...(keyring ? { keyring } : {}), - }, - accounts: [`token:${profile}`, oauthAccount(PROVIDER.name, profile)], - }, - ], - stateFiles: (profile, { env }) => [join(stateOf(env), "crm", profile)], -} - -/** The store keeps one account per portal, so deleting one profile's data deletes every profile's on that portal. */ -const refuseSharedDelete = (command: Command) => { - if (command.opts().deleteData !== true) return - const { env, keyring, profile } = contextOf(command) - const portals = portalsHere(env, keyring) - const own = portals.find((one) => one.profile === profile) - const sharing = own ? portals.filter((one) => one.profile !== profile && one.portal === own.portal) : [] - if (sharing.length === 0 || !own) return - const names = sharing.map((one) => one.profile).join(", ") - throw new CliError( - "conflict", - `${names} also read${sharing.length === 1 ? "s" : ""} ${own.portal}, and the store keeps one copy of a portal: ` + - `--delete-data would delete their deals, leads, contacts and companies too. Use --keep-data, or remove ` + - `${names} first`, - { reason: "account-remove.portal-shared", profiles: sharing.map((one) => one.profile), portal: own.portal }, +/** The portal and user of a profile's saved webhook; one from `B24_TOKEN` is no profile's own. */ +const savedOf = (profile: string, env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined) => { + const stored = new ProfileTokenStore({ app: IDENTITY, env, ...(keyring ? { keyring } : {}), warn: () => {} }).read( + profile, ) + if (!stored || stored.source === "environment") return undefined + const webhook = parseWebhook(stored.secret) + return { account: new URL(webhook.origin).host, user: webhook.userId } } -export const accountCommand = (): Command => - annotate(new Command("account"), { effects: LOCAL_READ }) - .description("this profile on this computer") - .addCommand( - // An incoming webhook has no sign-out to call, so b24's removal never reaches the portal. - annotate(accountRemoveCommand(IDENTITY, removal, { resolveSettings: configuration.resolveSettings }), { - effects: LOCAL_WRITE, - }).hook("preAction", (_, action) => refuseSharedDelete(action)), - ) +/** The store names a Bitrix24 account by its portal host, and one portal has a webhook user per employee. */ +export const B24_ACCOUNT: CrmAccountOptions = { + provider: PROVIDER.name, + service: "Bitrix24", + held: (profile, { env, keyring }) => { + const remembered = rememberedOf(profile, env) + try { + const saved = savedOf(profile, env, keyring) + if (saved) return { ...saved, signedIn: true } + } catch (error) { + // Nothing else tells which portal's copy --delete-data would delete. + if (!remembered) throw error + } + return remembered && { ...remembered, signedIn: false } + }, + signedOut: (profile) => + `the webhook address or application sign-in of ${profile} (the webhook or application itself stays in Bitrix24)`, + resolveSettings: configuration.resolveSettings, +} diff --git a/src/commands/crm-shared.ts b/src/commands/crm-shared.ts index d2a45eb..5112d70 100644 --- a/src/commands/crm-shared.ts +++ b/src/commands/crm-shared.ts @@ -10,6 +10,7 @@ import { permissions } from "../config.js" import { BITRIX_WRITES } from "../crm/capabilities.js" import { IDENTITY } from "../identity.js" import { contextOf, signInOf, storedSignIn, transportFor } from "../portal.js" +import { B24_ACCOUNT } from "./account.js" /** The sign-in's own portal user, read offline from its entry; a profile with none reads none of the copy's deals. */ const ownUser = (command: Command): string | null => { @@ -105,6 +106,7 @@ export const crmSharedCommands = (): Command[] => { writes: BITRIX_WRITES, live: ["person", "organization", "user"], files: true, + account: B24_ACCOUNT, }) return [...holder.commands] } diff --git a/src/commands/session.test.ts b/src/commands/session.test.ts index d71aa31..1500b09 100644 --- a/src/commands/session.test.ts +++ b/src/commands/session.test.ts @@ -148,7 +148,7 @@ describe("session", () => { expect(ran.json().error).toMatchObject({ code: "conflict", reason: "session.duplicate", - message: expect.stringContaining("b24 work account remove --keep-data"), + message: expect.stringContaining("b24 work session end"), }) expect(asked.calls).toHaveLength(0) expect(keyring.get("bitrix24-cli", "token:home")).toBeNull() diff --git a/src/commands/session.ts b/src/commands/session.ts index 30db66e..ac5696d 100644 --- a/src/commands/session.ts +++ b/src/commands/session.ts @@ -1,4 +1,4 @@ -import { CliError, isCliError, type KeyringStore } from "@wirecat/cli-base" +import { CliError, isCliError } from "@wirecat/cli-base" import { annotate } from "@wirecat/cli-base/commands" import { readSecret } from "@wirecat/cli-core" import { @@ -26,31 +26,15 @@ import { secretInputOf, signInSteps, } from "@wirecat/cli-core/cli" +import { refuseTakenCrmAccount } from "@wirecat/cli-core/crm/cli" import { Command } from "commander" import { appSignIn, appSourceOf, appStorage, portalHost } from "../bitrix/oauth.js" -import { parseWebhook, type Webhook } from "../bitrix/webhook.js" +import { parseWebhook } from "../bitrix/webhook.js" import { configuration } from "../config.js" import { IDENTITY } from "../identity.js" import { appAuthFor, type B24Environment, contextOf, transportFor, withPortal } from "../portal.js" import { webhookUser } from "../whoami.js" -import { portalsHere } from "./account.js" - -/** A second profile on the same webhook user would sync the same copy twice and split its permissions. */ -const refuseDuplicate = (env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined, profile: string, at: Webhook) => { - const portal = new URL(at.origin).host - const other = portalsHere(env, keyring, { savedOnly: true }).find( - (one) => one.profile !== profile && one.portal === portal && one.userId === at.userId, - ) - if (!other) return - const b24 = IDENTITY.command - throw new CliError( - "conflict", - `profile ${other.profile} already uses this webhook (${portal}, user ${at.userId}). Use \`${b24} ${other.profile}\`, ` + - `sign it in again with \`${b24} ${other.profile} session start\`, or remove it with ` + - `\`${b24} ${other.profile} account remove --keep-data\` and then sign in as ${profile}`, - { reason: "session.duplicate", profile: other.profile, portal }, - ) -} +import { B24_ACCOUNT } from "./account.js" const USER_METHODS = new Set(["user.current", "user.admin"]) @@ -76,10 +60,15 @@ export const refuseSignInHere = (command: Command) => { * here uses it, and the portal answers who made it. Keeps nothing. */ export const checkedWebhook = async (command: Command, address: string) => { - const { env, profile, keyring, run } = contextOf(command) + const { env, profile, keyring, settings, run } = contextOf(command) const webhook = parseWebhook(address) const portal = new URL(webhook.origin).host - refuseDuplicate(env, keyring, profile, webhook) + refuseTakenCrmAccount( + IDENTITY, + B24_ACCOUNT, + { env, profile, profiles: settings.configuredProfiles, ...(keyring ? { keyring } : {}) }, + { account: portal, user: webhook.userId }, + ) const user = await run((events) => webhookUser(transportFor(command, webhook, events))).catch((error: unknown) => { if ( isCliError(error) && diff --git a/src/program.ts b/src/program.ts index bf9d223..0cf6512 100644 --- a/src/program.ts +++ b/src/program.ts @@ -23,7 +23,6 @@ import { import { appUpdate } from "@wirecat/cli-core/update" import type { Command } from "commander" import { appSourceOf } from "./bitrix/oauth.js" -import { accountCommand } from "./commands/account.js" import { apiCommand } from "./commands/api.js" import { callsCommand } from "./commands/calls.js" import { crmSharedCommands } from "./commands/crm-shared.js" @@ -109,7 +108,6 @@ export const definition = (): ProgramDefinition => { commands: () => [ commandsCommand(IDENTITY), sessionCommand(), - accountCommand(), ...crmSharedCommands(), productsCommand(), callsCommand(), diff --git a/src/reasons.ts b/src/reasons.ts index 345d1f8..ddb473d 100644 --- a/src/reasons.ts +++ b/src/reasons.ts @@ -19,8 +19,6 @@ const OWN: [reason: string, code: string, message: string][] = [ ["webhook.malformed", "validation_error", "that is not a Bitrix24 incoming webhook address"], ["webhook.refused", "authentication_error", "Bitrix24 refused this webhook or application sign-in"], ["webhook.scope-missing", "permission_error", "the webhook has no scope for this method"], - ["session.duplicate", "conflict", "another profile here already uses this webhook"], - ["account-remove.portal-shared", "conflict", "another profile reads the same portal, whose copy the store shares"], ["bitrix.scope-all-refused", "configuration_error", "b24 never copies the whole CRM; set scope to mine"], ["bitrix.access-denied", "permission_error", "the webhook's user may not do this"], ["webhook.app-only", "permission_error", "Bitrix24 lets only an installed app call this method, not a webhook"],