@roilab/crm-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ Todos los cambios notables se documentan aquí. El formato sigue
4
+ [Keep a Changelog](https://keepachangelog.com/es/) y el versionado es
5
+ [SemVer](https://semver.org/lang/es/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+ - Comprobación diaria de versión contra el registro de npm; `crm doctor` avisa
11
+ cuando hay una versión más reciente.
12
+
13
+ ## [0.1.0] — 2026-04-23
14
+
15
+ ### Added
16
+ - Publicación inicial en npm como `@roilab/crm-cli`.
17
+ - Flujo de dispositivo (OAuth-style) para login sin pegar API keys.
18
+ - Sustantivos: `auth`, `task`, `comment`, `client`, `domain`, `backlink`,
19
+ `change`, `scope`, `competitor`, `tag`, `member`, `recall`, `search`,
20
+ `inbox`, `review`, `doctor`.
21
+ - Flag `--shadow` para forzar que una escritura aterrice como propuesta
22
+ pendiente de revisión.
23
+ - Flag `--wait-for-approval` para bloquear hasta decisión humana.
24
+ - `crm recall <url>` como memoria cross-entity antes de crear trabajo nuevo.
25
+ - Todas las cadenas visibles en español.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ROILab Intelligence
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @roilab/crm-cli
2
+
3
+ > CLI for humans and AI agents to drive the ROILab SEO+CRM platform.
4
+
5
+ CLI para el SEO + CRM de ROILab, pensado tanto para humanos como para agentes de
6
+ IA (Claude Code, Cursor, Windsurf). Envoltura JSON siempre, exit codes numéricos,
7
+ escrituras idempotentes y login sin pegar API keys en texto plano (flujo de
8
+ dispositivo tipo OAuth).
9
+
10
+ ## Instalación
11
+
12
+ ### Agentes (recomendado)
13
+
14
+ Sin instalación previa, siempre la última versión:
15
+
16
+ ```bash
17
+ npx -y @roilab/crm-cli@latest <comando>
18
+ ```
19
+
20
+ ### Humanos
21
+
22
+ Para dejar `crm` en el PATH:
23
+
24
+ ```bash
25
+ npm i -g @roilab/crm-cli
26
+ crm --help
27
+ ```
28
+
29
+ Actualiza con:
30
+
31
+ ```bash
32
+ npm i -g @roilab/crm-cli@latest
33
+ ```
34
+
35
+ El propio CLI comprueba una vez al día si hay una versión nueva en npm y avisa
36
+ por stderr. Para forzar la comprobación, ejecuta `crm doctor`.
37
+
38
+ ## Primer login (30 segundos)
39
+
40
+ ```bash
41
+ crm auth login --device-name mi-portatil
42
+ # Abre la URL que aparece en el navegador, aprueba.
43
+ crm auth whoami
44
+ crm doctor
45
+ ```
46
+
47
+ El CLI guarda tokens rotativos en `~/.config/crm/credentials.json` (modo `0600`).
48
+ Nunca se escribe una API key en claro en disco por esta vía.
49
+
50
+ ## Comandos
51
+
52
+ ```bash
53
+ crm recall https://example.com/pricing
54
+ crm task list --status todo --domain dom_xyz --limit 20
55
+ crm task create --title "Arreglar H1 en /pricing" --domain dom_xyz --shadow
56
+ crm comment create --task tsk_abc --body "Desplegado en prod" --kind agent_log
57
+ crm domain metrics dom_xyz --start 2026-03-01 --end 2026-04-01 --markdown
58
+ crm review list --mine
59
+ ```
60
+
61
+ `crm --help` imprime todos los sustantivos; `crm <noun> --help` imprime los
62
+ verbos; la documentación completa vive en la app, pestaña **Documentación**, que
63
+ se auto-genera desde el registro de endpoints — siempre refleja la versión
64
+ servida.
65
+
66
+ ## Flags globales
67
+
68
+ Disponibles en cada comando:
69
+
70
+ - `--json` — envoltura JSON completa (por defecto).
71
+ - `--quiet` — solo `data`.
72
+ - `--ids-only` — un id por línea.
73
+ - `--count` — un único entero.
74
+ - `--markdown` — resumen legible (no es JSON).
75
+ - `--jq <expr>` — jq mini (`.a`, `.a.b`, `.a[]`, `.a[].b`).
76
+ - `--shadow` — fuerza que la escritura aterrice como propuesta pendiente de
77
+ revisión humana.
78
+ - `--wait-for-approval --timeout 30m` — bloquea hasta que un humano decida.
79
+ - `--idempotency-key <key>` — idempotency key estable (automática en escrituras).
80
+
81
+ ## Seguridad
82
+
83
+ - Sin scripts `preinstall` / `postinstall` / `install` — nada que se ejecute al
84
+ instalar el paquete.
85
+ - Auth por flujo de dispositivo: no se comparten secretos entre máquinas; el
86
+ access token caduca en 1 h y el refresh token rota en cada uso.
87
+ - Archivo de credenciales con permisos `0600`, aislado por perfil.
88
+ - Publicación con atestación de procedencia (`npm publish --provenance`) para
89
+ que se pueda verificar el origen del tarball.
90
+
91
+ ## Licencia
92
+
93
+ MIT — ver [LICENSE](./LICENSE).
package/SKILL.md ADDED
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: crm
3
+ description: Drive the ROILab SEO+CRM from a shell. Tasks, comments, analytics, backlinks, change events, and cross-entity recall — every action is auditable and attributed to you as an agent.
4
+ ---
5
+
6
+ # `crm` — CLI for AI agents + humans
7
+
8
+ This skill teaches you to operate the ROILab SEO+CRM via the `crm` binary. All writes you make are stamped `actorType: "agent"` and associated with your API key, so there is a robot badge next to your changes in the web UI. Humans can filter and review what you did.
9
+
10
+ ## Getting started
11
+
12
+ Two ways to authenticate, pick the one that matches your environment.
13
+
14
+ **Device flow — for human-driven use (recommended):**
15
+
16
+ ```bash
17
+ crm auth login --api-url https://crm.roilab.es
18
+ # Prints a URL + 8-char code. Open the URL in your already-signed-in
19
+ # browser and click "Approve". The CLI polls and stores a 1-hour access
20
+ # token + 30-day refresh token. Tokens auto-rotate; nothing long-lived
21
+ # ends up on disk.
22
+ ```
23
+
24
+ **API key — for unattended use (CI, agents-as-a-service):**
25
+
26
+ ```bash
27
+ export CRM_API_KEY=crm_ak_... # or crm auth login crm_ak_...
28
+ crm doctor # verify reachability + auth
29
+ crm task list --status todo --limit 5
30
+ ```
31
+
32
+ API keys are long-lived and workspace-scoped; leak-sensitive. Prefer the
33
+ device flow for interactive use; use raw keys only where a browser isn't
34
+ available.
35
+
36
+ If you need a new API key, ask the human to visit `Settings → Developers
37
+ → API Keys` in the web UI and share one.
38
+
39
+ ## Output contract — read this carefully
40
+
41
+ Every command emits a JSON envelope. Use `--jq` for filtering, **never pipe to `jq`**:
42
+
43
+ ```bash
44
+ crm task list --jq '.data[].title' # OK
45
+ crm task list | jq '.data[].title' # WRONG — the envelope matters
46
+ ```
47
+
48
+ Flags (mutually exclusive except `--jq`):
49
+ - `--json` — default. Full envelope with `ok`, `data`, `summary`, `breadcrumbs`, `meta`.
50
+ - `--quiet` — just `data`. Good for pipelines.
51
+ - `--ids-only` — one id per line.
52
+ - `--count` — a single integer.
53
+ - `--markdown` — human preview (NOT JSON, do not parse).
54
+ - `--jq <expr>` — tiny filter: `.a`, `.a.b`, `.a[]`, `.a[].b`, `.`. Full jq is intentionally not bundled.
55
+
56
+ Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit codes:
57
+
58
+ | Code | Meaning |
59
+ |------|---------|
60
+ | 0 | success |
61
+ | 2 | not found |
62
+ | 3 | auth failure |
63
+ | 4 | forbidden / missing scope |
64
+ | 5 | rate-limited |
65
+ | 6 | network / timeout |
66
+ | 7 | validation |
67
+ | 8 | ambiguous ("which one did you mean?") |
68
+ | 9 | conflict / idempotency key mismatch |
69
+ | 10 | business rule violation |
70
+
71
+ ## Work as an agent, not a human
72
+
73
+ 1. **Always `recall` before creating**. When a user asks you to "fix the H1 on /pricing", run `crm recall "https://example.com/pricing"` first. You may find a task already open for it, a past fix that was reverted, or a competitor overlap note. Skipping this is how you duplicate work.
74
+
75
+ 2. **Log decisions explicitly**. Comments default to `--kind=agent_log` for you (a minor trace). When you *chose* a course of action, use `--kind=decision`:
76
+ ```bash
77
+ crm comment create --task tsk_abc --kind decision \
78
+ --body "Chose to revert meta title; A/B showed −8% CTR in 14d"
79
+ ```
80
+
81
+ 3. **Write an outcome when completing tasks**. The UI shows this as a pinned summary:
82
+ ```bash
83
+ crm task update tsk_abc --status done
84
+ # Then: PATCH /tasks/tsk_abc with outcome field (v2 CLI flag: `--outcome`)
85
+ ```
86
+
87
+ 4. **Use `reviewRequired`**. Your task creates default to `reviewRequired=true` — the human sees them in a dedicated inbox section. Only pass `--no-review` for low-stakes rework (e.g. re-filing a recurring instance).
88
+
89
+ 5. **Every write gets an idempotency key**. The CLI autogenerates one per invocation, so retries within a single command are safe. If you're orchestrating retries across invocations, pass `--idempotency-key <ulid>` so the retry replays instead of double-creating.
90
+
91
+ 6. **You choose shadow or autonomous per write**. Every write has two possible fates:
92
+ - **autonomous** — the write lands live immediately.
93
+ - **shadow** — the write lands as a pending proposal; the human reviews + approves / rejects in `/dashboard/inbox` before it materialises.
94
+
95
+ How it gets decided on a single call:
96
+ - Your key has a per-action default (`autonomous` or `shadow`). Absence ⇒ `autonomous`.
97
+ - Pass `--shadow` on the command to *upgrade* this specific call into shadow (e.g. for risky or irreversible writes). This is strictly safer and **always honored**.
98
+ - You **cannot** downgrade a key's `shadow` default to autonomous on a per-call basis. If a human set your key to shadow-by-default for an action, they wanted review every time. If you need autonomy, ask the human to update the key policy.
99
+ - **Hard deny** (you cannot perform this action at all) is *not* a policy value — it's expressed via `scopes` on the key. A missing scope returns a plain 403; it never enters the shadow/autonomous decision.
100
+
101
+ Once a write is in shadow mode:
102
+ - `meta.approvalStatus === "pending"` on the envelope. Do not create follow-up work (comments, edits, change events) that depends on it being visible — it is not.
103
+ - Either poll with `crm review show <kind> <id>` until the status changes, or add `--wait-for-approval --timeout 30m` to the write so the CLI blocks for you.
104
+ - Check your own pending queue with `crm review list --mine`.
105
+ - The response envelope includes breadcrumbs: "Poll decision" (for you) and "View in Inbox" (for the human).
106
+
107
+ **Rule of thumb**: if the change is hard to reverse (deleting work, merging branches of logic, sending external messages, big content rewrites), pass `--shadow` even if your default is autonomous. Low-stakes routine updates (status nudges, agent_log comments, tag adjustments) can run autonomously.
108
+
109
+ ## Common recipes
110
+
111
+ ```bash
112
+ # Read-only triage before acting
113
+ crm recall https://example.com/pricing --jq '.data[] | {type, when, snippet}'
114
+ crm change list --domain dom_xyz --url /pricing --jq '.data[].items[].type'
115
+ crm backlink lost --domain dom_xyz --since 2026-01-01 --count
116
+
117
+ # Create a measured task
118
+ crm task create \
119
+ --title "Fix H1 on /pricing" \
120
+ --domain dom_xyz \
121
+ --description "Current H1 buries the value prop; replace with 'Plans that scale with you'." \
122
+ --idempotency-key 01HY8X...
123
+
124
+ # Log a change event after shipping (via a future `crm change create` in v2)
125
+ # For now, the POST /domains/:id/changes endpoint is the fastest path.
126
+
127
+ # Search across everything
128
+ crm search "meta title" --kind change --domain dom_xyz --limit 5
129
+ ```
130
+
131
+ ## Things that are not obvious
132
+
133
+ - Task ids start with `tsk_`, domains with `dom_`, scopes with `sco_`. You pass these as the first positional arg to `get`/`update`. Never pass a URL where an id is expected.
134
+ - **Scope comments are useful**: if a task has a scoped propertyLink (via `scopeId`), use `crm scope get <id>` to see the fingerprint + filters before assuming the KPI measurement window.
135
+ - Layer 3 GSC queries (top queries / top pages by URL filter) are an **in-flight v2 addition**. For now use `crm domain metrics` for time-series.
136
+ - Web UI paths: `/dashboard/tasks/<id>` for a specific task, `/dashboard/inbox` for your review queue, `/developers` for the endpoint catalog.
137
+
138
+ ## Escape hatches
139
+
140
+ - `crm doctor --json` — always safe; doesn't mutate anything.
141
+ - `crm commands` — future v2 addition that dumps the full command catalog as JSON (see `SURFACE.txt` in this package meanwhile).
142
+ - `crm auth whoami` — what identity am I acting under? Check this first if attribution looks wrong in the UI.
package/SURFACE.txt ADDED
@@ -0,0 +1,69 @@
1
+ # Generated by scripts/generate-surface-txt.ts — do not hand-edit.
2
+ # Format: one line per command, flags flat, types terse.
3
+ # Agents: grep this to discover capabilities without reading help pages.
4
+
5
+ CMD crm auth login [key] --profile <name> --api-url <url> --device-name <label>
6
+ CMD crm auth whoami
7
+ CMD crm auth list
8
+ CMD crm auth switch <name>
9
+ CMD crm auth logout [name]
10
+
11
+ CMD crm task list --status <status> --domain <id> --assignee <id> --tag <id> --limit <n>
12
+ CMD crm task get <id>
13
+ CMD crm task search <query> --limit <n>
14
+ CMD crm task create --title <title> --description <text> --domain <id> --status <status> --assignee <id...> --tag <id...> --due <date> --client-visible --no-review
15
+ CMD crm task update <id> --title <title> --status <status> --domain <id> --due <date> --client-visible <bool>
16
+
17
+ CMD crm comment list <taskId>
18
+ CMD crm comment create --task <id> --body <text> --kind <note|agent_log|decision>
19
+
20
+ CMD crm client list
21
+ CMD crm client get <id>
22
+
23
+ CMD crm domain list --client <id>
24
+ CMD crm domain metrics <id> --start <date> --end <date>
25
+
26
+ CMD crm backlink list --domain <id> --status <status>
27
+ CMD crm backlink lost --domain <id> --since <iso>
28
+
29
+ CMD crm change list --domain <id> --url <url> --since <iso>
30
+
31
+ CMD crm scope list --domain <id> --kind <saved|ephemeral>
32
+ CMD crm scope get <id>
33
+
34
+ CMD crm competitor list --domain <id>
35
+
36
+ CMD crm tag list
37
+ CMD crm member list
38
+
39
+ CMD crm recall <url> --since <iso>
40
+ # search result rows: { id, kind: task|description|comment|change, score, snippet, breadcrumb[] }
41
+ # Use --jq '.data[].snippet' for titles-in-context; NOT .data[].title (not present)
42
+ CMD crm search <query> --kind <task|description|comment|change|all> --domain <id>
43
+
44
+ CMD crm inbox list
45
+ CMD crm inbox read <category>
46
+
47
+ CMD crm review list --mine --key <apiKeyId>
48
+ CMD crm review show <task|comment|edit> <id>
49
+ CMD crm review approve <task|comment|edit> <id>
50
+ CMD crm review reject <task|comment|edit> <id> --reason <text>
51
+
52
+ CMD crm doctor
53
+
54
+ # Global flags (available on every command):
55
+ FLAG --json full JSON envelope (default)
56
+ FLAG --quiet only `data`, no envelope
57
+ FLAG --ids-only one id per line
58
+ FLAG --count single integer
59
+ FLAG --markdown human-readable preview
60
+ FLAG --jq <expr> tiny jq (.a, .a.b, .a[], .a[].b)
61
+ FLAG --profile <name> named credentials profile
62
+ FLAG --workspace <id> workspace override
63
+ FLAG --all walk Link-next pages
64
+ FLAG --limit <n> max rows
65
+ FLAG --since <iso> lower bound on creation/update time
66
+ FLAG --idempotency-key stable retry key (autogenerated on writes if omitted)
67
+ FLAG --wait-for-approval block until a human decides (shadow-mode writes only)
68
+ FLAG --timeout <dur> timeout for --wait-for-approval, e.g. 30s, 5m, 2h (default 30m)
69
+ FLAG --shadow force this write to land as a pending proposal for human review (one-way: agents cannot downgrade to autonomous)
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `crm` CLI entry point.
4
+ *
5
+ * Philosophy: keep this tiny — defer everything to commands modules. Fast
6
+ * cold start + easy to reason about.
7
+ */
8
+ import { Command } from "commander";
9
+ import { registerGlobalFlags } from "../src/commands/options.js";
10
+ import { registerAuth } from "../src/commands/auth.js";
11
+ import { registerTask } from "../src/commands/task.js";
12
+ import { registerComment } from "../src/commands/comment.js";
13
+ import { registerGeneric } from "../src/commands/generic.js";
14
+ import { registerDoctor } from "../src/commands/doctor.js";
15
+ import { registerReview } from "../src/commands/review.js";
16
+ import { maybeNudgeFromCache } from "../src/utils/version-check.js";
17
+ const program = new Command();
18
+ program
19
+ .name("crm")
20
+ .description("CLI para humanos y agentes de IA que manejan el SEO+CRM de ROILab. Envoltura JSON siempre, exit codes numéricos, escrituras idempotentes.")
21
+ .version("0.1.0");
22
+ registerGlobalFlags(program);
23
+ registerAuth(program);
24
+ registerTask(program);
25
+ registerComment(program);
26
+ registerGeneric(program);
27
+ registerReview(program);
28
+ registerDoctor(program);
29
+ // Nudge basado en cache: instantáneo, sin red. `crm doctor` refresca contra npm.
30
+ maybeNudgeFromCache();
31
+ program.parseAsync(process.argv).catch((err) => {
32
+ process.stderr.write(`[INTERNO] ${err instanceof Error ? err.message : String(err)}\n`);
33
+ process.exit(1);
34
+ });
35
+ //# sourceMappingURL=crm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crm.js","sourceRoot":"","sources":["../../bin/crm.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAC9B,OAAO;KACJ,IAAI,CAAC,KAAK,CAAC;KACX,WAAW,CACV,2IAA2I,CAC5I;KACA,OAAO,CAAC,OAAO,CAAC,CAAC;AAEpB,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAE7B,YAAY,CAAC,OAAO,CAAC,CAAC;AACtB,YAAY,CAAC,OAAO,CAAC,CAAC;AACtB,eAAe,CAAC,OAAO,CAAC,CAAC;AACzB,eAAe,CAAC,OAAO,CAAC,CAAC;AACzB,cAAc,CAAC,OAAO,CAAC,CAAC;AACxB,cAAc,CAAC,OAAO,CAAC,CAAC;AAExB,iFAAiF;AACjF,mBAAmB,EAAE,CAAC;AAEtB,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IAC7C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACxF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Credential store — holds either an API key OR a device-flow session
3
+ * (access + refresh token pair) for one or more named profiles.
4
+ *
5
+ * Precedence for resolution (highest first):
6
+ * 1. `CRM_API_KEY` / `CRM_TOKEN` env var
7
+ * 2. `--profile <name>` explicit selection
8
+ * 3. `activeProfile` pointer in the credentials file
9
+ *
10
+ * Storage: `~/.config/crm/credentials.json` (mode 0600). A system keyring
11
+ * (keytar) is a planned follow-up; for now the file is the single source.
12
+ *
13
+ * Session format (device flow):
14
+ * { accessToken, refreshToken, accessExpiresAt, refreshExpiresAt, ... }
15
+ *
16
+ * API-key format (legacy / unattended agents):
17
+ * { apiKey, ... }
18
+ *
19
+ * Both use the same ResolvedCredentials shape downstream — the transport
20
+ * layer doesn't care which token it's carrying, just that it's live.
21
+ */
22
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join } from "node:path";
25
+ const DEFAULT_API_BASE_URL = "http://localhost:3000";
26
+ function credentialsDir() {
27
+ return join(homedir(), ".config", "crm");
28
+ }
29
+ function credentialsPath() {
30
+ return join(credentialsDir(), "credentials.json");
31
+ }
32
+ function load() {
33
+ const path = credentialsPath();
34
+ if (!existsSync(path)) {
35
+ return { activeProfile: "default", profiles: {} };
36
+ }
37
+ try {
38
+ const raw = readFileSync(path, "utf8");
39
+ const parsed = JSON.parse(raw);
40
+ // Retro-fit pre-`kind` rows (API-key-only era) so reads stay consistent.
41
+ for (const [name, p] of Object.entries(parsed.profiles ?? {})) {
42
+ const asAny = p;
43
+ if (typeof asAny.kind !== "string" && typeof asAny.apiKey === "string") {
44
+ parsed.profiles[name] = {
45
+ kind: "apiKey",
46
+ apiKey: asAny.apiKey,
47
+ apiBaseUrl: asAny.apiBaseUrl,
48
+ createdAt: asAny.createdAt ?? new Date().toISOString(),
49
+ };
50
+ }
51
+ }
52
+ return parsed;
53
+ }
54
+ catch {
55
+ return { activeProfile: "default", profiles: {} };
56
+ }
57
+ }
58
+ function save(file) {
59
+ const dir = credentialsDir();
60
+ if (!existsSync(dir))
61
+ mkdirSync(dir, { recursive: true });
62
+ const path = credentialsPath();
63
+ writeFileSync(path, JSON.stringify(file, null, 2), { encoding: "utf8" });
64
+ try {
65
+ chmodSync(path, 0o600);
66
+ }
67
+ catch {
68
+ // Windows, etc. — no-op
69
+ }
70
+ }
71
+ /** Resolve credentials from env or the configured profile. Throws if missing. */
72
+ export function resolveCredentials(explicitProfile) {
73
+ const envBaseUrl = process.env.CRM_API_URL ?? DEFAULT_API_BASE_URL;
74
+ const envKey = process.env.CRM_API_KEY ?? process.env.CRM_TOKEN;
75
+ if (envKey) {
76
+ return {
77
+ apiKey: envKey,
78
+ apiBaseUrl: envBaseUrl,
79
+ profileName: "env",
80
+ source: "env",
81
+ };
82
+ }
83
+ const file = load();
84
+ const profileName = explicitProfile ?? file.activeProfile;
85
+ const profile = file.profiles[profileName];
86
+ if (!profile) {
87
+ throw new Error(`No credentials for profile "${profileName}". Run \`crm auth login\` to add one, or set CRM_API_KEY / CRM_TOKEN.`);
88
+ }
89
+ if (profile.kind === "apiKey") {
90
+ return {
91
+ apiKey: profile.apiKey,
92
+ apiBaseUrl: profile.apiBaseUrl ?? DEFAULT_API_BASE_URL,
93
+ profileName,
94
+ source: "profile",
95
+ };
96
+ }
97
+ return {
98
+ apiKey: profile.accessToken,
99
+ apiBaseUrl: profile.apiBaseUrl ?? DEFAULT_API_BASE_URL,
100
+ profileName,
101
+ source: "profile",
102
+ session: {
103
+ refreshToken: profile.refreshToken,
104
+ accessExpiresAt: profile.accessExpiresAt,
105
+ refreshExpiresAt: profile.refreshExpiresAt,
106
+ },
107
+ };
108
+ }
109
+ /** Store an API-key profile. */
110
+ export function saveProfile(profileName, apiKey, apiBaseUrl) {
111
+ const file = load();
112
+ file.profiles[profileName] = {
113
+ kind: "apiKey",
114
+ apiKey,
115
+ apiBaseUrl: apiBaseUrl ?? DEFAULT_API_BASE_URL,
116
+ createdAt: new Date().toISOString(),
117
+ };
118
+ if (!file.activeProfile || !file.profiles[file.activeProfile]) {
119
+ file.activeProfile = profileName;
120
+ }
121
+ save(file);
122
+ }
123
+ /** Store a device-flow session profile. */
124
+ export function saveSession(profileName, session) {
125
+ const file = load();
126
+ file.profiles[profileName] = {
127
+ kind: "session",
128
+ accessToken: session.accessToken,
129
+ refreshToken: session.refreshToken,
130
+ accessExpiresAt: session.accessExpiresAt,
131
+ refreshExpiresAt: session.refreshExpiresAt,
132
+ apiBaseUrl: session.apiBaseUrl ?? DEFAULT_API_BASE_URL,
133
+ deviceName: session.deviceName,
134
+ createdAt: new Date().toISOString(),
135
+ };
136
+ if (!file.activeProfile || !file.profiles[file.activeProfile]) {
137
+ file.activeProfile = profileName;
138
+ }
139
+ save(file);
140
+ }
141
+ /** Update just the tokens on an existing session profile (used by refresh). */
142
+ export function updateSessionTokens(profileName, tokens) {
143
+ const file = load();
144
+ const profile = file.profiles[profileName];
145
+ if (!profile || profile.kind !== "session")
146
+ return;
147
+ profile.accessToken = tokens.accessToken;
148
+ profile.refreshToken = tokens.refreshToken;
149
+ profile.accessExpiresAt = tokens.accessExpiresAt;
150
+ profile.refreshExpiresAt = tokens.refreshExpiresAt;
151
+ profile.lastRefreshedAt = Date.now();
152
+ save(file);
153
+ }
154
+ /** Switch the active profile pointer. */
155
+ export function switchProfile(profileName) {
156
+ const file = load();
157
+ if (!file.profiles[profileName]) {
158
+ throw new Error(`Profile "${profileName}" not found.`);
159
+ }
160
+ file.activeProfile = profileName;
161
+ save(file);
162
+ }
163
+ /** List known profiles. Does not return the secrets. */
164
+ export function listProfiles() {
165
+ const file = load();
166
+ return Object.entries(file.profiles).map(([name, p]) => ({
167
+ name,
168
+ kind: p.kind,
169
+ apiBaseUrl: p.apiBaseUrl ?? DEFAULT_API_BASE_URL,
170
+ createdAt: p.createdAt,
171
+ active: file.activeProfile === name,
172
+ deviceName: p.kind === "session" ? p.deviceName : undefined,
173
+ accessExpiresAt: p.kind === "session" ? p.accessExpiresAt : undefined,
174
+ }));
175
+ }
176
+ /** Remove a profile. If it was active, falls back to the first remaining one. */
177
+ export function removeProfile(profileName) {
178
+ const file = load();
179
+ if (!file.profiles[profileName])
180
+ return;
181
+ delete file.profiles[profileName];
182
+ if (file.activeProfile === profileName) {
183
+ file.activeProfile = Object.keys(file.profiles)[0] ?? "default";
184
+ }
185
+ save(file);
186
+ }
187
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../../src/auth/credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA+BjC,MAAM,oBAAoB,GAAG,uBAAuB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