@installagent/sdk 0.7.0 → 0.8.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.
@@ -0,0 +1,32 @@
1
+ import { type ExecFileFn } from "./exec.js";
2
+ import { type PlatformInfo } from "./platform.js";
3
+ export type AccessService = "google-service-account" | "google-oauth" | "google-oauth-client" | "slack" | "github";
4
+ export type AccessStatus = "valid" | "rejected" | "unverified" | "skipped";
5
+ export interface AccessCheckItem {
6
+ /** The vault item's title — a name, never a value. */
7
+ title: string;
8
+ service: AccessService | null;
9
+ status: AccessStatus;
10
+ detail: string;
11
+ }
12
+ export interface AccessCheckResult {
13
+ slug: string;
14
+ vault: string;
15
+ items: AccessCheckItem[];
16
+ counts: Record<AccessStatus, number>;
17
+ }
18
+ export interface AccessCheckOptions {
19
+ workspaceDir?: string;
20
+ /** Test this vault instead of the one in CLIENT.md (use when CLIENT.md names a vault that does not exist). */
21
+ vault?: string;
22
+ execFileImpl?: ExecFileFn;
23
+ fetchImpl?: typeof fetch;
24
+ now?: () => number;
25
+ platform?: PlatformInfo;
26
+ }
27
+ /** The vault named in the client's CLIENT.md, else the portal's default name. */
28
+ export declare function clientVaultFor(slug: string, workspaceDir: string): string;
29
+ /** What a key is, from the shape of its value. Null when no probe exists for it. */
30
+ export declare function classifyKey(value: string): AccessService | null;
31
+ /** Test every API-key item in the client's vault. Logins and unknown keys are listed, never read or tested. */
32
+ export declare function accessCheck(slug: string, options?: AccessCheckOptions): Promise<AccessCheckResult>;
@@ -0,0 +1,339 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { readManifestKey } from "./client-manifest.js";
4
+ import { findWorkspaceRoot } from "./env-file.js";
5
+ import { execFailureDetail, execFileAsync } from "./exec.js";
6
+ import { GoogleServiceAccountAuthError, getServiceAccountAccessToken, } from "./google-service-account.js";
7
+ import { SLUG_PATTERN } from "./new-client.js";
8
+ import { opReachable } from "./op-cli.js";
9
+ import { detectPlatformInfo } from "./platform.js";
10
+ // `ia access check <slug>`: does each key the client handed over still work?
11
+ // The access tracker says HAVE from a person's word; nothing tested it, so a
12
+ // token that expired or was revoked still read HAVE. This runs ONE read-only
13
+ // call per key in the client's 1Password vault (the same idea as the live
14
+ // checks in `ia doctor`) and reports valid, rejected or unverified.
15
+ //
16
+ // Secret handling: only the vault's item list (titles, ids, categories) is
17
+ // read in bulk. The `credential` field is read from API-key items, and a small
18
+ // .json file from Document items (where `ia secrets mint` stores a Google
19
+ // key). A value is kept in a local variable, sent to its own service, and
20
+ // dropped. A result holds
21
+ // fixed words and, at most, a workspace name or an expiry date. Logins
22
+ // (username + password) are never read: no safe test exists for them.
23
+ const CHECK_TIMEOUT_MS = 5000;
24
+ // A service-account key file is about 2.4 KB; anything past this is not one.
25
+ const KEY_FILE_MAX_BYTES = 16 * 1024;
26
+ const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
27
+ // The narrowest scope that still mints a token. A service account may ask for
28
+ // any scope for itself (no delegation), so this proves the key and nothing more.
29
+ const GOOGLE_PROBE_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
30
+ /** `op item list --format json` reports "API_CREDENTIAL"; the SDK names it "ApiCredentials". */
31
+ const categoryKey = (category) => category.replace(/[^a-z]/gi, "").toUpperCase();
32
+ /** The vault named in the client's CLIENT.md, else the portal's default name. */
33
+ export function clientVaultFor(slug, workspaceDir) {
34
+ const clientMd = join(workspaceDir, "clients", `client-${slug}`, "CLIENT.md");
35
+ const declared = existsSync(clientMd)
36
+ ? readManifestKey(readFileSync(clientMd, "utf8"), "onepassword_vault")
37
+ : undefined;
38
+ // Real CLIENT.md lines carry a note after the name: "client-x # convention", "client-x (created …)".
39
+ const name = declared?.split(/\s+(?:#|\(|—|–)/)[0].trim();
40
+ const usable = name && !/^<.*>$/.test(name) && !name.includes("_HERE");
41
+ return usable && name.toLowerCase() !== "none" ? name : `client-${slug}`;
42
+ }
43
+ /** What a key is, from the shape of its value. Null when no probe exists for it. */
44
+ export function classifyKey(value) {
45
+ const text = value.trim();
46
+ if (text.startsWith("{")) {
47
+ try {
48
+ const json = JSON.parse(text);
49
+ if (json.type === "service_account" && json.client_email && json.private_key) {
50
+ return "google-service-account";
51
+ }
52
+ if (json.client_id && json.client_secret && json.refresh_token)
53
+ return "google-oauth";
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ return null;
59
+ }
60
+ // The portal intake stores an OAuth client as username = client id, credential = secret.
61
+ if (/^GOCSPX-/.test(text))
62
+ return "google-oauth-client";
63
+ if (/^xox[abp]-/.test(text))
64
+ return "slack";
65
+ if (/^(ghp_|gho_|ghu_|ghs_|github_pat_)/.test(text))
66
+ return "github";
67
+ return null;
68
+ }
69
+ const unverified = (detail) => ({ status: "unverified", detail });
70
+ async function probeSlack(token, fetchImpl) {
71
+ const res = await fetchImpl("https://slack.com/api/auth.test", {
72
+ method: "POST",
73
+ headers: { Authorization: `Bearer ${token}` },
74
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
75
+ });
76
+ if (res.status === 429)
77
+ return unverified("Slack is rate limiting; try again in a minute");
78
+ const body = (await res.json());
79
+ if (body.ok)
80
+ return {
81
+ status: "valid",
82
+ detail: `Slack accepts it${body.team ? ` (workspace ${body.team})` : ""}`,
83
+ };
84
+ const dead = ["invalid_auth", "token_revoked", "token_expired", "account_inactive", "not_authed"];
85
+ if (body.error && dead.includes(body.error)) {
86
+ return {
87
+ status: "rejected",
88
+ detail: `Slack rejected it (${body.error}); ask the client for a new token`,
89
+ };
90
+ }
91
+ return unverified(`Slack gave an answer this check does not know (${body.error ?? `HTTP ${res.status}`})`);
92
+ }
93
+ async function probeGithub(token, fetchImpl) {
94
+ // /rate_limit works for every kind of token and needs no scope. It answers
95
+ // 200 with NO token too, so the 401 is the signal and the header is the proof.
96
+ const res = await fetchImpl("https://api.github.com/rate_limit", {
97
+ headers: {
98
+ Authorization: `Bearer ${token}`,
99
+ Accept: "application/vnd.github+json",
100
+ "User-Agent": "ia-access-check",
101
+ },
102
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
103
+ });
104
+ if (res.status === 401) {
105
+ return {
106
+ status: "rejected",
107
+ detail: "GitHub rejected it (HTTP 401); the token expired or was revoked",
108
+ };
109
+ }
110
+ if (!res.ok)
111
+ return unverified(`GitHub gave HTTP ${res.status}`);
112
+ const expiry = res.headers.get("github-authentication-token-expiration");
113
+ return {
114
+ status: "valid",
115
+ detail: `GitHub accepts it${expiry ? ` (expires ${expiry.slice(0, 10)})` : " (no expiry date)"}`,
116
+ };
117
+ }
118
+ async function probeGoogleServiceAccount(raw, fetchImpl, now) {
119
+ try {
120
+ await getServiceAccountAccessToken(raw, GOOGLE_PROBE_SCOPE, fetchImpl, now);
121
+ return { status: "valid", detail: "Google accepts the service-account key" };
122
+ }
123
+ catch (error) {
124
+ if (error instanceof GoogleServiceAccountAuthError) {
125
+ const http = /HTTP (\d{3})/.exec(error.message)?.[1];
126
+ if (http && (http.startsWith("5") || http === "429"))
127
+ return unverified(`Google gave HTTP ${http}`);
128
+ return {
129
+ status: "rejected",
130
+ detail: `Google rejected the service-account key${http ? ` (HTTP ${http})` : ""}; the key was deleted or disabled`,
131
+ };
132
+ }
133
+ // Name only: a message can echo request data.
134
+ return unverified(`could not finish the check (${error instanceof Error ? error.name : "error"})`);
135
+ }
136
+ }
137
+ /**
138
+ * Tests the OAuth client pair, not a refresh token (the vault rarely holds one;
139
+ * n8n does). A refresh request with a dummy token answers `invalid_grant` when
140
+ * Google accepts the client id and secret, and `invalid_client` when it does not.
141
+ */
142
+ async function probeGoogleOauthClient(clientId, clientSecret, fetchImpl) {
143
+ const res = await fetchImpl(GOOGLE_TOKEN_URL, {
144
+ method: "POST",
145
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
146
+ body: new URLSearchParams({
147
+ grant_type: "refresh_token",
148
+ client_id: clientId,
149
+ client_secret: clientSecret,
150
+ refresh_token: "ia-access-check",
151
+ }),
152
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
153
+ });
154
+ const body = (await res.json().catch(() => ({})));
155
+ if (body.error === "invalid_grant") {
156
+ return {
157
+ status: "valid",
158
+ detail: "Google accepts the OAuth client id and secret. The refresh token lives in n8n and is not tested here",
159
+ };
160
+ }
161
+ if (body.error === "invalid_client") {
162
+ return {
163
+ status: "rejected",
164
+ detail: "Google rejected the OAuth client id or secret (invalid_client); the secret was reset or the client deleted",
165
+ };
166
+ }
167
+ return unverified(`Google gave an answer this check does not know (${body.error ?? `HTTP ${res.status}`})`);
168
+ }
169
+ async function probeGoogleOauth(raw, fetchImpl) {
170
+ const json = JSON.parse(raw);
171
+ const res = await fetchImpl(GOOGLE_TOKEN_URL, {
172
+ method: "POST",
173
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
174
+ body: new URLSearchParams({
175
+ grant_type: "refresh_token",
176
+ client_id: json.client_id,
177
+ client_secret: json.client_secret,
178
+ refresh_token: json.refresh_token,
179
+ }),
180
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
181
+ });
182
+ if (res.ok)
183
+ return { status: "valid", detail: "Google accepts the refresh token" };
184
+ const body = (await res.json().catch(() => ({})));
185
+ if (body.error === "invalid_grant") {
186
+ return {
187
+ status: "rejected",
188
+ detail: "Google rejected the refresh token (invalid_grant): it expired or was revoked. " +
189
+ "An OAuth consent screen in Testing status expires it after 7 days",
190
+ };
191
+ }
192
+ if (body.error === "invalid_client") {
193
+ return {
194
+ status: "rejected",
195
+ detail: "Google rejected the OAuth client id or secret (invalid_client)",
196
+ };
197
+ }
198
+ return unverified(`Google gave an answer this check does not know (${body.error ?? `HTTP ${res.status}`})`);
199
+ }
200
+ /** Test every API-key item in the client's vault. Logins and unknown keys are listed, never read or tested. */
201
+ export async function accessCheck(slug, options = {}) {
202
+ if (!SLUG_PATTERN.test(slug))
203
+ throw new Error(`"${slug}" is not a client slug (lowercase letters, digits, hyphens)`);
204
+ const workspaceDir = resolve(options.workspaceDir ?? findWorkspaceRoot() ?? ".");
205
+ const execFileImpl = options.execFileImpl ?? execFileAsync;
206
+ const fetchImpl = options.fetchImpl ?? fetch;
207
+ const now = options.now ?? Date.now;
208
+ const vault = options.vault?.trim() || clientVaultFor(slug, workspaceDir);
209
+ if (!/^[^\n/]{1,100}$/.test(vault))
210
+ throw new Error("the vault name must be one line, at most 100 characters, with no slash");
211
+ const reachable = await opReachable(execFileImpl, options.platform ?? detectPlatformInfo());
212
+ if (reachable !== true)
213
+ throw new Error(`1Password is not usable: ${reachable}`);
214
+ let listed;
215
+ try {
216
+ const { stdout } = await execFileImpl("op", [
217
+ "item",
218
+ "list",
219
+ "--vault",
220
+ vault,
221
+ "--format",
222
+ "json",
223
+ ]);
224
+ listed = JSON.parse(stdout);
225
+ }
226
+ catch (error) {
227
+ throw new Error(`could not list the 1Password vault "${vault}": ${execFailureDetail(error).detail}`);
228
+ }
229
+ const items = [];
230
+ for (const item of listed) {
231
+ const base = { title: item.title, service: null };
232
+ const kind = categoryKey(item.category ?? "");
233
+ if (kind === "LOGIN" || kind === "PASSWORD") {
234
+ items.push({
235
+ ...base,
236
+ status: "skipped",
237
+ detail: "login or password: no safe test; confirm it by hand",
238
+ });
239
+ continue;
240
+ }
241
+ if (kind !== "APICREDENTIAL" && kind !== "DOCUMENT") {
242
+ items.push({
243
+ ...base,
244
+ status: "skipped",
245
+ detail: "not an API-key or key-file item; this check does not read it",
246
+ });
247
+ continue;
248
+ }
249
+ let value;
250
+ try {
251
+ if (kind === "DOCUMENT") {
252
+ // `ia secrets mint gcp-service-account-key --to-op` stores the key as a
253
+ // Document. Look at the file list first (metadata only); read the file
254
+ // only when it is a small .json, so no contract or PDF is ever pulled in.
255
+ const { stdout: meta } = await execFileImpl("op", [
256
+ "item",
257
+ "get",
258
+ item.id,
259
+ "--vault",
260
+ vault,
261
+ "--format",
262
+ "json",
263
+ ]);
264
+ const files = JSON.parse(meta).files ?? [];
265
+ const keyFile = files.find((file) => /\.json$/i.test(file.name ?? "") && (file.size ?? 0) <= KEY_FILE_MAX_BYTES);
266
+ if (!keyFile) {
267
+ items.push({
268
+ ...base,
269
+ status: "skipped",
270
+ detail: "a document, but not a small .json key file",
271
+ });
272
+ continue;
273
+ }
274
+ const { stdout } = await execFileImpl("op", ["document", "get", item.id, "--vault", vault]);
275
+ value = stdout.trim();
276
+ }
277
+ else {
278
+ const { stdout } = await execFileImpl("op", [
279
+ "read",
280
+ `op://${vault}/${item.id}/credential`,
281
+ ]);
282
+ value = stdout.trim();
283
+ }
284
+ }
285
+ catch {
286
+ items.push({
287
+ ...base,
288
+ status: "unverified",
289
+ detail: "could not read the key from 1Password",
290
+ });
291
+ continue;
292
+ }
293
+ const service = classifyKey(value);
294
+ if (!service) {
295
+ items.push({ ...base, status: "skipped", detail: "no test exists for this kind of key" });
296
+ continue;
297
+ }
298
+ let clientId = "";
299
+ if (service === "google-oauth-client") {
300
+ try {
301
+ const { stdout } = await execFileImpl("op", ["read", `op://${vault}/${item.id}/username`]);
302
+ clientId = stdout.trim();
303
+ }
304
+ catch {
305
+ // falls through to the skip below
306
+ }
307
+ if (!clientId.endsWith(".apps.googleusercontent.com")) {
308
+ items.push({
309
+ title: item.title,
310
+ service,
311
+ status: "skipped",
312
+ detail: "an OAuth client secret with no client id in the username field",
313
+ });
314
+ continue;
315
+ }
316
+ }
317
+ let verdict;
318
+ try {
319
+ verdict =
320
+ service === "google-oauth-client"
321
+ ? await probeGoogleOauthClient(clientId, value, fetchImpl)
322
+ : service === "slack"
323
+ ? await probeSlack(value, fetchImpl)
324
+ : service === "github"
325
+ ? await probeGithub(value, fetchImpl)
326
+ : service === "google-service-account"
327
+ ? await probeGoogleServiceAccount(value, fetchImpl, now)
328
+ : await probeGoogleOauth(value, fetchImpl);
329
+ }
330
+ catch (error) {
331
+ verdict = unverified(`could not reach the service (${error instanceof Error ? error.name : "error"})`);
332
+ }
333
+ items.push({ title: item.title, service, ...verdict });
334
+ }
335
+ const counts = { valid: 0, rejected: 0, unverified: 0, skipped: 0 };
336
+ for (const item of items)
337
+ counts[item.status] += 1;
338
+ return { slug, vault, items, counts };
339
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { type AccessCheckItem, type AccessCheckOptions, type AccessCheckResult, type AccessService, type AccessStatus, accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
1
2
  export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type MirrorRow, type MirrorState, type MirrorSummary, } from "./agent-mirror.js";
2
3
  export { type AgentBankOptions, type AgentTemplateInfo, type AgentTemplateMatch, type CreateFromTemplateInput, type CreateFromTemplateResult, createFromAgentTemplate, type ListAgentTemplatesResult, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, type SanitizedWorkflow, type SaveAgentTemplateInput, type SaveAgentTemplateOptions, type SaveAgentTemplateResult, type SearchAgentTemplatesOptions, type SearchAgentTemplatesResult, type SopState, type StrippedCredential, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
3
4
  export { CLAUDE_CONFIG_DIR_ENV, type ClaudeHoursExportOptions, type ClaudeHoursExportResult, type ClaudeHoursSummaryRow, compactClaudeHoursExport, type DeliverClaudeHoursExportOptions, type DeliverClaudeHoursExportResult, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, type SaveClaudeHoursExportOptions, type SendClaudeHoursExportOptions, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // @installagent/sdk — the only place with real logic. apps/cli and
2
2
  // apps/mcp are thin adapters over these exports; every operation here must be
3
3
  // reachable from both. See ../../docs/spec.md.
4
+ export { accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
4
5
  export { checkAgentMirror, } from "./agent-mirror.js";
5
6
  export { createFromAgentTemplate, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
6
7
  export { CLAUDE_CONFIG_DIR_ENV, compactClaudeHoursExport, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
package/dist/pr-open.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type ExecFileFn } from "./exec.js";
2
2
  /**
3
3
  * `ia pr open` — push the current branch and open a DRAFT pull request, with
4
- * the three checks that the Slack Merge button made necessary:
4
+ * the checks that the Slack Merge button made necessary:
5
5
  *
6
6
  * 1. The gh account is the workspace's work account (`.github-account` at the
7
7
  * workspace root). A PR under a personal account lands on the wrong identity
@@ -11,6 +11,8 @@ import { type ExecFileFn } from "./exec.js";
11
11
  * same branch was silently lost (6 incidents in 20 days, Oct 2026).
12
12
  * 3. The branch has no OPEN pull request. More commits on an open PR is the
13
13
  * same trap one click later: open a new PR per slice.
14
+ * 4. The branch has at least one commit ahead of the base. An empty branch
15
+ * pushes fine and leaves a dead remote branch behind.
14
16
  *
15
17
  * The PR opens as a draft, so no Slack card (and no Merge button) exists until
16
18
  * someone marks it ready on purpose.
package/dist/pr-open.js CHANGED
@@ -69,6 +69,15 @@ export async function prOpen(options = {}) {
69
69
  throw new Error(`PR #${open.number} from ${branch} is still open (${open.url}). Do not add commits to it: ` +
70
70
  "the Merge button squashes the head as it is. Open a new branch for the next slice.");
71
71
  }
72
+ // 4. The branch has commits of its own. An empty branch pushes fine, then
73
+ // `gh pr create` has nothing to open. Compare with origin/<base> when the
74
+ // checkout has it, else the local base branch.
75
+ const hasRemoteBase = await git("rev-parse", "--verify", "--quiet", `origin/${base}`).then(() => true, () => false);
76
+ const baseRef = hasRemoteBase ? `origin/${base}` : base;
77
+ if (Number(await git("rev-list", "--count", `${baseRef}..HEAD`)) === 0) {
78
+ throw new Error(`${branch} has no commits ahead of ${baseRef}. Commit your changes on this branch first, ` +
79
+ "then re-run `ia pr open`.");
80
+ }
72
81
  const result = {
73
82
  repo,
74
83
  branch,
@@ -38,6 +38,9 @@ export const TEMPLATE_SYNCED_FILES = [
38
38
  "CADENCE.md",
39
39
  "ci/repo-lint.mjs",
40
40
  "ci/repo-lint.test.mjs",
41
+ // repo-lint imports log-progress (rule 9), so the two always travel together.
42
+ "ci/log-progress.mjs",
43
+ "ci/log-progress.test.mjs",
41
44
  "lefthook.yml",
42
45
  ".github/workflows/repo-lint.yml",
43
46
  ".github/workflows/pr-to-slack.yml",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@installagent/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Install Agent's shared SDK for internal team operations (client repos, n8n workflows, docs search, and more).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",