@installagent/sdk 0.5.0 → 0.7.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,230 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { execFailureDetail, execFileAsync } from "./exec.js";
5
+ import { mintFathomWebhook, } from "./fathom-webhook.js";
6
+ import { mintGcpServiceAccountKey, } from "./gcp-service-account-key.js";
7
+ import { mintGeminiApiKey, } from "./gemini-api-key.js";
8
+ import { opReachable } from "./op-cli.js";
9
+ import { detectPlatformInfo } from "./platform.js";
10
+ const NAME_PATTERN = /^[^\n\r\t]{1,100}$/;
11
+ /** `<project> - gcp-sa-key - <sa name>`, the n8n credential naming shape. */
12
+ export function defaultOpTitle(request) {
13
+ switch (request.type) {
14
+ case "gcp-service-account-key":
15
+ return `${request.project} - gcp-sa-key - ${request.serviceAccountEmail.split("@")[0]}`;
16
+ case "gemini-api-key":
17
+ return `${request.project} - gemini-api-key - ${request.displayName?.trim() || "ia-minted"}`;
18
+ case "fathom-webhook": {
19
+ let host = "webhook";
20
+ try {
21
+ host = new URL(request.destinationUrl).host || host;
22
+ }
23
+ catch {
24
+ // mintFathomWebhook rejects the URL itself, after the preflight.
25
+ }
26
+ return `fathom - webhook-secret - ${host}`;
27
+ }
28
+ }
29
+ }
30
+ export async function mintToOnePassword(options) {
31
+ const vault = options.vault.trim();
32
+ const title = (options.title ?? defaultOpTitle(options.request)).trim();
33
+ if (!NAME_PATTERN.test(vault)) {
34
+ throw new Error("--to-op needs a vault name (one line, at most 100 characters)");
35
+ }
36
+ if (!NAME_PATTERN.test(title)) {
37
+ throw new Error("the 1Password item title must be one line, at most 100 characters");
38
+ }
39
+ const execFileImpl = options.execFileImpl ?? execFileAsync;
40
+ const platform = options.platform ?? detectPlatformInfo();
41
+ const ready = await opPreflight(execFileImpl, platform, vault, title);
42
+ if (ready !== true)
43
+ return { ok: false, error: ready };
44
+ const mints = {
45
+ gcp: mintGcpServiceAccountKey,
46
+ gemini: mintGeminiApiKey,
47
+ fathom: mintFathomWebhook,
48
+ ...options.mints,
49
+ };
50
+ const minted = await mintOnce(options.request, mints);
51
+ if (!minted.ok)
52
+ return { ok: false, error: minted.error };
53
+ const stored = await storeInOp(execFileImpl, vault, title, minted.secret, minted.store);
54
+ if (stored !== true) {
55
+ return {
56
+ ok: false,
57
+ error: `minted, but NOT stored in 1Password (${redact(stored, minted.secret)}). The value was not printed. Revoke it, then retry.`,
58
+ revoke: minted.revoke,
59
+ };
60
+ }
61
+ return {
62
+ ok: true,
63
+ type: options.request.type,
64
+ vault,
65
+ title,
66
+ reference: `op://${vault}/${title}`,
67
+ details: minted.details,
68
+ };
69
+ }
70
+ async function mintOnce(request, mints) {
71
+ switch (request.type) {
72
+ case "gcp-service-account-key": {
73
+ const { type: _type, ...opts } = request;
74
+ const result = await mints.gcp(opts);
75
+ if (!result.ok)
76
+ return result;
77
+ const keyId = privateKeyId(result.keyJson);
78
+ return {
79
+ ok: true,
80
+ secret: result.keyJson,
81
+ store: { kind: "document", fileName: `${result.serviceAccountEmail.split("@")[0]}.json` },
82
+ details: [
83
+ `service account ${result.serviceAccountEmail} in ${result.project}`,
84
+ ...(keyId ? [`key id ${keyId}`] : []),
85
+ ],
86
+ revoke: keyId
87
+ ? `gcloud iam service-accounts keys delete ${keyId} --iam-account=${result.serviceAccountEmail} --project=${result.project}`
88
+ : `gcloud iam service-accounts keys list --iam-account=${result.serviceAccountEmail} --project=${result.project}, then delete the newest key`,
89
+ };
90
+ }
91
+ case "gemini-api-key": {
92
+ const { type: _type, ...opts } = request;
93
+ const result = await mints.gemini(opts);
94
+ if (!result.ok)
95
+ return result;
96
+ return {
97
+ ok: true,
98
+ secret: result.keyString,
99
+ store: { kind: "api-credential" },
100
+ details: [`key ${result.keyName}, restricted to ${result.restrictedTo}`],
101
+ revoke: `gcloud services api-keys delete ${result.keyName}`,
102
+ };
103
+ }
104
+ case "fathom-webhook": {
105
+ const { type: _type, ...opts } = request;
106
+ const result = await mints.fathom(opts);
107
+ if (!result.ok)
108
+ return result;
109
+ return {
110
+ ok: true,
111
+ secret: result.webhookSecret,
112
+ store: { kind: "api-credential" },
113
+ details: [
114
+ `webhook ${result.webhookId} → ${result.destinationUrl}`,
115
+ `triggers: ${result.triggers.join(", ")}`,
116
+ ],
117
+ revoke: `delete webhook ${result.webhookId} in Fathom (Settings → API Access)`,
118
+ };
119
+ }
120
+ }
121
+ }
122
+ /** The key's id is public (it names the key in IAM), unlike the key material. */
123
+ function privateKeyId(keyJson) {
124
+ try {
125
+ const id = JSON.parse(keyJson).private_key_id;
126
+ return typeof id === "string" && /^[0-9a-f]{20,}$/.test(id) ? id : undefined;
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ }
132
+ /** op installed + signed in, the vault visible, the title free. Never mints. */
133
+ async function opPreflight(execFileImpl, platform, vault, title) {
134
+ const reachable = await opReachable(execFileImpl, platform);
135
+ if (reachable !== true)
136
+ return `${reachable}. Nothing was minted.`;
137
+ // `item list` returns titles and ids only — never field values.
138
+ let stdout;
139
+ try {
140
+ ({ stdout } = await execFileImpl("op", ["item", "list", "--vault", vault, "--format", "json"]));
141
+ }
142
+ catch (error) {
143
+ return `1Password vault "${vault}" is not visible to your op session (${execFailureDetail(error).detail}). Check the name (CLIENT.md onepassword_vault) and your access, then retry. Nothing was minted.`;
144
+ }
145
+ let titles = [];
146
+ try {
147
+ titles = JSON.parse(stdout || "[]")
148
+ .map((item) => item.title)
149
+ .filter((t) => typeof t === "string");
150
+ }
151
+ catch {
152
+ return "could not read the vault's item list from op (unexpected output). Nothing was minted.";
153
+ }
154
+ if (titles.some((t) => t.toLowerCase() === title.toLowerCase())) {
155
+ return `"${title}" already exists in ${vault} — ia never overwrites an item. Pass a new --op-title, or rotate the old item by hand. Nothing was minted.`;
156
+ }
157
+ return true;
158
+ }
159
+ /**
160
+ * One write through a private temp file. A key JSON becomes a Document (the
161
+ * file a service-account credential is uploaded as); a single string becomes
162
+ * an API Credential item from a JSON template (1Password's documented item
163
+ * template shape: title, category, fields). Returns true, or op's error text.
164
+ */
165
+ async function storeInOp(execFileImpl, vault, title, secret, store) {
166
+ const dir = await mkdtemp(join(tmpdir(), "ia-op-"));
167
+ try {
168
+ if (store.kind === "document") {
169
+ const path = join(dir, store.fileName);
170
+ await writeFile(path, secret, { mode: 0o600 });
171
+ await execFileImpl("op", [
172
+ "document",
173
+ "create",
174
+ path,
175
+ "--vault",
176
+ vault,
177
+ "--title",
178
+ title,
179
+ "--file-name",
180
+ store.fileName,
181
+ ]);
182
+ }
183
+ else {
184
+ const path = join(dir, "item.json");
185
+ const template = {
186
+ title,
187
+ category: "API_CREDENTIAL",
188
+ fields: [
189
+ {
190
+ id: "credential",
191
+ type: "CONCEALED",
192
+ label: "credential",
193
+ value: secret,
194
+ },
195
+ ],
196
+ };
197
+ await writeFile(path, JSON.stringify(template), { mode: 0o600 });
198
+ await execFileImpl("op", ["item", "create", "--vault", vault, "--template", path]);
199
+ }
200
+ return true;
201
+ }
202
+ catch (error) {
203
+ return execFailureDetail(error).detail;
204
+ }
205
+ finally {
206
+ await rm(dir, { recursive: true, force: true });
207
+ }
208
+ }
209
+ /**
210
+ * Belt and braces: op's stderr should never echo the value, but if it did, cut
211
+ * it — the whole value, and for a key JSON every long string inside it (an
212
+ * echo of `private_key` alone is still the key).
213
+ */
214
+ function redact(text, secret) {
215
+ const fragments = [secret];
216
+ try {
217
+ const parsed = JSON.parse(secret);
218
+ for (const value of Object.values(parsed)) {
219
+ if (typeof value === "string" && value.length >= 16)
220
+ fragments.push(value);
221
+ }
222
+ }
223
+ catch {
224
+ // Not JSON: the whole value is the only fragment.
225
+ }
226
+ return fragments
227
+ .filter(Boolean)
228
+ .sort((a, b) => b.length - a.length)
229
+ .reduce((out, fragment) => out.split(fragment).join("[redacted]"), text);
230
+ }
@@ -108,6 +108,23 @@ export interface PortalAddUserResult {
108
108
  slug: string;
109
109
  user: PortalOrgUser;
110
110
  }
111
+ /**
112
+ * Change one contact. Name it by `email` (case-insensitive) OR by `name` (only
113
+ * a contact with no email) — exactly one. Change `role`, `status` or both.
114
+ */
115
+ export interface PortalSetUserInput {
116
+ slug: string;
117
+ email?: string;
118
+ name?: string;
119
+ role?: "member" | "owner";
120
+ status?: "active" | "disabled";
121
+ }
122
+ export interface PortalSetUserResult {
123
+ slug: string;
124
+ user: PortalOrgUser;
125
+ /** False when the contact already had these values (nothing was written). */
126
+ changed: boolean;
127
+ }
111
128
  export interface PortalListOrgsResult {
112
129
  orgs: PortalOrg[];
113
130
  }
@@ -204,6 +221,13 @@ export declare function portalSetDriveFolder(input: {
204
221
  folderId: string;
205
222
  }, options?: PortalAdminOptions): Promise<PortalSetDriveFolderResult>;
206
223
  export declare function portalAddUser(input: PortalAddUserInput, options?: PortalAdminOptions): Promise<PortalAddUserResult>;
224
+ /**
225
+ * Change a contact's role and/or status (PATCH /api/admin/users). The portal
226
+ * never deletes a contact: `disabled` keeps the row (uploads, feedback and
227
+ * sign-in links point at it) and stops new magic-link sign-ins. Errors name
228
+ * the field, never the email or name.
229
+ */
230
+ export declare function portalSetUser(input: PortalSetUserInput, options?: PortalAdminOptions): Promise<PortalSetUserResult>;
207
231
  export declare function portalListOrgs(options?: PortalAdminOptions): Promise<PortalListOrgsResult>;
208
232
  /**
209
233
  * The client-side check of a create: an agent needs its n8n workflow id, an
@@ -114,6 +114,35 @@ export async function portalAddUser(input, options = {}) {
114
114
  ...(input.role ? { role: input.role } : {}),
115
115
  });
116
116
  }
117
+ /**
118
+ * Change a contact's role and/or status (PATCH /api/admin/users). The portal
119
+ * never deletes a contact: `disabled` keeps the row (uploads, feedback and
120
+ * sign-in links point at it) and stops new magic-link sign-ins. Errors name
121
+ * the field, never the email or name.
122
+ */
123
+ export async function portalSetUser(input, options = {}) {
124
+ const slug = normalizeSlug(input.slug, "org");
125
+ const email = input.email?.trim();
126
+ const name = input.name?.trim();
127
+ if (Boolean(email) === Boolean(name)) {
128
+ throw new Error("give exactly one of --email or --name to find the contact");
129
+ }
130
+ if (input.role !== undefined && input.role !== "member" && input.role !== "owner") {
131
+ throw new Error("role must be member|owner");
132
+ }
133
+ if (input.status !== undefined && input.status !== "active" && input.status !== "disabled") {
134
+ throw new Error("status must be active|disabled");
135
+ }
136
+ if (input.role === undefined && input.status === undefined) {
137
+ throw new Error("give --role and/or --status to change");
138
+ }
139
+ return portalRequest("PATCH", "/api/admin/users", options, {
140
+ slug,
141
+ ...(email ? { email } : { name }),
142
+ ...(input.role ? { role: input.role } : {}),
143
+ ...(input.status ? { status: input.status } : {}),
144
+ });
145
+ }
117
146
  export async function portalListOrgs(options = {}) {
118
147
  return portalRequest("GET", "/api/admin/orgs", options);
119
148
  }
@@ -1,3 +1,4 @@
1
+ import { type GcpManifestKey } from "./client-manifest.js";
1
2
  /**
2
3
  * Files that must stay byte-identical between clients/client-template/ and
3
4
  * every clients/client-<slug>/ repo — the enforcement chain (the lint script
@@ -49,12 +50,21 @@ export interface TemplateSyncRepoResult {
49
50
  dir: string;
50
51
  files: TemplateSyncFileResult[];
51
52
  inSync: boolean;
53
+ /**
54
+ * CLIENT.md's Google Cloud keys (gcp_project / gcp_account) that are absent
55
+ * or still the placeholder. Report only: CLIENT.md is per-client, so even
56
+ * `--apply` never writes it — a technician fills the keys in that repo.
57
+ * Empty when both are set (or `none`), or when the repo has no CLIENT.md.
58
+ */
59
+ manifestGaps: GcpManifestKey[];
52
60
  }
53
61
  export interface TemplateSyncResult {
54
62
  templateDir: string;
55
63
  files: string[];
56
64
  repos: TemplateSyncRepoResult[];
57
65
  driftedRepoCount: number;
66
+ /** Repos whose CLIENT.md lacks gcp_project / gcp_account (or holds the placeholder). */
67
+ manifestGapRepoCount: number;
58
68
  applied: boolean;
59
69
  }
60
70
  /**
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { copyFile, mkdir, readdir, readFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
+ import { readGcpManifestFromRepo } from "./client-manifest.js";
4
5
  /**
5
6
  * Files that must stay byte-identical between clients/client-template/ and
6
7
  * every clients/client-<slug>/ repo — the enforcement chain (the lint script
@@ -89,11 +90,15 @@ export async function templateSync(options) {
89
90
  }
90
91
  fileResults.push({ file: rel, status });
91
92
  }
93
+ const manifest = readGcpManifestFromRepo(dir);
92
94
  repos.push({
93
95
  slug,
94
96
  dir,
95
97
  files: fileResults,
96
98
  inSync: fileResults.every((f) => f.status === "in-sync" || f.status === "fixed"),
99
+ manifestGaps: manifest
100
+ ? [...manifest.missing, ...manifest.unfilled, ...manifest.invalid]
101
+ : [],
97
102
  });
98
103
  }
99
104
  return {
@@ -101,6 +106,7 @@ export async function templateSync(options) {
101
106
  files,
102
107
  repos,
103
108
  driftedRepoCount: repos.filter((r) => !r.inSync).length,
109
+ manifestGapRepoCount: repos.filter((r) => r.manifestGaps.length > 0).length,
104
110
  applied: apply,
105
111
  };
106
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@installagent/sdk",
3
- "version": "0.5.0",
3
+ "version": "0.7.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",