@secretenvs/cli 1.6.0 → 2.0.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 (3) hide show
  1. package/README.md +13 -13
  2. package/dist/index.js +97 -85
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -6,19 +6,19 @@ are bundled into the build, so the packed tarball installs on its own.
6
6
 
7
7
  ## Commands
8
8
 
9
- | Command | What it does |
10
- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
11
- | `secretenvs login [--url <baseUrl>]` | Prompts for email and password (hidden), plus a 2FA code if the account has it on; stores an API token. |
12
- | `secretenvs logout` | Deletes the stored credentials. |
13
- | `secretenvs whoami` | Shows the server, account and token prefix, and checks the token still works. |
14
- | `secretenvs projects` | Lists accessible projects (slug, role, name). |
15
- | `secretenvs envs -p <project>` | Lists the environments of a project. |
16
- | `secretenvs list -p <project> -e <env> [--reveal]` | Lists keys and their source (`env` / `shared`). Values are masked. |
17
- | `secretenvs set KEY=VALUE -p <project> -e <env>` | Creates or updates an environment variable (needs EDITOR). |
18
- | `secretenvs history KEY -p <project> -e <env> [--shared] [--limit]` | Lists versions: number, change, author, time. Values are never shown. |
19
- | `secretenvs rollback KEY --to <n> -p <project> -e <env> [--shared] [--yes]` | Restores version `n` as a **new** version (needs EDITOR). Asks to confirm. |
20
- | `secretenvs pull -p <project> -e <env> [--out .env] [--format dotenv\|json] [--force]` | Writes the resolved variables to a file (mode `0600`). |
21
- | `secretenvs run -p <project> -e <env> -- <command...>` | Runs a command with the variables injected into its environment. |
9
+ | Command | What it does |
10
+ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
+ | `secretenvs login [--url <baseUrl>]` | Asks for an API token you created in the web app (Settings > API tokens), checks it with the server and stores it. There is no email and password login: accounts sign in through SIAM. |
12
+ | `secretenvs logout` | Deletes the stored credentials. |
13
+ | `secretenvs whoami` | Shows the server, account and token prefix, and checks the token still works. |
14
+ | `secretenvs projects` | Lists accessible projects (slug, role, name). |
15
+ | `secretenvs envs -p <project>` | Lists the environments of a project. |
16
+ | `secretenvs list -p <project> -e <env> [--reveal]` | Lists keys and their source (`env` / `shared`). Values are masked. |
17
+ | `secretenvs set KEY=VALUE -p <project> -e <env>` | Creates or updates an environment variable (needs EDITOR). |
18
+ | `secretenvs history KEY -p <project> -e <env> [--shared] [--limit]` | Lists versions: number, change, author, time. Values are never shown. |
19
+ | `secretenvs rollback KEY --to <n> -p <project> -e <env> [--shared] [--yes]` | Restores version `n` as a **new** version (needs EDITOR). Asks to confirm. |
20
+ | `secretenvs pull -p <project> -e <env> [--out .env] [--format dotenv\|json] [--force]` | Writes the resolved variables to a file (mode `0600`). |
21
+ | `secretenvs run -p <project> -e <env> -- <command...>` | Runs a command with the variables injected into its environment. |
22
22
 
23
23
  Every command supports `--help`. Failures print a message to stderr and exit
24
24
  with a non-zero code. `run` exits with the code of the command it started.
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ function defaultDeps() {
24
24
  var spawnCommand = (command, args, options) => crossSpawn(command, args, options);
25
25
 
26
26
  // src/program.ts
27
- import { Command, CommanderError } from "commander";
27
+ import { Command, CommanderError, Option } from "commander";
28
28
 
29
29
  // src/commands.ts
30
30
  import { chmod as chmod2, writeFile as writeFile2 } from "fs/promises";
@@ -41,12 +41,8 @@ var MAX_KEY_LENGTH = 128;
41
41
  var MAX_VALUE_BYTES = 64 * 1024;
42
42
  var MAX_NAME_LENGTH = 64;
43
43
  var MAX_BULK_VARIABLES = 500;
44
- var MIN_PASSWORD_LENGTH = 12;
45
- var MAX_PASSWORD_LENGTH = 256;
46
44
  var MAX_VERSIONS_LIMIT = 100;
47
- var CSRF_HEADER_NAME = "x-requested-with";
48
- var CSRF_HEADER_VALUE = "secretenvs-web";
49
- var MAX_AUTH_CODE_LENGTH = 32;
45
+ var TOKEN_PREFIX = "svt_";
50
46
  var ProjectRole = z.enum(["OWNER", "ADMIN", "EDITOR", "VIEWER"]);
51
47
  var TokenAccess = z.enum(["READ", "READ_WRITE"]);
52
48
  var VersionChangeType = z.enum(["CREATED", "UPDATED", "ROLLBACK"]);
@@ -54,7 +50,6 @@ var ErrorCode = z.enum([
54
50
  "VALIDATION_ERROR",
55
51
  "BAD_REQUEST",
56
52
  "UNAUTHENTICATED",
57
- "MFA_REQUIRED",
58
53
  "FORBIDDEN",
59
54
  "NOT_FOUND",
60
55
  "CONFLICT",
@@ -76,36 +71,19 @@ var variableValue = z2.string().refine(
76
71
  var secretExpiry = isoDate.refine((value) => Date.parse(value) > Date.now(), {
77
72
  message: "Expiry must be in the future"
78
73
  }).nullable();
79
- var password2 = z2.string().min(MIN_PASSWORD_LENGTH).max(MAX_PASSWORD_LENGTH);
80
- var RegisterInput = z2.object({ email, name, password: password2 }).strict();
81
- var authCode = z2.string().trim().min(1, "Enter your code").max(MAX_AUTH_CODE_LENGTH);
82
- var LoginInput = z2.object({
83
- email,
84
- password: z2.string().min(1).max(MAX_PASSWORD_LENGTH),
85
- code: authCode.optional()
86
- }).strict();
87
74
  var UserDto = z2.object({
88
75
  id,
89
76
  email,
90
77
  name,
91
78
  createdAt: isoDate,
92
- twoFactorEnabled: z2.boolean(),
93
- // Name the user gave the authenticator app at setup; null while 2FA is off.
94
- twoFactorAppName: z2.string().nullable(),
95
79
  // Whether the account may use the /admin pages (set directly in the database).
96
80
  isSuperAdmin: z2.boolean()
97
81
  }).strict();
98
- var TwoFactorSetupDto = z2.object({ secret: z2.string(), otpauthUri: z2.string() }).strict();
99
- var TwoFactorSetupInput = z2.object({ password: z2.string().min(1).max(MAX_PASSWORD_LENGTH) }).strict();
100
- var TwoFactorEnableInput = z2.object({
101
- appName: z2.string().trim().min(1, "Enter the app name").max(MAX_NAME_LENGTH),
102
- code: z2.string().trim().regex(/^\d{6}$/, "Enter the 6-digit code")
103
- }).strict();
104
- var TwoFactorConfirmInput = z2.object({
105
- password: z2.string().min(1).max(MAX_PASSWORD_LENGTH),
106
- code: authCode
82
+ var AuthOptionsDto = z2.object({
83
+ // Where people manage their SIAM account (name, email, password, two-factor); null when the
84
+ // server does not say.
85
+ profileUrl: z2.string().nullable()
107
86
  }).strict();
108
- var RecoveryCodesDto = z2.object({ recoveryCodes: z2.array(z2.string()) }).strict();
109
87
  var CreateProjectInput = z2.object({ name, slug, description: z2.string().max(500).optional() }).strict();
110
88
  var UpdateProjectInput = z2.object({
111
89
  name: name.optional(),
@@ -244,6 +222,7 @@ var SdkProjectDto = z2.object({
244
222
  role: ProjectRole,
245
223
  environments: z2.array(SdkEnvironmentDto)
246
224
  }).strict();
225
+ var SdkMeDto = z2.object({ id, email, name }).strict();
247
226
  var adminPerson = z2.object({ id, name, email }).strict();
248
227
  var AdminProjectDto = ProjectDto.extend({
249
228
  owner: adminPerson.nullable(),
@@ -264,14 +243,7 @@ var AdminUserDetailDto = AdminUserDto.extend({
264
243
  // Every project the user is a member of, with their role there.
265
244
  projects: z2.array(z2.object({ id, name, slug, role: ProjectRole }).strict())
266
245
  });
267
- var AdminUpdateUserInput = z2.object({
268
- name: name.optional(),
269
- email: email.optional(),
270
- disabled: z2.boolean().optional()
271
- }).strict().refine(
272
- (input2) => input2.name !== void 0 || input2.email !== void 0 || input2.disabled !== void 0,
273
- { message: "Provide name, email and/or disabled" }
274
- );
246
+ var AdminUpdateUserInput = z2.object({ disabled: z2.boolean() }).strict();
275
247
  var CreateTokenInput = z2.object({
276
248
  name,
277
249
  access: TokenAccess,
@@ -324,10 +296,59 @@ var apiEnvironmentSchema = z3.object({
324
296
  TRUST_PROXY: z3.coerce.number().int().min(0).max(10).default(0),
325
297
  // Shared secret for the daily expiry-reminder call (see docs/DEPLOYMENT.md). Unset turns
326
298
  // that endpoint off.
327
- CRON_SECRET: z3.string().min(32).max(256).optional()
328
- }).strict().transform((environment) => ({
299
+ CRON_SECRET: z3.string().min(32).max(256).optional(),
300
+ // Sign-in through SIAM (https://siam.ankityadav.net.in/docs) is the only way in, so the four
301
+ // IAM_* values below are required (see the refinement). The one exception is local
302
+ // development with DEV_SIAM_STUB, and NODE_ENV=test, where tests inject their own SIAM.
303
+ IAM_BASE_URL: z3.url().optional(),
304
+ IAM_CLIENT_ID: z3.string().min(1).max(256).optional(),
305
+ IAM_CLIENT_SECRET: z3.string().min(1).max(512).optional(),
306
+ IAM_REDIRECT_URI: z3.url().optional(),
307
+ // The page where people manage their SIAM account (name, email, password, two-factor). The
308
+ // account page links to it. Optional: without it the page just says to use SIAM.
309
+ IAM_PROFILE_URL: z3.url().refine(
310
+ (value) => ["http:", "https:"].includes(new URL(value).protocol),
311
+ "Expected an HTTP(S) URL"
312
+ ).optional(),
313
+ // A SIAM permission the user must hold to get in (e.g. `secretenvs.access`). Unset: any
314
+ // active SIAM account may sign in. A SIAM superadmin always may.
315
+ IAM_REQUIRED_PERMISSION: z3.string().min(1).max(128).optional(),
316
+ // Link a SIAM sign-in to an existing local account with the same email. Off by default,
317
+ // because it is only safe when SIAM verifies that people own the email they sign up with.
318
+ IAM_LINK_BY_EMAIL: z3.enum(["true", "false"]).optional(),
319
+ // Local development only: replaces SIAM with a built-in stand-in that signs in one fixed
320
+ // fake user without asking for anything. Refused outside NODE_ENV=development.
321
+ DEV_SIAM_STUB: z3.enum(["true", "false"]).optional()
322
+ }).strict().superRefine((environment, context) => {
323
+ const names = [
324
+ "IAM_BASE_URL",
325
+ "IAM_CLIENT_ID",
326
+ "IAM_CLIENT_SECRET",
327
+ "IAM_REDIRECT_URI"
328
+ ];
329
+ const stub = environment.DEV_SIAM_STUB === "true";
330
+ if (stub && environment.NODE_ENV !== "development") {
331
+ context.addIssue({
332
+ code: "custom",
333
+ path: ["DEV_SIAM_STUB"],
334
+ message: "Only allowed when NODE_ENV is development"
335
+ });
336
+ }
337
+ if (stub || environment.NODE_ENV === "test") return;
338
+ for (const name2 of names) {
339
+ if (environment[name2] === void 0) {
340
+ context.addIssue({
341
+ code: "custom",
342
+ path: [name2],
343
+ message: "Required: SIAM is the only way to sign in"
344
+ });
345
+ }
346
+ }
347
+ }).transform((environment) => ({
329
348
  ...environment,
330
- COOKIE_SECURE: environment.COOKIE_SECURE === void 0 ? environment.NODE_ENV === "production" : environment.COOKIE_SECURE === "true"
349
+ COOKIE_SECURE: environment.COOKIE_SECURE === void 0 ? environment.NODE_ENV === "production" : environment.COOKIE_SECURE === "true",
350
+ IAM_LINK_BY_EMAIL: environment.IAM_LINK_BY_EMAIL === "true",
351
+ DEV_SIAM_STUB: environment.DEV_SIAM_STUB === "true"
331
352
  }));
332
353
 
333
354
  // ../sdk/dist/index.js
@@ -455,6 +476,10 @@ var SecretEnvs = class {
455
476
  this.#fetch = fetchImpl;
456
477
  this.#env = env;
457
478
  }
479
+ /** The account the token belongs to (name and email only). */
480
+ async me() {
481
+ return this.#get("/api/v1/sdk/me", (body) => SdkMeDto.parse(body));
482
+ }
458
483
  /** Projects visible to the token, with their environments. */
459
484
  async listProjects() {
460
485
  return this.#get(
@@ -654,23 +679,6 @@ async function send(fetchFn, baseUrl, request, parse) {
654
679
  if (status === 404) throw new SecretEnvsNotFoundError(message, status, code);
655
680
  throw new SecretEnvsApiError(message, status, code);
656
681
  }
657
- function cliLogin(options) {
658
- return send(
659
- options.fetch,
660
- options.baseUrl,
661
- {
662
- method: "POST",
663
- path: "/api/v1/auth/cli-login",
664
- headers: { [CSRF_HEADER_NAME]: CSRF_HEADER_VALUE },
665
- body: {
666
- email: options.email,
667
- password: options.password,
668
- ...options.code !== void 0 && { code: options.code }
669
- }
670
- },
671
- (body) => CreatedTokenDto.parse(body)
672
- );
673
- }
674
682
  var ManagementClient = class {
675
683
  #token;
676
684
  #baseUrl;
@@ -995,6 +1003,7 @@ var out = (deps, text) => {
995
1003
  deps.stdout.write(`${text}
996
1004
  `);
997
1005
  };
1006
+ var MAX_TOKEN_LENGTH = 256;
998
1007
  async function login(deps, options) {
999
1008
  if (!deps.interactive) {
1000
1009
  throw new CliError("`secretenvs login` needs an interactive terminal.");
@@ -1013,36 +1022,36 @@ async function login(deps, options) {
1013
1022
  error instanceof SecretEnvsError ? error.message : "Invalid server URL"
1014
1023
  );
1015
1024
  }
1016
- const email2 = (await deps.prompts.input({ message: "Email" })).trim();
1017
- const password3 = await deps.prompts.password({ message: "Password" });
1018
- const attempt = (code) => cliLogin({
1019
- fetch: deps.fetch,
1020
- baseUrl,
1021
- email: email2,
1022
- password: password3,
1023
- ...code !== void 0 && { code }
1024
- });
1025
- const created = await attempt().catch(async (error) => {
1026
- if (error instanceof SecretEnvsAuthError && error.code === "MFA_REQUIRED") {
1027
- const code = (await deps.prompts.input({
1028
- message: "Authentication code (or a recovery code)"
1029
- })).trim();
1030
- return attempt(code);
1031
- }
1032
- throw error;
1033
- }).catch((error) => {
1025
+ out(
1026
+ deps,
1027
+ "Create an API token with read and write access in the web app (Settings > API tokens), then paste it here."
1028
+ );
1029
+ const token = (await deps.prompts.password({ message: "API token" })).trim();
1030
+ if (!token.startsWith(TOKEN_PREFIX) || token.length > MAX_TOKEN_LENGTH) {
1031
+ throw new CliError(
1032
+ `That does not look like a SecretEnvs API token (they start with ${TOKEN_PREFIX}).`
1033
+ );
1034
+ }
1035
+ const sdk = new SecretEnvs({ token, baseUrl, fetch: deps.fetch, env: {} });
1036
+ let account;
1037
+ try {
1038
+ account = await sdk.me();
1039
+ } catch (error) {
1034
1040
  if (error instanceof SecretEnvsAuthError) {
1035
- throw new CliError(error.message);
1041
+ throw new CliError(
1042
+ "The server did not accept that token. Check that you copied all of it, and that it has not expired or been revoked."
1043
+ );
1036
1044
  }
1037
1045
  throw error;
1038
- });
1046
+ }
1047
+ const prefix = token.slice(0, 8);
1039
1048
  await writeCredentials(credentialsPath(deps.homeDir), {
1040
1049
  baseUrl,
1041
- token: created.token,
1042
- email: email2,
1043
- prefix: created.prefix
1050
+ token,
1051
+ email: account.email,
1052
+ prefix
1044
1053
  });
1045
- out(deps, `Logged in as ${email2} on ${baseUrl}`);
1054
+ out(deps, `Logged in as ${account.email} on ${baseUrl} (token ${prefix}...)`);
1046
1055
  }
1047
1056
  async function logout(deps) {
1048
1057
  const removed = await deleteCredentials(credentialsPath(deps.homeDir));
@@ -1053,11 +1062,10 @@ async function logout(deps) {
1053
1062
  }
1054
1063
  async function whoami(deps) {
1055
1064
  const { auth, sdk } = await connect(deps);
1056
- const projects = await sdk.listProjects();
1057
- const account = auth.email ?? (auth.source === "environment" ? "unknown (token from SECRETENVS_TOKEN)" : "unknown");
1065
+ const [account, projects] = await Promise.all([sdk.me(), sdk.listProjects()]);
1058
1066
  const token = auth.prefix ? `${auth.prefix}... (${auth.source})` : auth.source;
1059
1067
  out(deps, `Server: ${sdk.toJSON().baseUrl}`);
1060
- out(deps, `Account: ${account}`);
1068
+ out(deps, `Account: ${account.email}`);
1061
1069
  out(deps, `Token: ${token}`);
1062
1070
  out(deps, `Projects: ${projects.length} accessible`);
1063
1071
  }
@@ -1327,14 +1335,18 @@ async function runCommand(deps, command, flags) {
1327
1335
  }
1328
1336
 
1329
1337
  // src/program.ts
1330
- var VERSION = true ? "1.6.0" : "dev";
1338
+ var VERSION = true ? "2.0.0" : "dev";
1331
1339
  function buildProgram(deps, setExitCode) {
1332
1340
  const program = new Command().name("secretenvs").description("Read and manage SecretEnvs variables from the terminal").version(VERSION).configureOutput({
1333
1341
  writeOut: (text) => deps.stdout.write(text),
1334
1342
  writeErr: (text) => deps.stderr.write(text)
1335
1343
  }).exitOverride();
1336
1344
  const target = (command) => command.option("-p, --project <slug>", "project slug (or SECRETENVS_PROJECT)").option("-e, --env <slug>", "environment slug (or SECRETENVS_ENV)");
1337
- program.command("login").description("Log in with email and password and store an API token").option("--url <baseUrl>", "server URL, e.g. https://vault.example.com").action((options) => login(deps, options));
1345
+ program.command("login").description(
1346
+ "Store an API token created in the web app (Settings > API tokens)"
1347
+ ).option("--url <baseUrl>", "server URL, e.g. https://vault.example.com").addOption(
1348
+ new Option("--token", "no effect: always asks for a token").hideHelp()
1349
+ ).action((options) => login(deps, options));
1338
1350
  program.command("logout").description("Delete the stored credentials").action(() => logout(deps));
1339
1351
  program.command("whoami").description("Show the current server, account and token").action(() => whoami(deps));
1340
1352
  program.command("projects").description("List accessible projects").action(() => listProjects(deps));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secretenvs/cli",
3
- "version": "1.6.0",
3
+ "version": "2.0.0",
4
4
  "description": "Command-line client for reading and managing SecretEnvs variables.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankityadavpurson/secretenvs#readme",
@@ -44,8 +44,8 @@
44
44
  "zod": "^4.1.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@secretenvs/contracts": "1.6.0",
48
- "@secretenvs/sdk": "1.6.0",
47
+ "@secretenvs/contracts": "2.0.0",
48
+ "@secretenvs/sdk": "2.0.0",
49
49
  "@types/cross-spawn": "^6.0.6",
50
50
  "tsup": "^8.5.0",
51
51
  "typescript": "~5.9.3",