@seekrit/mcp 0.8.6 → 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 +444 -129
  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
@@ -374,8 +383,7 @@ const ENTITLEMENT_KEYS = Object.keys({
374
383
  metric: "monthly_resolves"
375
384
  }
376
385
  });
377
- //#endregion
378
- //#region ../../packages/core/src/plans.ts
386
+ // ../../packages/core/src/plans.ts
379
387
  const PLAN_FAMILIES = {
380
388
  free: {
381
389
  id: "free",
@@ -408,8 +416,7 @@ const PLAN_FAMILIES = {
408
416
  };
409
417
  const PLAN_FAMILY_IDS = Object.keys(PLAN_FAMILIES);
410
418
  PLAN_FAMILY_IDS.filter((family) => !PLAN_FAMILIES[family].hidden);
411
- //#endregion
412
- //#region ../../packages/core/src/billing.ts
419
+ // ../../packages/core/src/billing.ts
413
420
  /**
414
421
  * Lifecycle states a subscription can be in. Mirrors the biller's own states
415
422
  * (Stripe) but is provider-neutral so a different biller could map onto it.
@@ -421,8 +428,7 @@ const SUBSCRIPTION_STATUSES = [
421
428
  "canceled",
422
429
  "paused"
423
430
  ];
424
- //#endregion
425
- //#region ../../packages/core/src/branches.ts
431
+ // ../../packages/core/src/branches.ts
426
432
  /**
427
433
  * Branch (ephemeral) environments — a per-PR/preview overlay on an existing
428
434
  * application environment.
@@ -466,8 +472,7 @@ function parseBranchTtl(input) {
466
472
  if (multiplier === void 0) return null;
467
473
  return value * multiplier;
468
474
  }
469
- //#endregion
470
- //#region ../../packages/core/src/change-requests.ts
475
+ // ../../packages/core/src/change-requests.ts
471
476
  const CHANGE_REQUEST_STATUSES = [
472
477
  "open",
473
478
  "applied",
@@ -475,8 +480,141 @@ const CHANGE_REQUEST_STATUSES = [
475
480
  "withdrawn",
476
481
  "superseded"
477
482
  ];
478
- //#endregion
479
- //#region ../../packages/core/src/dotenv.ts
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
480
618
  /**
481
619
  * Apply double-quote escapes in a single left-to-right pass.
482
620
  *
@@ -565,8 +703,7 @@ function skipSpace(content, from, end) {
565
703
  while (i < end && (content[i] === " " || content[i] === " ")) i++;
566
704
  return i;
567
705
  }
568
- //#endregion
569
- //#region ../../packages/core/src/interpolate.ts
706
+ // ../../packages/core/src/interpolate.ts
570
707
  /**
571
708
  * Secret references: `${OTHER_SECRET}` inside a secret value.
572
709
  *
@@ -1063,8 +1200,7 @@ z.discriminatedUnion("provider", [
1063
1200
  mintGcpLeaseSchema,
1064
1201
  mintMongoLeaseSchema
1065
1202
  ]);
1066
- //#endregion
1067
- //#region ../../packages/core/src/types.ts
1203
+ // ../../packages/core/src/types.ts
1068
1204
  /**
1069
1205
  * Transactional notification emails seekrit can send. Each id is one
1070
1206
  * user-facing on/off toggle (see `NOTIFICATION_TYPE_META`). These carry only
@@ -1087,8 +1223,7 @@ const NOTIFICATION_TYPES = [
1087
1223
  "change_request_opened",
1088
1224
  "change_request_decided"
1089
1225
  ];
1090
- //#endregion
1091
- //#region ../../packages/core/src/schemas.ts
1226
+ // ../../packages/core/src/schemas.ts
1092
1227
  /** URL-safe identifier segment: `my-app`, `production`, … */
1093
1228
  const slugSchema = z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "must be lowercase alphanumeric with hyphens");
1094
1229
  const nameSchema = z.string().trim().min(1).max(128);
@@ -1096,7 +1231,7 @@ const nameSchema = z.string().trim().min(1).max(128);
1096
1231
  const emailSchema = z.string().trim().toLowerCase().pipe(z.email().max(320));
1097
1232
  /** Env-var style secret name: FOO, DATABASE_URL, apiKey2 … */
1098
1233
  const secretNameSchema = z.string().min(1).max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "must be a valid environment variable name");
1099
- z.enum([
1234
+ const orgRoleSchema = z.enum([
1100
1235
  "owner",
1101
1236
  "admin",
1102
1237
  "member"
@@ -1135,7 +1270,20 @@ z.object({
1135
1270
  name: nameSchema,
1136
1271
  slug: slugSchema
1137
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();
1138
1280
  z.object({
1281
+ userId: z.string().min(1),
1282
+ grants: z.array(appAccessKeySchema).max(5e3)
1283
+ });
1284
+ z.object({ role: orgRoleSchema });
1285
+ z.object({
1286
+ appAccessGrants: appAccessGrantsSchema,
1139
1287
  groupId: z.string().min(1),
1140
1288
  /** Precedence among an env's groups (higher wins). Appended if omitted. */
1141
1289
  position: z.number().int().min(0).optional(),
@@ -1146,6 +1294,11 @@ z.object({
1146
1294
  })).optional()
1147
1295
  });
1148
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(),
1149
1302
  name: nameSchema,
1150
1303
  slug: slugSchema,
1151
1304
  /** Environment DEK wrapped to the creator's public key — created client-side. */
@@ -1207,7 +1360,23 @@ z.object({
1207
1360
  /** The same DEK wrapped to each of the parent's existing grant-holders. */
1208
1361
  grants: z.array(grantEnvironmentKeySchema).max(500).default([])
1209
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);
1210
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(),
1211
1380
  name: nameSchema,
1212
1381
  tokenId: z.string().regex(/^skt_[0-9A-Za-z]+$/),
1213
1382
  /** SHA-256 hash (base64url) of the full token string. */
@@ -2852,8 +3021,7 @@ z.object({
2852
3021
  mode: z.enum(["auto", "manual"]).optional(),
2853
3022
  enabled: z.boolean().optional()
2854
3023
  });
2855
- //#endregion
2856
- //#region ../../packages/core/src/vault.ts
3024
+ // ../../packages/core/src/vault.ts
2857
3025
  /** One encrypted credential within a connection. */
2858
3026
  const VAULT_SLOTS = [
2859
3027
  "oauth2",
@@ -3137,8 +3305,7 @@ z.object({
3137
3305
  userRef: vaultUserRefSchema,
3138
3306
  leaseId: leaseIdSchema
3139
3307
  });
3140
- //#endregion
3141
- //#region ../../packages/crypto/src/encoding.ts
3308
+ // ../../packages/crypto/src/encoding.ts
3142
3309
  const CHUNK = 32768;
3143
3310
  /** Base64url (no padding) — portable across browsers, Workers, and Node. */
3144
3311
  function toBase64Url(bytes) {
@@ -3169,8 +3336,7 @@ function utf8Encode(text) {
3169
3336
  function utf8Decode(bytes) {
3170
3337
  return new TextDecoder().decode(bytes);
3171
3338
  }
3172
- //#endregion
3173
- //#region ../../packages/crypto/src/errors.ts
3339
+ // ../../packages/crypto/src/errors.ts
3174
3340
  var SeekritCryptoError = class extends Error {
3175
3341
  code;
3176
3342
  constructor(code, message) {
@@ -3190,8 +3356,7 @@ function splitBlob(blob, prefix, segments) {
3190
3356
  if (parts.length !== segments + 1 || parts.some((p) => p.length === 0)) throw new SeekritCryptoError("MALFORMED_BLOB", `malformed "${prefix}" blob`);
3191
3357
  return parts.slice(1);
3192
3358
  }
3193
- //#endregion
3194
- //#region ../../packages/crypto/src/aes.ts
3359
+ // ../../packages/crypto/src/aes.ts
3195
3360
  const SECRET_PREFIX = "sc1";
3196
3361
  const IV_LENGTH$1 = 12;
3197
3362
  /** Generate a fresh 256-bit data encryption key for an environment. */
@@ -3236,8 +3401,7 @@ async function decryptSecret(dek, blob, aad) {
3236
3401
  function secretAad(environmentId, secretName) {
3237
3402
  return `${environmentId}/${secretName}`;
3238
3403
  }
3239
- //#endregion
3240
- //#region ../../packages/crypto/src/keys.ts
3404
+ // ../../packages/crypto/src/keys.ts
3241
3405
  async function generateKeyPair() {
3242
3406
  const pair = await crypto.subtle.generateKey({
3243
3407
  name: "ECDH",
@@ -3270,8 +3434,7 @@ async function importPrivateKeyPkcs8(pkcs8) {
3270
3434
  namedCurve: "P-256"
3271
3435
  }, true, ["deriveBits"]);
3272
3436
  }
3273
- //#endregion
3274
- //#region ../../packages/crypto/src/wrap.ts
3437
+ // ../../packages/crypto/src/wrap.ts
3275
3438
  /**
3276
3439
  * ECIES-style key wrapping: an ephemeral P-256 keypair performs ECDH against
3277
3440
  * the recipient's public key; the shared secret is run through HKDF-SHA256 to
@@ -3339,8 +3502,7 @@ async function unwrapDek(wrapped, privateKey) {
3339
3502
  throw new SeekritCryptoError("DECRYPT_FAILED", "DEK unwrap failed: wrong private key or tampered grant");
3340
3503
  }
3341
3504
  }
3342
- //#endregion
3343
- //#region ../../packages/crypto/src/kms.ts
3505
+ // ../../packages/crypto/src/kms.ts
3344
3506
  /**
3345
3507
  * Client-side KMS envelope encryption. A managed `encrypt` key is a 256-bit
3346
3508
  * AES-GCM key whose material reaches the client only as a `wd1.` grant (wrapped
@@ -3455,8 +3617,7 @@ async function generateDataKey(material, ref) {
3455
3617
  ].join(".")
3456
3618
  };
3457
3619
  }
3458
- //#endregion
3459
- //#region ../../packages/crypto/src/random.ts
3620
+ // ../../packages/crypto/src/random.ts
3460
3621
  const ALPHABETS = {
3461
3622
  alphanumeric: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
3462
3623
  hex: "0123456789abcdef",
@@ -3492,8 +3653,7 @@ function generateSecretValue(length, alphabet = "alphanumeric") {
3492
3653
  }
3493
3654
  return out;
3494
3655
  }
3495
- //#endregion
3496
- //#region ../../packages/crypto/src/mysql.ts
3656
+ // ../../packages/crypto/src/mysql.ts
3497
3657
  /**
3498
3658
  * Client-side construction of a MySQL/MariaDB `mysql_native_password`
3499
3659
  * authentication string, for minting *temporary MySQL login credentials*
@@ -3549,8 +3709,7 @@ async function generateMysqlCredential(options = {}) {
3549
3709
  verifier: await mysqlNativePasswordVerifier(password)
3550
3710
  };
3551
3711
  }
3552
- //#endregion
3553
- //#region ../../packages/crypto/src/passphrase.ts
3712
+ // ../../packages/crypto/src/passphrase.ts
3554
3713
  /**
3555
3714
  * User private keys are stored server-side encrypted under a key derived from
3556
3715
  * the user's passphrase, so any browser or CLI session can fetch and unlock
@@ -3591,8 +3750,7 @@ async function decryptPrivateKey(passphrase, blob) {
3591
3750
  throw new SeekritCryptoError("DECRYPT_FAILED", "wrong passphrase or corrupted key blob");
3592
3751
  }
3593
3752
  }
3594
- //#endregion
3595
- //#region ../../packages/crypto/src/shamir.ts
3753
+ // ../../packages/crypto/src/shamir.ts
3596
3754
  /**
3597
3755
  * Shamir's Secret Sharing over GF(2^8) — the same field AES uses, with the
3598
3756
  * reduction polynomial x^8 + x^4 + x^3 + x + 1 (0x11b). Splits a byte string
@@ -3686,8 +3844,7 @@ async function generatePostgresCredential(options = {}) {
3686
3844
  iterations
3687
3845
  };
3688
3846
  }
3689
- //#endregion
3690
- //#region ../../packages/crypto/src/sign.ts
3847
+ // ../../packages/crypto/src/sign.ts
3691
3848
  /**
3692
3849
  * Managed signing keys for the client-side KMS — ECDSA over P-256 (the curve
3693
3850
  * already used for principal keypairs; universal in WebCrypto). A `sign` key's
@@ -3749,15 +3906,16 @@ function signatureKeyRef(signature) {
3749
3906
  version
3750
3907
  };
3751
3908
  }
3752
- //#endregion
3753
- //#region ../../packages/crypto/src/token.ts
3909
+ // ../../packages/crypto/src/token.ts
3754
3910
  /**
3755
3911
  * Service tokens (CI, docker builds, agent proxies, k8s, …) are self-contained
3756
- * principals: the token string itself carries the private key, so the server
3757
- * never holds it. The server stores only the SHA-256 hash of the full token
3758
- * (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.
3759
3915
  *
3760
- * 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.
3761
3919
  */
3762
3920
  const TOKEN_PREFIX = "skt";
3763
3921
  const TOKEN_ID_LENGTH = 22;
@@ -3781,17 +3939,17 @@ async function createServiceToken() {
3781
3939
  const { publicKeyJwk, privateKeyJwk } = await generateKeyPair();
3782
3940
  const pkcs8 = await exportPrivateKeyPkcs8(await importPrivateKey(privateKeyJwk));
3783
3941
  const tokenId = randomTokenId();
3784
- const token = `${tokenId}_${toBase64Url(pkcs8)}`;
3942
+ const token = `${tokenId}_v2.${toBase64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))}.${toBase64Url(pkcs8)}`;
3785
3943
  return {
3786
3944
  token,
3787
3945
  tokenId,
3788
- tokenHash: await hashToken(token),
3946
+ tokenHash: await hashToken(serviceTokenAuth(token)),
3789
3947
  publicKeyJwk
3790
3948
  };
3791
3949
  }
3792
3950
  async function parseServiceToken(token) {
3793
- const match = /^(skt_[0-9A-Za-z]+)_([A-Za-z0-9_-]+)$/.exec(token);
3794
- 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");
3795
3953
  const [, tokenId, keyB64] = match;
3796
3954
  try {
3797
3955
  return {
@@ -3802,12 +3960,23 @@ async function parseServiceToken(token) {
3802
3960
  throw new SeekritCryptoError("MALFORMED_TOKEN", "service token private key is corrupted");
3803
3961
  }
3804
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
+ }
3805
3975
  function isServiceToken(value) {
3806
3976
  return value.startsWith(`${TOKEN_PREFIX}_`);
3807
3977
  }
3808
- //#endregion
3809
- //#region ../cli/package.json
3810
- var version$1 = "1.9.2";
3978
+ // ../cli/package.json
3979
+ var version$1 = "2.4.0";
3811
3980
  const PROJECT_FILE = "seekrit.json";
3812
3981
  function globalConfigPath() {
3813
3982
  return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "seekrit", "config.json");
@@ -3857,8 +4026,7 @@ function writeProjectConfig(config, dir = process.cwd()) {
3857
4026
  writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
3858
4027
  return path;
3859
4028
  }
3860
- //#endregion
3861
- //#region ../../packages/api-client/src/index.ts
4029
+ // ../../packages/api-client/src/index.ts
3862
4030
  /**
3863
4031
  * The proposer's note travels as a header, not a body field: an unprotected
3864
4032
  * environment ignores it, so the same call works either way and no caller has
@@ -3895,13 +4063,15 @@ var SeekritClient = class {
3895
4063
  ...extraHeaders
3896
4064
  };
3897
4065
  if (this.client) headers["x-seekrit-client"] = this.client;
3898
- if (this.auth.type === "bearer") headers.authorization = `Bearer ${this.auth.token}`;
4066
+ if (this.auth.type === "bearer") headers.authorization = `Bearer ${apiBearerToken(this.auth.token)}`;
3899
4067
  else if (this.auth.type === "dynamic") {
3900
4068
  const token = await this.auth.getToken();
3901
4069
  if (!token) throw new SeekritApiError(401, "unauthorized", "session expired");
3902
- headers.authorization = `Bearer ${token}`;
3903
- } else if (this.auth.type === "m2m") headers.authorization = `Basic ${btoa(`${this.auth.clientId}:${this.auth.clientSecret}`)}`;
3904
- 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;
3905
4075
  if (body !== void 0) headers["content-type"] = "application/json";
3906
4076
  const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
3907
4077
  method,
@@ -3991,6 +4161,66 @@ var SeekritClient = class {
3991
4161
  listMembers(orgId) {
3992
4162
  return this.request("GET", `/v1/orgs/${orgId}/members`);
3993
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
+ }
3994
4224
  /**
3995
4225
  * The org-wide "require a second factor for all members" policy. `configured`
3996
4226
  * is false when the identity provider isn't wired up (local dev), in which
@@ -4175,6 +4405,46 @@ var SeekritClient = class {
4175
4405
  return this.request("POST", `/v1/orgs/${orgId}/change-requests/${id}/withdraw`);
4176
4406
  }
4177
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
+ }
4178
4448
  getMyEnvKey(orgId, envId) {
4179
4449
  return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/key`);
4180
4450
  }
@@ -4261,6 +4531,42 @@ var SeekritClient = class {
4261
4531
  deleteHoneyToken(orgId, honeyTokenId) {
4262
4532
  return this.request("DELETE", `/v1/orgs/${orgId}/honey-tokens/${honeyTokenId}`);
4263
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
+ }
4264
4570
  listAgents(orgId) {
4265
4571
  return this.request("GET", `/v1/orgs/${orgId}/agents`);
4266
4572
  }
@@ -4339,6 +4645,7 @@ var SeekritClient = class {
4339
4645
  * identity are three different answers.
4340
4646
  */
4341
4647
  introspectAgentTask(token) {
4648
+ if (!token.startsWith("skd_")) throw new Error("expected a dispatched task token");
4342
4649
  return this.request("POST", "/v1/tasks/introspect", { token });
4343
4650
  }
4344
4651
  /** End a run's authority now. Idempotent. */
@@ -4640,8 +4947,7 @@ var SeekritClient = class {
4640
4947
  return this.request("DELETE", `/v1/orgs/${orgId}/vault/projects/${projectId}/webhooks/${webhookId}`);
4641
4948
  }
4642
4949
  };
4643
- //#endregion
4644
- //#region ../cli/src/io.ts
4950
+ // ../cli/src/io.ts
4645
4951
  let failThrows = false;
4646
4952
  /**
4647
4953
  * In `seekrit mcp` the process is a long-lived stdio server, so a `fail()`
@@ -4693,8 +4999,7 @@ function promptHidden(question) {
4693
4999
  });
4694
5000
  });
4695
5001
  }
4696
- //#endregion
4697
- //#region ../cli/src/context.ts
5002
+ // ../cli/src/context.ts
4698
5003
  /** Sent as `x-seekrit-client` so the API attributes usage to the CLI (analytics). */
4699
5004
  const CLI_CLIENT = `cli/${version$1}`;
4700
5005
  /**
@@ -4764,13 +5069,29 @@ async function getPrivateKey(ctx) {
4764
5069
  const { encryptedPrivateKey } = await ctx.client.getMyKeys();
4765
5070
  return importPrivateKey(await decryptPrivateKey(process.env.SEEKRIT_PASSPHRASE ?? await promptHidden("Passphrase: "), encryptedPrivateKey));
4766
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
+ }
4767
5089
  /** Recover one environment's DEK for the current principal. */
4768
5090
  async function getDek(ctx, orgId, envId) {
4769
5091
  const [{ wrappedDek }, privateKey] = await Promise.all([ctx.client.getMyEnvKey(orgId, envId), getPrivateKey(ctx)]);
4770
5092
  return unwrapDek(wrappedDek, privateKey);
4771
5093
  }
4772
- //#endregion
4773
- //#region ../cli/src/group-sync-grants.ts
5094
+ // ../cli/src/group-sync-grants.ts
4774
5095
  /** Wrap a newly composed group layer for connections already syncing the app env or its branches. */
4775
5096
  async function syncGrantsForGroupLink(ctx, orgId, envId, envSlug, groupId) {
4776
5097
  const [{ groups }, { bindings }, { branches }] = await Promise.all([
@@ -4795,8 +5116,7 @@ async function syncGrantsForGroupLink(ctx, orgId, envId, envSlug, groupId) {
4795
5116
  };
4796
5117
  }));
4797
5118
  }
4798
- //#endregion
4799
- //#region ../cli/src/target.ts
5119
+ // ../cli/src/target.ts
4800
5120
  /** Resolve the target org from a flag, the committed config, or a lone org. */
4801
5121
  async function resolveOrg(ctx, orgSlug) {
4802
5122
  const wanted = orgSlug ?? findProjectConfig()?.org;
@@ -4829,7 +5149,11 @@ async function boundEnvTarget(ctx, opts) {
4829
5149
  try {
4830
5150
  ({scope} = await ctx.client.resolve(opts.branch ? { branch: opts.branch } : {}));
4831
5151
  } catch (err) {
4832
- 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;
4833
5157
  }
4834
5158
  const env = scope.branchOf ?? {
4835
5159
  envId: scope.envId,
@@ -4856,7 +5180,10 @@ async function boundEnvTarget(ctx, opts) {
4856
5180
  * it this way; this is the same rule, in one place, for both.
4857
5181
  */
4858
5182
  async function resolveEnvTarget(ctx, opts) {
4859
- 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
+ }
4860
5187
  const org = await resolveOrg(ctx, opts.org);
4861
5188
  if (!opts.env) fail("specify --env");
4862
5189
  if (opts.group) {
@@ -4945,8 +5272,7 @@ async function resolveGroup(ctx, opts) {
4945
5272
  slug: group.slug
4946
5273
  };
4947
5274
  }
4948
- //#endregion
4949
- //#region ../cli/src/kms.ts
5275
+ // ../cli/src/kms.ts
4950
5276
  /** The calling principal's identity + public key (for a self-grant). */
4951
5277
  async function kmsCallerIdentity(ctx) {
4952
5278
  if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
@@ -5009,8 +5335,7 @@ async function kmsRecoverMaterial(ctx, orgId, keyId, version) {
5009
5335
  currentVersion: mat.currentVersion
5010
5336
  };
5011
5337
  }
5012
- //#endregion
5013
- //#region ../cli/src/m2m.ts
5338
+ // ../cli/src/m2m.ts
5014
5339
  /**
5015
5340
  * Resolve M2M client credentials from (in order) the process environment, a
5016
5341
  * `.env` overlay (for `seekrit run`), then saved config. Both halves must come
@@ -5077,16 +5402,22 @@ async function ensureM2mAdminToken(dotenvVars = {}) {
5077
5402
  if (!creds) return null;
5078
5403
  const cached = readCachedM2mToken(creds.clientId);
5079
5404
  if (cached) {
5080
- process.env.SEEKRIT_TOKEN = cached;
5081
- 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
+ }
5082
5414
  }
5083
5415
  const token = await mintAdminToken(process.env.SEEKRIT_API_URL ?? dotenvVars.SEEKRIT_API_URL ?? readGlobalConfig().apiUrl ?? "https://api.seekrit.dev", creds);
5084
5416
  cacheM2mToken(creds.clientId, token);
5085
5417
  process.env.SEEKRIT_TOKEN = token;
5086
5418
  return token;
5087
5419
  }
5088
- //#endregion
5089
- //#region ../cli/src/cache.ts
5420
+ // ../cli/src/cache.ts
5090
5421
  /** Render an age for a log line, rounded to its largest whole unit. */
5091
5422
  function humanize(ms) {
5092
5423
  const secs = Math.floor(ms / 1e3);
@@ -5260,8 +5591,7 @@ function overlayEnvFiles(values, provenance, envFiles) {
5260
5591
  }
5261
5592
  return loaded;
5262
5593
  }
5263
- //#endregion
5264
- //#region ../cli/src/mcp.ts
5594
+ // ../cli/src/mcp.ts
5265
5595
  /** Lowercase-alphanumeric string for a fresh Postgres role name. */
5266
5596
  function randomLower(length) {
5267
5597
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
@@ -5308,9 +5638,18 @@ function serverInstructions() {
5308
5638
  "Auth comes from SEEKRIT_TOKEN (a skt_… token), SEEKRIT_CLIENT_ID +",
5309
5639
  "SEEKRIT_CLIENT_SECRET (machine credentials — an admin token is minted and",
5310
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.",
5311
5643
  "Decrypting under a user session (not a token) additionally needs",
5312
5644
  "SEEKRIT_PASSPHRASE set in this server's env — there's no TTY to prompt on.",
5313
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
+ "",
5314
5653
  "Model: org → apps/groups → environments → secrets. Call `whoami` first, then",
5315
5654
  "`get_started` for the recommended end-to-end recipe. Prefer `run_command` over",
5316
5655
  "`get_secret reveal:true` — it injects secrets into a subprocess so plaintext",
@@ -5377,21 +5716,6 @@ function getCtx() {
5377
5716
  function ensureDecryptable(ctx) {
5378
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)");
5379
5718
  }
5380
- /**
5381
- * The calling principal's public key JWK — needed to wrap a freshly generated
5382
- * DEK when creating an environment. Service tokens carry their private key, so
5383
- * we derive the public half from it; users publish theirs at key setup.
5384
- */
5385
- async function principalPublicKeyJwk(ctx) {
5386
- if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
5387
- const { privateKey } = await parseServiceToken(ctx.auth.token);
5388
- const { d: _d, key_ops: _ops, ext: _ext, ...pub } = await crypto.subtle.exportKey("jwk", privateKey);
5389
- return JSON.stringify(pub);
5390
- }
5391
- const { user } = await ctx.client.me();
5392
- if (!user.publicKeyJwk) throw new Error("this user has no keypair yet — run `seekrit keys setup` first");
5393
- return user.publicKeyJwk;
5394
- }
5395
5719
  /** Run a child command with `env` and capture its output (values never returned). */
5396
5720
  function runChild(cmd, args, env, cwd) {
5397
5721
  return new Promise((resolve, reject) => {
@@ -5785,11 +6109,13 @@ async function runMcpServer(options = {}) {
5785
6109
  const { apps } = await ctx.client.listApps(orgRef.id);
5786
6110
  const appRow = apps.find((a) => a.slug === app || a.id === app);
5787
6111
  if (!appRow) throw new Error(`no app "${app}" in ${orgRef.slug}`);
5788
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
6112
+ const dek = generateDek();
6113
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5789
6114
  return (await ctx.client.createEnv(orgRef.id, appRow.id, {
5790
6115
  name,
5791
6116
  slug,
5792
- wrappedDek
6117
+ wrappedDek,
6118
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(orgRef.id, { appId: appRow.id }, dek)
5793
6119
  })).environment;
5794
6120
  });
5795
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 }, {
@@ -5852,11 +6178,13 @@ async function runMcpServer(options = {}) {
5852
6178
  org,
5853
6179
  group
5854
6180
  });
5855
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
6181
+ const dek = generateDek();
6182
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5856
6183
  return (await ctx.client.createGroupEnv(g.orgId, g.id, {
5857
6184
  name,
5858
6185
  slug,
5859
- wrappedDek
6186
+ wrappedDek,
6187
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(g.orgId, { groupId: g.id }, dek)
5860
6188
  })).environment;
5861
6189
  });
5862
6190
  tool("compose_group", "Compose a group into an application environment (higher position wins on name clashes).", { idempotent: true }, {
@@ -5878,6 +6206,7 @@ async function runMcpServer(options = {}) {
5878
6206
  });
5879
6207
  const syncGrants = await syncGrantsForGroupLink(ctx, target.orgId, target.envId, target.envSlug, g.id);
5880
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)),
5881
6210
  groupId: g.id,
5882
6211
  position,
5883
6212
  syncGrants
@@ -6080,32 +6409,21 @@ async function runMcpServer(options = {}) {
6080
6409
  env
6081
6410
  }) : { orgId: (await resolveOrg(ctx, org)).id };
6082
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;
6083
6418
  await ctx.client.createToken(target.orgId, {
6084
6419
  name,
6085
6420
  tokenId: created.tokenId,
6086
6421
  tokenHash: created.tokenHash,
6087
6422
  publicKeyJwk: created.publicKeyJwk,
6088
6423
  role,
6089
- environmentId: "envId" in target ? target.envId : null
6424
+ environmentId: "envId" in target ? target.envId : null,
6425
+ initialGrants
6090
6426
  });
6091
- if (boundToEnv && "envId" in target) {
6092
- ensureDecryptable(ctx);
6093
- const grantEnv = async (envId) => {
6094
- const dek = await getDek(ctx, target.orgId, envId);
6095
- await ctx.client.grantEnvKey(target.orgId, envId, {
6096
- principalType: "service_token",
6097
- principalId: created.tokenId,
6098
- wrappedDek: await wrapDek(dek, created.publicKeyJwk)
6099
- });
6100
- };
6101
- await grantEnv(target.envId);
6102
- const { groups } = await ctx.client.listEnvGroups(target.orgId, target.envId);
6103
- for (const g of groups) {
6104
- const { environments } = await ctx.client.listGroupEnvs(target.orgId, g.groupId);
6105
- const slice = environments.find((e) => e.slug === target.envSlug);
6106
- if (slice) await grantEnv(slice.id);
6107
- }
6108
- }
6109
6427
  return {
6110
6428
  token: created.token,
6111
6429
  tokenId: created.tokenId,
@@ -6134,7 +6452,6 @@ async function runMcpServer(options = {}) {
6134
6452
  const ctx = getCtx();
6135
6453
  ensureDecryptable(ctx);
6136
6454
  const { orgId, envId, label } = await resolveEnvTarget(ctx, o);
6137
- const dek = await getDek(ctx, orgId, envId);
6138
6455
  let principalType;
6139
6456
  let principalId;
6140
6457
  let publicKeyJwk;
@@ -6158,11 +6475,11 @@ async function runMcpServer(options = {}) {
6158
6475
  t.publicKeyJwk
6159
6476
  ];
6160
6477
  }
6161
- await ctx.client.grantEnvKey(orgId, envId, {
6478
+ await ctx.client.grantEnvironmentAccess(orgId, envId, {
6162
6479
  principalType,
6163
6480
  principalId,
6164
- wrappedDek: await wrapDek(dek, publicKeyJwk)
6165
- });
6481
+ publicKeyJwk
6482
+ }, (id) => getDek(ctx, orgId, id));
6166
6483
  return {
6167
6484
  ok: true,
6168
6485
  env: label,
@@ -6293,8 +6610,7 @@ async function runMcpServer(options = {}) {
6293
6610
  });
6294
6611
  await server.connect(new StdioServerTransport());
6295
6612
  }
6296
- //#endregion
6297
- //#region src/index.ts
6613
+ // src/index.ts
6298
6614
  /**
6299
6615
  * `@seekrit/mcp` — a standalone, `npx`-able entrypoint for seekrit's MCP server.
6300
6616
  *
@@ -6311,10 +6627,9 @@ async function runMcpServer(options = {}) {
6311
6627
  * `seekrit mcp`. tsdown bundles the shared server source in at build time, so the
6312
6628
  * published package is self-contained and needs no `@seekrit/cli` install.
6313
6629
  */
6314
- runMcpServer({ version: "0.8.6" }).catch((err) => {
6630
+ runMcpServer({ version: "0.9.0" }).catch((err) => {
6315
6631
  const message = err instanceof Error ? err.message : String(err);
6316
6632
  process.stderr.write(`seekrit-mcp: fatal: ${message}\n`);
6317
6633
  process.exit(1);
6318
6634
  });
6319
- //#endregion
6320
6635
  export {};
package/package.json CHANGED
@@ -1,8 +1,31 @@
1
1
  {
2
2
  "name": "@seekrit/mcp",
3
- "version": "0.8.6",
4
- "description": "npx-able MCP server for seekrit — let Claude Code and other MCP clients provision, manage, and inject end-to-end encrypted secrets.",
3
+ "version": "0.9.0",
4
+ "description": "npx-able MCP server for seekrit (https://seekrit.dev), a zero-knowledge secrets manager and credential broker for AI agents — let Claude Code and other MCP clients provision, manage, and inject secrets.",
5
5
  "mcpName": "dev.seekrit/mcp",
6
+ "homepage": "https://seekrit.dev/docs/guides/ai-agents",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/seekritdev/agent-plugin.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/seekritdev/agent-plugin/issues"
13
+ },
14
+ "keywords": [
15
+ "seekrit",
16
+ "mcp",
17
+ "mcp-server",
18
+ "model-context-protocol",
19
+ "claude-code",
20
+ "cursor",
21
+ "ai-agents",
22
+ "secrets",
23
+ "secrets-manager",
24
+ "credentials",
25
+ "api-keys",
26
+ "zero-knowledge",
27
+ "credential-broker"
28
+ ],
6
29
  "type": "module",
7
30
  "publishConfig": {
8
31
  "access": "public"
@@ -17,14 +40,14 @@
17
40
  "node": ">=20"
18
41
  },
19
42
  "dependencies": {
20
- "@modelcontextprotocol/sdk": "^1.30.1",
21
- "zod": "^4.6.5"
43
+ "@modelcontextprotocol/sdk": "^1.32.2",
44
+ "zod": "^4.6.7"
22
45
  },
23
46
  "devDependencies": {
24
- "@types/node": "^26.6.1",
25
- "tsdown": "^0.23.0",
26
- "vitest": "^5.0.1",
27
- "@seekrit/cli": "1.9.2"
47
+ "@types/node": "^26.6.6",
48
+ "tsdown": "^0.23.5",
49
+ "vitest": "^5.1.0",
50
+ "@seekrit/cli": "2.4.0"
28
51
  },
29
52
  "scripts": {
30
53
  "build": "tsdown",