@seekrit/mcp 0.8.6 → 0.10.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 +2120 -294
  2. package/package.json +31 -8
package/dist/index.js CHANGED
@@ -2,13 +2,14 @@
2
2
  import { spawn } from "node:child_process";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
- import { z } from "zod";
5
+ import * as z from "zod";
6
+ import { z as z$1 } from "zod";
6
7
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
8
  import { homedir } from "node:os";
8
9
  import { dirname, join, parse } from "node:path";
9
10
  import { createInterface } from "node:readline";
10
11
  import { Writable } from "node:stream";
11
- //#region ../../packages/core/src/agent-policy.ts
12
+ // ../../packages/core/src/agent-policy.ts
12
13
  /** A bare hostname: no scheme, no port, no path, no wildcard. */
13
14
  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
15
  const policyMethodSchema = z.string().trim().toUpperCase().regex(/^[A-Z]{3,10}$/, "method must be an HTTP method name");
@@ -18,11 +19,15 @@ const policyMethodSchema = z.string().trim().toUpperCase().regex(/^[A-Z]{3,10}$/
18
19
  */
19
20
  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
21
  const policySecretNameSchema = z.string().trim().regex(/^[A-Za-z0-9_]+$/, "secret names are letters, digits, and underscores");
22
+ /** A TCP port. 0 is refused: it never matches a connection, so a rule naming it is a mistake. */
23
+ const policyPortSchema = z.number().int().min(1).max(65535);
21
24
  z.object({
22
25
  host: policyHostSchema,
23
26
  methods: z.array(policyMethodSchema).max(16).default([]),
24
27
  paths: z.array(policyPathSchema).max(64).default([]),
25
28
  allow: z.array(policySecretNameSchema).max(64).default([]),
29
+ https_ports: z.array(policyPortSchema).max(32).optional(),
30
+ http_ports: z.array(policyPortSchema).max(32).optional(),
26
31
  label: z.string().trim().max(120).optional()
27
32
  });
28
33
  z.object({
@@ -41,6 +46,11 @@ z.object({
41
46
  });
42
47
  z.object({
43
48
  host: policyHostSchema,
49
+ /** How the agent reaches the host. Omit for a destination the operator fixed. */
50
+ transport: z.object({
51
+ scheme: z.enum(["https", "http"]),
52
+ port: policyPortSchema
53
+ }).optional(),
44
54
  method: policyMethodSchema,
45
55
  path: z.string().trim().min(1).max(2048),
46
56
  secret: policySecretNameSchema.optional()
@@ -52,6 +62,7 @@ const activityEntrySchema = z.object({
52
62
  decision: z.enum([
53
63
  "allow",
54
64
  "no_rule",
65
+ "port_not_allowed",
55
66
  "method_not_allowed",
56
67
  "path_not_allowed",
57
68
  "secret_not_allowed",
@@ -87,6 +98,26 @@ z.object({
87
98
  */
88
99
  entries: z.array(activityEntrySchema).min(1).max(500)
89
100
  });
101
+ // ../../packages/core/src/agent-login.ts
102
+ /** Where each kind of login is stored unless told otherwise. */
103
+ const AGENT_LOGIN_SECRETS = {
104
+ /** Codex's `auth.json`, as an envelope. */
105
+ codex: "CODEX_LOGIN",
106
+ /** Claude Code's full `.credentials.json`, as an envelope. */
107
+ claude: "CLAUDE_LOGIN",
108
+ /** A `claude setup-token` token — a plain secret, the variable Claude Code reads. */
109
+ claudeToken: "CLAUDE_CODE_OAUTH_TOKEN"
110
+ };
111
+ /** The serialized prefix of every version of the envelope (`kind` is always first). */
112
+ const ENVELOPE_PREFIX = "{\"kind\":\"seekrit.agent-login/";
113
+ /**
114
+ * Whether a decrypted secret value is a managed agent login. Such a value is a
115
+ * *file*, never an environment variable: `seekrit run` keeps it out of the
116
+ * child's environment.
117
+ */
118
+ function isAgentLoginValue(value) {
119
+ return value.startsWith(ENVELOPE_PREFIX);
120
+ }
90
121
  /**
91
122
  * Twelve hours, matching `[control] max_ttl` in a proxy config. A task is meant
92
123
  * to bound one run; something that needs longer wants a policy change, not a
@@ -136,8 +167,7 @@ z.object({
136
167
  z.object({
137
168
  /** The presented token. In the body, never a URL — it is a credential. */
138
169
  token: z.string().trim().min(8).max(512) });
139
- //#endregion
140
- //#region ../../packages/core/src/archive.ts
170
+ // ../../packages/core/src/archive.ts
141
171
  /**
142
172
  * The **break-glass archive** format: one signed JSON file holding everything
143
173
  * seekrit stores for an org, in the form seekrit stores it — ciphertext stays
@@ -374,8 +404,7 @@ const ENTITLEMENT_KEYS = Object.keys({
374
404
  metric: "monthly_resolves"
375
405
  }
376
406
  });
377
- //#endregion
378
- //#region ../../packages/core/src/plans.ts
407
+ // ../../packages/core/src/plans.ts
379
408
  const PLAN_FAMILIES = {
380
409
  free: {
381
410
  id: "free",
@@ -408,8 +437,7 @@ const PLAN_FAMILIES = {
408
437
  };
409
438
  const PLAN_FAMILY_IDS = Object.keys(PLAN_FAMILIES);
410
439
  PLAN_FAMILY_IDS.filter((family) => !PLAN_FAMILIES[family].hidden);
411
- //#endregion
412
- //#region ../../packages/core/src/billing.ts
440
+ // ../../packages/core/src/billing.ts
413
441
  /**
414
442
  * Lifecycle states a subscription can be in. Mirrors the biller's own states
415
443
  * (Stripe) but is provider-neutral so a different biller could map onto it.
@@ -421,8 +449,7 @@ const SUBSCRIPTION_STATUSES = [
421
449
  "canceled",
422
450
  "paused"
423
451
  ];
424
- //#endregion
425
- //#region ../../packages/core/src/branches.ts
452
+ // ../../packages/core/src/branches.ts
426
453
  /**
427
454
  * Branch (ephemeral) environments — a per-PR/preview overlay on an existing
428
455
  * application environment.
@@ -466,8 +493,7 @@ function parseBranchTtl(input) {
466
493
  if (multiplier === void 0) return null;
467
494
  return value * multiplier;
468
495
  }
469
- //#endregion
470
- //#region ../../packages/core/src/change-requests.ts
496
+ // ../../packages/core/src/change-requests.ts
471
497
  const CHANGE_REQUEST_STATUSES = [
472
498
  "open",
473
499
  "applied",
@@ -475,8 +501,141 @@ const CHANGE_REQUEST_STATUSES = [
475
501
  "withdrawn",
476
502
  "superseded"
477
503
  ];
478
- //#endregion
479
- //#region ../../packages/core/src/dotenv.ts
504
+ // ../../packages/core/src/connect.ts
505
+ /** Workload authentication is separate from secret-decryption principals. */
506
+ const workloadPublicKeySchema = z.object({
507
+ kty: z.literal("EC"),
508
+ crv: z.literal("P-256"),
509
+ x: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
510
+ y: z.string().regex(/^[A-Za-z0-9_-]{43}$/)
511
+ }).strict();
512
+ const audienceSchema = z.string().min(1).max(256).regex(/^[^\s]+$/);
513
+ /** HTTPS endpoint syntax. Resolved-address safety is enforced by the server runtime. */
514
+ const connectUrlSchema = z.string().max(2048).url().refine((value) => {
515
+ try {
516
+ const u = new URL(value);
517
+ 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);
518
+ } catch {
519
+ return false;
520
+ }
521
+ }, "use a public HTTPS hostname without credentials, query, fragment, or port");
522
+ const federationPolicySchema = z.object({
523
+ issuer: connectUrlSchema,
524
+ jwksUri: connectUrlSchema,
525
+ audience: audienceSchema,
526
+ subject: z.string().min(1).max(512),
527
+ 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) => ![
528
+ "iss",
529
+ "aud",
530
+ "sub",
531
+ "exp",
532
+ "iat",
533
+ "nbf"
534
+ ].includes(key))).default({})
535
+ }).strict();
536
+ z.object({
537
+ name: z.string().trim().min(1).max(100),
538
+ environmentId: z.string().min(1).max(128),
539
+ publicKey: workloadPublicKeySchema.optional(),
540
+ federation: federationPolicySchema.optional(),
541
+ audiences: z.array(audienceSchema).max(20).default([]),
542
+ maxTtlSeconds: z.number().int().min(60).max(900).default(300)
543
+ }).strict().refine((v) => !!v.publicKey !== !!v.federation, "choose a public key or a federation policy");
544
+ z.object({
545
+ enabled: z.boolean().optional(),
546
+ publicKey: workloadPublicKeySchema.optional()
547
+ }).strict().refine((v) => v.enabled !== void 0 || v.publicKey !== void 0);
548
+ 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");
549
+ const githubScopeSchema = z.object({
550
+ repositoryIds: z.array(z.number().int().positive().max(Number.MAX_SAFE_INTEGER)).min(1).max(100),
551
+ permissions: githubPermissionsSchema
552
+ }).strict();
553
+ /** Exact paths or explicitly allowed descendants, without URL decoding ambiguity. */
554
+ 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");
555
+ const proxyRuleSchema = z.object({
556
+ path: connectPathSchema,
557
+ descendants: z.boolean().default(false),
558
+ methods: z.array(z.enum([
559
+ "GET",
560
+ "POST",
561
+ "PUT",
562
+ "PATCH",
563
+ "DELETE",
564
+ "HEAD"
565
+ ])).min(1).max(6)
566
+ }).strict();
567
+ const staticScopeSchema = z.object({ rules: z.array(proxyRuleSchema).min(1).max(30) }).strict();
568
+ 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();
569
+ const oauthConfigSchema = oauthScopeSchema.extend({
570
+ provider: z.literal("oauth"),
571
+ grantType: z.enum(["client_credentials", "authorization_code"]),
572
+ clientId: z.string().min(1).max(512),
573
+ tokenEndpoint: connectUrlSchema,
574
+ authorizationEndpoint: connectUrlSchema.optional(),
575
+ tokenAuthMethod: z.enum(["client_secret_basic", "client_secret_post"]).default("client_secret_basic")
576
+ });
577
+ const customApiConfigSchema = staticScopeSchema.extend({
578
+ provider: z.literal("custom_api"),
579
+ origin: connectUrlSchema.refine((value) => {
580
+ try {
581
+ return new URL(value).pathname === "/";
582
+ } catch {
583
+ return false;
584
+ }
585
+ }, "use an origin without a path"),
586
+ 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)),
587
+ headerPrefix: z.string().max(64).regex(/^[\x20-\x7e]*$/).default("Bearer ")
588
+ });
589
+ const connectConfigSchema = z.discriminatedUnion("provider", [
590
+ customApiConfigSchema,
591
+ oauthConfigSchema,
592
+ githubScopeSchema.extend({
593
+ provider: z.literal("github_app"),
594
+ appId: z.string().regex(/^[A-Za-z0-9_.-]{1,128}$/),
595
+ installationId: z.string().regex(/^[1-9][0-9]{0,19}$/)
596
+ }),
597
+ staticScopeSchema.extend({
598
+ provider: z.literal("static_key"),
599
+ service: z.literal("resend"),
600
+ 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)
601
+ })
602
+ ]).refine((v) => v.provider !== "oauth" || v.grantType !== "authorization_code" || !!v.authorizationEndpoint, "authorization-code connections require an authorization endpoint");
603
+ const connectGrantPolicySchema = z.discriminatedUnion("provider", [
604
+ staticScopeSchema.extend({ provider: z.literal("custom_api") }),
605
+ oauthScopeSchema.extend({ provider: z.literal("oauth") }),
606
+ githubScopeSchema.extend({ provider: z.literal("github_app") }),
607
+ staticScopeSchema.extend({ provider: z.literal("static_key") })
608
+ ]);
609
+ z.object({
610
+ name: z.string().trim().min(1).max(100),
611
+ config: connectConfigSchema,
612
+ credentialWrapped: z.string().startsWith("wd1.").max(32e3)
613
+ }).strict();
614
+ z.object({
615
+ enabled: z.boolean().optional(),
616
+ credentialWrapped: z.string().startsWith("wd1.").max(32e3).optional()
617
+ }).strict().refine((v) => v.enabled !== void 0 || v.credentialWrapped !== void 0);
618
+ z.object({
619
+ workloadId: z.string().min(1).max(128),
620
+ connectionId: z.string().min(1).max(128),
621
+ policy: connectGrantPolicySchema
622
+ }).strict();
623
+ z.object({
624
+ path: connectPathSchema,
625
+ method: z.enum([
626
+ "GET",
627
+ "POST",
628
+ "PUT",
629
+ "PATCH",
630
+ "DELETE",
631
+ "HEAD"
632
+ ]).default("GET"),
633
+ query: z.record(z.string().min(1).max(100), z.string().max(2048)).default({}),
634
+ /** JSON only; callers cannot inject authorization or forwarding headers. */
635
+ body: z.string().max(65536).optional()
636
+ }).strict().refine((v) => !["GET", "HEAD"].includes(v.method) || v.body === void 0, "GET and HEAD cannot carry a body");
637
+ z.object({ audience: audienceSchema }).strict();
638
+ // ../../packages/core/src/dotenv.ts
480
639
  /**
481
640
  * Apply double-quote escapes in a single left-to-right pass.
482
641
  *
@@ -565,8 +724,24 @@ function skipSpace(content, from, end) {
565
724
  while (i < end && (content[i] === " " || content[i] === " ")) i++;
566
725
  return i;
567
726
  }
568
- //#endregion
569
- //#region ../../packages/core/src/interpolate.ts
727
+ // ../../packages/core/src/ids.ts
728
+ const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
729
+ /**
730
+ * Generate a prefixed, URL-safe random ID, e.g. `org_h9K2x…`.
731
+ * Uses rejection sampling so every character is uniformly distributed.
732
+ */
733
+ function randomId(prefix, length = 24) {
734
+ let out = "";
735
+ while (out.length < length) {
736
+ const bytes = crypto.getRandomValues(new Uint8Array(length - out.length));
737
+ for (const byte of bytes) {
738
+ if (byte < 248) out += ALPHABET[byte % 62];
739
+ if (out.length === length) break;
740
+ }
741
+ }
742
+ return `${prefix}_${out}`;
743
+ }
744
+ // ../../packages/core/src/interpolate.ts
570
745
  /**
571
746
  * Secret references: `${OTHER_SECRET}` inside a secret value.
572
747
  *
@@ -711,6 +886,578 @@ function interpolateSecrets(values) {
711
886
  unresolved: [...unresolved].sort()
712
887
  };
713
888
  }
889
+ // ../../packages/core/src/managed-providers/common.ts
890
+ const managedEndpointSchema = z.string().url().max(2048).refine((value) => {
891
+ try {
892
+ const url = new URL(value);
893
+ url.port = "";
894
+ return connectUrlSchema.safeParse(url.toString()).success;
895
+ } catch {
896
+ return false;
897
+ }
898
+ }, "use a public HTTPS endpoint without embedded credentials, query, or fragment");
899
+ const managedTtlSchema = z.number().int().min(60).max(604800).optional();
900
+ const nameSchema$1 = z.string().min(1).max(128).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/);
901
+ // ../../packages/core/src/managed-providers/aws-cache.ts
902
+ const cacheRegionSchema = z.string().regex(/^[a-z]{2}(?:-[a-z]+)+-\d$/);
903
+ const cacheGroupSchema = z.string().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9-]*$/);
904
+ const cacheAccessSchema = z.string().min(1).max(4096).refine((value) => /^on(?:\s|$)/.test(value) && !/(?:^|\s)(?:nopass|resetpass|[>#<])/.test(value), "ACL must enable the user and must not contain password directives");
905
+ // ../../packages/core/src/managed-providers/memorydb.ts
906
+ const memorydbTargetConfigSchema = z.object({
907
+ provider: z.literal("memorydb"),
908
+ executor: z.literal("in_do"),
909
+ region: cacheRegionSchema,
910
+ aclName: cacheGroupSchema,
911
+ accessString: cacheAccessSchema,
912
+ maxTtlSeconds: managedTtlSchema
913
+ }).strict();
914
+ // ../../packages/core/src/native-providers/cassandra.ts
915
+ const cassandraSettingsSchema = z.object({
916
+ host: z.string().min(1).max(253).regex(/^[a-zA-Z0-9_.:-]+$/),
917
+ port: z.number().int().min(1).max(65535).default(9042),
918
+ roles: z.array(z.string().min(1).max(128).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/)).min(1).max(32).refine((roles) => new Set(roles).size === roles.length, "roles must be unique"),
919
+ caCertificate: z.string().min(1).max(16384).optional()
920
+ }).strict();
921
+ // ../../packages/core/src/native-providers/entra.ts
922
+ const entraSettingsSchema = z.object({
923
+ tenantId: z.string().uuid(),
924
+ domain: z.string().min(1).max(253).regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/),
925
+ groups: z.array(z.string().uuid()).min(1).max(32).refine((v) => new Set(v).size === v.length, "Groups must be unique.")
926
+ }).strict();
927
+ // ../../packages/core/src/native-providers/ibm-api-connect.ts
928
+ const id$1 = z.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+$/);
929
+ const ibmApiConnectSettingsSchema = z.object({
930
+ endpoint: z.string().url().refine((value) => {
931
+ const url = new URL(value);
932
+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash;
933
+ }, "Use an HTTPS platform API endpoint without credentials or query parameters."),
934
+ organization: id$1,
935
+ catalog: id$1,
936
+ consumerOrganization: id$1,
937
+ application: id$1,
938
+ caCertificate: z.string().min(1).max(16384).optional()
939
+ }).strict();
940
+ // ../../packages/core/src/native-providers/kafka.ts
941
+ const broker = z.string().max(260).regex(/^[a-zA-Z0-9_.-]+:[0-9]+$/).refine((value) => {
942
+ const port = Number(value.slice(value.lastIndexOf(":") + 1));
943
+ return Number.isInteger(port) && port > 0 && port <= 65535;
944
+ }, "Use host:port with a valid TLS listener port");
945
+ const acl = z.object({
946
+ resourceType: z.enum(["topic", "group"]),
947
+ resourceName: z.string().min(1).max(249).regex(/^[a-zA-Z0-9_.-]+$/).refine((v) => v !== "." && v !== ".."),
948
+ patternType: z.enum(["literal", "prefixed"]).default("literal"),
949
+ operation: z.enum([
950
+ "read",
951
+ "write",
952
+ "describe"
953
+ ])
954
+ }).strict().refine((a) => a.resourceType !== "group" || a.operation !== "write", "Consumer groups support read or describe");
955
+ const kafkaSettingsSchema = z.object({
956
+ brokers: z.array(broker).min(1).max(16).refine((items) => new Set(items.map((v) => v.toLowerCase())).size === items.length, "Brokers must be unique"),
957
+ adminMechanism: z.enum([
958
+ "PLAIN",
959
+ "SCRAM-SHA-256",
960
+ "SCRAM-SHA-512"
961
+ ]).default("SCRAM-SHA-256"),
962
+ acls: z.array(acl).min(1).max(64),
963
+ caCertificate: z.string().min(1).max(16384).optional()
964
+ }).strict();
965
+ // ../../packages/core/src/native-providers/ldap.ts
966
+ const dn = z.string().min(3).max(2048).refine((v) => v.includes("=") && !/[\0\r\n]/.test(v), "Enter a distinguished name.");
967
+ const ldapSettingsSchema = z.object({
968
+ endpoint: z.string().url().refine((v) => {
969
+ const u = new URL(v);
970
+ return u.protocol === "ldaps:" && !!u.hostname && !u.username && !u.password && !u.search && !u.hash && ["", "/"].includes(u.pathname);
971
+ }, "Use an LDAPS origin without credentials or a search base."),
972
+ usersDn: dn,
973
+ groups: z.array(dn).min(1).max(32).refine((v) => new Set(v).size === v.length, "Groups must be unique."),
974
+ memberAttribute: z.enum(["member", "uniqueMember"]).default("member"),
975
+ caCertificate: z.string().min(1).max(16384).optional()
976
+ }).strict();
977
+ // ../../packages/core/src/native-providers/sap-hana.ts
978
+ const sapHanaSettingsSchema = z.object({
979
+ host: z.string().min(1).max(253).regex(/^[a-zA-Z0-9_.:-]+$/),
980
+ port: z.number().int().min(1).max(65535),
981
+ roles: z.array(z.string().min(1).max(256).regex(/^[a-zA-Z_][a-zA-Z0-9_.:$#-]*$/)).min(1).max(32).refine((roles) => new Set(roles).size === roles.length, "roles must be unique"),
982
+ caCertificate: z.string().min(1).max(16384).optional()
983
+ }).strict();
984
+ // ../../packages/core/src/native-providers/vertica.ts
985
+ const verticaSettingsSchema = z.object({
986
+ host: z.string().min(1).max(253).regex(/^[a-zA-Z0-9_.:-]+$/),
987
+ port: z.number().int().min(1).max(65535).default(5433),
988
+ database: z.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),
989
+ roles: z.array(z.string().min(1).max(128).regex(/^[a-zA-Z_][a-zA-Z0-9_$-]*$/)).min(1).max(32).refine((roles) => new Set(roles).size === roles.length, "roles must be unique"),
990
+ caCertificate: z.string().min(1).max(16384).optional()
991
+ }).strict();
992
+ // ../../packages/core/src/native-leases.ts
993
+ /** Providers executed by the enrolled Rust provisioner. Credentials and settings
994
+ * are sealed together in the browser; these schemas also drive CLI validation. */
995
+ const NATIVE_LEASE_KINDS = [
996
+ "kafka",
997
+ "sap-hana",
998
+ "cassandra",
999
+ "vertica",
1000
+ "kubernetes",
1001
+ "entra",
1002
+ "ldap",
1003
+ "ibm-api-connect"
1004
+ ];
1005
+ function isNativeLeaseKind(value) {
1006
+ return NATIVE_LEASE_KINDS.includes(value);
1007
+ }
1008
+ const privateHttpsEndpointSchema = z.string().url().refine((value) => {
1009
+ const url = new URL(value);
1010
+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash;
1011
+ }, "Use HTTPS without credentials, a query, or a fragment.");
1012
+ const caCertificateSchema = z.string().min(1).max(16384).optional();
1013
+ const dnsLabel = z.string().min(1).max(63).regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/);
1014
+ const schemas = {
1015
+ kafka: kafkaSettingsSchema,
1016
+ "sap-hana": sapHanaSettingsSchema,
1017
+ cassandra: cassandraSettingsSchema,
1018
+ vertica: verticaSettingsSchema,
1019
+ "ibm-api-connect": ibmApiConnectSettingsSchema,
1020
+ ldap: ldapSettingsSchema,
1021
+ entra: entraSettingsSchema,
1022
+ kubernetes: z.object({
1023
+ endpoint: privateHttpsEndpointSchema,
1024
+ namespace: dnsLabel,
1025
+ serviceAccount: z.string().min(1).max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/),
1026
+ audiences: z.array(z.string().min(1).max(2048)).min(1).max(16),
1027
+ caCertificate: caCertificateSchema
1028
+ }).strict()
1029
+ };
1030
+ function nativeSettings(provider, settings) {
1031
+ return schemas[provider].parse(settings);
1032
+ }
1033
+ // ../../packages/core/src/managed-providers/elasticache.ts
1034
+ const elasticacheTargetConfigSchema = z.object({
1035
+ provider: z.literal("elasticache"),
1036
+ executor: z.literal("in_do"),
1037
+ region: cacheRegionSchema,
1038
+ userGroupId: cacheGroupSchema,
1039
+ engine: z.enum(["redis", "valkey"]).default("redis"),
1040
+ accessString: cacheAccessSchema,
1041
+ maxTtlSeconds: managedTtlSchema
1042
+ }).strict();
1043
+ // ../../packages/core/src/managed-providers/snowflake.ts
1044
+ const identifier = z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_$]{0,254}$/).transform((value) => value.toUpperCase());
1045
+ const snowflakeTargetConfigSchema = z.object({
1046
+ provider: z.literal("snowflake"),
1047
+ executor: z.literal("in_do"),
1048
+ account: z.string().min(1).max(200).regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/i),
1049
+ adminRole: identifier.default("USERADMIN"),
1050
+ roles: z.array(identifier).min(1).max(50),
1051
+ warehouse: identifier.optional(),
1052
+ networkPolicy: identifier.optional(),
1053
+ maxTtlSeconds: managedTtlSchema
1054
+ }).strict();
1055
+ // ../../packages/core/src/managed-providers/couchbase.ts
1056
+ const resourceName = z.string().min(1).max(255);
1057
+ const access = z.object({
1058
+ privileges: z.array(z.enum(["data_reader", "data_writer"])).min(1).max(2),
1059
+ resources: z.object({ buckets: z.array(z.object({
1060
+ name: resourceName,
1061
+ scopes: z.array(z.object({
1062
+ name: resourceName,
1063
+ collections: z.array(resourceName).min(1).max(100).optional()
1064
+ }).strict()).min(1).max(100).optional()
1065
+ }).strict()).min(1).max(100) }).strict()
1066
+ }).strict();
1067
+ const couchbaseTargetConfigSchema = z.object({
1068
+ provider: z.literal("couchbase"),
1069
+ executor: z.literal("in_do"),
1070
+ organizationId: z.string().uuid(),
1071
+ projectId: z.string().uuid(),
1072
+ clusterId: z.string().uuid(),
1073
+ credentialType: z.enum(["basic", "advanced"]).default("basic"),
1074
+ access: z.array(access).min(1).max(100).optional(),
1075
+ userRoles: z.array(resourceName).min(1).max(100).optional(),
1076
+ maxTtlSeconds: managedTtlSchema
1077
+ }).strict().superRefine((value, ctx) => {
1078
+ if (value.credentialType === "basic" ? !value.access || !!value.userRoles : !value.userRoles || !!value.access) ctx.addIssue({
1079
+ code: "custom",
1080
+ message: "basic credentials require access only; advanced credentials require userRoles only"
1081
+ });
1082
+ });
1083
+ // ../../packages/core/src/managed-providers/mongodb-atlas.ts
1084
+ const mongoAtlasTargetConfigSchema = z.object({
1085
+ provider: z.literal("mongodb-atlas"),
1086
+ executor: z.literal("in_do"),
1087
+ projectId: z.string().regex(/^[a-f0-9]{24}$/),
1088
+ roles: z.array(z.object({
1089
+ roleName: z.string().min(1).max(128),
1090
+ databaseName: z.string().min(1).max(64),
1091
+ collectionName: z.string().min(1).max(128).optional()
1092
+ }).strict()).min(1).max(100),
1093
+ clusters: z.array(z.string().min(1).max(64)).min(1).max(100),
1094
+ maxTtlSeconds: managedTtlSchema
1095
+ }).strict();
1096
+ // ../../packages/core/src/managed-providers/milvus.ts
1097
+ const milvusTargetConfigSchema = z.object({
1098
+ provider: z.literal("milvus"),
1099
+ executor: z.literal("in_do"),
1100
+ endpoint: managedEndpointSchema,
1101
+ roles: z.array(z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).min(1).max(50),
1102
+ maxTtlSeconds: managedTtlSchema
1103
+ }).strict();
1104
+ // ../../packages/core/src/managed-providers/rabbitmq.ts
1105
+ const rabbitmqTargetConfigSchema = z.object({
1106
+ provider: z.literal("rabbitmq"),
1107
+ executor: z.literal("in_do"),
1108
+ endpoint: managedEndpointSchema,
1109
+ vhost: z.string().min(1).max(255),
1110
+ configure: z.string().max(2048).default("^$"),
1111
+ write: z.string().max(2048).default("^$"),
1112
+ read: z.string().max(2048).default("^$"),
1113
+ maxTtlSeconds: managedTtlSchema
1114
+ }).strict();
1115
+ // ../../packages/core/src/managed-providers/clickhouse.ts
1116
+ const clickhouseTargetConfigSchema = z.object({
1117
+ provider: z.literal("clickhouse"),
1118
+ executor: z.literal("in_do"),
1119
+ endpoint: managedEndpointSchema,
1120
+ roles: z.array(nameSchema$1).min(1).max(50),
1121
+ database: nameSchema$1.optional(),
1122
+ cluster: nameSchema$1.optional(),
1123
+ maxTtlSeconds: managedTtlSchema
1124
+ }).strict();
1125
+ // ../../packages/core/src/managed-providers/elasticsearch.ts
1126
+ const role = z.object({
1127
+ cluster: z.array(z.string().min(1).max(100)).max(100).default([]),
1128
+ indices: z.array(z.object({
1129
+ names: z.array(z.string().min(1).max(256)).min(1).max(100),
1130
+ privileges: z.array(z.string().min(1).max(100)).min(1).max(100),
1131
+ allow_restricted_indices: z.literal(false).optional()
1132
+ }).strict()).max(100).default([])
1133
+ }).strict();
1134
+ const elasticsearchTargetConfigSchema = z.object({
1135
+ provider: z.literal("elasticsearch"),
1136
+ executor: z.literal("in_do"),
1137
+ endpoint: managedEndpointSchema,
1138
+ credentialType: z.enum(["user", "api_key"]).default("user"),
1139
+ roles: z.array(z.string().min(1).max(128)).min(1).max(100).optional(),
1140
+ roleDescriptors: z.record(z.string().min(1).max(128), role).refine((value) => Object.keys(value).length > 0 && Object.keys(value).length <= 20, "supply explicit key permissions").optional(),
1141
+ maxTtlSeconds: managedTtlSchema
1142
+ }).strict().superRefine((value, ctx) => {
1143
+ if (value.credentialType === "user" && !value.roles?.length) ctx.addIssue({
1144
+ code: "custom",
1145
+ path: ["roles"],
1146
+ message: "select at least one user role"
1147
+ });
1148
+ if (value.credentialType === "api_key" && !value.roleDescriptors) ctx.addIssue({
1149
+ code: "custom",
1150
+ path: ["roleDescriptors"],
1151
+ message: "supply explicit key permissions"
1152
+ });
1153
+ });
1154
+ // ../../packages/core/src/managed-leases.ts
1155
+ /** Providers whose credential is generated by the broker or upstream service. */
1156
+ const MANAGED_LEASE_KINDS = [
1157
+ ...NATIVE_LEASE_KINDS,
1158
+ "openrouter",
1159
+ "tailscale",
1160
+ "elasticsearch",
1161
+ "clickhouse",
1162
+ "rabbitmq",
1163
+ "milvus",
1164
+ "mongodb-atlas",
1165
+ "couchbase",
1166
+ "snowflake",
1167
+ "elasticache",
1168
+ "memorydb",
1169
+ "mssql",
1170
+ "azure-sql"
1171
+ ];
1172
+ const openRouterTargetConfigSchema = z.object({
1173
+ provider: z.literal("openrouter"),
1174
+ executor: z.literal("in_do"),
1175
+ workspaceId: z.string().uuid().optional(),
1176
+ creditLimit: z.number().finite().nonnegative(),
1177
+ limitReset: z.enum([
1178
+ "daily",
1179
+ "weekly",
1180
+ "monthly"
1181
+ ]).optional(),
1182
+ includeByokInLimit: z.boolean().optional(),
1183
+ maxTtlSeconds: z.number().int().min(60).max(604800).optional()
1184
+ }).strict();
1185
+ const tailscaleTargetConfigSchema = z.object({
1186
+ provider: z.literal("tailscale"),
1187
+ executor: z.literal("in_do"),
1188
+ tailnet: z.string().min(1).max(253).regex(/^[a-zA-Z0-9@._-]+$/),
1189
+ credentialType: z.enum([
1190
+ "auth",
1191
+ "client",
1192
+ "federated"
1193
+ ]),
1194
+ tags: z.array(z.string().regex(/^tag:[a-zA-Z0-9_-]+$/)).max(100).default([]),
1195
+ reusable: z.boolean().default(false),
1196
+ ephemeral: z.boolean().default(true),
1197
+ preauthorized: z.boolean().default(false),
1198
+ scopes: z.array(z.string().min(1).max(128)).max(100).default([]),
1199
+ issuer: z.string().url().optional(),
1200
+ audience: z.string().min(1).max(2048).optional(),
1201
+ subject: z.string().min(1).max(2048).optional(),
1202
+ maxTtlSeconds: z.number().int().min(60).max(604800).optional()
1203
+ }).strict().superRefine((value, ctx) => {
1204
+ if (value.credentialType !== "auth" && !value.scopes.length) ctx.addIssue({
1205
+ code: "custom",
1206
+ path: ["scopes"],
1207
+ message: "select at least one scope"
1208
+ });
1209
+ if (value.credentialType === "federated" && (!value.issuer?.startsWith("https://") || !value.audience || !value.subject)) ctx.addIssue({
1210
+ code: "custom",
1211
+ path: ["issuer"],
1212
+ message: "federation requires HTTPS issuer, audience, and subject"
1213
+ });
1214
+ });
1215
+ const hostedManagedTargetConfigSchema = z.discriminatedUnion("provider", [
1216
+ clickhouseTargetConfigSchema,
1217
+ rabbitmqTargetConfigSchema,
1218
+ milvusTargetConfigSchema,
1219
+ mongoAtlasTargetConfigSchema,
1220
+ couchbaseTargetConfigSchema,
1221
+ snowflakeTargetConfigSchema,
1222
+ elasticacheTargetConfigSchema,
1223
+ memorydbTargetConfigSchema,
1224
+ openRouterTargetConfigSchema,
1225
+ tailscaleTargetConfigSchema,
1226
+ elasticsearchTargetConfigSchema
1227
+ ]);
1228
+ function hasLocalServiceEndpoint(provider) {
1229
+ return [
1230
+ "milvus",
1231
+ "rabbitmq",
1232
+ "clickhouse",
1233
+ "elasticsearch"
1234
+ ].includes(provider);
1235
+ }
1236
+ /** Reuse the provider's existing permission validation without accepting a
1237
+ * remotely supplied destination for a locally held administrator credential. */
1238
+ function customerSettingsAsHosted(provider, settings) {
1239
+ const endpoint = typeof settings.endpoint === "string" ? settings.endpoint : void 0;
1240
+ if (hasLocalServiceEndpoint(provider) && endpoint !== void 0) {
1241
+ const url = new URL(z.string().parse(endpoint));
1242
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new Error("Use an HTTPS service endpoint without credentials.");
1243
+ }
1244
+ const normalized = hostedManagedTargetConfigSchema.parse({
1245
+ ...settings,
1246
+ provider,
1247
+ executor: "in_do",
1248
+ ...hasLocalServiceEndpoint(provider) ? { endpoint: "https://customer-service.example.com" } : {}
1249
+ });
1250
+ return endpoint === void 0 ? normalized : {
1251
+ ...normalized,
1252
+ endpoint
1253
+ };
1254
+ }
1255
+ const mssqlSettingsSchema = z.object({ roles: z.array(z.string().min(1).max(128).refine((role) => !role.includes("\0"))).min(1).max(100).refine((roles) => new Set(roles).size === roles.length, "roles must be unique") }).strict();
1256
+ function normalizeCustomerSettings(provider, settings) {
1257
+ return provider === "mssql" || provider === "azure-sql" ? mssqlSettingsSchema.parse(settings) : isNativeLeaseKind(provider) ? nativeSettings(provider, settings) : customerSettingsAsHosted(provider, settings);
1258
+ }
1259
+ /** Permissions remain configured in Seekrit; destination and admin secret stay local. */
1260
+ const remoteManagedTargetConfigSchema = z.object({
1261
+ provider: z.enum(MANAGED_LEASE_KINDS),
1262
+ executor: z.literal("remote"),
1263
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
1264
+ transport: z.enum(["push", "pull"]).default("push"),
1265
+ provisionerUrl: managedEndpointSchema.optional(),
1266
+ settings: z.record(z.string(), z.unknown()),
1267
+ maxTtlSeconds: managedTtlSchema
1268
+ }).strict().superRefine((config, ctx) => {
1269
+ if (config.provider === "azure-sql" && !config.provisionerId) ctx.addIssue({
1270
+ code: "custom",
1271
+ path: ["provisionerId"],
1272
+ message: "Register a provisioner for Azure SQL execution."
1273
+ });
1274
+ if (!config.provisionerId && config.transport === "push" && !config.provisionerUrl) ctx.addIssue({
1275
+ code: "custom",
1276
+ path: ["provisionerUrl"],
1277
+ message: "HTTPS mode requires a provisioner URL"
1278
+ });
1279
+ if (config.transport === "pull" && config.provisionerUrl) ctx.addIssue({
1280
+ code: "custom",
1281
+ path: ["provisionerUrl"],
1282
+ message: "outbound mode does not use a provisioner URL"
1283
+ });
1284
+ if ([
1285
+ "provider",
1286
+ "executor",
1287
+ "maxTtlSeconds"
1288
+ ].some((key) => key in config.settings)) {
1289
+ ctx.addIssue({
1290
+ code: "custom",
1291
+ path: ["settings"],
1292
+ message: "settings contain a reserved field"
1293
+ });
1294
+ return;
1295
+ }
1296
+ if (config.provider === "kubernetes" && config.maxTtlSeconds !== void 0 && config.maxTtlSeconds < 900) ctx.addIssue({
1297
+ code: "custom",
1298
+ path: ["maxTtlSeconds"],
1299
+ message: "Kubernetes requires at least 15 minutes."
1300
+ });
1301
+ try {
1302
+ if (!config.provisionerId && config.settings.endpoint !== void 0) throw new Error("Register a provisioner to configure its endpoint in Seekrit.");
1303
+ if (config.provisionerId && hasLocalServiceEndpoint(config.provider) && !config.settings.endpoint) throw new Error("Configure the service endpoint in Seekrit.");
1304
+ if (isNativeLeaseKind(config.provider) && !config.provisionerId) throw new Error("Select a registered customer provisioner.");
1305
+ normalizeCustomerSettings(config.provider, config.settings);
1306
+ } catch (error) {
1307
+ if (error instanceof z.ZodError) for (const issue of error.issues) ctx.addIssue({
1308
+ code: "custom",
1309
+ path: ["settings", ...issue.path],
1310
+ message: issue.message
1311
+ });
1312
+ else ctx.addIssue({
1313
+ code: "custom",
1314
+ path: ["settings"],
1315
+ message: "invalid service settings"
1316
+ });
1317
+ }
1318
+ }).transform((config) => {
1319
+ const normalized = normalizeCustomerSettings(config.provider, config.settings);
1320
+ return {
1321
+ ...config,
1322
+ settings: Object.fromEntries(Object.entries(normalized).filter(([key]) => ![
1323
+ "provider",
1324
+ "executor",
1325
+ "maxTtlSeconds"
1326
+ ].includes(key) && (key !== "endpoint" || config.settings.endpoint !== void 0)))
1327
+ };
1328
+ });
1329
+ const managedTargetConfigSchema = z.union([hostedManagedTargetConfigSchema, remoteManagedTargetConfigSchema]);
1330
+ const id = z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/);
1331
+ const timestamp = z.number().int().nonnegative().safe();
1332
+ const provisionerPrincipalSchema = z.object({
1333
+ type: z.enum(["user", "service_token"]),
1334
+ id,
1335
+ publicKeyJwk: z.string().min(1).max(1024)
1336
+ }).strict();
1337
+ const provisionerBootstrapSchema = z.object({
1338
+ version: z.literal(1),
1339
+ orgId: id,
1340
+ provisionerId: id,
1341
+ authority: provisionerPrincipalSchema,
1342
+ createdAt: timestamp
1343
+ }).strict();
1344
+ const provisionerGrantSchema = z.object({
1345
+ version: z.literal(1),
1346
+ id,
1347
+ orgId: id,
1348
+ provisionerId: id,
1349
+ principal: provisionerPrincipalSchema,
1350
+ targets: z.array(id.or(z.literal("*"))).min(1).max(100),
1351
+ manage: z.boolean(),
1352
+ issuedAt: timestamp,
1353
+ expiresAt: timestamp
1354
+ }).strict();
1355
+ const provisionerChainSchema = z.object({
1356
+ bootstrap: z.string().max(4096).startsWith("pb1."),
1357
+ grants: z.array(z.string().max(4096).startsWith("pg1.")).max(3)
1358
+ }).strict();
1359
+ z.object({
1360
+ version: z.literal(1),
1361
+ orgId: id,
1362
+ provisionerId: id,
1363
+ targetId: id,
1364
+ provider: id,
1365
+ leaseId: id,
1366
+ instanceId: id,
1367
+ nonce: id,
1368
+ targetDigest: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
1369
+ action: z.unknown(),
1370
+ recipientPublicKey: z.string().max(1024).optional(),
1371
+ issuedAt: timestamp,
1372
+ expiresAt: timestamp
1373
+ }).strict();
1374
+ const provisionerAuthorizationSchema = provisionerChainSchema.extend({ proof: z.string().max(16384).startsWith("pr1.") });
1375
+ const utf8 = new TextEncoder();
1376
+ function b64(bytes) {
1377
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
1378
+ }
1379
+ function unb64(value) {
1380
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid authorization encoding");
1381
+ return Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/")), (c) => c.charCodeAt(0));
1382
+ }
1383
+ function readProvisionerEnvelope(envelope, prefix) {
1384
+ const parts = envelope.split(".");
1385
+ if (envelope.length > 16384 || parts.length !== 3 || parts[0] !== prefix) throw new Error("Invalid customer authorization envelope");
1386
+ return JSON.parse(new TextDecoder("utf-8", {
1387
+ fatal: true,
1388
+ ignoreBOM: false
1389
+ }).decode(unb64(parts[1] ?? "")));
1390
+ }
1391
+ function provisionerPublicKey(value) {
1392
+ const jwk = JSON.parse(value);
1393
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256" || !jwk.x || !jwk.y || jwk.d) throw new Error("Customer authorization requires a public P-256 key");
1394
+ return {
1395
+ kty: "EC",
1396
+ crv: "P-256",
1397
+ x: jwk.x,
1398
+ y: jwk.y
1399
+ };
1400
+ }
1401
+ async function signProvisionerEnvelope(prefix, key, payload) {
1402
+ const encoded = b64(utf8.encode(JSON.stringify(payload)));
1403
+ const signature = await crypto.subtle.sign({
1404
+ name: "ECDSA",
1405
+ hash: "SHA-256"
1406
+ }, key, utf8.encode(`${prefix}\n${encoded}`));
1407
+ return `${prefix}.${encoded}.${b64(new Uint8Array(signature))}`;
1408
+ }
1409
+ async function verifyProvisionerEnvelope(envelope, prefix, publicKeyJwk) {
1410
+ const payload = readProvisionerEnvelope(envelope, prefix);
1411
+ const [, encoded, signature] = envelope.split(".");
1412
+ const key = await crypto.subtle.importKey("jwk", provisionerPublicKey(publicKeyJwk), {
1413
+ name: "ECDSA",
1414
+ namedCurve: "P-256"
1415
+ }, false, ["verify"]);
1416
+ if (!await crypto.subtle.verify({
1417
+ name: "ECDSA",
1418
+ hash: "SHA-256"
1419
+ }, key, unb64(signature ?? ""), utf8.encode(`${prefix}\n${encoded}`))) throw new Error("Invalid customer authorization signature");
1420
+ return payload;
1421
+ }
1422
+ /** The API compares bootstrap to its registration; the Rust service additionally
1423
+ * verifies its MAC with a root-derived key unavailable to the API. */
1424
+ async function verifyProvisionerChain(chain, orgId, provisionerId, now = Date.now()) {
1425
+ provisionerChainSchema.parse(chain);
1426
+ const root = provisionerBootstrapSchema.parse(readProvisionerEnvelope(chain.bootstrap, "pb1"));
1427
+ if (root.orgId !== orgId || root.provisionerId !== provisionerId || root.authority.type !== "user") throw new Error("Customer authorization belongs to another provisioner");
1428
+ provisionerPublicKey(root.authority.publicKeyJwk);
1429
+ let access = {
1430
+ principal: root.authority,
1431
+ targets: ["*"],
1432
+ manage: true,
1433
+ expiresAt: Number.MAX_SAFE_INTEGER,
1434
+ chain
1435
+ };
1436
+ for (const envelope of chain.grants) {
1437
+ if (!access.manage) throw new Error("This permission cannot delegate access");
1438
+ const grant = provisionerGrantSchema.parse(await verifyProvisionerEnvelope(envelope, "pg1", access.principal.publicKeyJwk));
1439
+ if (grant.orgId !== orgId || grant.provisionerId !== provisionerId || grant.issuedAt > now + 3e5 || grant.expiresAt <= now || grant.expiresAt <= grant.issuedAt || grant.expiresAt - grant.issuedAt > 7776e6 || grant.expiresAt > access.expiresAt || !grant.targets.every((t) => access.targets.includes("*") || access.targets.includes(t)) || grant.manage && grant.principal.type !== "user") throw new Error("Expired or invalid customer access grant");
1440
+ provisionerPublicKey(grant.principal.publicKeyJwk);
1441
+ access = {
1442
+ principal: grant.principal,
1443
+ targets: grant.targets,
1444
+ manage: grant.manage,
1445
+ expiresAt: grant.expiresAt,
1446
+ chain
1447
+ };
1448
+ }
1449
+ return access;
1450
+ }
1451
+ /** Targets carry their templates inside encrypted configuration. */
1452
+ function provisionerTransportAction(action) {
1453
+ if (action.kind === "sql") return {
1454
+ kind: "sql",
1455
+ statements: [],
1456
+ parameters: action.parameters
1457
+ };
1458
+ if (action.kind === "ssh-sign") return action;
1459
+ return { kind: "noop" };
1460
+ }
714
1461
  z.enum([
715
1462
  "postgres",
716
1463
  "mysql",
@@ -718,7 +1465,8 @@ z.enum([
718
1465
  "redis",
719
1466
  "aws",
720
1467
  "gcp",
721
- "mongodb"
1468
+ "mongodb",
1469
+ ...MANAGED_LEASE_KINDS
722
1470
  ]);
723
1471
  const executorModeSchema = z.enum(["in_do", "remote"]);
724
1472
  /**
@@ -787,7 +1535,12 @@ const awsRegionSchema$1 = z.string().regex(/^[a-z]{2}(?:-[a-z]+)+-\d$/, "must be
787
1535
  * documented safe set and bound the length.
788
1536
  */
789
1537
  const awsExternalIdSchema = z.string().regex(/^[\w+=,.@:/-]{2,1224}$/, "must be a valid STS external id");
790
- z.string().regex(/^[\w+=,.@-]{2,64}$/, "must be 2–64 chars of [A-Za-z0-9_+=,.@-]");
1538
+ /**
1539
+ * An STS session name stamped onto the assumed-role credential (and surfaced in
1540
+ * CloudTrail). We derive it from the lease id, so this is a sanity gate matching
1541
+ * the AWS-documented pattern.
1542
+ */
1543
+ const awsRoleSessionNameSchema = z.string().regex(/^[\w+=,.@-]{2,64}$/, "must be 2–64 chars of [A-Za-z0-9_+=,.@-]");
791
1544
  /**
792
1545
  * A GCP service-account email the broker is allowed to impersonate (or that
793
1546
  * appears in a delegation chain). Structurally validated and bounded: it is
@@ -818,7 +1571,14 @@ const p256PublicKeyJwkSchema = z.string().max(2048).refine((s) => {
818
1571
  return false;
819
1572
  }
820
1573
  }, "must be a JWK-serialized P-256 public key");
821
- z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, "must be 1–64 chars of [A-Za-z0-9_-]");
1574
+ /**
1575
+ * A MongoDB user name. Derived from the lease id (so it's server-chosen, not
1576
+ * user input), but validated as a strict token anyway: MongoDB user documents
1577
+ * are structured BSON — there is no string interpolation to inject into — yet a
1578
+ * bounded `[A-Za-z0-9_.-]` name keeps the created principal readable in
1579
+ * `db.getUsers()` and free of the `.`/`$` characters Mongo reserves.
1580
+ */
1581
+ const mongoUserNameSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, "must be 1–64 chars of [A-Za-z0-9_-]");
822
1582
  /**
823
1583
  * A MongoDB database name — the db a preset role is granted on, or the
824
1584
  * authentication database a leased user is created in. MongoDB forbids
@@ -839,6 +1599,11 @@ const postgresAccessLevelSchema = z.enum([
839
1599
  "readwrite",
840
1600
  "custom"
841
1601
  ]);
1602
+ /** The group role each preset's leased credentials inherit. */
1603
+ const POSTGRES_GROUP_ROLES = {
1604
+ readonly: "seekrit_readonly",
1605
+ readwrite: "seekrit_readwrite"
1606
+ };
842
1607
  const mysqlAccessLevelSchema = z.enum([
843
1608
  "readonly",
844
1609
  "readwrite",
@@ -854,6 +1619,11 @@ const mongoAccessLevelSchema = z.enum([
854
1619
  "readwrite",
855
1620
  "custom"
856
1621
  ]);
1622
+ /** The built-in MongoDB role each preset grants on the target database. */
1623
+ const MONGO_PRESET_ROLES = {
1624
+ readonly: "read",
1625
+ readwrite: "readWrite"
1626
+ };
857
1627
  const connectionSchema = z.object({
858
1628
  host: z.string().min(1),
859
1629
  port: z.number().int().min(1).max(65535),
@@ -864,6 +1634,8 @@ const statementSchema$1 = z.string().min(1).max(4e3);
864
1634
  /** A bare SQL identifier (schema name) — no quotes/whitespace/semicolons. */
865
1635
  const identifierSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/, "must be an identifier");
866
1636
  const postgresTargetConfigSchema = z.object({
1637
+ tls: z.boolean().optional(),
1638
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
867
1639
  provider: z.literal("postgres"),
868
1640
  executor: executorModeSchema,
869
1641
  accessLevel: postgresAccessLevelSchema.optional(),
@@ -876,6 +1648,8 @@ const postgresTargetConfigSchema = z.object({
876
1648
  /** A MySQL account host part (`'name'@'<host>'`) — no quotes/whitespace. */
877
1649
  const mysqlHostSchema$1 = z.string().regex(/^[A-Za-z0-9_.%:-]{1,255}$/, "must be a host pattern");
878
1650
  const mysqlTargetConfigSchema = z.object({
1651
+ tls: z.boolean().optional(),
1652
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
879
1653
  provider: z.literal("mysql"),
880
1654
  executor: executorModeSchema,
881
1655
  accessLevel: mysqlAccessLevelSchema.optional(),
@@ -892,6 +1666,7 @@ const redisConnectionSchema = z.object({
892
1666
  db: z.number().int().min(0).max(15).optional()
893
1667
  });
894
1668
  const redisTargetConfigSchema = z.object({
1669
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
895
1670
  provider: z.literal("redis"),
896
1671
  executor: executorModeSchema,
897
1672
  accessLevel: redisAccessLevelSchema.optional(),
@@ -901,8 +1676,9 @@ const redisTargetConfigSchema = z.object({
901
1676
  revokeStatements: z.array(statementSchema$1).max(16).optional()
902
1677
  });
903
1678
  const sshTargetConfigSchema = z.object({
1679
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
904
1680
  provider: z.literal("ssh"),
905
- executor: z.literal("in_do"),
1681
+ executor: executorModeSchema,
906
1682
  caPublicKey: sshPublicKeySchema,
907
1683
  allowedPrincipals: z.array(sshPrincipalSchema).max(64).optional(),
908
1684
  extensions: z.array(sshExtensionSchema).max(16).optional(),
@@ -914,8 +1690,9 @@ const sshTargetConfigSchema = z.object({
914
1690
  });
915
1691
  const AWS_MAX_TTL_SECONDS = 43200;
916
1692
  const awsTargetConfigSchema = z.object({
1693
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
917
1694
  provider: z.literal("aws"),
918
- executor: z.literal("in_do"),
1695
+ executor: executorModeSchema,
919
1696
  roleArn: awsRoleArnSchema,
920
1697
  region: awsRegionSchema$1,
921
1698
  externalId: awsExternalIdSchema.optional(),
@@ -924,16 +1701,18 @@ const awsTargetConfigSchema = z.object({
924
1701
  });
925
1702
  const GCP_MAX_TTL_SECONDS = 43200;
926
1703
  const gcpTargetConfigSchema = z.object({
1704
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
927
1705
  provider: z.literal("gcp"),
928
- executor: z.literal("in_do"),
1706
+ executor: executorModeSchema,
929
1707
  serviceAccount: gcpServiceAccountEmailSchema,
930
1708
  scopes: z.array(gcpOauthScopeSchema).min(1).max(32).optional(),
931
1709
  delegates: z.array(gcpServiceAccountEmailSchema).max(8).optional(),
932
1710
  maxTtlSeconds: z.number().int().min(60).max(GCP_MAX_TTL_SECONDS).optional()
933
1711
  });
934
1712
  const mongoTargetConfigSchema = z.object({
1713
+ provisionerId: z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/).optional(),
935
1714
  provider: z.literal("mongodb"),
936
- executor: z.literal("in_do"),
1715
+ executor: executorModeSchema,
937
1716
  accessLevel: mongoAccessLevelSchema.optional(),
938
1717
  connection: connectionSchema,
939
1718
  authSource: mongoDatabaseNameSchema.optional(),
@@ -941,16 +1720,34 @@ const mongoTargetConfigSchema = z.object({
941
1720
  tls: z.boolean().optional(),
942
1721
  maxTtlSeconds: z.number().int().min(60).max(604800).optional()
943
1722
  });
944
- const leaseTargetConfigSchema = z.discriminatedUnion("provider", [
1723
+ const leaseTargetConfigSchema = z.union([
945
1724
  postgresTargetConfigSchema,
946
1725
  mysqlTargetConfigSchema,
947
1726
  redisTargetConfigSchema,
948
1727
  sshTargetConfigSchema,
949
1728
  awsTargetConfigSchema,
950
1729
  gcpTargetConfigSchema,
951
- mongoTargetConfigSchema
952
- ]);
1730
+ mongoTargetConfigSchema,
1731
+ managedTargetConfigSchema
1732
+ ]).superRefine((config, ctx) => {
1733
+ if (config.executor === "remote" && [
1734
+ "ssh",
1735
+ "aws",
1736
+ "gcp",
1737
+ "mongodb"
1738
+ ].includes(config.provider) && !("provisionerId" in config && config.provisionerId)) ctx.addIssue({
1739
+ code: "custom",
1740
+ path: ["provisionerId"],
1741
+ message: "Select a registered customer provisioner."
1742
+ });
1743
+ if ("provisionerId" in config && config.provisionerId && config.executor !== "remote") ctx.addIssue({
1744
+ code: "custom",
1745
+ path: ["executor"],
1746
+ message: "A provisioner target must run in your network."
1747
+ });
1748
+ });
953
1749
  z.object({
1750
+ id: z.string().regex(/^lt_[A-Za-z0-9_-]{24}$/).optional(),
954
1751
  name: z.string().trim().min(1).max(128),
955
1752
  config: leaseTargetConfigSchema,
956
1753
  /**
@@ -959,7 +1756,7 @@ z.object({
959
1756
  * control plane stores only this ciphertext — it never sees the plaintext.
960
1757
  */
961
1758
  wrappedAdminSecret: z.string().min(1)
962
- });
1759
+ }).refine((v) => !("provisionerId" in v.config && v.config.provisionerId) || v.wrappedAdminSecret.startsWith("wd1.") && v.wrappedAdminSecret.length <= 49152, "Encrypted provisioner configuration must be a wd1 blob no larger than 48 KiB");
963
1760
  /** Requested lease lifetime, shared by all providers. */
964
1761
  const ttlSecondsSchema = z.number().int().min(60).max(604800);
965
1762
  /**
@@ -970,6 +1767,7 @@ const ttlSecondsSchema = z.number().int().min(60).max(604800);
970
1767
  const mintPostgresLeaseSchema = z.object({
971
1768
  provider: z.literal("postgres"),
972
1769
  targetId: z.string().min(1),
1770
+ authorization: provisionerAuthorizationSchema.optional(),
973
1771
  roleName: postgresRoleNameSchema,
974
1772
  verifier: scramVerifierSchema,
975
1773
  ttlSeconds: ttlSecondsSchema
@@ -982,6 +1780,7 @@ const mintPostgresLeaseSchema = z.object({
982
1780
  const mintMysqlLeaseSchema = z.object({
983
1781
  provider: z.literal("mysql"),
984
1782
  targetId: z.string().min(1),
1783
+ authorization: provisionerAuthorizationSchema.optional(),
985
1784
  roleName: mysqlUserNameSchema,
986
1785
  verifier: mysqlNativeVerifierSchema,
987
1786
  ttlSeconds: ttlSecondsSchema
@@ -994,6 +1793,7 @@ const mintMysqlLeaseSchema = z.object({
994
1793
  const mintRedisLeaseSchema = z.object({
995
1794
  provider: z.literal("redis"),
996
1795
  targetId: z.string().min(1),
1796
+ authorization: provisionerAuthorizationSchema.optional(),
997
1797
  roleName: redisUserNameSchema,
998
1798
  verifier: redisSha256VerifierSchema,
999
1799
  ttlSeconds: ttlSecondsSchema
@@ -1006,6 +1806,7 @@ const mintRedisLeaseSchema = z.object({
1006
1806
  const mintSshLeaseSchema = z.object({
1007
1807
  provider: z.literal("ssh"),
1008
1808
  targetId: z.string().min(1),
1809
+ authorization: provisionerAuthorizationSchema.optional(),
1009
1810
  publicKey: sshPublicKeySchema,
1010
1811
  principals: z.array(sshPrincipalSchema).min(1).max(32),
1011
1812
  ttlSeconds: ttlSecondsSchema
@@ -1022,6 +1823,7 @@ const mintSshLeaseSchema = z.object({
1022
1823
  const mintAwsLeaseSchema = z.object({
1023
1824
  provider: z.literal("aws"),
1024
1825
  targetId: z.string().min(1),
1826
+ authorization: provisionerAuthorizationSchema.optional(),
1025
1827
  recipientPublicKey: p256PublicKeyJwkSchema,
1026
1828
  ttlSeconds: z.number().int().min(900).max(AWS_MAX_TTL_SECONDS)
1027
1829
  });
@@ -1038,6 +1840,7 @@ const mintAwsLeaseSchema = z.object({
1038
1840
  const mintGcpLeaseSchema = z.object({
1039
1841
  provider: z.literal("gcp"),
1040
1842
  targetId: z.string().min(1),
1843
+ authorization: provisionerAuthorizationSchema.optional(),
1041
1844
  recipientPublicKey: p256PublicKeyJwkSchema,
1042
1845
  ttlSeconds: z.number().int().min(60).max(GCP_MAX_TTL_SECONDS)
1043
1846
  });
@@ -1051,9 +1854,23 @@ const mintGcpLeaseSchema = z.object({
1051
1854
  const mintMongoLeaseSchema = z.object({
1052
1855
  provider: z.literal("mongodb"),
1053
1856
  targetId: z.string().min(1),
1857
+ authorization: provisionerAuthorizationSchema.optional(),
1054
1858
  recipientPublicKey: p256PublicKeyJwkSchema,
1055
1859
  ttlSeconds: ttlSecondsSchema
1056
1860
  });
1861
+ const mintManagedLeaseSchema = z.object({
1862
+ provider: z.enum(MANAGED_LEASE_KINDS),
1863
+ targetId: z.string().min(1),
1864
+ authorization: provisionerAuthorizationSchema.optional(),
1865
+ recipientPublicKey: p256PublicKeyJwkSchema.refine((value) => {
1866
+ try {
1867
+ return !("d" in JSON.parse(value));
1868
+ } catch {
1869
+ return false;
1870
+ }
1871
+ }, "send only a public key"),
1872
+ ttlSeconds: ttlSecondsSchema
1873
+ });
1057
1874
  z.discriminatedUnion("provider", [
1058
1875
  mintPostgresLeaseSchema,
1059
1876
  mintMysqlLeaseSchema,
@@ -1061,10 +1878,648 @@ z.discriminatedUnion("provider", [
1061
1878
  mintSshLeaseSchema,
1062
1879
  mintAwsLeaseSchema,
1063
1880
  mintGcpLeaseSchema,
1064
- mintMongoLeaseSchema
1881
+ mintMongoLeaseSchema,
1882
+ mintManagedLeaseSchema
1065
1883
  ]);
1066
- //#endregion
1067
- //#region ../../packages/core/src/types.ts
1884
+ // ../../packages/core/src/providers/aws.ts
1885
+ /**
1886
+ * Tier-2 AWS provider. Unlike the verifier-injection providers, the target
1887
+ * (AWS/STS) mints the credential itself, so `render` cannot produce a
1888
+ * zero-knowledge verifier — instead it produces an {@link AwsStsSpec} the broker
1889
+ * executor runs: assume `roleArn` via STS, then wrap the returned credential to
1890
+ * the consumer's ephemeral public key before returning it. `render` stays pure
1891
+ * and secret-free (it never touches the admin credential or the network); the
1892
+ * consumer's private key never leaves their machine, so the plaintext
1893
+ * credential is only ever decryptable there.
1894
+ *
1895
+ * Revocation is a no-op: STS session credentials can't be revoked individually,
1896
+ * so v1 relies on the short `DurationSeconds` STS itself enforces — exactly like
1897
+ * the SSH provider's short-TTL certificates.
1898
+ */
1899
+ /** Clamp a requested TTL into STS's `DurationSeconds` window and the target's cap. */
1900
+ function clampDuration(requested, maxTtlSeconds) {
1901
+ return Math.max(900, Math.min(requested, Math.min(maxTtlSeconds ?? 43200, AWS_MAX_TTL_SECONDS)));
1902
+ }
1903
+ const awsProvider = {
1904
+ kind: "aws",
1905
+ zkTier: 2,
1906
+ render(config, req, ctx) {
1907
+ if (req.provider !== "aws") throw new Error("aws provider received a non-aws request");
1908
+ const cfg = config;
1909
+ awsRoleArnSchema.parse(cfg.roleArn);
1910
+ p256PublicKeyJwkSchema.parse(req.recipientPublicKey);
1911
+ const roleSessionName = awsRoleSessionNameSchema.parse(ctx.leaseId);
1912
+ const durationSeconds = clampDuration(req.ttlSeconds, cfg.maxTtlSeconds);
1913
+ return {
1914
+ resourceRef: roleSessionName,
1915
+ expiresAt: new Date(ctx.nowMs + durationSeconds * 1e3).toISOString(),
1916
+ provision: {
1917
+ kind: "aws-sts",
1918
+ spec: {
1919
+ roleArn: cfg.roleArn,
1920
+ roleSessionName,
1921
+ durationSeconds,
1922
+ region: cfg.region,
1923
+ externalId: cfg.externalId,
1924
+ policy: cfg.sessionPolicy,
1925
+ recipientPublicKey: req.recipientPublicKey
1926
+ }
1927
+ },
1928
+ revoke: { kind: "noop" }
1929
+ };
1930
+ },
1931
+ renderRevoke() {
1932
+ return { kind: "noop" };
1933
+ }
1934
+ };
1935
+ // ../../packages/core/src/providers/gcp.ts
1936
+ /**
1937
+ * Tier-2 GCP provider. Like {@link awsProvider}, the target (GCP's IAM
1938
+ * Credentials API) mints the credential itself, so `render` cannot produce a
1939
+ * zero-knowledge verifier — instead it produces a {@link GcpImpersonateSpec} the
1940
+ * broker executor runs: impersonate `serviceAccount` via `generateAccessToken`,
1941
+ * then wrap the returned OAuth token to the consumer's ephemeral public key
1942
+ * before returning it. `render` stays pure and secret-free (it never touches the
1943
+ * admin key or the network); the consumer's private key never leaves their
1944
+ * machine, so the plaintext token is only ever decryptable there.
1945
+ *
1946
+ * Revocation is a no-op: short-lived access tokens can't be revoked
1947
+ * individually, so v1 relies on the short `lifetime` GCP itself enforces —
1948
+ * exactly like the AWS and SSH providers.
1949
+ */
1950
+ /** The default scope when a target sets none — full API access, IAM-scoped. */
1951
+ const GCP_DEFAULT_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
1952
+ /** Clamp a requested TTL into GCP's `lifetime` window and the target's cap. */
1953
+ function clampLifetime(requested, maxTtlSeconds) {
1954
+ return Math.max(60, Math.min(requested, Math.min(maxTtlSeconds ?? 43200, GCP_MAX_TTL_SECONDS)));
1955
+ }
1956
+ const gcpProvider = {
1957
+ kind: "gcp",
1958
+ zkTier: 2,
1959
+ render(config, req, ctx) {
1960
+ if (req.provider !== "gcp") throw new Error("gcp provider received a non-gcp request");
1961
+ const cfg = config;
1962
+ gcpServiceAccountEmailSchema.parse(cfg.serviceAccount);
1963
+ p256PublicKeyJwkSchema.parse(req.recipientPublicKey);
1964
+ const scopes = cfg.scopes?.length ? cfg.scopes : [GCP_DEFAULT_SCOPE];
1965
+ for (const scope of scopes) gcpOauthScopeSchema.parse(scope);
1966
+ const lifetimeSeconds = clampLifetime(req.ttlSeconds, cfg.maxTtlSeconds);
1967
+ const expiresAt = new Date(ctx.nowMs + lifetimeSeconds * 1e3).toISOString();
1968
+ return {
1969
+ resourceRef: cfg.serviceAccount,
1970
+ expiresAt,
1971
+ provision: {
1972
+ kind: "gcp-iam",
1973
+ spec: {
1974
+ serviceAccount: cfg.serviceAccount,
1975
+ scopes,
1976
+ lifetimeSeconds,
1977
+ delegates: cfg.delegates,
1978
+ recipientPublicKey: req.recipientPublicKey
1979
+ }
1980
+ },
1981
+ revoke: { kind: "noop" }
1982
+ };
1983
+ },
1984
+ renderRevoke() {
1985
+ return { kind: "noop" };
1986
+ }
1987
+ };
1988
+ // ../../packages/core/src/providers/managed.ts
1989
+ function managedLeaseProvider(kind) {
1990
+ return {
1991
+ kind,
1992
+ zkTier: 2,
1993
+ render(target, request, context) {
1994
+ const config = managedTargetConfigSchema.parse(target);
1995
+ if (config.provider !== kind || request.provider !== kind || !("recipientPublicKey" in request)) throw new Error("managed credential provider mismatch");
1996
+ p256PublicKeyJwkSchema.parse(request.recipientPublicKey);
1997
+ const name = `sk_${context.leaseId}`;
1998
+ if (!/^sk_[a-zA-Z0-9_-]{1,64}$/.test(name)) throw new Error("invalid lease id");
1999
+ const ttl = Math.min(request.ttlSeconds, config.maxTtlSeconds ?? 604800);
2000
+ if (kind === "kubernetes" && ttl < 900) throw new Error("Kubernetes leases require at least 15 minutes.");
2001
+ const expiresAt = new Date(context.nowMs + ttl * 1e3).toISOString();
2002
+ const spec = {
2003
+ config,
2004
+ name,
2005
+ expiresAt,
2006
+ recipientPublicKey: request.recipientPublicKey
2007
+ };
2008
+ return {
2009
+ resourceRef: name,
2010
+ expiresAt,
2011
+ provision: {
2012
+ kind: "managed-credential",
2013
+ spec
2014
+ },
2015
+ revoke: {
2016
+ kind: "managed-credential",
2017
+ spec: {
2018
+ ...spec,
2019
+ recipientPublicKey: ""
2020
+ }
2021
+ }
2022
+ };
2023
+ },
2024
+ renderRevoke(target, resourceRef) {
2025
+ const config = managedTargetConfigSchema.parse(target);
2026
+ if (config.provider !== kind || !/^sk_[a-zA-Z0-9_-]{1,64}$/.test(resourceRef)) throw new Error("invalid managed credential revoke");
2027
+ return {
2028
+ kind: "managed-credential",
2029
+ spec: {
2030
+ config,
2031
+ name: resourceRef,
2032
+ recipientPublicKey: "",
2033
+ expiresAt: ""
2034
+ }
2035
+ };
2036
+ }
2037
+ };
2038
+ }
2039
+ // ../../packages/core/src/providers/mongodb.ts
2040
+ /**
2041
+ * Tier-2 MongoDB provider. Unlike the verifier-injection providers, MongoDB's
2042
+ * `createUser` hashes the password *server-side* (there is no supported path to
2043
+ * inject a precomputed SCRAM credential), so `render` cannot produce a
2044
+ * zero-knowledge verifier. Instead it produces a {@link MongoUserSpec} the
2045
+ * broker executor runs: generate a password, `createUser` with the preset
2046
+ * roles, then wrap the credential to the consumer's ephemeral public key before
2047
+ * returning it. `render` stays pure and secret-free — it never generates the
2048
+ * password, touches the admin credential, or hits the network; the consumer's
2049
+ * private key never leaves their machine, so the plaintext credential is only
2050
+ * ever decryptable there.
2051
+ *
2052
+ * Revocation is real (unlike AWS/SSH): the broker's alarm-driven `dropUser` ends
2053
+ * the lease. Access levels map to MongoDB's built-in roles — `read` /
2054
+ * `readWrite` on the target database — or an explicit `roles` array for custom.
2055
+ */
2056
+ /** Clamp a requested TTL to the target's optional cap. */
2057
+ function clampTtl(requested, maxTtlSeconds) {
2058
+ return maxTtlSeconds ? Math.min(requested, maxTtlSeconds) : requested;
2059
+ }
2060
+ /** The role grants a target's access level maps to. Defaults to read-only. */
2061
+ function rolesFor(config) {
2062
+ const db = config.connection.database;
2063
+ if (config.accessLevel === "custom") {
2064
+ if (!config.roles || config.roles.length === 0) throw new Error("mongodb custom target requires a non-empty roles array");
2065
+ return config.roles;
2066
+ }
2067
+ const preset = config.accessLevel === "readwrite" ? "readwrite" : "readonly";
2068
+ return [{
2069
+ role: MONGO_PRESET_ROLES[preset],
2070
+ db
2071
+ }];
2072
+ }
2073
+ const mongoProvider = {
2074
+ kind: "mongodb",
2075
+ zkTier: 2,
2076
+ render(config, req, ctx) {
2077
+ if (config.provider !== "mongodb") throw new Error("mongoProvider given a non-mongodb config");
2078
+ if (req.provider !== "mongodb") throw new Error("mongo provider received a non-mongodb request");
2079
+ p256PublicKeyJwkSchema.parse(req.recipientPublicKey);
2080
+ const username = mongoUserNameSchema.parse(ctx.leaseId);
2081
+ const authSource = mongoDatabaseNameSchema.parse(config.authSource ?? "admin");
2082
+ const database = mongoDatabaseNameSchema.parse(config.connection.database);
2083
+ const roles = rolesFor(config);
2084
+ const ttlSeconds = clampTtl(req.ttlSeconds, config.maxTtlSeconds);
2085
+ const expiresAt = new Date(ctx.nowMs + ttlSeconds * 1e3).toISOString();
2086
+ return {
2087
+ resourceRef: username,
2088
+ expiresAt,
2089
+ provision: {
2090
+ kind: "mongo-user",
2091
+ spec: {
2092
+ username,
2093
+ authSource,
2094
+ database,
2095
+ roles,
2096
+ recipientPublicKey: req.recipientPublicKey,
2097
+ expiresAt
2098
+ }
2099
+ },
2100
+ revoke: {
2101
+ kind: "mongo-user",
2102
+ spec: {
2103
+ username,
2104
+ authSource,
2105
+ database: "",
2106
+ roles: [],
2107
+ recipientPublicKey: "",
2108
+ expiresAt: ""
2109
+ }
2110
+ }
2111
+ };
2112
+ },
2113
+ renderRevoke(config, resourceRef) {
2114
+ if (config.provider !== "mongodb") throw new Error("mongoProvider given a non-mongodb config");
2115
+ return {
2116
+ kind: "mongo-user",
2117
+ spec: {
2118
+ username: mongoUserNameSchema.parse(resourceRef),
2119
+ authSource: mongoDatabaseNameSchema.parse(config.authSource ?? "admin"),
2120
+ database: "",
2121
+ roles: [],
2122
+ recipientPublicKey: "",
2123
+ expiresAt: ""
2124
+ }
2125
+ };
2126
+ }
2127
+ };
2128
+ // ../../packages/core/src/providers/mysql.ts
2129
+ /**
2130
+ * Tier-1 MySQL/MariaDB provider. The consumer generated the password and its
2131
+ * `mysql_native_password` verifier locally (see @seekrit/crypto
2132
+ * `mysqlNativePasswordVerifier`); we only ever see the verifier, which
2133
+ * `CREATE USER … IDENTIFIED WITH mysql_native_password AS '<hash>'` stores
2134
+ * verbatim and which cannot be used to authenticate (login is a
2135
+ * challenge-response needing a `SHA1(password)` preimage). So the handed-out
2136
+ * credential is zero-knowledge end to end — the provider merely renders SQL.
2137
+ *
2138
+ * Unlike Postgres there is no account-level `VALID UNTIL`: the broker's
2139
+ * alarm-driven `DROP USER` is the sole expiry mechanism. Preset access levels
2140
+ * apply inline `GRANT`s (MySQL roles need activation, an awkward fit for a
2141
+ * plain connection URL), so there is no shared group role / setup SQL.
2142
+ */
2143
+ const DEFAULT_HOST = "%";
2144
+ /** Mirror of the registration-time host schema (render must not trust inputs). */
2145
+ const HOST_RE = /^[A-Za-z0-9_.%:-]{1,255}$/;
2146
+ /** Escape a backtick-quoted identifier by doubling backticks. */
2147
+ function ident(name) {
2148
+ return name.replace(/`/g, "``");
2149
+ }
2150
+ function render$2(template, vars) {
2151
+ return template.replace(/\{\{(name|verifier)\}\}/g, (_, key) => key === "name" ? vars.name : vars.verifier);
2152
+ }
2153
+ /**
2154
+ * Concrete create/revoke templates for a target. Presets synthesize a
2155
+ * `CREATE USER` plus an inline `GRANT` scoped to the target database; custom
2156
+ * (or a legacy target with no access level) uses the admin's statements,
2157
+ * falling back to a bare CREATE USER / DROP USER. Host and database come from
2158
+ * the (trusted, registration-validated) config and are baked in directly;
2159
+ * only `{{name}}`/`{{verifier}}` remain as per-lease placeholders.
2160
+ */
2161
+ function statementsFor$2(config) {
2162
+ const account = `'{{name}}'@'${config.userHost && HOST_RE.test(config.userHost) ? config.userHost : DEFAULT_HOST}'`;
2163
+ const create = `CREATE USER ${account} IDENTIFIED WITH mysql_native_password AS '{{verifier}}';`;
2164
+ const revoke = `DROP USER IF EXISTS ${account};`;
2165
+ if (config.accessLevel === "readonly" || config.accessLevel === "readwrite") {
2166
+ const db = ident(config.connection.database);
2167
+ return {
2168
+ create: [create, `GRANT ${config.accessLevel === "readonly" ? "SELECT" : "SELECT, INSERT, UPDATE, DELETE"} ON \`${db}\`.* TO ${account};`],
2169
+ revoke: [revoke]
2170
+ };
2171
+ }
2172
+ return {
2173
+ create: config.createStatements ?? [create],
2174
+ revoke: config.revokeStatements ?? [revoke]
2175
+ };
2176
+ }
2177
+ const mysqlProvider = {
2178
+ kind: "mysql",
2179
+ zkTier: 1,
2180
+ render(config, req, ctx) {
2181
+ if (config.provider !== "mysql") throw new Error("mysqlProvider given a non-mysql config");
2182
+ if (req.provider !== "mysql") throw new Error("mysql provider received a non-mysql request");
2183
+ mysqlUserNameSchema.parse(req.roleName);
2184
+ mysqlNativeVerifierSchema.parse(req.verifier);
2185
+ const expiresAt = new Date(ctx.nowMs + req.ttlSeconds * 1e3).toISOString();
2186
+ const vars = {
2187
+ name: req.roleName,
2188
+ verifier: req.verifier
2189
+ };
2190
+ const { create, revoke } = statementsFor$2(config);
2191
+ const parameters = config.executor === "remote" && config.provisionerId ? { parameters: {
2192
+ name: req.roleName,
2193
+ verifier: req.verifier,
2194
+ validUntil: expiresAt
2195
+ } } : {};
2196
+ return {
2197
+ resourceRef: req.roleName,
2198
+ expiresAt,
2199
+ provision: {
2200
+ kind: "sql",
2201
+ ...parameters,
2202
+ statements: create.map((s) => render$2(s, vars))
2203
+ },
2204
+ revoke: {
2205
+ kind: "sql",
2206
+ ...parameters,
2207
+ statements: revoke.map((s) => render$2(s, {
2208
+ name: req.roleName,
2209
+ verifier: ""
2210
+ }))
2211
+ }
2212
+ };
2213
+ },
2214
+ renderRevoke(config, resourceRef) {
2215
+ if (config.provider !== "mysql") throw new Error("mysqlProvider given a non-mysql config");
2216
+ mysqlUserNameSchema.parse(resourceRef);
2217
+ return {
2218
+ kind: "sql",
2219
+ statements: statementsFor$2(config).revoke.map((s) => render$2(s, {
2220
+ name: resourceRef,
2221
+ verifier: ""
2222
+ }))
2223
+ };
2224
+ }
2225
+ };
2226
+ // ../../packages/core/src/providers/postgres.ts
2227
+ /**
2228
+ * Tier-1 Postgres provider. The consumer generated the password and its SCRAM
2229
+ * verifier locally (see @seekrit/crypto `scramSha256Verifier`); we only ever
2230
+ * see the verifier, which `CREATE ROLE … PASSWORD` stores verbatim and which
2231
+ * cannot be used to authenticate. So the handed-out credential is
2232
+ * zero-knowledge end to end — the provider merely renders SQL.
2233
+ *
2234
+ * Per-lease inputs are strict tokens (validated role name + verifier) and the
2235
+ * SQL is either an admin-configured template (custom) or derived from a preset
2236
+ * access level backed by a shared group role, so substitution cannot inject SQL.
2237
+ */
2238
+ const DEFAULT_CREATE$1 = [`CREATE ROLE "{{name}}" LOGIN PASSWORD '{{verifier}}' VALID UNTIL '{{valid_until}}';`];
2239
+ const DEFAULT_REVOKE$1 = [`DROP ROLE IF EXISTS "{{name}}";`];
2240
+ function render$1(template, vars) {
2241
+ return template.replace(/\{\{(name|verifier|valid_until)\}\}/g, (_, key) => vars[key] ?? "");
2242
+ }
2243
+ /**
2244
+ * The concrete create/revoke templates for a target. Read-only and read-write
2245
+ * create the temp role `IN ROLE <group>` so it inherits the group's grants;
2246
+ * custom (or a legacy target with no access level) uses the admin's statements,
2247
+ * falling back to a bare CREATE ROLE.
2248
+ */
2249
+ function statementsFor$1(config) {
2250
+ if (config.accessLevel === "readonly" || config.accessLevel === "readwrite") return {
2251
+ create: [`CREATE ROLE "{{name}}" LOGIN PASSWORD '{{verifier}}' VALID UNTIL '{{valid_until}}' IN ROLE ${POSTGRES_GROUP_ROLES[config.accessLevel]};`],
2252
+ revoke: DEFAULT_REVOKE$1
2253
+ };
2254
+ return {
2255
+ create: config.createStatements ?? DEFAULT_CREATE$1,
2256
+ revoke: config.revokeStatements ?? DEFAULT_REVOKE$1
2257
+ };
2258
+ }
2259
+ const postgresProvider = {
2260
+ kind: "postgres",
2261
+ zkTier: 1,
2262
+ render(config, req, ctx) {
2263
+ if (req.provider !== "postgres") throw new Error("postgres provider received a non-postgres request");
2264
+ postgresRoleNameSchema.parse(req.roleName);
2265
+ scramVerifierSchema.parse(req.verifier);
2266
+ const expiresAt = new Date(ctx.nowMs + req.ttlSeconds * 1e3).toISOString();
2267
+ const vars = {
2268
+ name: req.roleName,
2269
+ verifier: req.verifier,
2270
+ valid_until: expiresAt
2271
+ };
2272
+ const { create, revoke } = statementsFor$1(config);
2273
+ const parameters = config.executor === "remote" && config.provisionerId ? { parameters: {
2274
+ name: req.roleName,
2275
+ verifier: req.verifier,
2276
+ validUntil: expiresAt
2277
+ } } : {};
2278
+ return {
2279
+ resourceRef: req.roleName,
2280
+ expiresAt,
2281
+ provision: {
2282
+ kind: "sql",
2283
+ ...parameters,
2284
+ statements: create.map((s) => render$1(s, vars))
2285
+ },
2286
+ revoke: {
2287
+ kind: "sql",
2288
+ ...parameters,
2289
+ statements: revoke.map((s) => render$1(s, {
2290
+ name: req.roleName,
2291
+ verifier: "",
2292
+ valid_until: ""
2293
+ }))
2294
+ }
2295
+ };
2296
+ },
2297
+ renderRevoke(config, resourceRef) {
2298
+ postgresRoleNameSchema.parse(resourceRef);
2299
+ return {
2300
+ kind: "sql",
2301
+ statements: statementsFor$1(config).revoke.map((s) => render$1(s, {
2302
+ name: resourceRef,
2303
+ verifier: "",
2304
+ valid_until: ""
2305
+ }))
2306
+ };
2307
+ }
2308
+ };
2309
+ // ../../packages/core/src/providers/redis.ts
2310
+ /**
2311
+ * Tier-1 Redis (6+) provider. The consumer generated the password and its
2312
+ * SHA-256 hex digest locally (see @seekrit/crypto `redisSha256Verifier`); we
2313
+ * only ever see the digest, which `ACL SETUSER … on #<hex>` stores verbatim and
2314
+ * which cannot be used to authenticate (Redis `AUTH` hashes the plaintext it
2315
+ * receives and compares, so the stored digest is a preimage). So the handed-out
2316
+ * credential is zero-knowledge end to end — the provider merely renders
2317
+ * commands.
2318
+ *
2319
+ * Unlike Postgres there is no account-level expiry: the broker's alarm-driven
2320
+ * `ACL DELUSER` is the sole expiry mechanism (as with MySQL). Preset access
2321
+ * levels apply inline ACL rules (Redis ACL has no role inheritance), so there is
2322
+ * no shared group role / setup step.
2323
+ *
2324
+ * Each rendered statement is a single Redis command line; the executor
2325
+ * whitespace-tokenizes it into RESP arguments. The per-lease inputs are strict
2326
+ * tokens (validated user name + hex digest) with no whitespace or ACL-rule
2327
+ * characters, so substitution cannot inject an extra argument or permission.
2328
+ */
2329
+ const DEFAULT_CREATE = ["ACL SETUSER {{name}} on #{{verifier}}"];
2330
+ const DEFAULT_REVOKE = ["ACL DELUSER {{name}}"];
2331
+ /**
2332
+ * Inline ACL rules each preset grants: all keys (`~*`), the read (or read+write)
2333
+ * command category, and `+@connection` so client-handshake commands (HELLO,
2334
+ * PING, AUTH) work. No pub/sub channels (`&*`) — the categories don't enable
2335
+ * pub/sub anyway, and `&*` needs Redis 6.2+.
2336
+ */
2337
+ const PRESET_RULES = {
2338
+ readonly: "~* +@read +@connection",
2339
+ readwrite: "~* +@read +@write +@connection"
2340
+ };
2341
+ function render(template, vars) {
2342
+ return template.replace(/\{\{(name|verifier)\}\}/g, (_, key) => key === "name" ? vars.name : vars.verifier);
2343
+ }
2344
+ /**
2345
+ * Concrete create/revoke command lines for a target. Presets synthesize an
2346
+ * `ACL SETUSER` that enables the user (`on`), sets its password digest, and
2347
+ * grants the preset's inline rules; custom (or a legacy target with no access
2348
+ * level) uses the admin's statements, falling back to a no-privilege user.
2349
+ */
2350
+ function statementsFor(config) {
2351
+ if (config.accessLevel === "readonly" || config.accessLevel === "readwrite") return {
2352
+ create: [`ACL SETUSER {{name}} on #{{verifier}} ${PRESET_RULES[config.accessLevel]}`],
2353
+ revoke: DEFAULT_REVOKE
2354
+ };
2355
+ return {
2356
+ create: config.createStatements ?? DEFAULT_CREATE,
2357
+ revoke: config.revokeStatements ?? DEFAULT_REVOKE
2358
+ };
2359
+ }
2360
+ const redisProvider = {
2361
+ kind: "redis",
2362
+ zkTier: 1,
2363
+ render(config, req, ctx) {
2364
+ if (config.provider !== "redis") throw new Error("redisProvider given a non-redis config");
2365
+ if (req.provider !== "redis") throw new Error("redis provider received a non-redis request");
2366
+ redisUserNameSchema.parse(req.roleName);
2367
+ redisSha256VerifierSchema.parse(req.verifier);
2368
+ const expiresAt = new Date(ctx.nowMs + req.ttlSeconds * 1e3).toISOString();
2369
+ const vars = {
2370
+ name: req.roleName,
2371
+ verifier: req.verifier
2372
+ };
2373
+ const { create, revoke } = statementsFor(config);
2374
+ const parameters = config.executor === "remote" && config.provisionerId ? { parameters: {
2375
+ name: req.roleName,
2376
+ verifier: req.verifier,
2377
+ validUntil: expiresAt
2378
+ } } : {};
2379
+ return {
2380
+ resourceRef: req.roleName,
2381
+ expiresAt,
2382
+ provision: {
2383
+ kind: "sql",
2384
+ ...parameters,
2385
+ statements: create.map((s) => render(s, vars))
2386
+ },
2387
+ revoke: {
2388
+ kind: "sql",
2389
+ ...parameters,
2390
+ statements: revoke.map((s) => render(s, {
2391
+ name: req.roleName,
2392
+ verifier: ""
2393
+ }))
2394
+ }
2395
+ };
2396
+ },
2397
+ renderRevoke(config, resourceRef) {
2398
+ if (config.provider !== "redis") throw new Error("redisProvider given a non-redis config");
2399
+ redisUserNameSchema.parse(resourceRef);
2400
+ return {
2401
+ kind: "sql",
2402
+ statements: statementsFor(config).revoke.map((s) => render(s, {
2403
+ name: resourceRef,
2404
+ verifier: ""
2405
+ }))
2406
+ };
2407
+ }
2408
+ };
2409
+ // ../../packages/core/src/providers/ssh.ts
2410
+ /**
2411
+ * Tier-1 SSH certificate-authority provider. The consumer generated an
2412
+ * ephemeral keypair locally and sent only its public key; `render` produces a
2413
+ * validated {@link SshCertSpec} that the broker's `SshCaExecutor` signs with the
2414
+ * CA key. So render itself is pure and secret-free — it never sees the CA key,
2415
+ * and the consumer's private key never leaves their machine.
2416
+ *
2417
+ * A clock-skew grace is applied to `validAfter` so freshly minted certs work on
2418
+ * hosts whose clocks lag slightly. Revocation is a no-op: certificates are
2419
+ * self-contained, so v1 relies on short TTLs (a KRL is a follow-up).
2420
+ */
2421
+ /** Backdate the validity window so minor host clock skew doesn't reject certs. */
2422
+ const CLOCK_SKEW_GRACE_SECONDS = 60;
2423
+ // ../../packages/core/src/providers/index.ts
2424
+ /** Registry — new providers register here so callers resolve by kind. */
2425
+ const leaseProviders = {
2426
+ kafka: managedLeaseProvider("kafka"),
2427
+ "sap-hana": managedLeaseProvider("sap-hana"),
2428
+ cassandra: managedLeaseProvider("cassandra"),
2429
+ vertica: managedLeaseProvider("vertica"),
2430
+ "ibm-api-connect": managedLeaseProvider("ibm-api-connect"),
2431
+ ldap: managedLeaseProvider("ldap"),
2432
+ entra: managedLeaseProvider("entra"),
2433
+ kubernetes: managedLeaseProvider("kubernetes"),
2434
+ postgres: postgresProvider,
2435
+ mysql: mysqlProvider,
2436
+ redis: redisProvider,
2437
+ ssh: {
2438
+ kind: "ssh",
2439
+ zkTier: 1,
2440
+ render(config, req, ctx) {
2441
+ if (req.provider !== "ssh") throw new Error("ssh provider received a non-ssh request");
2442
+ const cfg = config;
2443
+ sshPublicKeySchema.parse(req.publicKey);
2444
+ const principals = req.principals.map((p) => sshPrincipalSchema.parse(p));
2445
+ if (cfg.allowedPrincipals?.length) {
2446
+ for (const p of principals) if (!cfg.allowedPrincipals.includes(p)) throw new Error(`principal "${p}" is not allowed by this target`);
2447
+ }
2448
+ const ttl = cfg.maxTtlSeconds ? Math.min(req.ttlSeconds, cfg.maxTtlSeconds) : req.ttlSeconds;
2449
+ const nowSec = Math.floor(ctx.nowMs / 1e3);
2450
+ const validAfter = nowSec - CLOCK_SKEW_GRACE_SECONDS;
2451
+ const validBefore = nowSec + ttl;
2452
+ return {
2453
+ resourceRef: ctx.leaseId,
2454
+ expiresAt: (/* @__PURE__ */ new Date(validBefore * 1e3)).toISOString(),
2455
+ provision: {
2456
+ kind: "ssh-sign",
2457
+ spec: {
2458
+ userPublicKey: req.publicKey,
2459
+ keyId: ctx.leaseId,
2460
+ principals,
2461
+ validAfter,
2462
+ validBefore,
2463
+ extensions: cfg.extensions
2464
+ }
2465
+ },
2466
+ revoke: { kind: "noop" }
2467
+ };
2468
+ },
2469
+ renderRevoke() {
2470
+ return { kind: "noop" };
2471
+ }
2472
+ },
2473
+ aws: awsProvider,
2474
+ gcp: gcpProvider,
2475
+ mongodb: mongoProvider,
2476
+ elasticsearch: managedLeaseProvider("elasticsearch"),
2477
+ clickhouse: managedLeaseProvider("clickhouse"),
2478
+ rabbitmq: managedLeaseProvider("rabbitmq"),
2479
+ milvus: managedLeaseProvider("milvus"),
2480
+ "mongodb-atlas": managedLeaseProvider("mongodb-atlas"),
2481
+ couchbase: managedLeaseProvider("couchbase"),
2482
+ snowflake: managedLeaseProvider("snowflake"),
2483
+ elasticache: managedLeaseProvider("elasticache"),
2484
+ memorydb: managedLeaseProvider("memorydb"),
2485
+ "azure-sql": managedLeaseProvider("azure-sql"),
2486
+ mssql: managedLeaseProvider("mssql"),
2487
+ openrouter: managedLeaseProvider("openrouter"),
2488
+ tailscale: managedLeaseProvider("tailscale")
2489
+ };
2490
+ function leaseProviderFor(kind) {
2491
+ return leaseProviders[kind];
2492
+ }
2493
+ // ../../packages/core/src/provisioners.ts
2494
+ const provisionerIdSchema = z.string().regex(/^prv_[A-Za-z0-9_-]{32}$/);
2495
+ z.object({
2496
+ id: provisionerIdSchema,
2497
+ name: z.string().trim().min(1).max(128),
2498
+ transport: z.enum(["pull", "push"]).default("pull"),
2499
+ provisionerUrl: managedEndpointSchema.optional(),
2500
+ publicKeyJwk: p256PublicKeyJwkSchema.refine((value) => !("d" in JSON.parse(value)), "Supply only the public key"),
2501
+ wrappedSigningKey: z.string().max(16384).startsWith("wd1."),
2502
+ bootstrap: z.string().max(4096).startsWith("pb1.")
2503
+ }).strict().superRefine((v, ctx) => {
2504
+ if (v.transport === "push" && !v.provisionerUrl) ctx.addIssue({
2505
+ code: "custom",
2506
+ path: ["provisionerUrl"],
2507
+ message: "Inbound mode requires an HTTPS endpoint."
2508
+ });
2509
+ if (v.transport === "pull" && v.provisionerUrl) ctx.addIssue({
2510
+ code: "custom",
2511
+ path: ["provisionerUrl"],
2512
+ message: "Outbound mode does not use an endpoint."
2513
+ });
2514
+ });
2515
+ // ../../packages/core/src/slug.ts
2516
+ /**
2517
+ * The slug rule, with no dependencies — so a caller that cannot afford zod (the
2518
+ * resolve gateway's bundle, see apps/api/src/gateway) validates with the same
2519
+ * pattern `slugSchema` uses rather than a copy of it.
2520
+ */
2521
+ const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2522
+ // ../../packages/core/src/types.ts
1068
2523
  /**
1069
2524
  * Transactional notification emails seekrit can send. Each id is one
1070
2525
  * user-facing on/off toggle (see `NOTIFICATION_TYPE_META`). These carry only
@@ -1087,16 +2542,15 @@ const NOTIFICATION_TYPES = [
1087
2542
  "change_request_opened",
1088
2543
  "change_request_decided"
1089
2544
  ];
1090
- //#endregion
1091
- //#region ../../packages/core/src/schemas.ts
2545
+ // ../../packages/core/src/schemas.ts
1092
2546
  /** URL-safe identifier segment: `my-app`, `production`, … */
1093
- const slugSchema = z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "must be lowercase alphanumeric with hyphens");
2547
+ const slugSchema = z.string().min(1).max(64).regex(SLUG_PATTERN, "must be lowercase alphanumeric with hyphens");
1094
2548
  const nameSchema = z.string().trim().min(1).max(128);
1095
2549
  /** An email address, normalized to trimmed lowercase before validation. */
1096
2550
  const emailSchema = z.string().trim().toLowerCase().pipe(z.email().max(320));
1097
2551
  /** Env-var style secret name: FOO, DATABASE_URL, apiKey2 … */
1098
2552
  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([
2553
+ const orgRoleSchema = z.enum([
1100
2554
  "owner",
1101
2555
  "admin",
1102
2556
  "member"
@@ -1135,7 +2589,20 @@ z.object({
1135
2589
  name: nameSchema,
1136
2590
  slug: slugSchema
1137
2591
  });
2592
+ /** Compose a group into an application environment (matched by env slug). */
2593
+ const appAccessKeySchema = z.object({
2594
+ environmentId: z.string().min(1),
2595
+ userId: z.string().min(1),
2596
+ wrappedDek: z.string().min(1).max(8192)
2597
+ });
2598
+ const appAccessGrantsSchema = z.array(appAccessKeySchema).max(5e3).optional();
1138
2599
  z.object({
2600
+ userId: z.string().min(1),
2601
+ grants: z.array(appAccessKeySchema).max(5e3)
2602
+ });
2603
+ z.object({ role: orgRoleSchema });
2604
+ z.object({
2605
+ appAccessGrants: appAccessGrantsSchema,
1139
2606
  groupId: z.string().min(1),
1140
2607
  /** Precedence among an env's groups (higher wins). Appended if omitted. */
1141
2608
  position: z.number().int().min(0).optional(),
@@ -1146,6 +2613,11 @@ z.object({
1146
2613
  })).optional()
1147
2614
  });
1148
2615
  z.object({
2616
+ /** Wrap the new DEK to all persistent app recipients. */
2617
+ userGrants: z.array(z.object({
2618
+ userId: z.string().min(1),
2619
+ wrappedDek: z.string().min(1).max(8192)
2620
+ })).max(5e3).optional(),
1149
2621
  name: nameSchema,
1150
2622
  slug: slugSchema,
1151
2623
  /** Environment DEK wrapped to the creator's public key — created client-side. */
@@ -1157,9 +2629,18 @@ z.object({
1157
2629
  */
1158
2630
  recoveryWrappedDek: z.string().min(1).nullish()
1159
2631
  });
1160
- z.object({
1161
- /** Opaque versioned ciphertext blob from @seekrit/crypto. */
1162
- ciphertext: z.string().min(1).max(65536) });
2632
+ z.object({
2633
+ /** Opaque versioned ciphertext blob from @seekrit/crypto. */
2634
+ ciphertext: z.string().min(1).max(65536),
2635
+ /**
2636
+ * Compare-and-swap: write only if the secret is currently at this version
2637
+ * (`0` = only if it does not exist yet), else 412 `precondition_failed`.
2638
+ * Omit for an unconditional write. This is what lets a writer that read,
2639
+ * changed, and wrote back — a refreshed agent login, say — find out that
2640
+ * someone else wrote in between instead of silently erasing their value.
2641
+ */
2642
+ expectedVersion: z.number().int().min(0).optional()
2643
+ });
1163
2644
  z.object({ version: z.number().int().positive() });
1164
2645
  z.object({ limit: z.coerce.number().int().min(1).max(200).default(50) });
1165
2646
  z.object({
@@ -1207,7 +2688,23 @@ z.object({
1207
2688
  /** The same DEK wrapped to each of the parent's existing grant-holders. */
1208
2689
  grants: z.array(grantEnvironmentKeySchema).max(500).default([])
1209
2690
  });
2691
+ /**
2692
+ * Token creation is client-driven so the server never sees the token secret:
2693
+ * the client generates the keypair + token string and submits only the hash
2694
+ * and public key.
2695
+ */
2696
+ const environmentGrantBatchSchema = z.array(z.object({
2697
+ environmentId: z.string().min(1),
2698
+ wrappedDek: z.string().min(1).max(8192)
2699
+ })).max(5e3);
2700
+ z.object({
2701
+ principalType: principalTypeSchema,
2702
+ principalId: z.string().min(1),
2703
+ grants: environmentGrantBatchSchema
2704
+ });
1210
2705
  z.object({
2706
+ /** Commit the token and all default resolve keys together, when supplied. */
2707
+ initialGrants: environmentGrantBatchSchema.optional(),
1211
2708
  name: nameSchema,
1212
2709
  tokenId: z.string().regex(/^skt_[0-9A-Za-z]+$/),
1213
2710
  /** SHA-256 hash (base64url) of the full token string. */
@@ -1497,8 +2994,37 @@ z.enum([
1497
2994
  "azure-key-vault",
1498
2995
  "huggingface-spaces",
1499
2996
  "openai-vault",
1500
- "claude-managed-agents"
2997
+ "claude-managed-agents",
2998
+ "coolify"
1501
2999
  ]);
3000
+ const coolifyConnectionConfigSchema = z.object({
3001
+ provider: z.literal("coolify"),
3002
+ baseUrl: z.string().trim().pipe(connectUrlSchema).transform((url, ctx) => {
3003
+ const parsed = new URL(url);
3004
+ if (![
3005
+ "/",
3006
+ "/api/v1",
3007
+ "/api/v1/"
3008
+ ].includes(parsed.pathname)) {
3009
+ ctx.addIssue({
3010
+ code: "custom",
3011
+ message: "Enter the Coolify instance origin or its /api/v1 URL."
3012
+ });
3013
+ return z.NEVER;
3014
+ }
3015
+ return parsed.origin;
3016
+ })
3017
+ });
3018
+ const coolifyDestinationSchema = z.object({
3019
+ provider: z.literal("coolify"),
3020
+ applicationUuid: z.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/, "Enter the Coolify application UUID."),
3021
+ target: z.enum(["production", "preview"]).default("production"),
3022
+ availability: z.enum([
3023
+ "runtime",
3024
+ "build",
3025
+ "both"
3026
+ ]).default("runtime")
3027
+ });
1502
3028
  /**
1503
3029
  * Vercel account scope. The API token itself is never here — it is wrapped to
1504
3030
  * the connection's public key and stored as ciphertext.
@@ -1915,7 +3441,8 @@ const syncConnectionConfigSchema = z.discriminatedUnion("provider", [
1915
3441
  azureKeyVaultConnectionConfigSchema,
1916
3442
  huggingfaceSpacesConnectionConfigSchema,
1917
3443
  openaiVaultConnectionConfigSchema,
1918
- claudeManagedAgentsConnectionConfigSchema
3444
+ claudeManagedAgentsConnectionConfigSchema,
3445
+ coolifyConnectionConfigSchema
1919
3446
  ]);
1920
3447
  const vercelDestinationSchema = z.object({
1921
3448
  provider: z.literal("vercel"),
@@ -2792,7 +4319,8 @@ const syncDestinationSchema = z.discriminatedUnion("provider", [
2792
4319
  azureKeyVaultDestinationSchema,
2793
4320
  huggingfaceSpacesDestinationSchema,
2794
4321
  openaiVaultDestinationSchema,
2795
- claudeManagedAgentsDestinationSchema
4322
+ claudeManagedAgentsDestinationSchema,
4323
+ coolifyDestinationSchema
2796
4324
  ]);
2797
4325
  /**
2798
4326
  * How seekrit secret names become destination key names. Applied in order:
@@ -2852,8 +4380,7 @@ z.object({
2852
4380
  mode: z.enum(["auto", "manual"]).optional(),
2853
4381
  enabled: z.boolean().optional()
2854
4382
  });
2855
- //#endregion
2856
- //#region ../../packages/core/src/vault.ts
4383
+ // ../../packages/core/src/vault.ts
2857
4384
  /** One encrypted credential within a connection. */
2858
4385
  const VAULT_SLOTS = [
2859
4386
  "oauth2",
@@ -3137,8 +4664,7 @@ z.object({
3137
4664
  userRef: vaultUserRefSchema,
3138
4665
  leaseId: leaseIdSchema
3139
4666
  });
3140
- //#endregion
3141
- //#region ../../packages/crypto/src/encoding.ts
4667
+ // ../../packages/crypto/src/encoding.ts
3142
4668
  const CHUNK = 32768;
3143
4669
  /** Base64url (no padding) — portable across browsers, Workers, and Node. */
3144
4670
  function toBase64Url(bytes) {
@@ -3169,8 +4695,7 @@ function utf8Encode(text) {
3169
4695
  function utf8Decode(bytes) {
3170
4696
  return new TextDecoder().decode(bytes);
3171
4697
  }
3172
- //#endregion
3173
- //#region ../../packages/crypto/src/errors.ts
4698
+ // ../../packages/crypto/src/errors.ts
3174
4699
  var SeekritCryptoError = class extends Error {
3175
4700
  code;
3176
4701
  constructor(code, message) {
@@ -3190,8 +4715,7 @@ function splitBlob(blob, prefix, segments) {
3190
4715
  if (parts.length !== segments + 1 || parts.some((p) => p.length === 0)) throw new SeekritCryptoError("MALFORMED_BLOB", `malformed "${prefix}" blob`);
3191
4716
  return parts.slice(1);
3192
4717
  }
3193
- //#endregion
3194
- //#region ../../packages/crypto/src/aes.ts
4718
+ // ../../packages/crypto/src/aes.ts
3195
4719
  const SECRET_PREFIX = "sc1";
3196
4720
  const IV_LENGTH$1 = 12;
3197
4721
  /** Generate a fresh 256-bit data encryption key for an environment. */
@@ -3236,8 +4760,7 @@ async function decryptSecret(dek, blob, aad) {
3236
4760
  function secretAad(environmentId, secretName) {
3237
4761
  return `${environmentId}/${secretName}`;
3238
4762
  }
3239
- //#endregion
3240
- //#region ../../packages/crypto/src/keys.ts
4763
+ // ../../packages/crypto/src/keys.ts
3241
4764
  async function generateKeyPair() {
3242
4765
  const pair = await crypto.subtle.generateKey({
3243
4766
  name: "ECDH",
@@ -3270,8 +4793,7 @@ async function importPrivateKeyPkcs8(pkcs8) {
3270
4793
  namedCurve: "P-256"
3271
4794
  }, true, ["deriveBits"]);
3272
4795
  }
3273
- //#endregion
3274
- //#region ../../packages/crypto/src/wrap.ts
4796
+ // ../../packages/crypto/src/wrap.ts
3275
4797
  /**
3276
4798
  * ECIES-style key wrapping: an ephemeral P-256 keypair performs ECDH against
3277
4799
  * the recipient's public key; the shared secret is run through HKDF-SHA256 to
@@ -3339,8 +4861,7 @@ async function unwrapDek(wrapped, privateKey) {
3339
4861
  throw new SeekritCryptoError("DECRYPT_FAILED", "DEK unwrap failed: wrong private key or tampered grant");
3340
4862
  }
3341
4863
  }
3342
- //#endregion
3343
- //#region ../../packages/crypto/src/kms.ts
4864
+ // ../../packages/crypto/src/kms.ts
3344
4865
  /**
3345
4866
  * Client-side KMS envelope encryption. A managed `encrypt` key is a 256-bit
3346
4867
  * AES-GCM key whose material reaches the client only as a `wd1.` grant (wrapped
@@ -3455,8 +4976,7 @@ async function generateDataKey(material, ref) {
3455
4976
  ].join(".")
3456
4977
  };
3457
4978
  }
3458
- //#endregion
3459
- //#region ../../packages/crypto/src/random.ts
4979
+ // ../../packages/crypto/src/random.ts
3460
4980
  const ALPHABETS = {
3461
4981
  alphanumeric: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
3462
4982
  hex: "0123456789abcdef",
@@ -3492,8 +5012,7 @@ function generateSecretValue(length, alphabet = "alphanumeric") {
3492
5012
  }
3493
5013
  return out;
3494
5014
  }
3495
- //#endregion
3496
- //#region ../../packages/crypto/src/mysql.ts
5015
+ // ../../packages/crypto/src/mysql.ts
3497
5016
  /**
3498
5017
  * Client-side construction of a MySQL/MariaDB `mysql_native_password`
3499
5018
  * authentication string, for minting *temporary MySQL login credentials*
@@ -3549,8 +5068,7 @@ async function generateMysqlCredential(options = {}) {
3549
5068
  verifier: await mysqlNativePasswordVerifier(password)
3550
5069
  };
3551
5070
  }
3552
- //#endregion
3553
- //#region ../../packages/crypto/src/passphrase.ts
5071
+ // ../../packages/crypto/src/passphrase.ts
3554
5072
  /**
3555
5073
  * User private keys are stored server-side encrypted under a key derived from
3556
5074
  * the user's passphrase, so any browser or CLI session can fetch and unlock
@@ -3591,8 +5109,58 @@ async function decryptPrivateKey(passphrase, blob) {
3591
5109
  throw new SeekritCryptoError("DECRYPT_FAILED", "wrong passphrase or corrupted key blob");
3592
5110
  }
3593
5111
  }
3594
- //#endregion
3595
- //#region ../../packages/crypto/src/shamir.ts
5112
+ // ../../packages/crypto/src/policy-key.ts
5113
+ /**
5114
+ * Signing with a principal's **existing** keypair, for agent access policy.
5115
+ *
5116
+ * Policy bundles are signed in the browser so the API can serve a blob it cannot
5117
+ * forge (`docs/agent-access-governance.md` §1). Every user already has a P-256
5118
+ * keypair whose private half is passphrase-encrypted and opaque to the server
5119
+ * (`users.public_key_jwk`), so this feature needs **no new key material**: no
5120
+ * second passphrase, no wrapping, no schema, and nothing extra for an admin to
5121
+ * lose. That was a deliberate condition of the design.
5122
+ *
5123
+ * The catch is that WebCrypto keys are algorithm-bound. A principal key is
5124
+ * imported for ECDH (`deriveBits`) and cannot sign, even though the underlying
5125
+ * curve is the same one ECDSA uses. So the JWK is re-imported here with the
5126
+ * algorithm hints stripped — the same private scalar, presented as an ECDSA key.
5127
+ *
5128
+ * **The tradeoff, stated plainly:** this reuses one key for two algorithms,
5129
+ * which key-management hygiene (NIST SP 800-57 §5.2) advises against. We accept
5130
+ * it because the alternative — a second keypair per admin — is the kind of
5131
+ * ceremony that gets skipped, and because both uses stay inside the same trust
5132
+ * boundary: the key already authorizes reading every secret the admin can read,
5133
+ * so a signature capability adds no reach an attacker holding it wouldn't have.
5134
+ * If a future version wants separation, the clean path is a managed KMS `sign`
5135
+ * key granted to publishers — the thumbprint pinning in the proxy works
5136
+ * unchanged, which is why the format carries the key rather than a user id.
5137
+ */
5138
+ const ECDSA_PARAMS$1 = {
5139
+ name: "ECDSA",
5140
+ namedCurve: "P-256"
5141
+ };
5142
+ /**
5143
+ * Re-import a principal's private key JWK as an ECDSA signing key.
5144
+ *
5145
+ * `key_ops`, `alg`, and `use` are dropped: they say "ECDH" on a principal key,
5146
+ * and WebCrypto refuses an import whose declared operations don't include the
5147
+ * requested usage. Everything that determines the key — `crv`, `d`, `x`, `y` —
5148
+ * is passed through untouched.
5149
+ */
5150
+ async function importPolicySigningKey(privateKeyJwk) {
5151
+ const jwk = JSON.parse(privateKeyJwk);
5152
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256") throw new SeekritCryptoError("MALFORMED_BLOB", "policy signing needs an EC P-256 principal key");
5153
+ if (!jwk.d) throw new SeekritCryptoError("MALFORMED_BLOB", "policy signing needs the private half of the key");
5154
+ const { kty, crv, d, x, y } = jwk;
5155
+ return crypto.subtle.importKey("jwk", {
5156
+ kty,
5157
+ crv,
5158
+ d,
5159
+ x,
5160
+ y
5161
+ }, ECDSA_PARAMS$1, false, ["sign"]);
5162
+ }
5163
+ // ../../packages/crypto/src/shamir.ts
3596
5164
  /**
3597
5165
  * Shamir's Secret Sharing over GF(2^8) — the same field AES uses, with the
3598
5166
  * reduction polynomial x^8 + x^4 + x^3 + x + 1 (0x11b). Splits a byte string
@@ -3686,8 +5254,7 @@ async function generatePostgresCredential(options = {}) {
3686
5254
  iterations
3687
5255
  };
3688
5256
  }
3689
- //#endregion
3690
- //#region ../../packages/crypto/src/sign.ts
5257
+ // ../../packages/crypto/src/sign.ts
3691
5258
  /**
3692
5259
  * Managed signing keys for the client-side KMS — ECDSA over P-256 (the curve
3693
5260
  * already used for principal keypairs; universal in WebCrypto). A `sign` key's
@@ -3749,15 +5316,16 @@ function signatureKeyRef(signature) {
3749
5316
  version
3750
5317
  };
3751
5318
  }
3752
- //#endregion
3753
- //#region ../../packages/crypto/src/token.ts
5319
+ // ../../packages/crypto/src/token.ts
3754
5320
  /**
3755
5321
  * 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).
5322
+ * principals. One local bundle holds independent authentication and decryption
5323
+ * material. Only serviceTokenAuth(token) may be sent to the API; the private
5324
+ * key stays local. The server stores the auth credential hash and public key.
3759
5325
  *
3760
- * Format: `skt_<token id>_<private key pkcs8, base64url>`
5326
+ * Bundle: `skt_<id>_v2.<32-byte auth secret>.<private key pkcs8, base64url>`
5327
+ * Wire: `skt_<id>_v2.<32-byte auth secret>`
5328
+ * Legacy bundles remain readable offline but must never be transmitted.
3761
5329
  */
3762
5330
  const TOKEN_PREFIX = "skt";
3763
5331
  const TOKEN_ID_LENGTH = 22;
@@ -3781,17 +5349,17 @@ async function createServiceToken() {
3781
5349
  const { publicKeyJwk, privateKeyJwk } = await generateKeyPair();
3782
5350
  const pkcs8 = await exportPrivateKeyPkcs8(await importPrivateKey(privateKeyJwk));
3783
5351
  const tokenId = randomTokenId();
3784
- const token = `${tokenId}_${toBase64Url(pkcs8)}`;
5352
+ const token = `${tokenId}_v2.${toBase64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))}.${toBase64Url(pkcs8)}`;
3785
5353
  return {
3786
5354
  token,
3787
5355
  tokenId,
3788
- tokenHash: await hashToken(token),
5356
+ tokenHash: await hashToken(serviceTokenAuth(token)),
3789
5357
  publicKeyJwk
3790
5358
  };
3791
5359
  }
3792
5360
  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");
5361
+ const match = /^(skt_[0-9A-Za-z]+)_(?:v2\.[A-Za-z0-9_-]{43}\.)?([A-Za-z0-9_-]+)$/.exec(token);
5362
+ if (!match || match[0] !== token) throw new SeekritCryptoError("MALFORMED_TOKEN", "not a valid seekrit service token");
3795
5363
  const [, tokenId, keyB64] = match;
3796
5364
  try {
3797
5365
  return {
@@ -3802,12 +5370,23 @@ async function parseServiceToken(token) {
3802
5370
  throw new SeekritCryptoError("MALFORMED_TOKEN", "service token private key is corrupted");
3803
5371
  }
3804
5372
  }
5373
+ /** Extract only the independent auth credential. Never fall back to a raw token. */
5374
+ function serviceTokenAuth(token) {
5375
+ const match = /^(skt_[0-9A-Za-z]+_v2\.[A-Za-z0-9_-]{43})(?:\.[A-Za-z0-9_-]+)?$/.exec(token);
5376
+ const auth = match?.[1];
5377
+ 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");
5378
+ return auth;
5379
+ }
5380
+ /** Preserve human/session credentials while stripping service-token private keys. */
5381
+ function apiBearerToken(token) {
5382
+ const value = token.trim();
5383
+ return isServiceToken(value) ? serviceTokenAuth(value) : token;
5384
+ }
3805
5385
  function isServiceToken(value) {
3806
5386
  return value.startsWith(`${TOKEN_PREFIX}_`);
3807
5387
  }
3808
- //#endregion
3809
- //#region ../cli/package.json
3810
- var version$1 = "1.9.2";
5388
+ // ../cli/package.json
5389
+ var version$1 = "2.9.0";
3811
5390
  const PROJECT_FILE = "seekrit.json";
3812
5391
  function globalConfigPath() {
3813
5392
  return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "seekrit", "config.json");
@@ -3857,8 +5436,7 @@ function writeProjectConfig(config, dir = process.cwd()) {
3857
5436
  writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
3858
5437
  return path;
3859
5438
  }
3860
- //#endregion
3861
- //#region ../../packages/api-client/src/index.ts
5439
+ // ../../packages/api-client/src/index.ts
3862
5440
  /**
3863
5441
  * The proposer's note travels as a header, not a body field: an unprotected
3864
5442
  * environment ignores it, so the same call works either way and no caller has
@@ -3878,30 +5456,93 @@ var SeekritApiError = class extends Error {
3878
5456
  this.code = code;
3879
5457
  }
3880
5458
  };
3881
- var SeekritClient = class {
5459
+ var SeekritClient = class SeekritClient {
3882
5460
  baseUrl;
5461
+ getLeaseSigner;
3883
5462
  auth;
3884
5463
  fetchImpl;
3885
5464
  client;
3886
5465
  constructor(options) {
3887
5466
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
3888
5467
  this.auth = options.auth;
5468
+ this.getLeaseSigner = options.getLeaseSigner;
3889
5469
  this.fetchImpl = options.fetch ?? ((...args) => fetch(...args));
3890
5470
  this.client = options.client;
3891
5471
  }
5472
+ /** Reuse this session while signing leases with its unlocked customer key. */
5473
+ withLeaseSigner(getLeaseSigner) {
5474
+ return new SeekritClient({
5475
+ baseUrl: this.baseUrl,
5476
+ auth: this.auth,
5477
+ fetch: this.fetchImpl,
5478
+ client: this.client,
5479
+ getLeaseSigner
5480
+ });
5481
+ }
5482
+ getProvisionerAccess(orgId, id) {
5483
+ return this.request("GET", `/v1/orgs/${orgId}/leases/provisioners/${id}/access`);
5484
+ }
5485
+ grantProvisionerAccess(orgId, id, chain) {
5486
+ return this.request("POST", `/v1/orgs/${orgId}/leases/provisioners/${id}/access`, chain);
5487
+ }
5488
+ revokeProvisionerAccess(orgId, id, type, principalId) {
5489
+ return this.request("DELETE", `/v1/orgs/${orgId}/leases/provisioners/${id}/access/${type}/${principalId}`);
5490
+ }
5491
+ async authorizeLease(orgId, input) {
5492
+ if (input.authorization) return input;
5493
+ const prep = await this.request("GET", `/v1/orgs/${orgId}/leases/targets/${input.targetId}/authorization`);
5494
+ if (!prep.required) return input;
5495
+ const token = this.auth.type === "bearer" ? this.auth.token : this.auth.type === "dynamic" ? await this.auth.getToken() : null;
5496
+ const signingKey = token && isServiceToken(token) ? await importPolicySigningKey(JSON.stringify(await crypto.subtle.exportKey("jwk", (await parseServiceToken(token)).privateKey))) : await this.getLeaseSigner?.();
5497
+ if (!signingKey) throw new Error("Unlock your Seekrit key to request a customer-provisioned lease.");
5498
+ const access = await verifyProvisionerChain(prep.chain, orgId, prep.provisionerId);
5499
+ if (!access.targets.includes("*") && !access.targets.includes(input.targetId)) throw new Error("Target is outside your provisioner access grant.");
5500
+ const leaseId = randomId("lea");
5501
+ const issuedAt = Date.now();
5502
+ const rendered = leaseProviderFor(input.provider).render(prep.config, input, {
5503
+ leaseId,
5504
+ nowMs: issuedAt
5505
+ });
5506
+ const expiresAt = Date.parse(rendered.expiresAt);
5507
+ if (expiresAt > access.expiresAt) throw new Error("Your access grant expires before this lease. Use a shorter duration or ask an administrator to renew it.");
5508
+ const proof = {
5509
+ version: 1,
5510
+ orgId,
5511
+ provisionerId: prep.provisionerId,
5512
+ targetId: input.targetId,
5513
+ provider: input.provider,
5514
+ leaseId,
5515
+ instanceId: prep.instanceId,
5516
+ nonce: crypto.randomUUID(),
5517
+ targetDigest: prep.targetDigest,
5518
+ action: provisionerTransportAction(rendered.provision),
5519
+ ..."recipientPublicKey" in input ? { recipientPublicKey: input.recipientPublicKey } : {},
5520
+ issuedAt,
5521
+ expiresAt
5522
+ };
5523
+ return {
5524
+ ...input,
5525
+ authorization: {
5526
+ ...prep.chain,
5527
+ proof: await signProvisionerEnvelope("pr1", signingKey, proof)
5528
+ }
5529
+ };
5530
+ }
3892
5531
  async request(method, path, body, extraHeaders) {
3893
5532
  const headers = {
3894
5533
  accept: "application/json",
3895
5534
  ...extraHeaders
3896
5535
  };
3897
5536
  if (this.client) headers["x-seekrit-client"] = this.client;
3898
- if (this.auth.type === "bearer") headers.authorization = `Bearer ${this.auth.token}`;
5537
+ if (this.auth.type === "bearer") headers.authorization = `Bearer ${apiBearerToken(this.auth.token)}`;
3899
5538
  else if (this.auth.type === "dynamic") {
3900
5539
  const token = await this.auth.getToken();
3901
5540
  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;
5541
+ headers.authorization = `Bearer ${apiBearerToken(token)}`;
5542
+ } else if (this.auth.type === "m2m") {
5543
+ if (isServiceToken(this.auth.clientId.trim()) || isServiceToken(this.auth.clientSecret.trim())) throw new Error("service tokens must use bearer authentication, not machine client credentials");
5544
+ headers.authorization = `Basic ${btoa(`${this.auth.clientId}:${this.auth.clientSecret}`)}`;
5545
+ } else headers["x-seekrit-dev-user"] = this.auth.email;
3905
5546
  if (body !== void 0) headers["content-type"] = "application/json";
3906
5547
  const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
3907
5548
  method,
@@ -3991,6 +5632,66 @@ var SeekritClient = class {
3991
5632
  listMembers(orgId) {
3992
5633
  return this.request("GET", `/v1/orgs/${orgId}/members`);
3993
5634
  }
5635
+ getMemberAccess(orgId) {
5636
+ return this.request("GET", `/v1/orgs/${orgId}/members/access`);
5637
+ }
5638
+ updateMemberRole(orgId, userId, role) {
5639
+ return this.request("PATCH", `/v1/orgs/${orgId}/members/${userId}`, { role });
5640
+ }
5641
+ getAppAccess(orgId, appId) {
5642
+ return this.request("GET", `/v1/orgs/${orgId}/apps/${appId}/access`);
5643
+ }
5644
+ provisionAppAccess(orgId, appId, userId, grants) {
5645
+ return this.request("POST", `/v1/orgs/${orgId}/apps/${appId}/access`, {
5646
+ userId,
5647
+ grants
5648
+ });
5649
+ }
5650
+ /**
5651
+ * Stop auto-granting this app's future environments to a member. Keys they
5652
+ * already hold stay; revoke those per environment with `revokeEnvKey`.
5653
+ */
5654
+ revokeAppAccess(orgId, appId, userId) {
5655
+ return this.request("DELETE", `/v1/orgs/${orgId}/apps/${appId}/access/${userId}`);
5656
+ }
5657
+ accessRecipients(orgId, target) {
5658
+ const path = "appId" in target ? `apps/${target.appId}` : `groups/${target.groupId}`;
5659
+ return this.request("GET", `/v1/orgs/${orgId}/${path}/access-recipients`);
5660
+ }
5661
+ /** The caller owns the new DEK; only public keys and wrapped blobs cross the API. */
5662
+ async wrapNewEnvironmentAccess(orgId, target, dek) {
5663
+ const { recipients } = await this.accessRecipients(orgId, target);
5664
+ return Promise.all(recipients.map(async (r) => {
5665
+ if (!r.publicKeyJwk) throw new Error(`${r.email} must finish key setup before creating this environment`);
5666
+ return {
5667
+ userId: r.userId,
5668
+ wrappedDek: await wrapDek(dek, r.publicKeyJwk)
5669
+ };
5670
+ }));
5671
+ }
5672
+ async wrapGroupAppAccess(orgId, envId, groupId, getDek) {
5673
+ const { environment } = await this.getEnv(orgId, envId);
5674
+ if (!environment.applicationId) throw new Error("only app environments can compose groups");
5675
+ const { recipients } = await this.accessRecipients(orgId, { appId: environment.applicationId });
5676
+ if (!recipients.length) return [];
5677
+ const { environments } = await this.listGroupEnvs(orgId, groupId);
5678
+ const result = [];
5679
+ for (const env of environments) {
5680
+ const { grants } = await this.listEnvKeys(orgId, env.id);
5681
+ const missing = recipients.filter((r) => !grants.some((g) => g.principalType === "user" && g.principalId === r.userId));
5682
+ if (!missing.length) continue;
5683
+ const dek = await getDek(env.id);
5684
+ for (const recipient of missing) {
5685
+ if (!recipient.publicKeyJwk) throw new Error(`${recipient.email} must finish key setup first`);
5686
+ result.push({
5687
+ environmentId: env.id,
5688
+ userId: recipient.userId,
5689
+ wrappedDek: await wrapDek(dek, recipient.publicKeyJwk)
5690
+ });
5691
+ }
5692
+ }
5693
+ return result;
5694
+ }
3994
5695
  /**
3995
5696
  * The org-wide "require a second factor for all members" policy. `configured`
3996
5697
  * is false when the identity provider isn't wired up (local dev), in which
@@ -4116,9 +5817,17 @@ var SeekritClient = class {
4116
5817
  *
4117
5818
  * `note` is the proposer's explanation, carried as a header so it is simply
4118
5819
  * ignored by an unprotected environment.
5820
+ *
5821
+ * `expectedVersion` makes the write a compare-and-swap: it lands only if the
5822
+ * secret is still at that version (`0` = does not exist yet), and otherwise
5823
+ * fails with a 412 `precondition_failed` {@link SeekritApiError}.
4119
5824
  */
4120
- setSecret(orgId, envId, name, ciphertext, note) {
4121
- return this.request("PUT", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`, { ciphertext }, changeNoteHeader(note));
5825
+ setSecret(orgId, envId, name, ciphertext, note, options = {}) {
5826
+ const body = options.expectedVersion === void 0 ? { ciphertext } : {
5827
+ ciphertext,
5828
+ expectedVersion: options.expectedVersion
5829
+ };
5830
+ return this.request("PUT", `/v1/orgs/${orgId}/envs/${envId}/secrets/${name}`, body, changeNoteHeader(note));
4122
5831
  }
4123
5832
  /** Queued for review in a protected environment — see {@link setSecret}. */
4124
5833
  deleteSecret(orgId, envId, name, note) {
@@ -4175,6 +5884,46 @@ var SeekritClient = class {
4175
5884
  return this.request("POST", `/v1/orgs/${orgId}/change-requests/${id}/withdraw`);
4176
5885
  }
4177
5886
  /** The calling principal's wrapped DEK for this environment. */
5887
+ getEnvironmentKeyScope(orgId, envId) {
5888
+ return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/key-scope`);
5889
+ }
5890
+ async prepareComposedKeyGrants(orgId, envId, principal, getDek) {
5891
+ const scope = await this.getEnvironmentKeyScope(orgId, envId);
5892
+ const grants = [];
5893
+ for (const layer of scope.environments) {
5894
+ if (scope.grants.some((g) => g.environmentId === layer.environmentId && g.principalType === principal.principalType && g.principalId === principal.principalId)) continue;
5895
+ try {
5896
+ const dek = await getDek(layer.environmentId);
5897
+ grants.push({
5898
+ environmentId: layer.environmentId,
5899
+ wrappedDek: await wrapDek(dek, principal.publicKeyJwk)
5900
+ });
5901
+ } catch (error) {
5902
+ if (error instanceof Error && error.message === "unlock cancelled") throw error;
5903
+ throw new Error(`Could not prepare access to ${layer.label}: ${error instanceof Error ? error.message : "key unavailable"}. No keys were granted.`);
5904
+ }
5905
+ }
5906
+ return grants;
5907
+ }
5908
+ grantComposedKeys(orgId, envId, input) {
5909
+ return this.request("POST", `/v1/orgs/${orgId}/envs/${envId}/keys/composed`, input);
5910
+ }
5911
+ /** Sharing an application environment includes the exact layers resolve reads. */
5912
+ async grantEnvironmentAccess(orgId, envId, principal, getDek) {
5913
+ const { environment } = await this.getEnv(orgId, envId);
5914
+ if (environment.applicationId) {
5915
+ const grants = await this.prepareComposedKeyGrants(orgId, envId, principal, getDek);
5916
+ await this.grantComposedKeys(orgId, envId, {
5917
+ principalType: principal.principalType,
5918
+ principalId: principal.principalId,
5919
+ grants
5920
+ });
5921
+ } else await this.grantEnvKey(orgId, envId, {
5922
+ principalType: principal.principalType,
5923
+ principalId: principal.principalId,
5924
+ wrappedDek: await wrapDek(await getDek(envId), principal.publicKeyJwk)
5925
+ });
5926
+ }
4178
5927
  getMyEnvKey(orgId, envId) {
4179
5928
  return this.request("GET", `/v1/orgs/${orgId}/envs/${envId}/key`);
4180
5929
  }
@@ -4261,6 +6010,42 @@ var SeekritClient = class {
4261
6010
  deleteHoneyToken(orgId, honeyTokenId) {
4262
6011
  return this.request("DELETE", `/v1/orgs/${orgId}/honey-tokens/${honeyTokenId}`);
4263
6012
  }
6013
+ getConnect(orgId) {
6014
+ return this.request("GET", `/v1/orgs/${orgId}/connect`);
6015
+ }
6016
+ getConnectBrokerKey(orgId) {
6017
+ return this.request("GET", `/v1/orgs/${orgId}/connect/broker-key`);
6018
+ }
6019
+ createWorkload(orgId, input) {
6020
+ return this.request("POST", `/v1/orgs/${orgId}/connect/workloads`, input);
6021
+ }
6022
+ updateWorkload(orgId, id, input) {
6023
+ return this.request("PATCH", `/v1/orgs/${orgId}/connect/workloads/${encodeURIComponent(id)}`, input);
6024
+ }
6025
+ createConnectConnection(orgId, input) {
6026
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections`, input);
6027
+ }
6028
+ updateConnectConnection(orgId, id, input) {
6029
+ return this.request("PATCH", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}`, input);
6030
+ }
6031
+ createConnectGrant(orgId, input) {
6032
+ return this.request("POST", `/v1/orgs/${orgId}/connect/grants`, input);
6033
+ }
6034
+ startConnectOAuth(orgId, id) {
6035
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/start`, {});
6036
+ }
6037
+ finishConnectOAuth(orgId, id, state, code) {
6038
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/finish`, {
6039
+ state,
6040
+ code
6041
+ });
6042
+ }
6043
+ disconnectConnectOAuth(orgId, id) {
6044
+ return this.request("POST", `/v1/orgs/${orgId}/connect/connections/${encodeURIComponent(id)}/oauth/disconnect`, {});
6045
+ }
6046
+ revokeConnectGrant(orgId, id) {
6047
+ return this.request("DELETE", `/v1/orgs/${orgId}/connect/grants/${encodeURIComponent(id)}`);
6048
+ }
4264
6049
  listAgents(orgId) {
4265
6050
  return this.request("GET", `/v1/orgs/${orgId}/agents`);
4266
6051
  }
@@ -4339,6 +6124,7 @@ var SeekritClient = class {
4339
6124
  * identity are three different answers.
4340
6125
  */
4341
6126
  introspectAgentTask(token) {
6127
+ if (!token.startsWith("skd_")) throw new Error("expected a dispatched task token");
4342
6128
  return this.request("POST", "/v1/tasks/introspect", { token });
4343
6129
  }
4344
6130
  /** End a run's authority now. Idempotent. */
@@ -4414,6 +6200,15 @@ var SeekritClient = class {
4414
6200
  getLeaseBrokerKey(orgId) {
4415
6201
  return this.request("GET", `/v1/orgs/${orgId}/leases/broker-key`);
4416
6202
  }
6203
+ listProvisioners(orgId) {
6204
+ return this.request("GET", `/v1/orgs/${orgId}/leases/provisioners`);
6205
+ }
6206
+ registerProvisioner(orgId, input) {
6207
+ return this.request("POST", `/v1/orgs/${orgId}/leases/provisioners`, input);
6208
+ }
6209
+ deleteProvisioner(orgId, id) {
6210
+ return this.request("DELETE", `/v1/orgs/${orgId}/leases/provisioners/${id}`);
6211
+ }
4417
6212
  listLeaseTargets(orgId) {
4418
6213
  return this.request("GET", `/v1/orgs/${orgId}/leases/targets`);
4419
6214
  }
@@ -4475,7 +6270,7 @@ var SeekritClient = class {
4475
6270
  return this.request("GET", `/v1/orgs/${orgId}/leases`);
4476
6271
  }
4477
6272
  mintLease(orgId, input) {
4478
- return this.request("POST", `/v1/orgs/${orgId}/leases`, input);
6273
+ return this.authorizeLease(orgId, input).then((body) => this.request("POST", `/v1/orgs/${orgId}/leases`, body));
4479
6274
  }
4480
6275
  revokeLease(orgId, leaseId) {
4481
6276
  return this.request("DELETE", `/v1/orgs/${orgId}/leases/${leaseId}`);
@@ -4640,8 +6435,7 @@ var SeekritClient = class {
4640
6435
  return this.request("DELETE", `/v1/orgs/${orgId}/vault/projects/${projectId}/webhooks/${webhookId}`);
4641
6436
  }
4642
6437
  };
4643
- //#endregion
4644
- //#region ../cli/src/io.ts
6438
+ // ../cli/src/io.ts
4645
6439
  let failThrows = false;
4646
6440
  /**
4647
6441
  * In `seekrit mcp` the process is a long-lived stdio server, so a `fail()`
@@ -4693,8 +6487,7 @@ function promptHidden(question) {
4693
6487
  });
4694
6488
  });
4695
6489
  }
4696
- //#endregion
4697
- //#region ../cli/src/context.ts
6490
+ // ../cli/src/context.ts
4698
6491
  /** Sent as `x-seekrit-client` so the API attributes usage to the CLI (analytics). */
4699
6492
  const CLI_CLIENT = `cli/${version$1}`;
4700
6493
  /**
@@ -4738,15 +6531,17 @@ function tryBuildContext(dotenvVars = {}) {
4738
6531
  email: devUser
4739
6532
  };
4740
6533
  else return null;
4741
- return {
6534
+ const ctx = {
4742
6535
  client: new SeekritClient({
4743
6536
  baseUrl: apiUrl,
4744
6537
  auth,
4745
- client: CLI_CLIENT
6538
+ client: CLI_CLIENT,
6539
+ getLeaseSigner: async () => importPolicySigningKey(JSON.stringify(await crypto.subtle.exportKey("jwk", await getPrivateKey(ctx))))
4746
6540
  }),
4747
6541
  auth,
4748
6542
  apiUrl
4749
6543
  };
6544
+ return ctx;
4750
6545
  }
4751
6546
  function isTokenAuth(ctx) {
4752
6547
  return ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token);
@@ -4764,13 +6559,29 @@ async function getPrivateKey(ctx) {
4764
6559
  const { encryptedPrivateKey } = await ctx.client.getMyKeys();
4765
6560
  return importPrivateKey(await decryptPrivateKey(process.env.SEEKRIT_PASSPHRASE ?? await promptHidden("Passphrase: "), encryptedPrivateKey));
4766
6561
  }
6562
+ /**
6563
+ * The calling principal's public key JWK — what a freshly generated DEK is
6564
+ * wrapped to when creating an environment. Service tokens carry their private
6565
+ * key, so the public half is derived from it; users publish theirs at key
6566
+ * setup. Shared by `seekrit env create`, `seekrit init`, and the MCP server so
6567
+ * a token can create an environment everywhere, not only over MCP.
6568
+ */
6569
+ async function principalPublicKeyJwk(ctx) {
6570
+ if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
6571
+ const { privateKey } = await parseServiceToken(ctx.auth.token);
6572
+ const { d: _d, key_ops: _ops, ext: _ext, ...pub } = await crypto.subtle.exportKey("jwk", privateKey);
6573
+ return JSON.stringify(pub);
6574
+ }
6575
+ const { user } = await ctx.client.me();
6576
+ if (!user.publicKeyJwk) fail("this user has no keypair yet — run `seekrit keys setup` first");
6577
+ return user.publicKeyJwk;
6578
+ }
4767
6579
  /** Recover one environment's DEK for the current principal. */
4768
6580
  async function getDek(ctx, orgId, envId) {
4769
6581
  const [{ wrappedDek }, privateKey] = await Promise.all([ctx.client.getMyEnvKey(orgId, envId), getPrivateKey(ctx)]);
4770
6582
  return unwrapDek(wrappedDek, privateKey);
4771
6583
  }
4772
- //#endregion
4773
- //#region ../cli/src/group-sync-grants.ts
6584
+ // ../cli/src/group-sync-grants.ts
4774
6585
  /** Wrap a newly composed group layer for connections already syncing the app env or its branches. */
4775
6586
  async function syncGrantsForGroupLink(ctx, orgId, envId, envSlug, groupId) {
4776
6587
  const [{ groups }, { bindings }, { branches }] = await Promise.all([
@@ -4795,8 +6606,7 @@ async function syncGrantsForGroupLink(ctx, orgId, envId, envSlug, groupId) {
4795
6606
  };
4796
6607
  }));
4797
6608
  }
4798
- //#endregion
4799
- //#region ../cli/src/target.ts
6609
+ // ../cli/src/target.ts
4800
6610
  /** Resolve the target org from a flag, the committed config, or a lone org. */
4801
6611
  async function resolveOrg(ctx, orgSlug) {
4802
6612
  const wanted = orgSlug ?? findProjectConfig()?.org;
@@ -4829,7 +6639,11 @@ async function boundEnvTarget(ctx, opts) {
4829
6639
  try {
4830
6640
  ({scope} = await ctx.client.resolve(opts.branch ? { branch: opts.branch } : {}));
4831
6641
  } 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)})`);
6642
+ if (err instanceof SeekritApiError && err.status < 500) {
6643
+ if (opts.env) return null;
6644
+ fail(`specify --env — this token has no environment of its own to fall back to (${err.message})`);
6645
+ }
6646
+ throw err;
4833
6647
  }
4834
6648
  const env = scope.branchOf ?? {
4835
6649
  envId: scope.envId,
@@ -4856,7 +6670,10 @@ async function boundEnvTarget(ctx, opts) {
4856
6670
  * it this way; this is the same rule, in one place, for both.
4857
6671
  */
4858
6672
  async function resolveEnvTarget(ctx, opts) {
4859
- if (!opts.app && !opts.group && isTokenAuth(ctx)) return boundEnvTarget(ctx, opts);
6673
+ if (!opts.app && !opts.group && isTokenAuth(ctx)) {
6674
+ const bound = await boundEnvTarget(ctx, opts);
6675
+ if (bound) return bound;
6676
+ }
4860
6677
  const org = await resolveOrg(ctx, opts.org);
4861
6678
  if (!opts.env) fail("specify --env");
4862
6679
  if (opts.group) {
@@ -4945,8 +6762,7 @@ async function resolveGroup(ctx, opts) {
4945
6762
  slug: group.slug
4946
6763
  };
4947
6764
  }
4948
- //#endregion
4949
- //#region ../cli/src/kms.ts
6765
+ // ../cli/src/kms.ts
4950
6766
  /** The calling principal's identity + public key (for a self-grant). */
4951
6767
  async function kmsCallerIdentity(ctx) {
4952
6768
  if (ctx.auth.type === "bearer" && isServiceToken(ctx.auth.token)) {
@@ -5009,8 +6825,7 @@ async function kmsRecoverMaterial(ctx, orgId, keyId, version) {
5009
6825
  currentVersion: mat.currentVersion
5010
6826
  };
5011
6827
  }
5012
- //#endregion
5013
- //#region ../cli/src/m2m.ts
6828
+ // ../cli/src/m2m.ts
5014
6829
  /**
5015
6830
  * Resolve M2M client credentials from (in order) the process environment, a
5016
6831
  * `.env` overlay (for `seekrit run`), then saved config. Both halves must come
@@ -5077,16 +6892,24 @@ async function ensureM2mAdminToken(dotenvVars = {}) {
5077
6892
  if (!creds) return null;
5078
6893
  const cached = readCachedM2mToken(creds.clientId);
5079
6894
  if (cached) {
5080
- process.env.SEEKRIT_TOKEN = cached;
5081
- return cached;
6895
+ let usable = false;
6896
+ try {
6897
+ serviceTokenAuth(cached);
6898
+ usable = true;
6899
+ } catch {}
6900
+ if (usable) {
6901
+ process.env.SEEKRIT_TOKEN = cached;
6902
+ return cached;
6903
+ }
5082
6904
  }
5083
6905
  const token = await mintAdminToken(process.env.SEEKRIT_API_URL ?? dotenvVars.SEEKRIT_API_URL ?? readGlobalConfig().apiUrl ?? "https://api.seekrit.dev", creds);
5084
6906
  cacheM2mToken(creds.clientId, token);
5085
6907
  process.env.SEEKRIT_TOKEN = token;
5086
6908
  return token;
5087
6909
  }
5088
- //#endregion
5089
- //#region ../cli/src/cache.ts
6910
+ AGENT_LOGIN_SECRETS.codex;
6911
+ AGENT_LOGIN_SECRETS.claude;
6912
+ // ../cli/src/cache.ts
5090
6913
  /** Render an age for a log line, rounded to its largest whole unit. */
5091
6914
  function humanize(ms) {
5092
6915
  const secs = Math.floor(ms / 1e3);
@@ -5183,6 +7006,7 @@ async function materializeEnv(ctx, opts) {
5183
7006
  const privateKey = await getPrivateKey(ctx);
5184
7007
  const values = {};
5185
7008
  const provenance = {};
7009
+ const origin = {};
5186
7010
  for (const layer of layers) {
5187
7011
  const dek = await unwrapDek(layer.wrappedDek, privateKey);
5188
7012
  let label;
@@ -5192,14 +7016,32 @@ async function materializeEnv(ctx, opts) {
5192
7016
  for (const secret of layer.secrets) {
5193
7017
  values[secret.name] = await decryptSecret(dek, secret.ciphertext, secretAad(layer.environmentId, secret.name));
5194
7018
  provenance[secret.name] = label;
7019
+ origin[secret.name] = {
7020
+ envId: layer.environmentId,
7021
+ dek
7022
+ };
5195
7023
  }
5196
7024
  }
7025
+ const agentLogins = {};
7026
+ for (const [name, value] of Object.entries(values)) {
7027
+ const from = origin[name];
7028
+ if (!from || !isAgentLoginValue(value)) continue;
7029
+ agentLogins[name] = {
7030
+ orgId: scope.orgId,
7031
+ envId: from.envId,
7032
+ dek: from.dek,
7033
+ value
7034
+ };
7035
+ delete values[name];
7036
+ delete provenance[name];
7037
+ }
5197
7038
  const loadedEnvFiles = overlayEnvFiles(values, provenance, opts.envFiles);
5198
7039
  return {
5199
7040
  ...interpolateValues(values, opts.interpolate !== false),
5200
7041
  provenance,
5201
7042
  scope,
5202
- loadedEnvFiles
7043
+ loadedEnvFiles,
7044
+ agentLogins
5203
7045
  };
5204
7046
  }
5205
7047
  /**
@@ -5260,8 +7102,7 @@ function overlayEnvFiles(values, provenance, envFiles) {
5260
7102
  }
5261
7103
  return loaded;
5262
7104
  }
5263
- //#endregion
5264
- //#region ../cli/src/mcp.ts
7105
+ // ../cli/src/mcp.ts
5265
7106
  /** Lowercase-alphanumeric string for a fresh Postgres role name. */
5266
7107
  function randomLower(length) {
5267
7108
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
@@ -5308,9 +7149,18 @@ function serverInstructions() {
5308
7149
  "Auth comes from SEEKRIT_TOKEN (a skt_… token), SEEKRIT_CLIENT_ID +",
5309
7150
  "SEEKRIT_CLIENT_SECRET (machine credentials — an admin token is minted and",
5310
7151
  "cached automatically on first use), or the config saved by `seekrit login`.",
7152
+ "No credential at all? `npx -y @seekrit/cli init --org-name \"<the real project>\" --yes`",
7153
+ "signs up, saves the credential, and creates an app with a development environment.",
5311
7154
  "Decrypting under a user session (not a token) additionally needs",
5312
7155
  "SEEKRIT_PASSPHRASE set in this server's env — there's no TTY to prompt on.",
5313
7156
  "",
7157
+ "NOT THE TOOL WHEN: the value is a throwaway for one local experiment (a shell",
7158
+ "variable is fine — say so); the runtime already injects secrets natively and the",
7159
+ "team uses it (offer seekrit as the source that syncs into it, not a second copy);",
7160
+ "the policy forbids any SaaS holding even ciphertext; or what's being stored is",
7161
+ "user data rather than configuration. An honest \"you don't need this here\" beats",
7162
+ "an install.",
7163
+ "",
5314
7164
  "Model: org → apps/groups → environments → secrets. Call `whoami` first, then",
5315
7165
  "`get_started` for the recommended end-to-end recipe. Prefer `run_command` over",
5316
7166
  "`get_secret reveal:true` — it injects secrets into a subprocess so plaintext",
@@ -5377,21 +7227,6 @@ function getCtx() {
5377
7227
  function ensureDecryptable(ctx) {
5378
7228
  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
7229
  }
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
7230
  /** Run a child command with `env` and capture its output (values never returned). */
5396
7231
  function runChild(cmd, args, env, cwd) {
5397
7232
  return new Promise((resolve, reject) => {
@@ -5433,10 +7268,10 @@ async function materializeFor(ctx, o) {
5433
7268
  });
5434
7269
  }
5435
7270
  const targetShape = {
5436
- org: z.string().optional().describe("organization slug or id (defaults to a lone org)"),
5437
- app: z.string().optional().describe("application slug or id (or set via configure_project)"),
5438
- group: z.string().optional().describe("target a group environment instead of an app"),
5439
- env: z.string().optional().describe("environment slug or id (a service token infers its own)")
7271
+ org: z$1.string().optional().describe("organization slug or id (defaults to a lone org)"),
7272
+ app: z$1.string().optional().describe("application slug or id (or set via configure_project)"),
7273
+ group: z$1.string().optional().describe("target a group environment instead of an app"),
7274
+ env: z$1.string().optional().describe("environment slug or id (a service token infers its own)")
5440
7275
  };
5441
7276
  async function runMcpServer(options = {}) {
5442
7277
  setFailThrows(true);
@@ -5496,14 +7331,14 @@ async function runMcpServer(options = {}) {
5496
7331
  };
5497
7332
  });
5498
7333
  tool("list_orgs", "List organizations the caller can access.", ro, {}, async () => (await getCtx().client.listOrgs()).orgs);
5499
- tool("list_apps", "List applications in an organization.", ro, { org: z.string().optional() }, async ({ org }) => {
7334
+ tool("list_apps", "List applications in an organization.", ro, { org: z$1.string().optional() }, async ({ org }) => {
5500
7335
  const ctx = getCtx();
5501
7336
  const orgRef = await resolveOrg(ctx, org);
5502
7337
  return (await ctx.client.listApps(orgRef.id)).apps;
5503
7338
  });
5504
7339
  tool("list_envs", "List environments of an application.", ro, {
5505
- org: z.string().optional(),
5506
- app: z.string()
7340
+ org: z$1.string().optional(),
7341
+ app: z$1.string()
5507
7342
  }, async ({ org, app }) => {
5508
7343
  const ctx = getCtx();
5509
7344
  const orgRef = await resolveOrg(ctx, org);
@@ -5513,9 +7348,9 @@ async function runMcpServer(options = {}) {
5513
7348
  return (await ctx.client.listEnvs(orgRef.id, appRow.id)).environments;
5514
7349
  });
5515
7350
  tool("list_branches", "List ephemeral branch configs in an application (optionally just one environment's).", ro, {
5516
- org: z.string().optional(),
5517
- app: z.string(),
5518
- env: z.string().optional()
7351
+ org: z$1.string().optional(),
7352
+ app: z$1.string(),
7353
+ env: z$1.string().optional()
5519
7354
  }, async ({ org, app, env }) => {
5520
7355
  const ctx = getCtx();
5521
7356
  const appRef = await resolveApp(ctx, {
@@ -5530,14 +7365,14 @@ async function runMcpServer(options = {}) {
5530
7365
  });
5531
7366
  return (await ctx.client.listBranches(parent.orgId, parent.envId)).branches;
5532
7367
  });
5533
- tool("list_groups", "List shared groups (reusable secret bags) in an organization.", ro, { org: z.string().optional() }, async ({ org }) => {
7368
+ tool("list_groups", "List shared groups (reusable secret bags) in an organization.", ro, { org: z$1.string().optional() }, async ({ org }) => {
5534
7369
  const ctx = getCtx();
5535
7370
  const orgRef = await resolveOrg(ctx, org);
5536
7371
  return (await ctx.client.listGroups(orgRef.id)).groups;
5537
7372
  });
5538
7373
  tool("list_group_envs", "List a group's environments (per-slug value sets).", ro, {
5539
- org: z.string().optional(),
5540
- group: z.string()
7374
+ org: z$1.string().optional(),
7375
+ group: z$1.string()
5541
7376
  }, async ({ org, group }) => {
5542
7377
  const ctx = getCtx();
5543
7378
  const g = await resolveGroup(ctx, {
@@ -5547,9 +7382,9 @@ async function runMcpServer(options = {}) {
5547
7382
  return (await ctx.client.listGroupEnvs(g.orgId, g.id)).environments;
5548
7383
  });
5549
7384
  tool("list_env_groups", "List the groups composed into an application environment (precedence order).", ro, {
5550
- org: z.string().optional(),
5551
- app: z.string(),
5552
- env: z.string()
7385
+ org: z$1.string().optional(),
7386
+ app: z$1.string(),
7387
+ env: z$1.string()
5553
7388
  }, async ({ org, app, env }) => {
5554
7389
  const ctx = getCtx();
5555
7390
  const target = await resolveAppEnv(ctx, {
@@ -5559,22 +7394,22 @@ async function runMcpServer(options = {}) {
5559
7394
  });
5560
7395
  return (await ctx.client.listEnvGroups(target.orgId, target.envId)).groups;
5561
7396
  });
5562
- tool("list_members", "List organization members and their public keys (for granting access).", ro, { org: z.string().optional() }, async ({ org }) => {
7397
+ tool("list_members", "List organization members and their public keys (for granting access).", ro, { org: z$1.string().optional() }, async ({ org }) => {
5563
7398
  const ctx = getCtx();
5564
7399
  const orgRef = await resolveOrg(ctx, org);
5565
7400
  return (await ctx.client.listMembers(orgRef.id)).members;
5566
7401
  });
5567
- tool("kms_list_keys", "List managed KMS keys the caller can see (metadata only).", ro, { org: z.string().optional() }, async ({ org }) => {
7402
+ tool("kms_list_keys", "List managed KMS keys the caller can see (metadata only).", ro, { org: z$1.string().optional() }, async ({ org }) => {
5568
7403
  const ctx = getCtx();
5569
7404
  const orgRef = await resolveOrg(ctx, org);
5570
7405
  return (await ctx.client.listKmsKeys(orgRef.id)).keys;
5571
7406
  });
5572
7407
  tool("kms_create_key", "Create an org-scoped managed key. Material is generated locally and wrapped to each grantee (self plus any listed users/tokens); the server never sees it. Use the CLI for app/group-scoped keys.", { idempotent: false }, {
5573
- org: z.string().optional(),
5574
- name: z.string(),
5575
- purpose: z.enum(["encrypt", "sign"]),
5576
- grantUsers: z.array(z.string()).optional(),
5577
- grantTokens: z.array(z.string()).optional()
7408
+ org: z$1.string().optional(),
7409
+ name: z$1.string(),
7410
+ purpose: z$1.enum(["encrypt", "sign"]),
7411
+ grantUsers: z$1.array(z$1.string()).optional(),
7412
+ grantTokens: z$1.array(z$1.string()).optional()
5578
7413
  }, async ({ org, name, purpose, grantUsers, grantTokens }) => {
5579
7414
  const ctx = getCtx();
5580
7415
  const orgRef = await resolveOrg(ctx, org);
@@ -5611,10 +7446,10 @@ async function runMcpServer(options = {}) {
5611
7446
  return key;
5612
7447
  });
5613
7448
  tool("kms_grant", "Grant a principal (user email or token id) use of a key's current version.", { idempotent: true }, {
5614
- org: z.string().optional(),
5615
- key: z.string(),
5616
- user: z.string().optional(),
5617
- token: z.string().optional()
7449
+ org: z$1.string().optional(),
7450
+ key: z$1.string(),
7451
+ user: z$1.string().optional(),
7452
+ token: z$1.string().optional()
5618
7453
  }, async ({ org, key, user, token }) => {
5619
7454
  const ctx = getCtx();
5620
7455
  ensureDecryptable(ctx);
@@ -5636,10 +7471,10 @@ async function runMcpServer(options = {}) {
5636
7471
  };
5637
7472
  });
5638
7473
  tool("kms_encrypt", "Encrypt a value under a managed encrypt key; returns a ce1 ciphertext blob. `context` (if given) is bound as AAD and must be supplied identically to decrypt.", { readOnly: true }, {
5639
- org: z.string().optional(),
5640
- key: z.string(),
5641
- plaintext: z.string(),
5642
- context: z.string().optional()
7474
+ org: z$1.string().optional(),
7475
+ key: z$1.string(),
7476
+ plaintext: z$1.string(),
7477
+ context: z$1.string().optional()
5643
7478
  }, async ({ org, key, plaintext, context }) => {
5644
7479
  const ctx = getCtx();
5645
7480
  ensureDecryptable(ctx);
@@ -5653,10 +7488,10 @@ async function runMcpServer(options = {}) {
5653
7488
  }, plaintext, context ?? "") };
5654
7489
  });
5655
7490
  tool("kms_decrypt", "Decrypt a ce1 blob. Supply the same `context` used to encrypt.", ro, {
5656
- org: z.string().optional(),
5657
- key: z.string(),
5658
- ciphertext: z.string(),
5659
- context: z.string().optional()
7491
+ org: z$1.string().optional(),
7492
+ key: z$1.string(),
7493
+ ciphertext: z$1.string(),
7494
+ context: z$1.string().optional()
5660
7495
  }, async ({ org, key, ciphertext, context }) => {
5661
7496
  const ctx = getCtx();
5662
7497
  ensureDecryptable(ctx);
@@ -5667,8 +7502,8 @@ async function runMcpServer(options = {}) {
5667
7502
  return { plaintext: await kmsDecrypt(material, ciphertext, context ?? "") };
5668
7503
  });
5669
7504
  tool("kms_generate_data_key", "Generate a data key under a managed encrypt key (envelope encryption). Returns the plaintext key (base64) and its wrapped form to store.", { readOnly: true }, {
5670
- org: z.string().optional(),
5671
- key: z.string()
7505
+ org: z$1.string().optional(),
7506
+ key: z$1.string()
5672
7507
  }, async ({ org, key }) => {
5673
7508
  const ctx = getCtx();
5674
7509
  ensureDecryptable(ctx);
@@ -5686,9 +7521,9 @@ async function runMcpServer(options = {}) {
5686
7521
  };
5687
7522
  });
5688
7523
  tool("kms_sign", "Sign a message with a managed signing key; returns an sg1 signature blob.", { readOnly: true }, {
5689
- org: z.string().optional(),
5690
- key: z.string(),
5691
- message: z.string()
7524
+ org: z$1.string().optional(),
7525
+ key: z$1.string(),
7526
+ message: z$1.string()
5692
7527
  }, async ({ org, key, message }) => {
5693
7528
  const ctx = getCtx();
5694
7529
  ensureDecryptable(ctx);
@@ -5702,10 +7537,10 @@ async function runMcpServer(options = {}) {
5702
7537
  }, message) };
5703
7538
  });
5704
7539
  tool("kms_verify", "Verify an sg1 signature over a message using a signing key's published public key (no grant needed).", ro, {
5705
- org: z.string().optional(),
5706
- key: z.string(),
5707
- signature: z.string(),
5708
- message: z.string()
7540
+ org: z$1.string().optional(),
7541
+ key: z$1.string(),
7542
+ signature: z$1.string(),
7543
+ message: z$1.string()
5709
7544
  }, async ({ org, key, signature, message }) => {
5710
7545
  const ctx = getCtx();
5711
7546
  const orgRef = await resolveOrg(ctx, org);
@@ -5726,15 +7561,15 @@ async function runMcpServer(options = {}) {
5726
7561
  updatedAt: s.updatedAt
5727
7562
  }));
5728
7563
  });
5729
- tool("list_tokens", "List an organization's service tokens (never the secret token strings).", ro, { org: z.string().optional() }, async ({ org }) => {
7564
+ tool("list_tokens", "List an organization's service tokens (never the secret token strings).", ro, { org: z$1.string().optional() }, async ({ org }) => {
5730
7565
  const ctx = getCtx();
5731
7566
  const orgRef = await resolveOrg(ctx, org);
5732
7567
  return (await ctx.client.listTokens(orgRef.id)).tokens;
5733
7568
  });
5734
7569
  tool("audit", "Read the organization's audit trail (most recent first).", ro, {
5735
- org: z.string().optional(),
5736
- limit: z.number().int().min(1).max(200).optional(),
5737
- action: z.string().optional().describe("filter by action, e.g. secret.updated")
7570
+ org: z$1.string().optional(),
7571
+ limit: z$1.number().int().min(1).max(200).optional(),
7572
+ action: z$1.string().optional().describe("filter by action, e.g. secret.updated")
5738
7573
  }, async ({ org, limit, action }) => {
5739
7574
  const ctx = getCtx();
5740
7575
  const orgRef = await resolveOrg(ctx, org);
@@ -5744,16 +7579,16 @@ async function runMcpServer(options = {}) {
5744
7579
  })).entries;
5745
7580
  });
5746
7581
  tool("create_org", "Create an organization. Requires a user session — service tokens cannot own a Stytch org.", { idempotent: false }, {
5747
- name: z.string(),
5748
- slug: z.string()
7582
+ name: z$1.string(),
7583
+ slug: z$1.string()
5749
7584
  }, async ({ name, slug }) => (await getCtx().client.createOrg({
5750
7585
  name,
5751
7586
  slug
5752
7587
  })).org);
5753
7588
  tool("create_app", "Create an application in an organization.", { idempotent: false }, {
5754
- org: z.string().optional(),
5755
- name: z.string(),
5756
- slug: z.string()
7589
+ org: z$1.string().optional(),
7590
+ name: z$1.string(),
7591
+ slug: z$1.string()
5757
7592
  }, async ({ org, name, slug }) => {
5758
7593
  const ctx = getCtx();
5759
7594
  const orgRef = await resolveOrg(ctx, org);
@@ -5763,9 +7598,9 @@ async function runMcpServer(options = {}) {
5763
7598
  })).app;
5764
7599
  });
5765
7600
  tool("create_group", "Create a shared group (reusable secret bag) in an organization.", { idempotent: false }, {
5766
- org: z.string().optional(),
5767
- name: z.string(),
5768
- slug: z.string()
7601
+ org: z$1.string().optional(),
7602
+ name: z$1.string(),
7603
+ slug: z$1.string()
5769
7604
  }, async ({ org, name, slug }) => {
5770
7605
  const ctx = getCtx();
5771
7606
  const orgRef = await resolveOrg(ctx, org);
@@ -5775,29 +7610,31 @@ async function runMcpServer(options = {}) {
5775
7610
  })).group;
5776
7611
  });
5777
7612
  tool("create_env", "Create an application environment. Generates the data key locally and grants it to the caller.", { idempotent: false }, {
5778
- org: z.string().optional(),
5779
- app: z.string(),
5780
- name: z.string(),
5781
- slug: z.string()
7613
+ org: z$1.string().optional(),
7614
+ app: z$1.string(),
7615
+ name: z$1.string(),
7616
+ slug: z$1.string()
5782
7617
  }, async ({ org, app, name, slug }) => {
5783
7618
  const ctx = getCtx();
5784
7619
  const orgRef = await resolveOrg(ctx, org);
5785
7620
  const { apps } = await ctx.client.listApps(orgRef.id);
5786
7621
  const appRow = apps.find((a) => a.slug === app || a.id === app);
5787
7622
  if (!appRow) throw new Error(`no app "${app}" in ${orgRef.slug}`);
5788
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
7623
+ const dek = generateDek();
7624
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5789
7625
  return (await ctx.client.createEnv(orgRef.id, appRow.id, {
5790
7626
  name,
5791
7627
  slug,
5792
- wrappedDek
7628
+ wrappedDek,
7629
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(orgRef.id, { appId: appRow.id }, dek)
5793
7630
  })).environment;
5794
7631
  });
5795
7632
  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 }, {
5796
- org: z.string().optional(),
5797
- app: z.string(),
5798
- from: z.string().describe("the environment to branch"),
5799
- slug: z.string().describe("the branch name, e.g. pr-142"),
5800
- ttl: z.string().optional().describe("lifetime: 12h, 7d, 2w, … or `never` (default 7d)")
7633
+ org: z$1.string().optional(),
7634
+ app: z$1.string(),
7635
+ from: z$1.string().describe("the environment to branch"),
7636
+ slug: z$1.string().describe("the branch name, e.g. pr-142"),
7637
+ ttl: z$1.string().optional().describe("lifetime: 12h, 7d, 2w, … or `never` (default 7d)")
5801
7638
  }, async ({ org, app, from, slug, ttl }) => {
5802
7639
  const ctx = getCtx();
5803
7640
  const parent = await resolveAppEnv(ctx, {
@@ -5828,9 +7665,9 @@ async function runMcpServer(options = {}) {
5828
7665
  })).branch;
5829
7666
  });
5830
7667
  tool("delete_branch", "Tear down a branch config and every value it overrode. The parent environment is untouched.", destructive, {
5831
- org: z.string().optional(),
5832
- app: z.string(),
5833
- branch: z.string()
7668
+ org: z$1.string().optional(),
7669
+ app: z$1.string(),
7670
+ branch: z$1.string()
5834
7671
  }, async ({ org, app, branch }) => {
5835
7672
  const ctx = getCtx();
5836
7673
  const appRef = await resolveApp(ctx, {
@@ -5842,29 +7679,31 @@ async function runMcpServer(options = {}) {
5842
7679
  return { deleted: target.slug };
5843
7680
  });
5844
7681
  tool("create_group_env", "Create a group environment. Generates the data key locally and grants it to the caller.", { idempotent: false }, {
5845
- org: z.string().optional(),
5846
- group: z.string(),
5847
- name: z.string(),
5848
- slug: z.string()
7682
+ org: z$1.string().optional(),
7683
+ group: z$1.string(),
7684
+ name: z$1.string(),
7685
+ slug: z$1.string()
5849
7686
  }, async ({ org, group, name, slug }) => {
5850
7687
  const ctx = getCtx();
5851
7688
  const g = await resolveGroup(ctx, {
5852
7689
  org,
5853
7690
  group
5854
7691
  });
5855
- const wrappedDek = await wrapDek(generateDek(), await principalPublicKeyJwk(ctx));
7692
+ const dek = generateDek();
7693
+ const wrappedDek = await wrapDek(dek, await principalPublicKeyJwk(ctx));
5856
7694
  return (await ctx.client.createGroupEnv(g.orgId, g.id, {
5857
7695
  name,
5858
7696
  slug,
5859
- wrappedDek
7697
+ wrappedDek,
7698
+ userGrants: await ctx.client.wrapNewEnvironmentAccess(g.orgId, { groupId: g.id }, dek)
5860
7699
  })).environment;
5861
7700
  });
5862
7701
  tool("compose_group", "Compose a group into an application environment (higher position wins on name clashes).", { idempotent: true }, {
5863
- org: z.string().optional(),
5864
- app: z.string(),
5865
- env: z.string(),
5866
- group: z.string(),
5867
- position: z.number().int().min(0).optional()
7702
+ org: z$1.string().optional(),
7703
+ app: z$1.string(),
7704
+ env: z$1.string(),
7705
+ group: z$1.string(),
7706
+ position: z$1.number().int().min(0).optional()
5868
7707
  }, async ({ org, app, env, group, position }) => {
5869
7708
  const ctx = getCtx();
5870
7709
  const target = await resolveAppEnv(ctx, {
@@ -5878,16 +7717,17 @@ async function runMcpServer(options = {}) {
5878
7717
  });
5879
7718
  const syncGrants = await syncGrantsForGroupLink(ctx, target.orgId, target.envId, target.envSlug, g.id);
5880
7719
  return (await ctx.client.linkEnvGroup(target.orgId, target.envId, {
7720
+ appAccessGrants: await ctx.client.wrapGroupAppAccess(target.orgId, target.envId, g.id, (id) => getDek(ctx, target.orgId, id)),
5881
7721
  groupId: g.id,
5882
7722
  position,
5883
7723
  syncGrants
5884
7724
  })).group;
5885
7725
  });
5886
7726
  tool("uncompose_group", "Remove a composed group from an application environment.", { idempotent: true }, {
5887
- org: z.string().optional(),
5888
- app: z.string(),
5889
- env: z.string(),
5890
- group: z.string()
7727
+ org: z$1.string().optional(),
7728
+ app: z$1.string(),
7729
+ env: z$1.string(),
7730
+ group: z$1.string()
5891
7731
  }, async ({ org, app, env, group }) => {
5892
7732
  const ctx = getCtx();
5893
7733
  const target = await resolveAppEnv(ctx, {
@@ -5904,9 +7744,9 @@ async function runMcpServer(options = {}) {
5904
7744
  });
5905
7745
  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 }, {
5906
7746
  ...targetShape,
5907
- name: z.string(),
5908
- value: z.string(),
5909
- note: z.string().optional()
7747
+ name: z$1.string(),
7748
+ value: z$1.string(),
7749
+ note: z$1.string().optional()
5910
7750
  }, async (o) => {
5911
7751
  const ctx = getCtx();
5912
7752
  ensureDecryptable(ctx);
@@ -5925,10 +7765,10 @@ async function runMcpServer(options = {}) {
5925
7765
  });
5926
7766
  tool("get_secret", "Return one secret. By default only reports presence + version; pass reveal:true to decrypt the plaintext into this response (avoid unless the value is actually needed — prefer run_command). A revealed current value has its ${OTHER_SECRET} references expanded against this environment's own secrets; pass raw:true for the stored text instead. Pass `version` to read an earlier version instead of the current one (always as stored, never expanded).", ro, {
5927
7767
  ...targetShape,
5928
- name: z.string(),
5929
- reveal: z.boolean().optional(),
5930
- raw: z.boolean().optional().describe("skip ${OTHER_SECRET} expansion (with reveal)"),
5931
- version: z.number().int().positive().optional().describe("an earlier version from list_secret_versions (default: current)")
7768
+ name: z$1.string(),
7769
+ reveal: z$1.boolean().optional(),
7770
+ raw: z$1.boolean().optional().describe("skip ${OTHER_SECRET} expansion (with reveal)"),
7771
+ version: z$1.number().int().positive().optional().describe("an earlier version from list_secret_versions (default: current)")
5932
7772
  }, async (o) => {
5933
7773
  const ctx = getCtx();
5934
7774
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
@@ -5962,8 +7802,8 @@ async function runMcpServer(options = {}) {
5962
7802
  });
5963
7803
  tool("list_secret_versions", "List a secret's version history: who wrote each version, when, and which ones were restores. Never returns values — pair it with restore_secret to roll back, or get_secret(version, reveal:true) to inspect one.", ro, {
5964
7804
  ...targetShape,
5965
- name: z.string(),
5966
- limit: z.number().int().min(1).max(200).optional().describe("default 20")
7805
+ name: z$1.string(),
7806
+ limit: z$1.number().int().min(1).max(200).optional().describe("default 20")
5967
7807
  }, async (o) => {
5968
7808
  const ctx = getCtx();
5969
7809
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
@@ -5980,9 +7820,9 @@ async function runMcpServer(options = {}) {
5980
7820
  });
5981
7821
  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 }, {
5982
7822
  ...targetShape,
5983
- name: z.string(),
5984
- version: z.number().int().positive(),
5985
- note: z.string().optional()
7823
+ name: z$1.string(),
7824
+ version: z$1.number().int().positive(),
7825
+ note: z$1.string().optional()
5986
7826
  }, async (o) => {
5987
7827
  const ctx = getCtx();
5988
7828
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
@@ -6001,8 +7841,8 @@ async function runMcpServer(options = {}) {
6001
7841
  });
6002
7842
  tool("delete_secret", "Delete a secret from an environment.", destructive, {
6003
7843
  ...targetShape,
6004
- name: z.string(),
6005
- note: z.string().optional()
7844
+ name: z$1.string(),
7845
+ note: z$1.string().optional()
6006
7846
  }, async (o) => {
6007
7847
  const ctx = getCtx();
6008
7848
  const { orgId, envId } = await resolveEnvTarget(ctx, o);
@@ -6021,15 +7861,15 @@ async function runMcpServer(options = {}) {
6021
7861
  destructive: true,
6022
7862
  idempotent: false
6023
7863
  }, {
6024
- command: z.string().describe("executable to run"),
6025
- args: z.array(z.string()).optional(),
6026
- org: z.string().optional(),
6027
- app: z.string().optional(),
6028
- env: z.string().optional().describe("environment slug (token auth infers this)"),
6029
- branch: z.string().optional().describe("read an ephemeral branch of that environment"),
6030
- with: z.record(z.string(), z.string()).optional().describe("group=env slice overrides"),
6031
- envFile: z.array(z.string()).optional().describe(".env files to overlay (default [.env])"),
6032
- cwd: z.string().optional()
7864
+ command: z$1.string().describe("executable to run"),
7865
+ args: z$1.array(z$1.string()).optional(),
7866
+ org: z$1.string().optional(),
7867
+ app: z$1.string().optional(),
7868
+ env: z$1.string().optional().describe("environment slug (token auth infers this)"),
7869
+ branch: z$1.string().optional().describe("read an ephemeral branch of that environment"),
7870
+ with: z$1.record(z$1.string(), z$1.string()).optional().describe("group=env slice overrides"),
7871
+ envFile: z$1.array(z$1.string()).optional().describe(".env files to overlay (default [.env])"),
7872
+ cwd: z$1.string().optional()
6033
7873
  }, async (o) => {
6034
7874
  const ctx = getCtx();
6035
7875
  ensureDecryptable(ctx);
@@ -6044,12 +7884,12 @@ async function runMcpServer(options = {}) {
6044
7884
  };
6045
7885
  });
6046
7886
  tool("export_env", "Write the resolved secrets to a dotenv file on disk and return the variable names written (never the values). Use to materialize a .env for local tooling.", destructive, {
6047
- file: z.string().describe("path to write, e.g. .env"),
6048
- org: z.string().optional(),
6049
- app: z.string().optional(),
6050
- env: z.string().optional(),
6051
- branch: z.string().optional().describe("read an ephemeral branch of that environment"),
6052
- with: z.record(z.string(), z.string()).optional()
7887
+ file: z$1.string().describe("path to write, e.g. .env"),
7888
+ org: z$1.string().optional(),
7889
+ app: z$1.string().optional(),
7890
+ env: z$1.string().optional(),
7891
+ branch: z$1.string().optional().describe("read an ephemeral branch of that environment"),
7892
+ with: z$1.record(z$1.string(), z$1.string()).optional()
6053
7893
  }, async (o) => {
6054
7894
  const ctx = getCtx();
6055
7895
  ensureDecryptable(ctx);
@@ -6063,11 +7903,11 @@ async function runMcpServer(options = {}) {
6063
7903
  };
6064
7904
  });
6065
7905
  tool("create_token", "Mint a service token, printed once. Runtime tokens bind to one app environment (auto-granted its keys, so a command/agent can decrypt it). Pass admin:true for an org-scoped provisioning token (create apps/groups/envs, grant, mint tokens) — admin tokens need no env binding.", { idempotent: false }, {
6066
- name: z.string().describe("display name, e.g. ci-deploy or agent-session"),
6067
- org: z.string().optional(),
6068
- app: z.string().optional().describe("bind to this app (runtime tokens)"),
6069
- env: z.string().optional().describe("bind to this env (runtime tokens)"),
6070
- admin: z.boolean().optional().describe("mint an org-scoped admin token")
7906
+ name: z$1.string().describe("display name, e.g. ci-deploy or agent-session"),
7907
+ org: z$1.string().optional(),
7908
+ app: z$1.string().optional().describe("bind to this app (runtime tokens)"),
7909
+ env: z$1.string().optional().describe("bind to this env (runtime tokens)"),
7910
+ admin: z$1.boolean().optional().describe("mint an org-scoped admin token")
6071
7911
  }, async ({ name, org, app, env, admin }) => {
6072
7912
  const ctx = getCtx();
6073
7913
  const role = admin ? "admin" : "member";
@@ -6080,32 +7920,21 @@ async function runMcpServer(options = {}) {
6080
7920
  env
6081
7921
  }) : { orgId: (await resolveOrg(ctx, org)).id };
6082
7922
  const created = await createServiceToken();
7923
+ if (boundToEnv) ensureDecryptable(ctx);
7924
+ const initialGrants = "envId" in target ? await ctx.client.prepareComposedKeyGrants(target.orgId, target.envId, {
7925
+ principalType: "service_token",
7926
+ principalId: created.tokenId,
7927
+ publicKeyJwk: created.publicKeyJwk
7928
+ }, (id) => getDek(ctx, target.orgId, id)) : void 0;
6083
7929
  await ctx.client.createToken(target.orgId, {
6084
7930
  name,
6085
7931
  tokenId: created.tokenId,
6086
7932
  tokenHash: created.tokenHash,
6087
7933
  publicKeyJwk: created.publicKeyJwk,
6088
7934
  role,
6089
- environmentId: "envId" in target ? target.envId : null
7935
+ environmentId: "envId" in target ? target.envId : null,
7936
+ initialGrants
6090
7937
  });
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
7938
  return {
6110
7939
  token: created.token,
6111
7940
  tokenId: created.tokenId,
@@ -6114,8 +7943,8 @@ async function runMcpServer(options = {}) {
6114
7943
  };
6115
7944
  });
6116
7945
  tool("revoke_token", "Revoke a service token by id.", destructive, {
6117
- org: z.string().optional(),
6118
- tokenId: z.string()
7946
+ org: z$1.string().optional(),
7947
+ tokenId: z$1.string()
6119
7948
  }, async ({ org, tokenId }) => {
6120
7949
  const ctx = getCtx();
6121
7950
  const orgRef = await resolveOrg(ctx, org);
@@ -6127,14 +7956,13 @@ async function runMcpServer(options = {}) {
6127
7956
  });
6128
7957
  tool("grant_env", "Grant a member (by email) or service token (by id) access to an environment's data key. Re-wraps the DEK to the grantee — the caller must already hold the key.", { idempotent: true }, {
6129
7958
  ...targetShape,
6130
- user: z.string().optional().describe("org member email"),
6131
- token: z.string().optional().describe("service token id (skt_…)")
7959
+ user: z$1.string().optional().describe("org member email"),
7960
+ token: z$1.string().optional().describe("service token id (skt_…)")
6132
7961
  }, async (o) => {
6133
7962
  if (Boolean(o.user) === Boolean(o.token)) throw new Error("pass exactly one of user or token");
6134
7963
  const ctx = getCtx();
6135
7964
  ensureDecryptable(ctx);
6136
7965
  const { orgId, envId, label } = await resolveEnvTarget(ctx, o);
6137
- const dek = await getDek(ctx, orgId, envId);
6138
7966
  let principalType;
6139
7967
  let principalId;
6140
7968
  let publicKeyJwk;
@@ -6158,11 +7986,11 @@ async function runMcpServer(options = {}) {
6158
7986
  t.publicKeyJwk
6159
7987
  ];
6160
7988
  }
6161
- await ctx.client.grantEnvKey(orgId, envId, {
7989
+ await ctx.client.grantEnvironmentAccess(orgId, envId, {
6162
7990
  principalType,
6163
7991
  principalId,
6164
- wrappedDek: await wrapDek(dek, publicKeyJwk)
6165
- });
7992
+ publicKeyJwk
7993
+ }, (id) => getDek(ctx, orgId, id));
6166
7994
  return {
6167
7995
  ok: true,
6168
7996
  env: label,
@@ -6170,16 +7998,16 @@ async function runMcpServer(options = {}) {
6170
7998
  principalId
6171
7999
  };
6172
8000
  });
6173
- tool("list_pg_targets", "List registered Postgres provisioning targets for temporary credentials.", ro, { org: z.string().optional() }, async ({ org }) => {
8001
+ tool("list_pg_targets", "List registered Postgres provisioning targets for temporary credentials.", ro, { org: z$1.string().optional() }, async ({ org }) => {
6174
8002
  const ctx = getCtx();
6175
8003
  const orgRef = await resolveOrg(ctx, org);
6176
8004
  return (await ctx.client.listLeaseTargets(orgRef.id)).targets;
6177
8005
  });
6178
8006
  tool("create_pg_lease", "Mint a short-lived Postgres credential against a target and return a ready-to-use connection URL. The password is generated on THIS machine and only its SCRAM verifier is sent to the API — the plaintext never reaches seekrit or Postgres at rest. The role auto-expires; revoke early with revoke_pg_lease.", { idempotent: false }, {
6179
- org: z.string().optional(),
6180
- target: z.string().describe("target id or name"),
6181
- role: z.string().optional().describe("role name to create (default: random tmp_ name)"),
6182
- ttlSeconds: z.number().int().min(60).max(604800).optional().describe("lifetime (default 3600)")
8007
+ org: z$1.string().optional(),
8008
+ target: z$1.string().describe("target id or name"),
8009
+ role: z$1.string().optional().describe("role name to create (default: random tmp_ name)"),
8010
+ ttlSeconds: z$1.number().int().min(60).max(604800).optional().describe("lifetime (default 3600)")
6183
8011
  }, async ({ org, target, role, ttlSeconds }) => {
6184
8012
  const ctx = getCtx();
6185
8013
  const orgRef = await resolveOrg(ctx, org);
@@ -6204,14 +8032,14 @@ async function runMcpServer(options = {}) {
6204
8032
  note: "short-lived credential; it auto-expires and the plaintext is not stored anywhere"
6205
8033
  };
6206
8034
  });
6207
- tool("list_pg_leases", "List Postgres leases (the ledger — never secret material).", ro, { org: z.string().optional() }, async ({ org }) => {
8035
+ tool("list_pg_leases", "List Postgres leases (the ledger — never secret material).", ro, { org: z$1.string().optional() }, async ({ org }) => {
6208
8036
  const ctx = getCtx();
6209
8037
  const orgRef = await resolveOrg(ctx, org);
6210
8038
  return (await ctx.client.listLeases(orgRef.id)).leases;
6211
8039
  });
6212
8040
  tool("revoke_pg_lease", "Revoke a Postgres lease now (drops the role immediately).", destructive, {
6213
- org: z.string().optional(),
6214
- leaseId: z.string()
8041
+ org: z$1.string().optional(),
8042
+ leaseId: z$1.string()
6215
8043
  }, async ({ org, leaseId }) => {
6216
8044
  const ctx = getCtx();
6217
8045
  const orgRef = await resolveOrg(ctx, org);
@@ -6221,16 +8049,16 @@ async function runMcpServer(options = {}) {
6221
8049
  leaseId
6222
8050
  };
6223
8051
  });
6224
- tool("list_mysql_targets", "List registered MySQL/MariaDB provisioning targets for temporary credentials.", ro, { org: z.string().optional() }, async ({ org }) => {
8052
+ tool("list_mysql_targets", "List registered MySQL/MariaDB provisioning targets for temporary credentials.", ro, { org: z$1.string().optional() }, async ({ org }) => {
6225
8053
  const ctx = getCtx();
6226
8054
  const orgRef = await resolveOrg(ctx, org);
6227
8055
  return (await ctx.client.listLeaseTargets(orgRef.id)).targets.filter((t) => t.provider === "mysql");
6228
8056
  });
6229
8057
  tool("create_mysql_lease", "Mint a short-lived MySQL/MariaDB credential against a target and return a ready-to-use connection URL. The password is generated on THIS machine and only its mysql_native_password hash is sent to the API — the plaintext never reaches seekrit or MySQL at rest. The user auto-expires; revoke early with revoke_mysql_lease.", { idempotent: false }, {
6230
- org: z.string().optional(),
6231
- target: z.string().describe("target id or name"),
6232
- user: z.string().optional().describe("user name to create (default: random tmp_ name)"),
6233
- ttlSeconds: z.number().int().min(60).max(604800).optional().describe("lifetime (default 3600)")
8058
+ org: z$1.string().optional(),
8059
+ target: z$1.string().describe("target id or name"),
8060
+ user: z$1.string().optional().describe("user name to create (default: random tmp_ name)"),
8061
+ ttlSeconds: z$1.number().int().min(60).max(604800).optional().describe("lifetime (default 3600)")
6234
8062
  }, async ({ org, target, user, ttlSeconds }) => {
6235
8063
  const ctx = getCtx();
6236
8064
  const orgRef = await resolveOrg(ctx, org);
@@ -6256,14 +8084,14 @@ async function runMcpServer(options = {}) {
6256
8084
  note: "short-lived credential; it auto-expires and the plaintext is not stored anywhere"
6257
8085
  };
6258
8086
  });
6259
- tool("list_mysql_leases", "List MySQL/MariaDB leases (the ledger — never secret material).", ro, { org: z.string().optional() }, async ({ org }) => {
8087
+ tool("list_mysql_leases", "List MySQL/MariaDB leases (the ledger — never secret material).", ro, { org: z$1.string().optional() }, async ({ org }) => {
6260
8088
  const ctx = getCtx();
6261
8089
  const orgRef = await resolveOrg(ctx, org);
6262
8090
  return (await ctx.client.listLeases(orgRef.id)).leases.filter((l) => l.provider === "mysql");
6263
8091
  });
6264
8092
  tool("revoke_mysql_lease", "Revoke a MySQL/MariaDB lease now (drops the user immediately).", destructive, {
6265
- org: z.string().optional(),
6266
- leaseId: z.string()
8093
+ org: z$1.string().optional(),
8094
+ leaseId: z$1.string()
6267
8095
  }, async ({ org, leaseId }) => {
6268
8096
  const ctx = getCtx();
6269
8097
  const orgRef = await resolveOrg(ctx, org);
@@ -6274,9 +8102,9 @@ async function runMcpServer(options = {}) {
6274
8102
  };
6275
8103
  });
6276
8104
  tool("configure_project", "Link a directory to an org/app by writing seekrit.json (like `seekrit init`). The environment is chosen by the service token at runtime.", destructive, {
6277
- org: z.string(),
6278
- app: z.string(),
6279
- dir: z.string().optional()
8105
+ org: z$1.string(),
8106
+ app: z$1.string(),
8107
+ dir: z$1.string().optional()
6280
8108
  }, async ({ org, app, dir }) => {
6281
8109
  const ctx = getCtx();
6282
8110
  const orgRef = await resolveOrg(ctx, org);
@@ -6293,8 +8121,7 @@ async function runMcpServer(options = {}) {
6293
8121
  });
6294
8122
  await server.connect(new StdioServerTransport());
6295
8123
  }
6296
- //#endregion
6297
- //#region src/index.ts
8124
+ // src/index.ts
6298
8125
  /**
6299
8126
  * `@seekrit/mcp` — a standalone, `npx`-able entrypoint for seekrit's MCP server.
6300
8127
  *
@@ -6311,10 +8138,9 @@ async function runMcpServer(options = {}) {
6311
8138
  * `seekrit mcp`. tsdown bundles the shared server source in at build time, so the
6312
8139
  * published package is self-contained and needs no `@seekrit/cli` install.
6313
8140
  */
6314
- runMcpServer({ version: "0.8.6" }).catch((err) => {
8141
+ runMcpServer({ version: "0.10.0" }).catch((err) => {
6315
8142
  const message = err instanceof Error ? err.message : String(err);
6316
8143
  process.stderr.write(`seekrit-mcp: fatal: ${message}\n`);
6317
8144
  process.exit(1);
6318
8145
  });
6319
- //#endregion
6320
8146
  export {};