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
16 changes: 16 additions & 0 deletions changes/feat-cli-config-verify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
### Added

- **`wirecat.config`'s `auth.verify`: the call that checks a token.** For `token` and `oauth2-pkce`, `{ operation, id,
name? }` names the operation that answers whose the token is and where its answer holds the account's id and name;
cli-template's `session start` checks a token with it.
- **`recalledAccount` from `@wirecat/cli-core/cli`**: the account a profile signed in to, as `session start`
remembered it, for a CLI's own account key (cli-template's CRM wiring from `wirecat.config`).

### Changed — may break callers

- **cli-core needs `@wirecat/cli-base` 0.112.0 or later** (peer `>=0.112.0 <1.0.0`), since 0.693.0, for
`signInRequirements` and `signInPlace`.
- **`parseCliConfig` refuses a URL that would put a secret, a space or no host into a CLI's files**: `spec.from`,
`auth.revokeUrl` and a relay redirect take an https URL with a host, and no user name, password, #fragment, or
key or token in its query. `auth.verify`'s `id` and `name` are dot paths. `hooks` takes a `.ts` or `.js` module
under `./`. An unknown field reads "not a field of wirecat.config", a missing one "missing".
2 changes: 1 addition & 1 deletion src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ export { readMeetingProjectCandidates } from "./meeting-project-candidates-read.
export { meetingResultItem } from "./meeting-results.js"
export { type MeetingSeriesInventoryReader, readMeetingSeriesInventory } from "./meeting-series-inventory-read.js"
export { addMeetingTagsCommand, type MeetingTagsCommandDeps } from "./meeting-tags-command.js"
export { accountFileFor, profilesHere, rememberAccount } from "./messenger/accounts.js"
export { accountFileFor, profilesHere, recalledAccount, rememberAccount } from "./messenger/accounts.js"
export { terminalAsker } from "./messenger/ask.js"
export type { CompletionOptions } from "./messenger/complete-command.js"
export {
Expand Down
68 changes: 67 additions & 1 deletion src/manifest/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,72 @@ describe("parseCliConfig", () => {
"identity.owner",
)
expect(() => parseCliConfig({ ...config, source: { provider: "acme" } })).toThrow("only a crm CLI")
expect(() => parseCliConfig({ ...config, extra: true })).toThrow("wirecat.config")
expect(() => parseCliConfig({ ...config, extra: true })).toThrow(
"wirecat.config: extra: not a field of wirecat.config",
)
})

it("takes each category, a crm CLI with its source, and a token's verify call", () => {
for (const category of ["mail", "files", "other"] as const)
expect(parseCliConfig({ ...config, category }).category).toBe(category)
expect(() => parseCliConfig({ ...config, category: "tracker" })).toThrow("wirecat.config: category")
const crm = { ...config, category: "crm" as const, source: { provider: "acme" } }
expect(parseCliConfig(crm).source).toEqual({ provider: "acme" })
const verify = { operation: "getV2Self", id: "workspace_id", name: "workspace_name" }
expect(parseCliConfig({ ...config, auth: { preset: "token", verify } }).auth).toEqual({ preset: "token", verify })
expect(() => parseCliConfig({ ...config, auth: { preset: "token", verify: { id: "id" } } })).toThrow(
"wirecat.config: auth.verify.operation: missing",
)
for (const id of ["", "a..b", ".a"])
expect(() => parseCliConfig({ ...config, auth: { preset: "token", verify: { operation: "me", id } } })).toThrow(
"auth.verify.id: a dot path",
)
})

it("refuses a URL that would put a secret, a space or no host into the CLI's files", () => {
for (const [from, why] of <[string, string][]>[
["https://user:pass@api.acme.test/o.json", "without a user name or password"],
["https://api.acme.test/o.json?api_key=x", "without a key or token in its query"],
["https://api.acme.test/o.json?accessToken=x", "without a key or token in its query"],
["https://api.acme.test/o.json?x=1#access_token=abc", "without a #fragment"],
["https://api.acme.test/a b.json", "without spaces"],
["https://@", "a valid https URL with a host"],
["https://api.acme.test:99999/x", "a valid https URL with a host"],
])
expect(() => parseCliConfig({ ...config, spec: { kind: "openapi", from } }), from).toThrow(
`spec.from: ${why.startsWith("a valid") ? why : `an https URL ${why}`}`,
)
for (const from of ["https://api.acme.test/o.json?v=2", "https://api.acme.test/auth/o.json?design=1&keyword=x"])
expect(parseCliConfig({ ...config, spec: { kind: "openapi", from } }), from).toBeTruthy()
const oauth = (extra: object) => ({ ...config, auth: { preset: "oauth2-pkce", scopes: [], ...extra } })
expect(() => parseCliConfig(oauth({ revokeUrl: "https://" }))).toThrow("auth.revokeUrl")
expect(() => parseCliConfig(oauth({ redirect: { kind: "relay", url: "https://u:p@r.test/" } }))).toThrow(
"auth.redirect.url",
)
})

it("refuses an old field and names a missing one", () => {
expect(() => parseCliConfig({ ...config, identity: { ...config.identity, provider: "acme" } })).toThrow(
"wirecat.config: identity.provider: not a field of wirecat.config",
)
const { spec: _, ...noSpec } = config
expect(() => parseCliConfig(noSpec)).toThrow("wirecat.config: spec: missing")
expect(() => parseCliConfig({ ...config, auth: { preset: "oauth2-pkce", scopes: [undefined] } })).toThrow(
/auth\.scopes\.0: (?!missing)/,
)
})

it("takes the hooks module only as a script in the project", () => {
for (const hooks of [
"./",
"./src/hooks.json",
"./src/hooks.ts ",
"./a/../../x.ts",
"src/hooks.ts",
"./.ts",
"./src/hooks.d.ts",
])
expect(() => parseCliConfig({ ...config, hooks }), hooks).toThrow("wirecat.config: hooks")
expect(parseCliConfig({ ...config, hooks: "./src/hooks.js" }).hooks).toBe("./src/hooks.js")
})
})
108 changes: 92 additions & 16 deletions src/manifest/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { isAbsolute } from "node:path"
import { CliError } from "@wirecat/cli-base"
import * as v from "valibot"
import type { CrmManifest } from "../crm/manifest/manifest.js"
import type { OAuthProvider } from "../oauth/provider.js"

/**
* The operation that answers whose the token is, and where its answer holds the account's id (and a name to show):
* `{ operation: "getV2Self", id: "workspace_id", name: "workspace_name" }`. `session start` checks a token with it.
*/
export interface CliVerify {
operation: string
id: string
name?: string
}

export type CliAuth =
| { preset: "none" }
/** A token or key, sent where the spec's `securitySchemes` say: a bearer header, an API key header or query. */
| { preset: "token" }
| { preset: "token"; verify?: CliVerify }
/** The browser sign-in the spec's authorization code flow declares; the redirect is what the app registered. */
| {
preset: "oauth2-pkce"
verify?: CliVerify
scopes: readonly string[]
scheme?: string
redirect?: OAuthProvider["redirect"]
Expand Down Expand Up @@ -56,9 +66,56 @@ const word = v.pipe(
v.regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "lower-case letters and digits, words joined by one dash"),
)

/** In the project: no absolute path, no `..`, no scheme. */
const projectPath = (text: string) =>
!isAbsolute(text) && !text.split(/[\\/]/).includes("..") && !/^[a-z][a-z0-9+.-]*:/i.test(text)
// A query parameter with such a word in its name holds a secret, which the URL would put into a committed file. Whole
// words, so `design` or `keyword` stay allowed.
const SECRET_WORDS = new Set([
"key",
"apikey",
"token",
"secret",
"sig",
"signature",
"auth",
"password",
"pass",
"passwd",
"credential",
"credentials",
"session",
"sessionid",
"jwt",
"code",
])
const secretName = (name: string) =>
name.split(/[_\-.]+|(?<=[a-z0-9])(?=[A-Z])/).some((part) => SECRET_WORDS.has(part.toLowerCase()))

const urlOf = (text: string) => (URL.canParse(text) ? new URL(text) : undefined)

/** An https URL that can be committed: a host, no spaces, no user name or password, no secret in its query. */
const httpsUrl = v.pipe(
v.string(),
v.check((text) => !/\s/.test(text), "an https URL without spaces"),
v.check((text) => {
const url = urlOf(text)
return url?.protocol === "https:" && url.hostname.length > 0
}, "a valid https URL with a host"),
v.check((text) => {
const url = urlOf(text)
return !url?.username && !url?.password
}, "an https URL without a user name or password, which would be committed"),
v.check(
(text) => ![...(urlOf(text)?.searchParams.keys() ?? [])].some(secretName),
"an https URL without a key or token in its query, which would be committed",
),
// A token handed back in the fragment (OAuth's implicit flow) would be committed too; a description needs none.
v.check((text) => !urlOf(text)?.hash, "an https URL without a #fragment"),
)

const dotPath = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dot path into the answer, such as data.id"))

const verify = v.optional(
v.strictObject({ operation: v.pipe(v.string(), v.minLength(1)), id: dotPath, name: v.optional(dotPath) }),
)

const schema = v.strictObject({
identity: v.strictObject({
Expand All @@ -70,44 +127,63 @@ const schema = v.strictObject({
}),
spec: v.strictObject({
kind: v.picklist(["openapi", "swagger"]),
from: v.pipe(
v.string(),
v.check((text) => /^https:\/\/[^/\s]+/.test(text), "the https URL the description is published at"),
),
from: httpsUrl,
}),
auth: v.variant("preset", [
v.strictObject({ preset: v.literal("none") }),
v.strictObject({ preset: v.literal("token") }),
v.strictObject({ preset: v.literal("token"), verify }),
v.strictObject({
preset: v.literal("oauth2-pkce"),
verify,
scopes: v.array(v.string()),
scheme: v.optional(v.string()),
revokeUrl: v.optional(v.pipe(v.string(), v.startsWith("https://"))),
revokeUrl: v.optional(httpsUrl),
authorizeParams: v.optional(v.record(v.string(), v.string())),
rotating: v.optional(v.boolean()),
redirect: v.optional(
v.variant("kind", [
v.strictObject({ kind: v.literal("loopback"), host: v.optional(v.literal("localhost")) }),
v.strictObject({ kind: v.literal("relay"), url: v.pipe(v.string(), v.startsWith("https://")) }),
v.strictObject({ kind: v.literal("relay"), url: httpsUrl }),
]),
),
}),
]),
category: v.picklist(CLI_CATEGORIES),
source: v.optional(v.looseObject({})),
hooks: v.optional(v.pipe(v.string(), v.startsWith("./"), v.check(projectPath, "a module in the project"))),
hooks: v.optional(
v.pipe(
v.string(),
v.regex(/^\.\/([^\s]*\/)?[^/\s.][^/\s]*\.[cm]?[jt]s$/, "a module in the project, such as ./src/hooks.ts"),
v.check((text) => !/\.d\.[cm]?ts$/.test(text), "a module, not a .d.ts declaration file"),
v.check((text) => !text.split(/[\\/]/).includes(".."), "a module in the project, without .."),
),
),
})

/** The config checked against its shape; every error names where it is. A CRM CLI needs its source. */
/**
* The config checked against its shape; every error names where it is. A CRM CLI needs its source. `source` comes back
* unchecked: `parseCrmManifest` checks it against the generated API.
*/
export const parseCliConfig = (input: unknown): CliConfig => {
const parsed = v.safeParse(schema, input)
if (!parsed.success) {
const [issue] = parsed.issues
throw new CliError("configuration_error", `wirecat.config: ${v.getDotPath(issue) ?? "(root)"}: ${issue.message}`, {
// valibot's own words for a key: "Invalid key: Expected never but received …". By the issue's shape, so a value
// that is undefined inside a list or record keeps valibot's words.
const keyed = issue.type === "strict_object" || issue.type === "variant"
const message =
keyed && issue.expected === "never"
? "not a field of wirecat.config"
: keyed && issue.input === undefined
? "missing"
: issue.message
throw new CliError("configuration_error", `wirecat.config: ${v.getDotPath(issue) ?? "(root)"}: ${message}`, {
reason: "manifest.invalid",
})
}
const config = parsed.output as CliConfig
// Typed, not cast: a field CliConfig needs that the schema lacks or types otherwise fails to compile (not the reverse).
const output: Omit<CliConfig, "source"> & { source?: Readonly<Record<string, unknown>> } = parsed.output
const config = output as CliConfig
if (config.category !== "crm" && config.source)
throw new CliError("configuration_error", "wirecat.config: source: only a crm CLI reads a source yet", {
reason: "manifest.invalid",
Expand Down
Loading