Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changes/refactor-cli-core-1.3-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Changed — may break callers

- **b24 is built on cli-core 1.3.0.** The store moves to version 77 on its first run, and tools on cli-core 1.0 still
open it. The first help screen names `b24 session list`.
- **`session list` rows have `state`**: `saved`, `missing` or `unknown`, as in the other WireCat CLIs. A profile whose
sign-in cannot be read stays `signed_in: null` and keeps its `error`.
- **`session start --credential-storage` with another value** says which value it got:
`--credential-storage takes keyring or file; got <value>`.
- The deadline of each Bitrix24 request and of the token request is cli-core's `timeLimit`, not a copy of it.
1 change: 1 addition & 0 deletions contracts/help.snap
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Works with:
linear Linear issues and projects, searchable with your other WireCat data

Start here: b24 work session start (any profile name works)
b24 session list your profiles and their logged-in accounts
Next: b24 commands every command, by section
b24 guide scenarios: command sequences for common tasks
b24 help options output, offline, timeouts, dry run
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "1.0.0",
"@wirecat/cli-core": "1.3.0",
"commander": "15.0.0",
"valibot": "1.5.0"
},
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 3 additions & 4 deletions src/bitrix/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
systemKeyring,
} from "@wirecat/cli-base"
import { hostFetch } from "@wirecat/cli-base/http"
import { timeLimit } from "@wirecat/cli-core/cli"
import {
accountTokenCodec,
credentialStorage,
Expand Down Expand Up @@ -132,9 +133,7 @@ const exchange = async (
client_secret: context.client.clientSecret ?? "",
[grant === "refresh_token" ? "refresh_token" : "code"]: given ?? "",
})
const deadline = new AbortController()
const timer = setTimeout(() => deadline.abort(), REQUEST_MS)
timer.unref()
const deadline = timeLimit(REQUEST_MS)
const signal = context.signal ? AbortSignal.any([context.signal, deadline.signal]) : deadline.signal
try {
let response: Response
Expand Down Expand Up @@ -177,7 +176,7 @@ const exchange = async (
scopes: typeof scope === "string" ? scope.split(",").filter(Boolean) : [],
}
} finally {
clearTimeout(timer)
deadline.clear()
}
}

Expand Down
28 changes: 12 additions & 16 deletions src/bitrix/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { lookup as dnsLookup } from "node:dns/promises"
import { isIP } from "node:net"
import { CliError, isCliError, realSleep, type SleepLike, wallClock } from "@wirecat/cli-base"
import { type FetchLike as HttpFetch, hostFetch, providerWaitMs, readJsonResponse } from "@wirecat/cli-base/http"
import { apiJson, currentAttempt, type EventSink, providerEvent, providerRequest } from "@wirecat/cli-core/cli"
import {
apiJson,
currentAttempt,
type EventSink,
providerEvent,
providerRequest,
timeLimit,
} from "@wirecat/cli-core/cli"
import { fetchCrmFile, providerCall } from "@wirecat/cli-core/crm"
import { isPublicAddress } from "@wirecat/cli-core/documents"
import type { Pacer } from "@wirecat/cli-core/sends"
Expand Down Expand Up @@ -228,12 +235,7 @@ export class BitrixTransport {
endpointTemplate: onPortal ? loggedPath(url) : `${url.hostname}/…`,
transport: "http",
})
const deadline = new AbortController()
const timer = setTimeout(
() => deadline.abort(new DOMException("download timed out", "TimeoutError")),
6 * this.#timeoutMs,
)
timer.unref()
const deadline = timeLimit(6 * this.#timeoutMs)
const signal = AbortSignal.any([deadline.signal, ...(this.#signal ? [this.#signal] : [])])
try {
const response = await fetch(url.href, { method: "GET", redirect: "error", signal }).catch((error) => {
Expand All @@ -258,7 +260,7 @@ export class BitrixTransport {
disposition: response.headers.get("content-disposition"),
}
} finally {
clearTimeout(timer)
deadline.clear()
}
}

Expand Down Expand Up @@ -320,13 +322,7 @@ export class BitrixTransport {
const app = "accessToken" in auth
const token = app ? await auth.accessToken(run.refresh).catch(unsent) : undefined
const path = `/rest/${run.api === 3 ? "api/" : ""}`
// Not AbortSignal.timeout: its timer holds the run's async context until the deadline (tg-cli, 2026-11-05).
const deadline = new AbortController()
const timer = setTimeout(
() => deadline.abort(new DOMException(`${method} timed out`, "TimeoutError")),
this.#timeoutMs,
)
timer.unref()
const deadline = timeLimit(this.#timeoutMs)
const end = providerRequest(method, this.#events ?? providerEvent, {
method: "POST",
endpointTemplate: `${path}${app ? "" : ":user/:token/"}${method}`,
Expand Down Expand Up @@ -397,7 +393,7 @@ export class BitrixTransport {
...(typeof answer.next === "number" ? { next: answer.next } : {}),
}
} finally {
clearTimeout(timer)
deadline.clear()
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/commands/session-app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,12 @@ describe("a profile signed in with a local application", () => {
const status = await b24(["work", "session", "status", "--json"], { keyring })
expect(status.json().item).toMatchObject({ kind: "app", token_from: "keyring", portal: "example.bitrix24.test" })
const listed = await b24(["session", "list", "--json"], { keyring })
expect(listed.json().items).toContainEqual({ profile: "work", signed_in: true, token_from: "keyring" })
expect(listed.json().items).toContainEqual({
profile: "work",
signed_in: true,
state: "saved",
token_from: "keyring",
})
expect((await b24(["work", "session", "end", "--json"], { keyring })).code).toBe(0)
expect(keyring.get(...ENTRY)).toBeNull()
const ended = await b24(["work", "session", "status", "--json"], { keyring })
Expand Down
15 changes: 8 additions & 7 deletions src/commands/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import {
rootOf,
secretInputOf,
signInSteps,
storageOf,
type TokenStorage,
} from "@wirecat/cli-core/cli"
import { refuseTakenCrmAccount } from "@wirecat/cli-core/crm/cli"
import { Command } from "commander"
Expand Down Expand Up @@ -86,7 +88,7 @@ const answer = (command: Command, item: unknown) => renderAnswer(command, output
const PASTE = "If the browser did not come back here, paste the address it ended on: "

/** The local application's sign-in; the webhook's address and the application's key are never a flag (WC-SECR-5). */
const startWithApp = async (command: Command, args: StartArgs, storage: "keyring" | "file") => {
const startWithApp = async (command: Command, args: StartArgs, storage: TokenStorage) => {
const { env, profile, tokens, keyring, run, environment } = contextOf(command)
const host = portalHost(args.portal ?? "")
const clientId = (args.clientId ?? env[`${IDENTITY.envPrefix}_BITRIX24_CLIENT_ID`] ?? "").trim()
Expand Down Expand Up @@ -163,7 +165,7 @@ const startWithApp = async (command: Command, args: StartArgs, storage: "keyring
}

interface StartArgs {
credentialStorage: string
credentialStorage: TokenStorage
portal?: string
clientId?: string
}
Expand Down Expand Up @@ -193,7 +195,8 @@ const startCommand = () =>
"--credential-storage <storage>",
"where the sign-in is kept: keyring (the default, which falls back to a private file by itself when no " +
"keyring works), or file, not recommended",
"keyring",
storageOf,
"keyring" as TokenStorage,
)
.option("--portal <host>", "sign in through a local application on this portal, such as example.bitrix24.ru")
.option(
Expand All @@ -203,8 +206,6 @@ const startCommand = () =>
)
.action(async function (this: Command, args: StartArgs) {
const storage = args.credentialStorage
if (storage !== "keyring" && storage !== "file")
throw new CliError("validation_error", "--credential-storage takes keyring or file")
const { env, profile, tokens, keyring } = contextOf(this)
refuseSignInHere(this)
if (args.portal !== undefined) return answer(this, await startWithApp(this, args, storage))
Expand Down Expand Up @@ -301,10 +302,10 @@ const listCommand = () =>
const items = profilesHere(IDENTITY, configuredProfiles, env).map((profile) => {
try {
const from = store.read(profile)?.source ?? appSourceOf(env, profile, environment.keyring)
return { profile, signed_in: from !== undefined, token_from: from ?? null }
return { profile, signed_in: from !== undefined, state: from ? "saved" : "missing", token_from: from ?? null }
} catch (error) {
if (!(error instanceof CliError)) throw error
return { profile, signed_in: null, token_from: null, error: error.message }
return { profile, signed_in: null, state: "unknown", token_from: null, error: error.message }
}
})
renderAnswer(
Expand Down
Loading