@seekrit/mcp 0.8.5 → 0.9.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.
Files changed (2) hide show
  1. package/dist/index.js +1056 -151
  2. package/package.json +31 -8
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { homedir } from "node:os";
8
8
  import { dirname, join, parse } from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { Writable } from "node:stream";
11
- //#region ../../packages/core/src/agent-policy.ts
11
+ // ../../packages/core/src/agent-policy.ts
12
12
  /** A bare hostname: no scheme, no port, no path, no wildcard. */
13
13
  const policyHostSchema = z.string().trim().min(1).max(253).toLowerCase().refine((h) => !/[:/\s*]/.test(h), { message: "host must be a bare hostname (no scheme, port, path, or wildcard)" }).refine((h) => /^[a-z0-9.-]+$/.test(h), { message: "host contains invalid characters" });
14
14
  const policyMethodSchema = z.string().trim().toUpperCase().regex(/^[A-Z]{3,10}$/, "method must be an HTTP method name");
@@ -18,11 +18,15 @@ const policyMethodSchema = z.string().trim().toUpperCase().regex(/^[A-Z]{3,10}$/
18
18
  */
19
19
  const policyPathSchema = z.string().trim().min(1).max(512).startsWith("/", "path pattern must start with /").refine((p) => !p.includes("?"), { message: "path patterns match the path only, not the query" });
20
20
  const policySecretNameSchema = z.string().trim().regex(/^[A-Za-z0-9_]+$/, "secret names are letters, digits, and underscores");
21
+ /** A TCP port. 0 is refused: it never matches a connection, so a rule naming it is a mistake. */
22
+ const policyPortSchema = z.number().int().min(1).max(65535);
21
23
  z.object({
22
24
  host: policyHostSchema,
23
25
  methods: z.array(policyMethodSchema).max(16).default([]),
24
26
  paths: z.array(policyPathSchema).max(64).default([]),
25
27
  allow: z.array(policySecretNameSchema).max(64).default([]),
28
+ https_ports: z.array(policyPortSchema).max(32).optional(),
29
+ http_ports: z.array(policyPortSchema).max(32).optional(),
26
30
  label: z.string().trim().max(120).optional()
27
31
  });
28
32
  z.object({
@@ -41,6 +45,11 @@ z.object({
41
45
  });
42
46
  z.object({
43
47
  host: policyHostSchema,
48
+ /** How the agent reaches the host. Omit for a destination the operator fixed. */
49
+ transport: z.object({
50
+ scheme: z.enum(["https", "http"]),
51
+ port: policyPortSchema
52
+ }).optional(),
44
53
  method: policyMethodSchema,
45
54
  path: z.string().trim().min(1).max(2048),
46
55
  secret: policySecretNameSchema.optional()
@@ -52,6 +61,7 @@ const activityEntrySchema = z.object({
52
61
  decision: z.enum([
53
62
  "allow",
54
63
  "no_rule",
64
+ "port_not_allowed",
55
65
  "method_not_allowed",
56
66
  "path_not_allowed",
57
67
  "secret_not_allowed",
@@ -136,8 +146,7 @@ z.object({
136
146
  z.object({
137
147
  /** The presented token. In the body, never a URL — it is a credential. */
138
148
  token: z.string().trim().min(8).max(512) });
139
- //#endregion
140
- //#region ../../packages/core/src/archive.ts
149
+ // ../../packages/core/src/archive.ts
141
150
  /**
142
151
  * The **break-glass archive** format: one signed JSON file holding everything
143
152
  * seekrit stores for an org, in the form seekrit stores it — ciphertext stays
@@ -275,12 +284,24 @@ const ENTITLEMENT_KEYS = Object.keys({
275
284
  description: "Single sign-on beyond the built-in providers.",
276
285
  default: true
277
286
  },
287
+ "feature.approvals": {
288
+ kind: "feature",
289
+ label: "Approval workflows",
290
+ description: "Require review before a change to a protected environment lands.",
291
+ default: true
292
+ },
278
293
  "feature.sync": {
279
294
  kind: "feature",
280
295
  label: "Third-party sync",
281
296
  description: "Push environment secrets to external platforms like Vercel.",
282
297
  default: true
283
298
  },
299
+ "feature.vault": {
300
+ kind: "feature",
301
+ label: "Vault",
302
+ description: "Capture, hold and apply your end users' credentials for an agent — without your systems or seekrit ever holding a plaintext.",
303
+ default: true
304
+ },
284
305
  "apps.max": {
285
306
  kind: "limit",
286
307
  label: "Applications",
@@ -341,6 +362,12 @@ const ENTITLEMENT_KEYS = Object.keys({
341
362
  description: "Maximum secrets with managed rotation configured.",
342
363
  default: null
343
364
  },
365
+ "vault.connections.max": {
366
+ kind: "limit",
367
+ label: "Vault connections",
368
+ description: "Maximum active end-user connections across the organization's Vault projects.",
369
+ default: null
370
+ },
344
371
  members: {
345
372
  kind: "metered",
346
373
  label: "Members",
@@ -356,8 +383,7 @@ const ENTITLEMENT_KEYS = Object.keys({
356
383
  metric: "monthly_resolves"
357
384
  }
358
385
  });
359
- //#endregion
360
- //#region ../../packages/core/src/plans.ts
386
+ // ../../packages/core/src/plans.ts
361
387
  const PLAN_FAMILIES = {
362
388
  free: {
363
389
  id: "free",
@@ -390,8 +416,7 @@ const PLAN_FAMILIES = {
390
416
  };
391
417
  const PLAN_FAMILY_IDS = Object.keys(PLAN_FAMILIES);
392
418
  PLAN_FAMILY_IDS.filter((family) => !PLAN_FAMILIES[family].hidden);
393
- //#endregion
394
- //#region ../../packages/core/src/billing.ts
419
+ // ../../packages/core/src/billing.ts
395
420
  /**
396
421
  * Lifecycle states a subscription can be in. Mirrors the biller's own states
397
422
  * (Stripe) but is provider-neutral so a different biller could map onto it.
@@ -403,8 +428,7 @@ const SUBSCRIPTION_STATUSES = [
403
428
  "canceled",
404
429
  "paused"
405
430
  ];
406
- //#endregion
407
- //#region ../../packages/core/src/branches.ts
431
+ // ../../packages/core/src/branches.ts
408
432
  /**
409
433
  * Branch (ephemeral) environments — a per-PR/preview overlay on an existing
410
434
  * application environment.
@@ -448,8 +472,149 @@ function parseBranchTtl(input) {
448
472
  if (multiplier === void 0) return null;
449
473
  return value * multiplier;
450
474
  }
451
- //#endregion
452
- //#region ../../packages/core/src/dotenv.ts
475
+ // ../../packages/core/src/change-requests.ts
476
+ const CHANGE_REQUEST_STATUSES = [
477
+ "open",
478
+ "applied",
479
+ "rejected",
480
+ "withdrawn",
481
+ "superseded"
482
+ ];
483
+ // ../../packages/core/src/connect.ts
484
+ /** Workload authentication is separate from secret-decryption principals. */
485
+ const workloadPublicKeySchema = z.object({
486
+ kty: z.literal("EC"),
487
+ crv: z.literal("P-256"),
488
+ x: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
489
+ y: z.string().regex(/^[A-Za-z0-9_-]{43}$/)
490
+ }).strict();
491
+ const audienceSchema = z.string().min(1).max(256).regex(/^[^\s]+$/);
492
+ /** HTTPS endpoint syntax. Resolved-address safety is enforced by the server runtime. */
493
+ const connectUrlSchema = z.string().max(2048).url().refine((value) => {
494
+ try {
495
+ const u = new URL(value);
496
+ return u.protocol === "https:" && !u.username && !u.password && !u.hash && !u.search && !u.port && u.hostname.length <= 253 && u.hostname.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) && u.hostname.includes(".") && !/^[0-9.]+$/.test(u.hostname) && !u.hostname.endsWith(".") && !/(^|\.)(localhost|local|localdomain|internal|invalid|home|home\.arpa|onion)$/.test(u.hostname);
497
+ } catch {
498
+ return false;
499
+ }
500
+ }, "use a public HTTPS hostname without credentials, query, fragment, or port");
501
+ const federationPolicySchema = z.object({
502
+ issuer: connectUrlSchema,
503
+ jwksUri: connectUrlSchema,
504
+ audience: audienceSchema,
505
+ subject: z.string().min(1).max(512),
506
+ claims: z.record(z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,63}$/), z.string().min(1).max(512)).refine((claims) => Object.keys(claims).length <= 20 && Object.keys(claims).every((key) => ![
507
+ "iss",
508
+ "aud",
509
+ "sub",
510
+ "exp",
511
+ "iat",
512
+ "nbf"
513
+ ].includes(key))).default({})
514
+ }).strict();
515
+ z.object({
516
+ name: z.string().trim().min(1).max(100),
517
+ environmentId: z.string().min(1).max(128),
518
+ publicKey: workloadPublicKeySchema.optional(),
519
+ federation: federationPolicySchema.optional(),
520
+ audiences: z.array(audienceSchema).max(20).default([]),
521
+ maxTtlSeconds: z.number().int().min(60).max(900).default(300)
522
+ }).strict().refine((v) => !!v.publicKey !== !!v.federation, "choose a public key or a federation policy");
523
+ z.object({
524
+ enabled: z.boolean().optional(),
525
+ publicKey: workloadPublicKeySchema.optional()
526
+ }).strict().refine((v) => v.enabled !== void 0 || v.publicKey !== void 0);
527
+ const githubPermissionsSchema = z.record(z.string().regex(/^[a-z_]{1,64}$/), z.enum(["read", "write"])).refine((p) => Object.keys(p).length > 0 && Object.keys(p).length <= 40, "specify between 1 and 40 permissions");
528
+ const githubScopeSchema = z.object({
529
+ repositoryIds: z.array(z.number().int().positive().max(Number.MAX_SAFE_INTEGER)).min(1).max(100),
530
+ permissions: githubPermissionsSchema
531
+ }).strict();
532
+ /** Exact paths or explicitly allowed descendants, without URL decoding ambiguity. */
533
+ const connectPathSchema = z.string().min(1).max(1024).refine((path) => /^\/[A-Za-z0-9_./~-]*$/.test(path) && !path.includes("//") && !path.split("/").some((part) => part === "." || part === ".."), "use an absolute API path without encoded characters or dot segments");
534
+ const proxyRuleSchema = z.object({
535
+ path: connectPathSchema,
536
+ descendants: z.boolean().default(false),
537
+ methods: z.array(z.enum([
538
+ "GET",
539
+ "POST",
540
+ "PUT",
541
+ "PATCH",
542
+ "DELETE",
543
+ "HEAD"
544
+ ])).min(1).max(6)
545
+ }).strict();
546
+ const staticScopeSchema = z.object({ rules: z.array(proxyRuleSchema).min(1).max(30) }).strict();
547
+ const oauthScopeSchema = z.object({ scopes: z.array(z.string().regex(/^[\x21\x23-\x5b\x5d-\x7e]{1,200}$/)).min(1).max(50).refine((scopes) => new Set(scopes).size === scopes.length, "scopes must be unique") }).strict();
548
+ const oauthConfigSchema = oauthScopeSchema.extend({
549
+ provider: z.literal("oauth"),
550
+ grantType: z.enum(["client_credentials", "authorization_code"]),
551
+ clientId: z.string().min(1).max(512),
552
+ tokenEndpoint: connectUrlSchema,
553
+ authorizationEndpoint: connectUrlSchema.optional(),
554
+ tokenAuthMethod: z.enum(["client_secret_basic", "client_secret_post"]).default("client_secret_basic")
555
+ });
556
+ const customApiConfigSchema = staticScopeSchema.extend({
557
+ provider: z.literal("custom_api"),
558
+ origin: connectUrlSchema.refine((value) => {
559
+ try {
560
+ return new URL(value).pathname === "/";
561
+ } catch {
562
+ return false;
563
+ }
564
+ }, "use an origin without a path"),
565
+ headerName: z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,63}$/).refine((v) => !/^(accept$|user-agent$|host|cookie|content-|proxy-|forwarded|x-forwarded-|cf-|connection|transfer-encoding|upgrade|trailer|te$)/i.test(v)),
566
+ headerPrefix: z.string().max(64).regex(/^[\x20-\x7e]*$/).default("Bearer ")
567
+ });
568
+ const connectConfigSchema = z.discriminatedUnion("provider", [
569
+ customApiConfigSchema,
570
+ oauthConfigSchema,
571
+ githubScopeSchema.extend({
572
+ provider: z.literal("github_app"),
573
+ appId: z.string().regex(/^[A-Za-z0-9_.-]{1,128}$/),
574
+ installationId: z.string().regex(/^[1-9][0-9]{0,19}$/)
575
+ }),
576
+ staticScopeSchema.extend({
577
+ provider: z.literal("static_key"),
578
+ service: z.literal("resend"),
579
+ rules: z.array(proxyRuleSchema.refine((rule) => rule.path === "/emails" || rule.path.startsWith("/emails/"), "the Resend connector supports only /emails and its descendants")).min(1).max(30)
580
+ })
581
+ ]).refine((v) => v.provider !== "oauth" || v.grantType !== "authorization_code" || !!v.authorizationEndpoint, "authorization-code connections require an authorization endpoint");
582
+ const connectGrantPolicySchema = z.discriminatedUnion("provider", [
583
+ staticScopeSchema.extend({ provider: z.literal("custom_api") }),
584
+ oauthScopeSchema.extend({ provider: z.literal("oauth") }),
585
+ githubScopeSchema.extend({ provider: z.literal("github_app") }),
586
+ staticScopeSchema.extend({ provider: z.literal("static_key") })
587
+ ]);
588
+ z.object({
589
+ name: z.string().trim().min(1).max(100),
590
+ config: connectConfigSchema,
591
+ credentialWrapped: z.string().startsWith("wd1.").max(32e3)
592
+ }).strict();
593
+ z.object({
594
+ enabled: z.boolean().optional(),
595
+ credentialWrapped: z.string().startsWith("wd1.").max(32e3).optional()
596
+ }).strict().refine((v) => v.enabled !== void 0 || v.credentialWrapped !== void 0);
597
+ z.object({
598
+ workloadId: z.string().min(1).max(128),
599
+ connectionId: z.string().min(1).max(128),
600
+ policy: connectGrantPolicySchema
601
+ }).strict();
602
+ z.object({
603
+ path: connectPathSchema,
604
+ method: z.enum([
605
+ "GET",
606
+ "POST",
607
+ "PUT",
608
+ "PATCH",
609
+ "DELETE",
610
+ "HEAD"
611
+ ]).default("GET"),
612
+ query: z.record(z.string().min(1).max(100), z.string().max(2048)).default({}),
613
+ /** JSON only; callers cannot inject authorization or forwarding headers. */
614
+ body: z.string().max(65536).optional()
615
+ }).strict().refine((v) => !["GET", "HEAD"].includes(v.method) || v.body === void 0, "GET and HEAD cannot carry a body");
616
+ z.object({ audience: audienceSchema }).strict();
617
+ // ../../packages/core/src/dotenv.ts
453
618
  /**
454
619
  * Apply double-quote escapes in a single left-to-right pass.
455
620
  *
@@ -538,8 +703,7 @@ function skipSpace(content, from, end) {
538
703
  while (i < end && (content[i] === " " || content[i] === " ")) i++;
539
704
  return i;
540
705
  }
541
- //#endregion
542
- //#region ../../packages/core/src/interpolate.ts
706
+ // ../../packages/core/src/interpolate.ts
543
707
  /**
544
708
  * Secret references: `${OTHER_SECRET}` inside a secret value.
545
709
  *
@@ -1036,8 +1200,7 @@ z.discriminatedUnion("provider", [
1036
1200
  mintGcpLeaseSchema,
1037
1201
  mintMongoLeaseSchema
1038
1202
  ]);
1039
- //#endregion
1040
- //#region ../../packages/core/src/types.ts
1203
+ // ../../packages/core/src/types.ts
1041
1204
  /**
1042
1205
  * Transactional notification emails seekrit can send. Each id is one
1043
1206
  * user-facing on/off toggle (see `NOTIFICATION_TYPE_META`). These carry only
@@ -1056,10 +1219,11 @@ const NOTIFICATION_TYPES = [
1056
1219
  "lease_expired",
1057
1220
  "sync_failed",
1058
1221
  "honey_token_tripped",
1059
- "secret_rotation_failed"
1222
+ "secret_rotation_failed",
1223
+ "change_request_opened",
1224
+ "change_request_decided"
1060
1225
  ];
1061
- //#endregion
1062
- //#region ../../packages/core/src/schemas.ts
1226
+ // ../../packages/core/src/schemas.ts
1063
1227
  /** URL-safe identifier segment: `my-app`, `production`, … */
1064
1228
  const slugSchema = z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "must be lowercase alphanumeric with hyphens");
1065
1229
  const nameSchema = z.string().trim().min(1).max(128);
@@ -1067,7 +1231,7 @@ const nameSchema = z.string().trim().min(1).max(128);
1067
1231
  const emailSchema = z.string().trim().toLowerCase().pipe(z.email().max(320));
1068
1232
  /** Env-var style secret name: FOO, DATABASE_URL, apiKey2 … */
1069
1233
  const secretNameSchema = z.string().min(1).max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "must be a valid environment variable name");
1070
- z.enum([
1234
+ const orgRoleSchema = z.enum([
1071
1235
  "owner",
1072
1236
  "admin",
1073
1237
  "member"
@@ -1106,12 +1270,35 @@ z.object({
1106
1270
  name: nameSchema,
1107
1271
  slug: slugSchema
1108
1272
  });
1273
+ /** Compose a group into an application environment (matched by env slug). */
1274
+ const appAccessKeySchema = z.object({
1275
+ environmentId: z.string().min(1),
1276
+ userId: z.string().min(1),
1277
+ wrappedDek: z.string().min(1).max(8192)
1278
+ });
1279
+ const appAccessGrantsSchema = z.array(appAccessKeySchema).max(5e3).optional();
1280
+ z.object({
1281
+ userId: z.string().min(1),
1282
+ grants: z.array(appAccessKeySchema).max(5e3)
1283
+ });
1284
+ z.object({ role: orgRoleSchema });
1109
1285
  z.object({
1286
+ appAccessGrants: appAccessGrantsSchema,
1110
1287
  groupId: z.string().min(1),
1111
1288
  /** Precedence among an env's groups (higher wins). Appended if omitted. */
1112
- position: z.number().int().min(0).optional()
1289
+ position: z.number().int().min(0).optional(),
1290
+ /** Client-wrapped group DEK for each sync connection newly reading this group. */
1291
+ syncGrants: z.array(z.object({
1292
+ connectionId: z.string().min(1),
1293
+ wrappedDek: z.string().min(1)
1294
+ })).optional()
1113
1295
  });
1114
1296
  z.object({
1297
+ /** Wrap the new DEK to all persistent app recipients. */
1298
+ userGrants: z.array(z.object({
1299
+ userId: z.string().min(1),
1300
+ wrappedDek: z.string().min(1).max(8192)
1301
+ })).max(5e3).optional(),
1115
1302
  name: nameSchema,
1116
1303
  slug: slugSchema,
1117
1304
  /** Environment DEK wrapped to the creator's public key — created client-side. */
@@ -1128,6 +1315,17 @@ z.object({
1128
1315
  ciphertext: z.string().min(1).max(65536) });
1129
1316
  z.object({ version: z.number().int().positive() });
1130
1317
  z.object({ limit: z.coerce.number().int().min(1).max(200).default(50) });
1318
+ z.object({
1319
+ requiredApprovals: z.number().int().min(1).max(10).default(1),
1320
+ allowSelfApproval: z.boolean().default(false)
1321
+ });
1322
+ z.object({ comment: z.string().trim().max(1e3).optional() });
1323
+ z.string().trim().min(1).max(1e3);
1324
+ z.object({
1325
+ status: z.enum(CHANGE_REQUEST_STATUSES).optional(),
1326
+ envId: z.string().min(1).optional(),
1327
+ limit: z.coerce.number().int().min(1).max(200).default(50)
1328
+ });
1131
1329
  z.object({
1132
1330
  publicKeyJwk: z.string().min(1),
1133
1331
  /**
@@ -1162,7 +1360,23 @@ z.object({
1162
1360
  /** The same DEK wrapped to each of the parent's existing grant-holders. */
1163
1361
  grants: z.array(grantEnvironmentKeySchema).max(500).default([])
1164
1362
  });
1363
+ /**
1364
+ * Token creation is client-driven so the server never sees the token secret:
1365
+ * the client generates the keypair + token string and submits only the hash
1366
+ * and public key.
1367
+ */
1368
+ const environmentGrantBatchSchema = z.array(z.object({
1369
+ environmentId: z.string().min(1),
1370
+ wrappedDek: z.string().min(1).max(8192)
1371
+ })).max(5e3);
1165
1372
  z.object({
1373
+ principalType: principalTypeSchema,
1374
+ principalId: z.string().min(1),
1375
+ grants: environmentGrantBatchSchema
1376
+ });
1377
+ z.object({
1378
+ /** Commit the token and all default resolve keys together, when supplied. */
1379
+ initialGrants: environmentGrantBatchSchema.optional(),
1166
1380
  name: nameSchema,
1167
1381
  tokenId: z.string().regex(/^skt_[0-9A-Za-z]+$/),
1168
1382
  /** SHA-256 hash (base64url) of the full token string. */
@@ -1450,7 +1664,9 @@ z.enum([
1450
1664
  "gcp-secret-manager",
1451
1665
  "langgraph-platform",
1452
1666
  "azure-key-vault",
1453
- "huggingface-spaces"
1667
+ "huggingface-spaces",
1668
+ "openai-vault",
1669
+ "claude-managed-agents"
1454
1670
  ]);
1455
1671
  /**
1456
1672
  * Vercel account scope. The API token itself is never here — it is wrapped to
@@ -1828,6 +2044,25 @@ const azureKeyVaultConnectionConfigSchema = z.object({
1828
2044
  * would invite pointing a connection at a host that silently swallows secrets.
1829
2045
  */
1830
2046
  const huggingfaceSpacesConnectionConfigSchema = z.object({ provider: z.literal("huggingface-spaces") });
2047
+ /** The wrapped credential is an OpenAI project API key with vault read/write access. */
2048
+ const openaiVaultConnectionConfigSchema = z.object({ provider: z.literal("openai-vault") });
2049
+ /**
2050
+ * Claude Managed Agents account scope — empty, for Hugging Face's reason.
2051
+ *
2052
+ * An Anthropic API key belongs to exactly one **workspace**, and vaults are
2053
+ * workspace-scoped: the key can reach every vault in its workspace and none
2054
+ * outside it. A vault ID is globally unique. So the key plus the destination is
2055
+ * the whole address, and the API's `anthropic-workspace-id` header — which
2056
+ * exists for credentials that span several workspaces — has nothing to select.
2057
+ *
2058
+ * There is no `baseUrl`, and adding one would not be enough. Bedrock, Vertex
2059
+ * AI, and Foundry do not offer Managed Agents at all. Claude Platform on AWS
2060
+ * does, at `aws-external-anthropic.{region}.api.aws` — but it authenticates
2061
+ * with SigV4 over an IAM credential, not an API key, so it is a different
2062
+ * credential shape and a different connector (one that would reuse
2063
+ * `lib/leases/aws-sigv4.ts`), not a different host for this one.
2064
+ */
2065
+ const claudeManagedAgentsConnectionConfigSchema = z.object({ provider: z.literal("claude-managed-agents") });
1831
2066
  const syncConnectionConfigSchema = z.discriminatedUnion("provider", [
1832
2067
  vercelConnectionConfigSchema,
1833
2068
  cloudflareWorkersConnectionConfigSchema,
@@ -1847,7 +2082,9 @@ const syncConnectionConfigSchema = z.discriminatedUnion("provider", [
1847
2082
  gcpSecretManagerConnectionConfigSchema,
1848
2083
  langgraphPlatformConnectionConfigSchema,
1849
2084
  azureKeyVaultConnectionConfigSchema,
1850
- huggingfaceSpacesConnectionConfigSchema
2085
+ huggingfaceSpacesConnectionConfigSchema,
2086
+ openaiVaultConnectionConfigSchema,
2087
+ claudeManagedAgentsConnectionConfigSchema
1851
2088
  ]);
1852
2089
  const vercelDestinationSchema = z.object({
1853
2090
  provider: z.literal("vercel"),
@@ -2626,6 +2863,83 @@ const huggingfaceSpacesDestinationSchema = z.object({
2626
2863
  /** Space ID as `owner/name`, e.g. `acme/support-demo`. */
2627
2864
  repoId: huggingfaceRepoIdSchema
2628
2865
  });
2866
+ /** One existing OpenAI vault; every credential in this binding gets the same host boundary. */
2867
+ const openaiVaultDestinationSchema = z.object({
2868
+ provider: z.literal("openai-vault"),
2869
+ vaultId: z.string().trim().regex(/^vault_[A-Za-z0-9_-]+$/, "must be an OpenAI vault ID"),
2870
+ allowedHosts: z.array(z.string().trim().toLowerCase().max(253).regex(/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/, "must be an exact hostname without scheme, port, path, or wildcard")).min(1).max(100).refine((hosts) => new Set(hosts).size === hosts.length, "hostnames must be unique")
2871
+ });
2872
+ /**
2873
+ * A vault ID as the Claude Console and API show it: `vlt_` and an opaque
2874
+ * alphanumeric tail. Held to that shape because the habitual slip — pasting the
2875
+ * vault's display name — is a 404 from inside an alarm, which says nothing
2876
+ * about which half of the address was wrong.
2877
+ */
2878
+ const claudeVaultIdSchema = z.string().trim().regex(/^vlt_[A-Za-z0-9]{1,128}$/, "must be a vault ID, e.g. vlt_01ABC… — not its display name");
2879
+ /** Ceiling on per-name host rules; a vault itself holds at most 20 credentials. */
2880
+ const CLAUDE_VAULT_MAX_HOST_RULES = 100;
2881
+ /** A hostname of two or more labels whose last label starts with a letter. */
2882
+ const CLAUDE_VAULT_HOSTNAME = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
2883
+ const CLAUDE_VAULT_IPV4 = /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
2884
+ /**
2885
+ * One host a secret's value may be substituted on, in the three forms the vault
2886
+ * API takes: a bare hostname (`api.openai.com`), a `*.`-prefixed wildcard
2887
+ * (`*.stripe.com`), or an IPv4 address.
2888
+ *
2889
+ * The API refuses URLs, ports, paths, and IPv6, so those are refused here too —
2890
+ * pasting `https://api.openai.com/v1` is the slip this exists for. Note the
2891
+ * wildcard's documented reach: `*.stripe.com` matches every subdomain of
2892
+ * `stripe.com` **but not `stripe.com` itself**, so a service reached at its apex
2893
+ * needs both entries. A bare TLD wildcard (`*.com`) is refused by shape.
2894
+ */
2895
+ const claudeVaultHostSchema = z.string().trim().toLowerCase().max(253).refine((host) => CLAUDE_VAULT_HOSTNAME.test(host) || CLAUDE_VAULT_IPV4.test(host), "must be a bare hostname (api.example.com), a *.example.com wildcard, or an IPv4 address — not a URL");
2896
+ /**
2897
+ * Where one secret's value may be substituted: a list of hosts, or the literal
2898
+ * `"unrestricted"`, which lets it reach any host the agent's *environment*
2899
+ * permits. The literal is spelled out rather than implied by an empty list, so
2900
+ * the widest setting is never something a binding arrives at by omission.
2901
+ */
2902
+ const claudeVaultHostRuleSchema = z.union([z.literal("unrestricted"), z.array(claudeVaultHostSchema).min(1).max(16)]);
2903
+ /**
2904
+ * One **Claude Managed Agents vault**, whose `environment_variable` credentials
2905
+ * a binding owns.
2906
+ *
2907
+ * Like `openai-vault`, a destination where the workload never holds the
2908
+ * plaintext either: an agent's sandbox sees an opaque placeholder in the
2909
+ * variable, and Anthropic's egress proxy swaps the real value in only on a
2910
+ * request to a host the credential names. So every name needs somewhere it is
2911
+ * allowed to go, and that is most of this shape:
2912
+ *
2913
+ * - `allowedHostsByName` — per destination name, after `nameTransform`. The
2914
+ * right tool: a Stripe key belongs on `api.stripe.com` and nowhere else.
2915
+ * - `allowedHosts` — for every name without its own rule.
2916
+ *
2917
+ * At least one must be given. A pushed name covered by neither **fails** rather
2918
+ * than going out `unrestricted` — the default-deny stance `apps/proxy` takes, so
2919
+ * a secret added to the environment later cannot silently widen where values
2920
+ * flow. Both levels apply beside the agent environment's own network policy,
2921
+ * which must also let the host through; this shape cannot see that policy.
2922
+ */
2923
+ const claudeManagedAgentsDestinationSchema = z.object({
2924
+ provider: z.literal("claude-managed-agents"),
2925
+ /** The vault's ID, e.g. `vlt_01ABC…`. */
2926
+ vaultId: claudeVaultIdSchema,
2927
+ /** Hosts for every name without its own entry in `allowedHostsByName`. */
2928
+ allowedHosts: claudeVaultHostRuleSchema.optional(),
2929
+ /** Destination name → the hosts that one value may be substituted on. */
2930
+ allowedHostsByName: z.record(secretNameSchema, claudeVaultHostRuleSchema).optional(),
2931
+ injectionLocation: z.enum([
2932
+ "header",
2933
+ "body",
2934
+ "both"
2935
+ ]).default("header")
2936
+ }).refine((d) => d.allowedHosts !== void 0 || Object.keys(d.allowedHostsByName ?? {}).length > 0, {
2937
+ message: "name the hosts each secret may be used on — allowedHosts for all of them, allowedHostsByName per name, or \"unrestricted\"",
2938
+ path: ["allowedHosts"]
2939
+ }).refine((d) => Object.keys(d.allowedHostsByName ?? {}).length <= CLAUDE_VAULT_MAX_HOST_RULES, {
2940
+ message: `at most ${CLAUDE_VAULT_MAX_HOST_RULES} per-name host rules`,
2941
+ path: ["allowedHostsByName"]
2942
+ });
2629
2943
  const syncDestinationSchema = z.discriminatedUnion("provider", [
2630
2944
  vercelDestinationSchema,
2631
2945
  cloudflareWorkersDestinationSchema,
@@ -2645,7 +2959,9 @@ const syncDestinationSchema = z.discriminatedUnion("provider", [
2645
2959
  gcpSecretManagerDestinationSchema,
2646
2960
  langgraphPlatformDestinationSchema,
2647
2961
  azureKeyVaultDestinationSchema,
2648
- huggingfaceSpacesDestinationSchema
2962
+ huggingfaceSpacesDestinationSchema,
2963
+ openaiVaultDestinationSchema,
2964
+ claudeManagedAgentsDestinationSchema
2649
2965
  ]);
2650
2966
  /**
2651
2967
  * How seekrit secret names become destination key names. Applied in order:
@@ -2705,8 +3021,291 @@ z.object({
2705
3021
  mode: z.enum(["auto", "manual"]).optional(),
2706
3022
  enabled: z.boolean().optional()
2707
3023
  });
2708
- //#endregion
2709
- //#region ../../packages/crypto/src/encoding.ts
3024
+ // ../../packages/core/src/vault.ts
3025
+ /** One encrypted credential within a connection. */
3026
+ const VAULT_SLOTS = [
3027
+ "oauth2",
3028
+ "api_key",
3029
+ "session",
3030
+ "login"
3031
+ ];
3032
+ const VAULT_CONNECTION_STATUSES = [
3033
+ "active",
3034
+ "reauth_required",
3035
+ "revoked"
3036
+ ];
3037
+ const VAULT_CONNECT_SESSION_MAX_TTL_SECONDS = 86400;
3038
+ /** Ciphertext bound: a `sc1.` blob of a 512 KiB session, with room for base64. */
3039
+ const VAULT_CIPHERTEXT_MAX_CHARS = 819200;
3040
+ /** Never above Browser Run's keep-alive ceiling, whatever a site profile asks for. */
3041
+ const VAULT_LEASE_MAX_MS = 12e5;
3042
+ const VAULT_LEASE_MIN_MS = 1e4;
3043
+ /** Fields `browser.fill` can type from a `login` slot. */
3044
+ const VAULT_FILL_FIELDS = [
3045
+ "username",
3046
+ "password",
3047
+ "totp"
3048
+ ];
3049
+ const VAULT_WEBHOOK_EVENTS = [
3050
+ "connection.ready",
3051
+ "connection.reauth_required",
3052
+ "connection.revoked"
3053
+ ];
3054
+ const base64urlMember = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "not a P-256 coordinate");
3055
+ const vaultPublicJwkSchema = z.object({
3056
+ kty: z.literal("EC"),
3057
+ crv: z.literal("P-256"),
3058
+ x: base64urlMember,
3059
+ y: base64urlMember
3060
+ });
3061
+ const isoInstant = z.iso.datetime({ offset: true });
3062
+ z.object({
3063
+ v: z.literal(1),
3064
+ accessToken: z.string().min(1).max(16384),
3065
+ tokenType: z.literal("Bearer"),
3066
+ accessTokenExpiresAt: isoInstant.optional(),
3067
+ refreshToken: z.string().min(1).max(16384).optional(),
3068
+ refreshTokenExpiresAt: isoInstant.optional(),
3069
+ scope: z.array(z.string().max(512)).max(128),
3070
+ obtainedAt: isoInstant
3071
+ });
3072
+ z.object({
3073
+ v: z.literal(1),
3074
+ key: z.string().min(1).max(8192)
3075
+ });
3076
+ /** RFC 6238 parameters, as an authenticator app would hold them. */
3077
+ const vaultTotpSchema = z.object({
3078
+ /** Base32 (RFC 4648), upper case, no padding, no separators. */
3079
+ secret: z.string().regex(/^[A-Z2-7]{16,128}$/, "TOTP secret must be base32"),
3080
+ digits: z.union([z.literal(6), z.literal(8)]),
3081
+ period: z.number().int().min(15).max(120),
3082
+ algorithm: z.enum([
3083
+ "SHA1",
3084
+ "SHA256",
3085
+ "SHA512"
3086
+ ])
3087
+ });
3088
+ z.object({
3089
+ v: z.literal(1),
3090
+ username: z.string().min(1).max(512),
3091
+ password: z.string().min(1).max(4096),
3092
+ totp: vaultTotpSchema.optional()
3093
+ });
3094
+ const vaultSessionCookieSchema = z.object({
3095
+ name: z.string().min(1).max(4096),
3096
+ value: z.string().max(16384),
3097
+ /** Kept exactly as captured — parent-domain cookies restore to their parent. */
3098
+ domain: z.string().min(1).max(253),
3099
+ path: z.string().min(1).max(4096),
3100
+ /** Unix seconds; -1 ⇒ a session cookie. */
3101
+ expires: z.number(),
3102
+ httpOnly: z.boolean(),
3103
+ secure: z.boolean(),
3104
+ sameSite: z.enum([
3105
+ "Strict",
3106
+ "Lax",
3107
+ "None"
3108
+ ]).optional(),
3109
+ partitionKey: z.unknown().optional()
3110
+ });
3111
+ z.object({
3112
+ v: z.literal(1),
3113
+ siteId: z.string().min(1).max(64),
3114
+ capturedAt: isoInstant,
3115
+ userAgent: z.string().max(1024),
3116
+ cookies: z.array(vaultSessionCookieSchema).max(4096),
3117
+ /** origin → key → value. */
3118
+ localStorage: z.record(z.string(), z.record(z.string(), z.string()))
3119
+ });
3120
+ const vaultProviderIdSchema = z.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9._-]*$/, "provider ids are lowercase letters, digits, dots and dashes");
3121
+ /**
3122
+ * What the dashboard, Connect and the SDK may know about a provider: its name,
3123
+ * its method, and — for the consent screen — a plain sentence about what the
3124
+ * agent will be able to do. Never the rules, the endpoints or the injection:
3125
+ * those are compiled into the executor and the API must not be able to serve a
3126
+ * different version of them.
3127
+ */
3128
+ const vaultCatalogProviderSchema = z.object({
3129
+ id: vaultProviderIdSchema,
3130
+ displayName: z.string().trim().min(1).max(80),
3131
+ method: z.enum(["oauth2", "api_key"]),
3132
+ /** The one sentence Connect shows: "read and send email as you". */
3133
+ consentSummary: z.string().trim().min(1).max(240),
3134
+ /** Hosts the executor will forward to, for display. */
3135
+ hosts: z.array(z.string().trim().min(1).max(253)).max(64).default([]),
3136
+ /** Where the end user finds the key (api_key providers). */
3137
+ helpUrl: z.url().max(2048).optional(),
3138
+ /** Label for the key field (api_key providers), e.g. "API key". */
3139
+ keyLabel: z.string().trim().min(1).max(60).optional(),
3140
+ /** OAuth scopes the provider will be asked for (oauth2 providers), for display. */
3141
+ scopes: z.array(z.string().trim().min(1).max(512)).max(64).optional()
3142
+ });
3143
+ const vaultCatalogSiteSchema = z.object({
3144
+ id: vaultProviderIdSchema,
3145
+ displayName: z.string().trim().min(1).max(80),
3146
+ consentSummary: z.string().trim().min(1).max(240),
3147
+ /** Origins the login form must live on (shown so the person can check). */
3148
+ loginOrigins: z.array(z.url().max(2048)).max(16).default([]),
3149
+ /** Where a restored session lands, for display. */
3150
+ startUrl: z.url().max(2048).optional()
3151
+ });
3152
+ const vaultCatalogSchema = z.object({
3153
+ v: z.literal(1),
3154
+ providers: z.array(vaultCatalogProviderSchema).max(200).default([]),
3155
+ sites: z.array(vaultCatalogSiteSchema).max(200).default([])
3156
+ });
3157
+ const vaultDisplaySchema = z.object({
3158
+ /** The platform's name as its users know it: "Instinct", not "instinct-prod". */
3159
+ name: z.string().trim().min(1).max(80),
3160
+ logoUrl: z.url().max(2048).startsWith("https://").optional(),
3161
+ /** `#rrggbb`. */
3162
+ accent: z.string().regex(/^#[0-9a-fA-F]{6}$/, "accent must be a #rrggbb colour").optional(),
3163
+ /** Origins a `returnUrl` may point at. Exact-match, scheme + host (+ port). */
3164
+ returnOrigins: z.array(z.url().max(2048)).max(16).default([])
3165
+ });
3166
+ z.object({
3167
+ name: nameSchema,
3168
+ display: vaultDisplaySchema.optional()
3169
+ });
3170
+ z.object({
3171
+ name: nameSchema.optional(),
3172
+ display: vaultDisplaySchema.optional(),
3173
+ status: z.enum(["active", "disabled"]).optional()
3174
+ });
3175
+ z.object({ name: nameSchema });
3176
+ /**
3177
+ * The platform's opaque identifier for its end user. Stored as given and
3178
+ * returned as given. It must not be an email address or anything else that
3179
+ * identifies the person outside the platform: the person has no seekrit
3180
+ * account, and this is the one field about them Vault holds in the clear.
3181
+ */
3182
+ const vaultUserRefSchema = z.string().trim().min(1).max(200).refine((v) => !/\s/.test(v), { message: "userRef must not contain whitespace" }).refine((v) => !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v), { message: "userRef must be an opaque identifier, not an email address" });
3183
+ z.object({
3184
+ userRef: vaultUserRefSchema,
3185
+ providerId: vaultProviderIdSchema,
3186
+ purpose: z.enum(["connect", "reconnect"]).default("connect"),
3187
+ /** Required for `reconnect`: the connection being repaired. */
3188
+ connectionId: z.string().trim().min(1).max(64).optional(),
3189
+ /** Where the done screen may send the person. Must match a registered origin. */
3190
+ returnUrl: z.url().max(2048).optional(),
3191
+ expiresInSeconds: z.number().int().min(60).max(VAULT_CONNECT_SESSION_MAX_TTL_SECONDS).optional()
3192
+ });
3193
+ z.object({
3194
+ userRef: vaultUserRefSchema,
3195
+ returnUrl: z.url().max(2048).optional(),
3196
+ expiresInSeconds: z.number().int().min(60).max(VAULT_CONNECT_SESSION_MAX_TTL_SECONDS).optional()
3197
+ });
3198
+ z.object({
3199
+ url: z.url().max(2048).refine((u) => u.startsWith("https://"), "webhook URLs must be https"),
3200
+ /** Defaults to every event. */
3201
+ events: z.array(z.enum(VAULT_WEBHOOK_EVENTS)).min(1).max(VAULT_WEBHOOK_EVENTS.length).optional(),
3202
+ description: z.string().trim().max(200).optional()
3203
+ });
3204
+ z.object({
3205
+ userRef: vaultUserRefSchema.optional(),
3206
+ status: z.enum(VAULT_CONNECTION_STATUSES).optional(),
3207
+ cursor: z.string().max(200).optional(),
3208
+ limit: z.coerce.number().int().min(1).max(200).default(50)
3209
+ });
3210
+ /** An `https://host[:port]` origin with nothing after it; `http://localhost` in dev. */
3211
+ const vaultOriginSchema = z.string().trim().max(2048).refine((v) => {
3212
+ let url;
3213
+ try {
3214
+ url = new URL(v);
3215
+ } catch {
3216
+ return false;
3217
+ }
3218
+ if (url.origin !== v) return false;
3219
+ if (url.protocol === "https:") return true;
3220
+ return url.protocol === "http:" && [
3221
+ "localhost",
3222
+ "127.0.0.1",
3223
+ "[::1]"
3224
+ ].includes(url.hostname);
3225
+ }, { message: "must be an https origin (scheme + host, nothing else)" });
3226
+ const vaultWrappingKeySchema = z.object({
3227
+ jwk: vaultPublicJwkSchema,
3228
+ thumbprint: z.string().regex(/^[A-Za-z0-9_-]{43}$/)
3229
+ });
3230
+ z.object({
3231
+ code: z.string().trim().min(16).max(200),
3232
+ origin: vaultOriginSchema,
3233
+ wrappingKey: vaultWrappingKeySchema,
3234
+ catalog: vaultCatalogSchema,
3235
+ sdkVersion: z.string().trim().min(1).max(40)
3236
+ });
3237
+ z.object({
3238
+ catalog: vaultCatalogSchema,
3239
+ sdkVersion: z.string().trim().min(1).max(40)
3240
+ });
3241
+ z.object({ wrappingKey: vaultWrappingKeySchema });
3242
+ /** One encrypted slot, as produced by Connect or the executor. */
3243
+ const vaultEncryptedSlotSchema = z.object({
3244
+ slot: z.enum(VAULT_SLOTS),
3245
+ revision: z.number().int().min(1),
3246
+ ciphertext: z.string().startsWith("sc1.").max(VAULT_CIPHERTEXT_MAX_CHARS),
3247
+ wrappedDek: z.string().startsWith("wd1.").max(2048),
3248
+ keyThumbprint: z.string().regex(/^[A-Za-z0-9_-]{43}$/)
3249
+ });
3250
+ z.object({
3251
+ slots: z.array(vaultEncryptedSlotSchema).min(1).max(2),
3252
+ /** "ava@example.com" / "@ava" — shown to the platform and the org, never used for auth. */
3253
+ accountLabel: z.string().trim().min(1).max(200).optional()
3254
+ });
3255
+ z.object({
3256
+ /** The revision the writer read; the write lands as `expectedRevision + 1`. */
3257
+ expectedRevision: z.number().int().min(0),
3258
+ ciphertext: z.string().startsWith("sc1.").max(VAULT_CIPHERTEXT_MAX_CHARS),
3259
+ wrappedDek: z.string().startsWith("wd1.").max(2048),
3260
+ keyThumbprint: z.string().regex(/^[A-Za-z0-9_-]{43}$/)
3261
+ });
3262
+ z.discriminatedUnion("status", [z.object({
3263
+ status: z.literal("reauth_required"),
3264
+ reason: z.string().trim().min(1).max(120)
3265
+ }), z.object({ status: z.literal("active") })]);
3266
+ z.object({ claimToken: z.string().min(16).max(200) });
3267
+ z.object({ token: z.string().min(16).max(200) });
3268
+ z.object({ consentVersion: z.literal(1) });
3269
+ z.object({ connectionId: z.string().trim().min(1).max(64) });
3270
+ z.object({
3271
+ login: vaultEncryptedSlotSchema.refine((slot) => slot.slot === "login", "must be the login slot").optional(),
3272
+ accountLabel: z.string().trim().min(1).max(200).optional()
3273
+ });
3274
+ z.object({
3275
+ userRef: vaultUserRefSchema,
3276
+ connectionId: z.string().trim().min(1).max(64),
3277
+ request: z.object({
3278
+ method: z.string().trim().toUpperCase().regex(/^[A-Z]{3,10}$/),
3279
+ url: z.url().max(8192),
3280
+ headers: z.record(z.string().max(256), z.string().max(16384)).optional(),
3281
+ /** UTF-8 text. Binary bodies are out of scope for V1. */
3282
+ body: z.string().max(4194304).optional()
3283
+ })
3284
+ });
3285
+ const connectionIdSchema = z.string().trim().min(1).max(64);
3286
+ const leaseIdSchema = z.string().trim().min(1).max(64);
3287
+ z.object({
3288
+ userRef: vaultUserRefSchema,
3289
+ connectionId: connectionIdSchema,
3290
+ /** How long the agent may hold the browser. Clamped to the site's ceiling. */
3291
+ keepAliveMs: z.number().int().min(VAULT_LEASE_MIN_MS).max(VAULT_LEASE_MAX_MS).optional()
3292
+ });
3293
+ z.object({
3294
+ userRef: vaultUserRefSchema,
3295
+ leaseId: leaseIdSchema,
3296
+ field: z.enum(VAULT_FILL_FIELDS)
3297
+ });
3298
+ z.object({
3299
+ userRef: vaultUserRefSchema,
3300
+ leaseId: leaseIdSchema,
3301
+ /** Write the rotated session back (default). `false` drops the browser without saving. */
3302
+ save: z.boolean().default(true)
3303
+ });
3304
+ z.object({
3305
+ userRef: vaultUserRefSchema,
3306
+ leaseId: leaseIdSchema
3307
+ });
3308
+ // ../../packages/crypto/src/encoding.ts
2710
3309
  const CHUNK = 32768;
2711
3310
  /** Base64url (no padding) — portable across browsers, Workers, and Node. */
2712
3311
  function toBase64Url(bytes) {
@@ -2737,8 +3336,7 @@ function utf8Encode(text) {
2737
3336
  function utf8Decode(bytes) {
2738
3337
  return new TextDecoder().decode(bytes);
2739
3338
  }
2740
- //#endregion
2741
- //#region ../../packages/crypto/src/errors.ts
3339
+ // ../../packages/crypto/src/errors.ts
2742
3340
  var SeekritCryptoError = class extends Error {
2743
3341
  code;
2744
3342
  constructor(code, message) {
@@ -2758,8 +3356,7 @@ function splitBlob(blob, prefix, segments) {
2758
3356
  if (parts.length !== segments + 1 || parts.some((p) => p.length === 0)) throw new SeekritCryptoError("MALFORMED_BLOB", `malformed "${prefix}" blob`);
2759
3357
  return parts.slice(1);
2760
3358
  }
2761
- //#endregion
2762
- //#region ../../packages/crypto/src/aes.ts
3359
+ // ../../packages/crypto/src/aes.ts
2763
3360
  const SECRET_PREFIX = "sc1";
2764
3361
  const IV_LENGTH$1 = 12;
2765
3362
  /** Generate a fresh 256-bit data encryption key for an environment. */
@@ -2804,8 +3401,7 @@ async function decryptSecret(dek, blob, aad) {
2804
3401
  function secretAad(environmentId, secretName) {
2805
3402
  return `${environmentId}/${secretName}`;
2806
3403
  }
2807
- //#endregion
2808
- //#region ../../packages/crypto/src/keys.ts
3404
+ // ../../packages/crypto/src/keys.ts
2809
3405
  async function generateKeyPair() {
2810
3406
  const pair = await crypto.subtle.generateKey({
2811
3407
  name: "ECDH",
@@ -2838,8 +3434,7 @@ async function importPrivateKeyPkcs8(pkcs8) {
2838
3434
  namedCurve: "P-256"
2839
3435
  }, true, ["deriveBits"]);
2840
3436
  }
2841
- //#endregion
2842
- //#region ../../packages/crypto/src/wrap.ts
3437
+ // ../../packages/crypto/src/wrap.ts
2843
3438
  /**
2844
3439
  * ECIES-style key wrapping: an ephemeral P-256 keypair performs ECDH against
2845
3440
  * the recipient's public key; the shared secret is run through HKDF-SHA256 to
@@ -2907,8 +3502,7 @@ async function unwrapDek(wrapped, privateKey) {
2907
3502
  throw new SeekritCryptoError("DECRYPT_FAILED", "DEK unwrap failed: wrong private key or tampered grant");
2908
3503
  }
2909
3504
  }
2910
- //#endregion
2911
- //#region ../../packages/crypto/src/kms.ts
3505
+ // ../../packages/crypto/src/kms.ts
2912
3506
  /**
2913
3507
  * Client-side KMS envelope encryption. A managed `encrypt` key is a 256-bit
2914
3508
  * AES-GCM key whose material reaches the client only as a `wd1.` grant (wrapped
@@ -3023,8 +3617,7 @@ async function generateDataKey(material, ref) {
3023
3617
  ].join(".")
3024
3618
  };
3025
3619
  }
3026
- //#endregion
3027
- //#region ../../packages/crypto/src/random.ts
3620
+ // ../../packages/crypto/src/random.ts
3028
3621
  const ALPHABETS = {
3029
3622
  alphanumeric: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
3030
3623
  hex: "0123456789abcdef",
@@ -3060,8 +3653,7 @@ function generateSecretValue(length, alphabet = "alphanumeric") {
3060
3653
  }
3061
3654
  return out;
3062
3655
  }
3063
- //#endregion
3064
- //#region ../../packages/crypto/src/mysql.ts
3656
+ // ../../packages/crypto/src/mysql.ts
3065
3657
  /**
3066
3658
  * Client-side construction of a MySQL/MariaDB `mysql_native_password`
3067
3659
  * authentication string, for minting *temporary MySQL login credentials*
@@ -3117,8 +3709,7 @@ async function generateMysqlCredential(options = {}) {
3117
3709
  verifier: await mysqlNativePasswordVerifier(password)
3118
3710
  };
3119
3711
  }
3120
- //#endregion
3121
- //#region ../../packages/crypto/src/passphrase.ts
3712
+ // ../../packages/crypto/src/passphrase.ts
3122
3713
  /**
3123
3714
  * User private keys are stored server-side encrypted under a key derived from
3124
3715
  * the user's passphrase, so any browser or CLI session can fetch and unlock
@@ -3159,8 +3750,7 @@ async function decryptPrivateKey(passphrase, blob) {
3159
3750
  throw new SeekritCryptoError("DECRYPT_FAILED", "wrong passphrase or corrupted key blob");
3160
3751
  }
3161
3752
  }
3162
- //#endregion
3163
- //#region ../../packages/crypto/src/shamir.ts
3753
+ // ../../packages/crypto/src/shamir.ts
3164
3754
  /**
3165
3755
  * Shamir's Secret Sharing over GF(2^8) — the same field AES uses, with the
3166
3756
  * reduction polynomial x^8 + x^4 + x^3 + x + 1 (0x11b). Splits a byte string
@@ -3254,8 +3844,7 @@ async function generatePostgresCredential(options = {}) {
3254
3844
  iterations
3255
3845
  };
3256
3846
  }
3257
- //#endregion
3258
- //#region ../../packages/crypto/src/sign.ts
3847
+ // ../../packages/crypto/src/sign.ts
3259
3848
  /**
3260
3849
  * Managed signing keys for the client-side KMS — ECDSA over P-256 (the curve
3261
3850
  * already used for principal keypairs; universal in WebCrypto). A `sign` key's
@@ -3317,15 +3906,16 @@ function signatureKeyRef(signature) {
3317
3906
  version
3318
3907
  };
3319
3908
  }
3320
- //#endregion
3321
- //#region ../../packages/crypto/src/token.ts
3909
+ // ../../packages/crypto/src/token.ts
3322
3910
  /**
3323
3911
  * Service tokens (CI, docker builds, agent proxies, k8s, …) are self-contained
3324
- * principals: the token string itself carries the private key, so the server
3325
- * never holds it. The server stores only the SHA-256 hash of the full token
3326
- * (for authentication) and the public key (for wrapping DEK grants).
3912
+ * principals. One local bundle holds independent authentication and decryption
3913
+ * material. Only serviceTokenAuth(token) may be sent to the API; the private
3914
+ * key stays local. The server stores the auth credential hash and public key.
3327
3915
  *
3328
- * Format: `skt_<token id>_<private key pkcs8, base64url>`
3916
+ * Bundle: `skt_<id>_v2.<32-byte auth secret>.<private key pkcs8, base64url>`
3917
+ * Wire: `skt_<id>_v2.<32-byte auth secret>`
3918
+ * Legacy bundles remain readable offline but must never be transmitted.
3329
3919
  */
3330
3920
  const TOKEN_PREFIX = "skt";
3331
3921
  const TOKEN_ID_LENGTH = 22;
@@ -3349,17 +3939,17 @@ async function createServiceToken() {
3349
3939
  const { publicKeyJwk, privateKeyJwk } = await generateKeyPair();
3350
3940
  const pkcs8 = await exportPrivateKeyPkcs8(await importPrivateKey(privateKeyJwk));
3351
3941
  const tokenId = randomTokenId();
3352
- const token = `${tokenId}_${toBase64Url(pkcs8)}`;
3942
+ const token = `${tokenId}_v2.${toBase64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))}.${toBase64Url(pkcs8)}`;
3353
3943
  return {
3354
3944
  token,
3355
3945
  tokenId,
3356
- tokenHash: await hashToken(token),
3946
+ tokenHash: await hashToken(serviceTokenAuth(token)),
3357
3947
  publicKeyJwk
3358
3948
  };
3359
3949
  }
3360
3950
  async function parseServiceToken(token) {
3361
- const match = /^(skt_[0-9A-Za-z]+)_([A-Za-z0-9_-]+)$/.exec(token);
3362
- if (!match) throw new SeekritCryptoError("MALFORMED_TOKEN", "not a valid seekrit service token");
3951
+ const match = /^(skt_[0-9A-Za-z]+)_(?:v2\.[A-Za-z0-9_-]{43}\.)?([A-Za-z0-9_-]+)$/.exec(token);
3952
+ if (!match || match[0] !== token) throw new SeekritCryptoError("MALFORMED_TOKEN", "not a valid seekrit service token");
3363
3953
  const [, tokenId, keyB64] = match;
3364
3954
  try {
3365
3955
  return {
@@ -3370,12 +3960,23 @@ async function parseServiceToken(token) {
3370
3960
  throw new SeekritCryptoError("MALFORMED_TOKEN", "service token private key is corrupted");
3371
3961
  }
3372
3962
  }
3963
+ /** Extract only the independent auth credential. Never fall back to a raw token. */
3964
+ function serviceTokenAuth(token) {
3965
+ const match = /^(skt_[0-9A-Za-z]+_v2\.[A-Za-z0-9_-]{43})(?:\.[A-Za-z0-9_-]+)?$/.exec(token);
3966
+ const auth = match?.[1];
3967
+ if (!match || match[0] !== token || !auth) throw new SeekritCryptoError("MALFORMED_TOKEN", "a v2 service token is required for API access; replace legacy tokens in the dashboard");
3968
+ return auth;
3969
+ }
3970
+ /** Preserve human/session credentials while stripping service-token private keys. */
3971
+ function apiBearerToken(token) {
3972
+ const value = token.trim();
3973
+ return isServiceToken(value) ? serviceTokenAuth(value) : token;
3974
+ }
3373
3975
  function isServiceToken(value) {
3374
3976
  return value.startsWith(`${TOKEN_PREFIX}_`);
3375
3977
  }
3376
- //#endregion
3377
- //#region ../cli/package.json
3378
- var version$1 = "1.6.5";
3978
+ // ../cli/package.json
3979
+ var version$1 = "2.4.0";
3379
3980
  const PROJECT_FILE = "seekrit.json";
3380
3981
  function globalConfigPath() {
3381
3982
  return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "seekrit", "config.json");
@@ -3425,8 +4026,16 @@ function writeProjectConfig(config, dir = process.cwd()) {
3425
4026
  writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
3426
4027
  return path;
3427
4028
  }
3428
- //#endregion
3429
- //#region ../../packages/api-client/src/index.ts
4029
+ // ../../packages/api-client/src/index.ts
4030
+ /**
4031
+ * The proposer's note travels as a header, not a body field: an unprotected
4032
+ * environment ignores it, so the same call works either way and no caller has
4033
+ * to know in advance whether a write will be queued.
4034
+ */
4035
+ function changeNoteHeader(note) {
4036
+ const trimmed = note?.trim();
4037
+ return trimmed ? { "x-seekrit-change-note": trimmed } : void 0;
4038
+ }
3430
4039
  var SeekritApiError = class extends Error {
3431
4040
  status;
3432
4041
  code;
@@ -3448,16 +4057,21 @@ var SeekritClient = class {
3448
4057
  this.fetchImpl = options.fetch ?? ((...args) => fetch(...args));
3449
4058
  this.client = options.client;
3450
4059
  }
3451
- async request(method, path, body) {
3452
- const headers = { accept: "application/json" };
4060
+ async request(method, path, body, extraHeaders) {
4061
+ const headers = {
4062
+ accept: "application/json",
4063
+ ...extraHeaders
4064
+ };
3453
4065
  if (this.client) headers["x-seekrit-client"] = this.client;
3454
- if (this.auth.type === "bearer") headers.authorization = `Bearer ${this.auth.token}`;
4066
+ if (this.auth.type === "bearer") headers.authorization = `Bearer ${apiBearerToken(this.auth.token)}`;
3455
4067
  else if (this.auth.type === "dynamic") {
3456
4068
  const token = await this.auth.getToken();
3457
4069
  if (!token) throw new SeekritApiError(401, "unauthorized", "session expired");
3458
- headers.authorization = `Bearer ${token}`;
3459
- } else if (this.auth.type === "m2m") headers.authorization = `Basic ${btoa(`${this.auth.clientId}:${this.auth.clientSecret}`)}`;
3460
- else headers["x-seekrit-dev-user"] = this.auth.email;
4070
+ headers.authorization = `Bearer ${apiBearerToken(token)}`;
4071
+ } else if (this.auth.type === "m2m") {
4072
+ if (isServiceToken(this.auth.clientId.trim()) || isServiceToken(this.auth.clientSecret.trim())) throw new Error("service tokens must use bearer authentication, not machine client credentials");
4073
+ headers.authorization = `Basic ${btoa(`${this.auth.clientId}:${this.auth.clientSecret}`)}`;
4074
+ } else headers["x-seekrit-dev-user"] = this.auth.email;
3461
4075
  if (body !== void 0) headers["content-type"] = "application/json";
3462
4076
  const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
3463
4077
  method,
@@ -3547,6 +4161,66 @@ var SeekritClient = class {
3547
4161
  listMembers(orgId) {
3548
4162
  return this.request("GET", `/v1/orgs/${orgId}/members`);
3549
4163
  }
4164
+ getMemberAccess(orgId) {
4165
+ return this.request("GET", `/v1/orgs/${orgId}/members/access`);
4166
+ }
4167
+ updateMemberRole(orgId, userId, role) {
4168
+ return this.request("PATCH", `/v1/orgs/${orgId}/members/${userId}`, { role });
4169
+ }
4170
+ getAppAccess(orgId, appId) {
4171
+ return this.request("GET", `/v1/orgs/${orgId}/apps/${appId}/access`);
4172
+ }
4173
+ provisionAppAccess(orgId, appId, userId, grants) {
4174
+ return this.request("POST", `/v1/orgs/${orgId}/apps/${appId}/access`, {
4175
+ userId,
4176
+ grants
4177
+ });
4178
+ }
4179
+ /**
4180
+ * Stop auto-granting this app's future environments to a member. Keys they
4181
+ * already hold stay; revoke those per environment with `revokeEnvKey`.
4182
+ */
4183
+ revokeAppAccess(orgId, appId, userId) {
4184
+ return this.request("DELETE", `/v1/orgs/${orgId}/apps/${appId}/access/${userId}`);
4185
+ }
4186
+ accessRecipients(orgId, target) {
4187
+ const path = "appId" in target ? `apps/${target.appId}` : `groups/${target.groupId}`;
4188
+ return this.request("GET", `/v1/orgs/${orgId}/${path}/access-recipients`);
4189
+ }
4190
+ /** The caller owns the new DEK; only public keys and wrapped blobs cross the API. */
4191
+ async wrapNewEnvironmentAccess(orgId, target, dek) {
4192
+ const { recipients } = await this.accessRecipients(orgId, target);
4193
+ return Promise.all(recipients.map(async (r) => {
4194
+ if (!r.publicKeyJwk) throw new Error(`${r.email} must finish key setup before creating this environment`);
4195
+ return {
4196
+ userId: r.userId,
4197
+ wrappedDek: await wrapDek(dek, r.publicKeyJwk)
4198
+ };
4199
+ }));
4200
+ }
4201
+ async wrapGroupAppAccess(orgId, envId, groupId, getDek) {
4202
+ const { environment } = await this.getEnv(orgId, envId);
4203
+ if (!environment.applicationId) throw new Error("only app environments can compose groups");
4204
+ const { recipients } = await this.accessRecipients(orgId, { appId: environment.applicationId });
4205
+ if (!recipients.length) return [];
4206
+ const { environments } = await this.listGroupEnvs(orgId, groupId);
4207
+ const result = [];
4208
+ for (const env of environments) {
4209
+ const { grants } = await this.listEnvKeys(orgId, env.id);
4210
+ const missing = recipients.filter((r) => !grants.some((g) => g.principalType === "user" && g.principalId === r.userId));
4211
+ if (!missing.length) continue;
4212
+ const dek = await getDek(env.id);
4213
+ for (const recipient of missing) {
4214
+ if (!recipient.publicKeyJwk) throw new Error(`${recipient.email} must finish key setup first`);
4215
+ result.push({
4216
+ environmentId: env.id,
4217
+ userId: recipient.userId,
4218
+ wrappedDek: await wrapDek(dek, recipient.publicKeyJwk)
4219
+ });
4220
+ }
4221
+ }
4222
+ return result;
4223
+ }
3550
4224
  /**
3551
4225
  * The org-wide "require a second factor for all members" policy. `configured`
3552
4226
  * is false when the identity provider isn't wired up (local dev), in which
@@ -3664,11 +4338,21 @@ var SeekritClient = class {
3664
4338
  listSecrets(orgId, envId) {
3665
4339
  return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/secrets`);
3666
4340
  }
3667
- setSecret(orgId, envId, name, ciphertext) {
3668
- return this.request("PUT", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`, { ciphertext });
4341
+ /**
4342
+ * Store a ciphertext. In a **protected** environment this does not write: the
4343
+ * server queues the change for review and answers `{ queued: true,
4344
+ * changeRequest }` (HTTP 202). Callers must branch on `queued` — reporting
4345
+ * success on a queued change tells someone a secret rotated when it has not.
4346
+ *
4347
+ * `note` is the proposer's explanation, carried as a header so it is simply
4348
+ * ignored by an unprotected environment.
4349
+ */
4350
+ setSecret(orgId, envId, name, ciphertext, note) {
4351
+ return this.request("PUT", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`, { ciphertext }, changeNoteHeader(note));
3669
4352
  }
3670
- deleteSecret(orgId, envId, name) {
3671
- return this.request("DELETE", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`);
4353
+ /** Queued for review in a protected environment — see {@link setSecret}. */
4354
+ deleteSecret(orgId, envId, name, note) {
4355
+ return this.request("DELETE", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`, void 0, changeNoteHeader(note));
3672
4356
  }
3673
4357
  /** A secret's append-only history, newest version first. */
3674
4358
  listSecretVersions(orgId, envId, name, query = {}) {
@@ -3680,10 +4364,87 @@ var SeekritClient = class {
3680
4364
  * ciphertext it already stores, so this appends a new version rather than
3681
4365
  * rewinding, and needs no DEK on the caller's side.
3682
4366
  */
3683
- restoreSecret(orgId, envId, name, version) {
3684
- return this.request("POST", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}/restore`, { version });
4367
+ restoreSecret(orgId, envId, name, version, note) {
4368
+ return this.request("POST", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}/restore`, { version }, changeNoteHeader(note));
4369
+ }
4370
+ /** An environment's protection settings, plus how many changes are waiting. */
4371
+ getEnvironmentProtection(orgId, envId) {
4372
+ return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/protection`);
4373
+ }
4374
+ /** Protect an environment, or change its settings. Admin only. */
4375
+ setEnvironmentProtection(orgId, envId, input = {}) {
4376
+ return this.request("PUT", `/v1/orgs/${orgId}/envs/${envId}/protection`, input);
4377
+ }
4378
+ /** Take the gate down. Queued changes stay queued. Admin only. */
4379
+ deleteEnvironmentProtection(orgId, envId) {
4380
+ return this.request("DELETE", `/v1/orgs/${orgId}/envs/${envId}/protection`);
4381
+ }
4382
+ listChangeRequests(orgId, query = {}) {
4383
+ const params = new URLSearchParams();
4384
+ if (query.status) params.set("status", query.status);
4385
+ if (query.envId) params.set("envId", query.envId);
4386
+ if (query.limit) params.set("limit", String(query.limit));
4387
+ const qs = params.size > 0 ? `?${params}` : "";
4388
+ return this.request("GET", `/v1/orgs/${orgId}/change-requests${qs}`);
4389
+ }
4390
+ getChangeRequest(orgId, id) {
4391
+ return this.request("GET", `/v1/orgs/${orgId}/change-requests/${id}`);
4392
+ }
4393
+ /**
4394
+ * Approve. When this is the approval that meets the threshold the change is
4395
+ * applied in the same call, so `status` comes back `applied` — or
4396
+ * `superseded`, if the secret moved on since the change was proposed.
4397
+ */
4398
+ approveChangeRequest(orgId, id, comment) {
4399
+ return this.request("POST", `/v1/orgs/${orgId}/change-requests/${id}/approve`, { comment });
4400
+ }
4401
+ rejectChangeRequest(orgId, id, comment) {
4402
+ return this.request("POST", `/v1/orgs/${orgId}/change-requests/${id}/reject`, { comment });
4403
+ }
4404
+ withdrawChangeRequest(orgId, id) {
4405
+ return this.request("POST", `/v1/orgs/${orgId}/change-requests/${id}/withdraw`);
3685
4406
  }
3686
4407
  /** The calling principal's wrapped DEK for this environment. */
4408
+ getEnvironmentKeyScope(orgId, envId) {
4409
+ return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/key-scope`);
4410
+ }
4411
+ async prepareComposedKeyGrants(orgId, envId, principal, getDek) {
4412
+ const scope = await this.getEnvironmentKeyScope(orgId, envId);
4413
+ const grants = [];
4414
+ for (const layer of scope.environments) {
4415
+ if (scope.grants.some((g) => g.environmentId === layer.environmentId && g.principalType === principal.principalType && g.principalId === principal.principalId)) continue;
4416
+ try {
4417
+ const dek = await getDek(layer.environmentId);
4418
+ grants.push({
4419
+ environmentId: layer.environmentId,
4420
+ wrappedDek: await wrapDek(dek, principal.publicKeyJwk)
4421
+ });
4422
+ } catch (error) {
4423
+ if (error instanceof Error && error.message === "unlock cancelled") throw error;
4424
+ throw new Error(`Could not prepare access to ${layer.label}: ${error instanceof Error ? error.message : "key unavailable"}. No keys were granted.`);
4425
+ }
4426
+ }
4427
+ return grants;
4428
+ }
4429
+ grantComposedKeys(orgId, envId, input) {
4430
+ return this.request("POST", `/v1/orgs/${orgId}/envs/${envId}/keys/composed`, input);
4431
+ }
4432
+ /** Sharing an application environment includes the exact layers resolve reads. */
4433
+ async grantEnvironmentAccess(orgId, envId, principal, getDek) {
4434
+ const { environment } = await this.getEnv(orgId, envId);
4435
+ if (environment.applicationId) {
4436
+ const grants = await this.prepareComposedKeyGrants(orgId, envId, principal, getDek);
4437
+ await this.grantComposedKeys(orgId, envId, {
4438
+ principalType: principal.principalType,
4439
+ principalId: principal.principalId,
4440
+ grants
4441
+ });
4442
+ } else await this.grantEnvKey(orgId, envId, {
4443
+ principalType: principal.principalType,
4444
+ principalId: principal.principalId,
4445
+ wrappedDek: await wrapDek(await getDek(envId), principal.publicKeyJwk)
4446
+ });
4447
+ }
3687
4448
  getMyEnvKey(orgId, envId) {
3688
4449
  return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/key`);
3689
4450
  }
@@ -3770,6 +4531,42 @@ var SeekritClient = class {
3770
4531
  deleteHoneyToken(orgId, honeyTokenId) {
3771
4532
  return this.request("DELETE", `/v1/orgs/${orgId}/honey-tokens/${honeyTokenId}`);
3772
4533
  }
4534
+ getConnect(orgId) {
4535
+ return this.request("GET", `/v1/orgs/${orgId}/connect`);
4536
+ }
4537
+ getConnectBrokerKey(orgId) {
4538
+ return this.request("GET", `/v1/orgs/${orgId}/connect/broker-key`);
4539
+ }
4540
+ createWorkload(orgId, input) {
4541
+ return this.request("POST", `/v1/orgs/${orgId}/connect/workloads`, input);
4542
+ }
4543
+ updateWorkload(orgId, id, input) {
4544
+ return this.request("PATCH", `/v1/orgs/${orgId}/connect/workloads/${encodeURIComponent(id)}`, input);
4545
+ }
4546
+ createConnectConnection(orgId, input) {
4547
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections`, input);
4548
+ }
4549
+ updateConnectConnection(orgId, id, input) {
4550
+ return this.request("PATCH", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}`, input);
4551
+ }
4552
+ createConnectGrant(orgId, input) {
4553
+ return this.request("POST", `/v1/orgs/${orgId}/connect/grants`, input);
4554
+ }
4555
+ startConnectOAuth(orgId, id) {
4556
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/start`, {});
4557
+ }
4558
+ finishConnectOAuth(orgId, id, state, code) {
4559
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/finish`, {
4560
+ state,
4561
+ code
4562
+ });
4563
+ }
4564
+ disconnectConnectOAuth(orgId, id) {
4565
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/disconnect`, {});
4566
+ }
4567
+ revokeConnectGrant(orgId, id) {
4568
+ return this.request("DELETE", `/v1/orgs/${orgId}/connect/grants/${encodeURIComponent(id)}`);
4569
+ }
3773
4570
  listAgents(orgId) {
3774
4571
  return this.request("GET", `/v1/orgs/${orgId}/agents`);
3775
4572
  }
@@ -3848,6 +4645,7 @@ var SeekritClient = class {
3848
4645
  * identity are three different answers.
3849
4646
  */
3850
4647
  introspectAgentTask(token) {
4648
+ if (!token.startsWith("skd_")) throw new Error("expected a dispatched task token");
3851
4649
  return this.request("POST", "/v1/tasks/introspect", { token });
3852
4650
  }
3853
4651
  /** End a run's authority now. Idempotent. */
@@ -4102,9 +4900,54 @@ var SeekritClient = class {
4102
4900
  redeemPromoCode(orgId, input) {
4103
4901
  return this.request("POST", `/v1/orgs/${orgId}/billing/promo`, input);
4104
4902
  }
4903
+ listVaultProjects(orgId) {
4904
+ return this.request("GET", `/v1/orgs/${orgId}/vault/projects`);
4905
+ }
4906
+ createVaultProject(orgId, input) {
4907
+ return this.request("POST", `/v1/orgs/${orgId}/vault/projects`, input);
4908
+ }
4909
+ getVaultProject(orgId, projectId) {
4910
+ return this.request("GET", `/v1/orgs/${orgId}/vault/projects/${projectId}`);
4911
+ }
4912
+ updateVaultProject(orgId, projectId, input) {
4913
+ return this.request("PATCH", `/v1/orgs/${orgId}/vault/projects/${projectId}`, input);
4914
+ }
4915
+ /**
4916
+ * Mint a platform key. The `secret` is the `skv_…` string, returned exactly
4917
+ * once; the server keeps only its hash. Needs a browser session with a fresh
4918
+ * second factor — the API answers `mfa_required` otherwise.
4919
+ */
4920
+ createVaultPlatformKey(orgId, projectId, input) {
4921
+ return this.request("POST", `/v1/orgs/${orgId}/vault/projects/${projectId}/keys`, input);
4922
+ }
4923
+ revokeVaultPlatformKey(orgId, projectId, keyId) {
4924
+ return this.request("DELETE", `/v1/orgs/${orgId}/vault/projects/${projectId}/keys/${keyId}`);
4925
+ }
4926
+ /** A one-time executor registration code (10 minutes). Same step-up rule as a key. */
4927
+ createVaultRegistrationCode(orgId, projectId) {
4928
+ return this.request("POST", `/v1/orgs/${orgId}/vault/projects/${projectId}/registration-codes`);
4929
+ }
4930
+ disableVaultExecutor(orgId, projectId) {
4931
+ return this.request("POST", `/v1/orgs/${orgId}/vault/projects/${projectId}/executor/disable`);
4932
+ }
4933
+ listVaultConnections(orgId, projectId, query = {}) {
4934
+ const params = new URLSearchParams();
4935
+ for (const [key, value] of Object.entries(query)) if (value !== void 0 && value !== "") params.set(key, String(value));
4936
+ const qs = params.toString();
4937
+ return this.request("GET", `/v1/orgs/${orgId}/vault/projects/${projectId}/connections${qs ? `?${qs}` : ""}`);
4938
+ }
4939
+ revokeVaultConnection(orgId, projectId, connectionId) {
4940
+ return this.request("POST", `/v1/orgs/${orgId}/vault/projects/${projectId}/connections/${connectionId}/revoke`);
4941
+ }
4942
+ /** Webhook endpoints a platform registered with its key; the dashboard reads and removes. */
4943
+ listVaultWebhooks(orgId, projectId) {
4944
+ return this.request("GET", `/v1/orgs/${orgId}/vault/projects/${projectId}/webhooks`);
4945
+ }
4946
+ deleteVaultWebhook(orgId, projectId, webhookId) {
4947
+ return this.request("DELETE", `/v1/orgs/${orgId}/vault/projects/${projectId}/webhooks/${webhookId}`);
4948
+ }
4105
4949
  };
4106
- //#endregion
4107
- //#region ../cli/src/io.ts
4950
+ // ../cli/src/io.ts
4108
4951
  let failThrows = false;
4109
4952
  /**
4110
4953
  * In `seekrit mcp` the process is a long-lived stdio server, so a `fail()`
@@ -4156,8 +4999,7 @@ function promptHidden(question) {
4156
4999
  });
4157
5000
  });
4158
5001
  }
4159
- //#endregion
4160
- //#region ../cli/src/context.ts
5002
+ // ../cli/src/context.ts
4161
5003
  /** Sent as `x-seekrit-client` so the API attributes usage to the CLI (analytics). */
4162
5004
  const CLI_CLIENT = `cli/${version$1}`;
4163
5005
  /**
@@ -4227,13 +5069,54 @@ async function getPrivateKey(ctx) {
4227
5069
  const { encryptedPrivateKey } = await ctx.client.getMyKeys();
4228
5070
  return importPrivateKey(await decryptPrivateKey(process.env.SEEKRIT_PASSPHRASE ?? await promptHidden("Passphrase: "), encryptedPrivateKey));
4229
5071
  }
5072
+ /**
5073
+ * The calling principal's public key JWK — what a freshly generated DEK is
5074
+ * wrapped to when creating an environment. Service tokens carry their private
5075
+ * key, so the public half is derived from it; users publish theirs at key
5076
+ * setup. Shared by `seekrit env create`, `seekrit init`, and the MCP server so
5077
+ * a token can create an environment everywhere, not only over MCP.
5078
+ */
5079
+ async function principalPublicKeyJwk(ctx) {
5080
+ if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
5081
+ const { privateKey } = await parseServiceToken(ctx.auth.token);
5082
+ const { d: _d, key_ops: _ops, ext: _ext, ...pub } = await crypto.subtle.exportKey("jwk", privateKey);
5083
+ return JSON.stringify(pub);
5084
+ }
5085
+ const { user } = await ctx.client.me();
5086
+ if (!user.publicKeyJwk) fail("this user has no keypair yet — run `seekrit keys setup` first");
5087
+ return user.publicKeyJwk;
5088
+ }
4230
5089
  /** Recover one environment's DEK for the current principal. */
4231
5090
  async function getDek(ctx, orgId, envId) {
4232
5091
  const [{ wrappedDek }, privateKey] = await Promise.all([ctx.client.getMyEnvKey(orgId, envId), getPrivateKey(ctx)]);
4233
5092
  return unwrapDek(wrappedDek, privateKey);
4234
5093
  }
4235
- //#endregion
4236
- //#region ../cli/src/target.ts
5094
+ // ../cli/src/group-sync-grants.ts
5095
+ /** Wrap a newly composed group layer for connections already syncing the app env or its branches. */
5096
+ async function syncGrantsForGroupLink(ctx, orgId, envId, envSlug, groupId) {
5097
+ const [{ groups }, { bindings }, { branches }] = await Promise.all([
5098
+ ctx.client.listEnvGroups(orgId, envId),
5099
+ ctx.client.listSyncBindings(orgId),
5100
+ ctx.client.listBranches(orgId, envId)
5101
+ ]);
5102
+ if (groups.some((group) => group.groupId === groupId)) return void 0;
5103
+ const targets = /* @__PURE__ */ new Set([envId, ...branches.map((branch) => branch.id)]);
5104
+ const connectionIds = new Set(bindings.filter((binding) => targets.has(binding.environmentId)).map((b) => b.connectionId));
5105
+ if (connectionIds.size === 0) return void 0;
5106
+ const [{ environments }, { connections }] = await Promise.all([ctx.client.listGroupEnvs(orgId, groupId), ctx.client.listSyncConnections(orgId)]);
5107
+ const groupEnv = environments.find((entry) => entry.slug === envSlug);
5108
+ if (!groupEnv) fail(`create a ${envSlug} environment in this group before composing it`);
5109
+ const dek = await getDek(ctx, orgId, groupEnv.id);
5110
+ return Promise.all([...connectionIds].map(async (connectionId) => {
5111
+ const connection = connections.find((entry) => entry.id === connectionId);
5112
+ if (!connection) fail("a sync connection could not be found; refresh and retry");
5113
+ return {
5114
+ connectionId,
5115
+ wrappedDek: await wrapDek(dek, connection.publicKeyJwk)
5116
+ };
5117
+ }));
5118
+ }
5119
+ // ../cli/src/target.ts
4237
5120
  /** Resolve the target org from a flag, the committed config, or a lone org. */
4238
5121
  async function resolveOrg(ctx, orgSlug) {
4239
5122
  const wanted = orgSlug ?? findProjectConfig()?.org;
@@ -4266,7 +5149,11 @@ async function boundEnvTarget(ctx, opts) {
4266
5149
  try {
4267
5150
  ({scope} = await ctx.client.resolve(opts.branch ? { branch: opts.branch } : {}));
4268
5151
  } catch (err) {
4269
- fail(`specify --env — this token has no environment of its own to fall back to (${err instanceof Error ? err.message : String(err)})`);
5152
+ if (err instanceof SeekritApiError && err.status < 500) {
5153
+ if (opts.env) return null;
5154
+ fail(`specify --env — this token has no environment of its own to fall back to (${err.message})`);
5155
+ }
5156
+ throw err;
4270
5157
  }
4271
5158
  const env = scope.branchOf ?? {
4272
5159
  envId: scope.envId,
@@ -4293,7 +5180,10 @@ async function boundEnvTarget(ctx, opts) {
4293
5180
  * it this way; this is the same rule, in one place, for both.
4294
5181
  */
4295
5182
  async function resolveEnvTarget(ctx, opts) {
4296
- if (!opts.app && !opts.group && isTokenAuth(ctx)) return boundEnvTarget(ctx, opts);
5183
+ if (!opts.app && !opts.group && isTokenAuth(ctx)) {
5184
+ const bound = await boundEnvTarget(ctx, opts);
5185
+ if (bound) return bound;
5186
+ }
4297
5187
  const org = await resolveOrg(ctx, opts.org);
4298
5188
  if (!opts.env) fail("specify --env");
4299
5189
  if (opts.group) {
@@ -4382,8 +5272,7 @@ async function resolveGroup(ctx, opts) {
4382
5272
  slug: group.slug
4383
5273
  };
4384
5274
  }
4385
- //#endregion
4386
- //#region ../cli/src/kms.ts
5275
+ // ../cli/src/kms.ts
4387
5276
  /** The calling principal's identity + public key (for a self-grant). */
4388
5277
  async function kmsCallerIdentity(ctx) {
4389
5278
  if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
@@ -4446,8 +5335,7 @@ async function kmsRecoverMaterial(ctx, orgId, keyId, version) {
4446
5335
  currentVersion: mat.currentVersion
4447
5336
  };
4448
5337
  }
4449
- //#endregion
4450
- //#region ../cli/src/m2m.ts
5338
+ // ../cli/src/m2m.ts
4451
5339
  /**
4452
5340
  * Resolve M2M client credentials from (in order) the process environment, a
4453
5341
  * `.env` overlay (for `seekrit run`), then saved config. Both halves must come
@@ -4514,16 +5402,22 @@ async function ensureM2mAdminToken(dotenvVars = {}) {
4514
5402
  if (!creds) return null;
4515
5403
  const cached = readCachedM2mToken(creds.clientId);
4516
5404
  if (cached) {
4517
- process.env.SEEKRIT_TOKEN = cached;
4518
- return cached;
5405
+ let usable = false;
5406
+ try {
5407
+ serviceTokenAuth(cached);
5408
+ usable = true;
5409
+ } catch {}
5410
+ if (usable) {
5411
+ process.env.SEEKRIT_TOKEN = cached;
5412
+ return cached;
5413
+ }
4519
5414
  }
4520
5415
  const token = await mintAdminToken(process.env.SEEKRIT_API_URL ?? dotenvVars.SEEKRIT_API_URL ?? readGlobalConfig().apiUrl ?? "https://api.seekrit.dev", creds);
4521
5416
  cacheM2mToken(creds.clientId, token);
4522
5417
  process.env.SEEKRIT_TOKEN = token;
4523
5418
  return token;
4524
5419
  }
4525
- //#endregion
4526
- //#region ../cli/src/cache.ts
5420
+ // ../cli/src/cache.ts
4527
5421
  /** Render an age for a log line, rounded to its largest whole unit. */
4528
5422
  function humanize(ms) {
4529
5423
  const secs = Math.floor(ms / 1e3);
@@ -4588,9 +5482,15 @@ async function fetchDecryptedVersion(ctx, orgId, envId, name, version) {
4588
5482
  if (!row) fail(`${name} has no version ${version} in its ${versions.length} newest versions`);
4589
5483
  return decryptSecret(dek, row.ciphertext, secretAad(envId, name));
4590
5484
  }
4591
- async function encryptAndSetSecret(ctx, orgId, envId, name, value) {
5485
+ /**
5486
+ * Encrypt and store one value. Returns the change request when the environment
5487
+ * is protected and the write was queued instead of stored — callers must say so
5488
+ * rather than reporting a write that has not happened.
5489
+ */
5490
+ async function encryptAndSetSecret(ctx, orgId, envId, name, value, note) {
4592
5491
  const ciphertext = await encryptSecret(await getDek(ctx, orgId, envId), value, secretAad(envId, name));
4593
- await ctx.client.setSecret(orgId, envId, name, ciphertext);
5492
+ const result = await ctx.client.setSecret(orgId, envId, name, ciphertext, note);
5493
+ return result.queued ? result.changeRequest : null;
4594
5494
  }
4595
5495
  /**
4596
5496
  * Resolve the full, layered environment for a running app: composed group
@@ -4691,8 +5591,7 @@ function overlayEnvFiles(values, provenance, envFiles) {
4691
5591
  }
4692
5592
  return loaded;
4693
5593
  }
4694
- //#endregion
4695
- //#region ../cli/src/mcp.ts
5594
+ // ../cli/src/mcp.ts
4696
5595
  /** Lowercase-alphanumeric string for a fresh Postgres role name. */
4697
5596
  function randomLower(length) {
4698
5597
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
@@ -4739,9 +5638,18 @@ function serverInstructions() {
4739
5638
  "Auth comes from SEEKRIT_TOKEN (a skt_… token), SEEKRIT_CLIENT_ID +",
4740
5639
  "SEEKRIT_CLIENT_SECRET (machine credentials — an admin token is minted and",
4741
5640
  "cached automatically on first use), or the config saved by `seekrit login`.",
5641
+ "No credential at all? `npx -y @seekrit/cli init --org-name \"<the real project>\" --yes`",
5642
+ "signs up, saves the credential, and creates an app with a development environment.",
4742
5643
  "Decrypting under a user session (not a token) additionally needs",
4743
5644
  "SEEKRIT_PASSPHRASE set in this server's env — there's no TTY to prompt on.",
4744
5645
  "",
5646
+ "NOT THE TOOL WHEN: the value is a throwaway for one local experiment (a shell",
5647
+ "variable is fine — say so); the runtime already injects secrets natively and the",
5648
+ "team uses it (offer seekrit as the source that syncs into it, not a second copy);",
5649
+ "the policy forbids any SaaS holding even ciphertext; or what's being stored is",
5650
+ "user data rather than configuration. An honest \"you don't need this here\" beats",
5651
+ "an install.",
5652
+ "",
4745
5653
  "Model: org → apps/groups → environments → secrets. Call `whoami` first, then",
4746
5654
  "`get_started` for the recommended end-to-end recipe. Prefer `run_command` over",
4747
5655
  "`get_secret reveal:true` — it injects secrets into a subprocess so plaintext",
@@ -4808,21 +5716,6 @@ function getCtx() {
4808
5716
  function ensureDecryptable(ctx) {
4809
5717
  if (!isTokenAuth(ctx) && !process.env.SEEKRIT_PASSPHRASE) throw new Error("this operation decrypts data; set SEEKRIT_PASSPHRASE in the MCP server env, or use a service token (SEEKRIT_TOKEN)");
4810
5718
  }
4811
- /**
4812
- * The calling principal's public key JWK — needed to wrap a freshly generated
4813
- * DEK when creating an environment. Service tokens carry their private key, so
4814
- * we derive the public half from it; users publish theirs at key setup.
4815
- */
4816
- async function principalPublicKeyJwk(ctx) {
4817
- if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
4818
- const { privateKey } = await parseServiceToken(ctx.auth.token);
4819
- const { d: _d, key_ops: _ops, ext: _ext, ...pub } = await crypto.subtle.exportKey("jwk", privateKey);
4820
- return JSON.stringify(pub);
4821
- }
4822
- const { user } = await ctx.client.me();
4823
- if (!user.publicKeyJwk) throw new Error("this user has no keypair yet — run `seekrit keys setup` first");
4824
- return user.publicKeyJwk;
4825
- }
4826
5719
  /** Run a child command with `env` and capture its output (values never returned). */
4827
5720
  function runChild(cmd, args, env, cwd) {
4828
5721
  return new Promise((resolve, reject) => {
@@ -5216,11 +6109,13 @@ async function runMcpServer(options = {}) {
5216
6109
  const { apps } = await ctx.client.listApps(orgRef.id);
5217
6110
  const appRow = apps.find((a) => a.slug === app || a.id === app);
5218
6111
  if (!appRow) throw new Error(`no app "${app}" in ${orgRef.slug}`);
5219
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
6112
+ const dek = generateDek();
6113
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5220
6114
  return (await ctx.client.createEnv(orgRef.id, appRow.id, {
5221
6115
  name,
5222
6116
  slug,
5223
- wrappedDek
6117
+ wrappedDek,
6118
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(orgRef.id, { appId: appRow.id }, dek)
5224
6119
  })).environment;
5225
6120
  });
5226
6121
  tool("create_branch", "Fork an environment into an ephemeral branch (a per-PR / preview config). The branch inherits the parent's secrets by layering at read time — nothing is copied or re-encrypted — and holds only the values you override on it. Generates the branch's data key locally, grants it to the caller, and shares it with the parent's other readers.", { idempotent: false }, {
@@ -5283,11 +6178,13 @@ async function runMcpServer(options = {}) {
5283
6178
  org,
5284
6179
  group
5285
6180
  });
5286
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
6181
+ const dek = generateDek();
6182
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5287
6183
  return (await ctx.client.createGroupEnv(g.orgId, g.id, {
5288
6184
  name,
5289
6185
  slug,
5290
- wrappedDek
6186
+ wrappedDek,
6187
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(g.orgId, { groupId: g.id }, dek)
5291
6188
  })).environment;
5292
6189
  });
5293
6190
  tool("compose_group", "Compose a group into an application environment (higher position wins on name clashes).", { idempotent: true }, {
@@ -5307,9 +6204,12 @@ async function runMcpServer(options = {}) {
5307
6204
  org,
5308
6205
  group
5309
6206
  });
6207
+ const syncGrants = await syncGrantsForGroupLink(ctx, target.orgId, target.envId, target.envSlug, g.id);
5310
6208
  return (await ctx.client.linkEnvGroup(target.orgId, target.envId, {
6209
+ appAccessGrants: await ctx.client.wrapGroupAppAccess(target.orgId, target.envId, g.id, (id) => getDek(ctx, target.orgId, id)),
5311
6210
  groupId: g.id,
5312
- position
6211
+ position,
6212
+ syncGrants
5313
6213
  })).group;
5314
6214
  });
5315
6215
  tool("uncompose_group", "Remove a composed group from an application environment.", { idempotent: true }, {
@@ -5331,16 +6231,23 @@ async function runMcpServer(options = {}) {
5331
6231
  await ctx.client.unlinkEnvGroup(target.orgId, target.envId, g.id);
5332
6232
  return { ok: true };
5333
6233
  });
5334
- tool("set_secret", "Encrypt a value locally and store it in an environment. A value may reference another secret as ${OTHER_SECRET}: the reference is stored literally and expanded whenever the secret is read, so it tracks the referenced value. Write $${OTHER_SECRET} for a literal.", { idempotent: false }, {
6234
+ tool("set_secret", "Encrypt a value locally and store it in an environment. A value may reference another secret as ${OTHER_SECRET}: the reference is stored literally and expanded whenever the secret is read, so it tracks the referenced value. Write $${OTHER_SECRET} for a literal. If the environment requires approval the write is QUEUED, not stored: the result carries queued:true and a changeRequestId, and the secret keeps its old value until a human approves.", { idempotent: false }, {
5335
6235
  ...targetShape,
5336
6236
  name: z.string(),
5337
- value: z.string()
6237
+ value: z.string(),
6238
+ note: z.string().optional()
5338
6239
  }, async (o) => {
5339
6240
  const ctx = getCtx();
5340
6241
  ensureDecryptable(ctx);
5341
6242
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
5342
- await encryptAndSetSecret(ctx, orgId, envId, o.name, o.value);
5343
- return {
6243
+ const queued = await encryptAndSetSecret(ctx, orgId, envId, o.name, o.value, o.note);
6244
+ return queued ? {
6245
+ ok: true,
6246
+ queued: true,
6247
+ name: o.name,
6248
+ changeRequestId: queued.id,
6249
+ requiredApprovals: queued.requiredApprovals
6250
+ } : {
5344
6251
  ok: true,
5345
6252
  name: o.name
5346
6253
  };
@@ -5403,26 +6310,38 @@ async function runMcpServer(options = {}) {
5403
6310
  tool("restore_secret", "Roll a secret back to an earlier version. The stored ciphertext is replayed as a NEW version (history is append-only, nothing is overwritten). Keyless — no decryption happens, so this works even without a key.", { idempotent: false }, {
5404
6311
  ...targetShape,
5405
6312
  name: z.string(),
5406
- version: z.number().int().positive()
6313
+ version: z.number().int().positive(),
6314
+ note: z.string().optional()
5407
6315
  }, async (o) => {
5408
6316
  const ctx = getCtx();
5409
6317
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
5410
- const { secret, restoredFrom } = await ctx.client.restoreSecret(orgId, envId, o.name, o.version);
5411
- return {
6318
+ const result = await ctx.client.restoreSecret(orgId, envId, o.name, o.version, o.note);
6319
+ return result.queued ? {
6320
+ ok: true,
6321
+ queued: true,
6322
+ name: o.name,
6323
+ changeRequestId: result.changeRequest.id
6324
+ } : {
5412
6325
  ok: true,
5413
6326
  name: o.name,
5414
- restoredFrom,
5415
- version: secret.version
6327
+ restoredFrom: result.restoredFrom,
6328
+ version: result.secret.version
5416
6329
  };
5417
6330
  });
5418
6331
  tool("delete_secret", "Delete a secret from an environment.", destructive, {
5419
6332
  ...targetShape,
5420
- name: z.string()
6333
+ name: z.string(),
6334
+ note: z.string().optional()
5421
6335
  }, async (o) => {
5422
6336
  const ctx = getCtx();
5423
6337
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
5424
- await ctx.client.deleteSecret(orgId, envId, o.name);
5425
- return {
6338
+ const removed = await ctx.client.deleteSecret(orgId, envId, o.name, o.note);
6339
+ return removed.queued ? {
6340
+ ok: true,
6341
+ queued: true,
6342
+ name: o.name,
6343
+ changeRequestId: removed.changeRequest.id
6344
+ } : {
5426
6345
  ok: true,
5427
6346
  name: o.name
5428
6347
  };
@@ -5490,32 +6409,21 @@ async function runMcpServer(options = {}) {
5490
6409
  env
5491
6410
  }) : { orgId: (await resolveOrg(ctx, org)).id };
5492
6411
  const created = await createServiceToken();
6412
+ if (boundToEnv) ensureDecryptable(ctx);
6413
+ const initialGrants = "envId" in target ? await ctx.client.prepareComposedKeyGrants(target.orgId, target.envId, {
6414
+ principalType: "service_token",
6415
+ principalId: created.tokenId,
6416
+ publicKeyJwk: created.publicKeyJwk
6417
+ }, (id) => getDek(ctx, target.orgId, id)) : void 0;
5493
6418
  await ctx.client.createToken(target.orgId, {
5494
6419
  name,
5495
6420
  tokenId: created.tokenId,
5496
6421
  tokenHash: created.tokenHash,
5497
6422
  publicKeyJwk: created.publicKeyJwk,
5498
6423
  role,
5499
- environmentId: "envId" in target ? target.envId : null
6424
+ environmentId: "envId" in target ? target.envId : null,
6425
+ initialGrants
5500
6426
  });
5501
- if (boundToEnv && "envId" in target) {
5502
- ensureDecryptable(ctx);
5503
- const grantEnv = async (envId) => {
5504
- const dek = await getDek(ctx, target.orgId, envId);
5505
- await ctx.client.grantEnvKey(target.orgId, envId, {
5506
- principalType: "service_token",
5507
- principalId: created.tokenId,
5508
- wrappedDek: await wrapDek(dek, created.publicKeyJwk)
5509
- });
5510
- };
5511
- await grantEnv(target.envId);
5512
- const { groups } = await ctx.client.listEnvGroups(target.orgId, target.envId);
5513
- for (const g of groups) {
5514
- const { environments } = await ctx.client.listGroupEnvs(target.orgId, g.groupId);
5515
- const slice = environments.find((e) => e.slug === target.envSlug);
5516
- if (slice) await grantEnv(slice.id);
5517
- }
5518
- }
5519
6427
  return {
5520
6428
  token: created.token,
5521
6429
  tokenId: created.tokenId,
@@ -5544,7 +6452,6 @@ async function runMcpServer(options = {}) {
5544
6452
  const ctx = getCtx();
5545
6453
  ensureDecryptable(ctx);
5546
6454
  const { orgId, envId, label } = await resolveEnvTarget(ctx, o);
5547
- const dek = await getDek(ctx, orgId, envId);
5548
6455
  let principalType;
5549
6456
  let principalId;
5550
6457
  let publicKeyJwk;
@@ -5568,11 +6475,11 @@ async function runMcpServer(options = {}) {
5568
6475
  t.publicKeyJwk
5569
6476
  ];
5570
6477
  }
5571
- await ctx.client.grantEnvKey(orgId, envId, {
6478
+ await ctx.client.grantEnvironmentAccess(orgId, envId, {
5572
6479
  principalType,
5573
6480
  principalId,
5574
- wrappedDek: await wrapDek(dek, publicKeyJwk)
5575
- });
6481
+ publicKeyJwk
6482
+ }, (id) => getDek(ctx, orgId, id));
5576
6483
  return {
5577
6484
  ok: true,
5578
6485
  env: label,
@@ -5703,8 +6610,7 @@ async function runMcpServer(options = {}) {
5703
6610
  });
5704
6611
  await server.connect(new StdioServerTransport());
5705
6612
  }
5706
- //#endregion
5707
- //#region src/index.ts
6613
+ // src/index.ts
5708
6614
  /**
5709
6615
  * `@seekrit/mcp` — a standalone, `npx`-able entrypoint for seekrit's MCP server.
5710
6616
  *
@@ -5721,10 +6627,9 @@ async function runMcpServer(options = {}) {
5721
6627
  * `seekrit mcp`. tsdown bundles the shared server source in at build time, so the
5722
6628
  * published package is self-contained and needs no `@seekrit/cli` install.
5723
6629
  */
5724
- runMcpServer({ version: "0.8.5" }).catch((err) => {
6630
+ runMcpServer({ version: "0.9.0" }).catch((err) => {
5725
6631
  const message = err instanceof Error ? err.message : String(err);
5726
6632
  process.stderr.write(`seekrit-mcp: fatal: ${message}\n`);
5727
6633
  process.exit(1);
5728
6634
  });
5729
- //#endregion
5730
6635
  export {};