Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .bumpy/encrypt-raw-output.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
varlock: minor
---

Add raw output format to varlock encrypt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ Use [`varlock encrypt`](/reference/cli/encryption/#encrypt) to create encrypted
```bash
# Interactive: encrypt a single value
varlock encrypt
# Script-friendly: print only the encrypted varlock() expression
printf '%s' "$SECRET" | varlock encrypt --format raw
# Batch: encrypt all sensitive plaintext values in .env.local
varlock encrypt --file .env.local
```
Expand Down Expand Up @@ -217,4 +219,4 @@ shasum -a 256 varlock-local-encrypt

**Reporting.** If you hit a detection on a current release, [file an issue](https://github.com/dmno-dev/varlock/issues) with the file path and the detection name. You can also [submit the file to Microsoft](https://www.microsoft.com/en-us/wdsi/filesubmission) as a false positive, which is what gets the definition corrected for everyone.

**What we do to prevent this.** Windows binaries are Authenticode-signed via Azure Artifact Signing, macOS binaries are Developer ID signed and notarized, and no binary is compressed with an executable packer (packers such as UPX are a well-known trigger for these detections).
**What we do to prevent this.** Windows binaries are Authenticode-signed via Azure Artifact Signing, macOS binaries are Developer ID signed and notarized, and no binary is compressed with an executable packer (packers such as UPX are a well-known trigger for these detections).
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ varlock encrypt [options]

**Options:**
- `--file`: Path to a `.env` file; encrypts all sensitive plaintext values in-place
- `--format`: Output format for single-value mode: `pretty` (default) or `raw`

**Examples:**
```bash
Expand All @@ -33,15 +34,31 @@ varlock encrypt
printf '%s' "$SECRET" | varlock encrypt
varlock encrypt < secret.txt

# Output only the varlock() expression to stdout for scripts
printf '%s' "$SECRET" | varlock encrypt --format raw

# Encrypt all sensitive plaintext values in a .env file
varlock encrypt --file .env.local
```

In single-value mode, you'll either be prompted to enter a value (hidden input) or the value will be read from stdin when piped. The encrypted output is printed for you to copy into your `.env.local` file:
In single-value mode, you'll either be prompted to enter a value (hidden input) or the value will be read from stdin when piped. By default, the encrypted output is printed for you to copy into your `.env.local` file:
```
SOME_SENSITIVE_KEY=varlock("local:<encrypted>")
```

Use `--format raw` to write only the `varlock("local:...")` expression to stdout. Raw mode requires a value on stdin and does not prompt, so command substitution captures only the env value:

```powershell
$envFilePath = '/path/to/your/.env.local'
@"
# @sensitive
VALUE_1=$(awesome-password -y | varlock encrypt --format raw)
"@ | Set-Content $envFilePath
```

`--format raw` is only supported for single-value mode, not with `--file`.
If stdin is a terminal, raw mode exits with an error. Pipe or redirect a value into it, or omit `--format raw` to use the interactive prompt.

:::tip
Piping via stdin avoids exposing secrets in your shell history. Prefer `printf '%s'` over `echo` to avoid a trailing newline (varlock strips a single trailing newline either way).
:::
Expand Down
9 changes: 9 additions & 0 deletions packages/varlock/src/cli/commands/encrypt.command-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ export const commandSpec = define({
name: 'encrypt',
description: 'Encrypt a value using device-local encryption',
args: {
format: {
type: 'enum',
choices: ['pretty', 'raw'],
default: 'pretty',
description: 'Output format for single-value mode',
},
'key-id': {
type: 'string',
description: 'Encryption key ID',
Expand All @@ -24,9 +30,12 @@ producing a varlock("local:...") reference that is safe to commit.

Single-value mode reads from stdin (or prompts interactively) so secrets stay out of
shell history. --file mode encrypts all @sensitive plaintext values in a .env file in place.
Use --format raw to print only the varlock() value expression to stdout. Raw mode requires
a value on stdin (pipe or redirect) and does not prompt.

Examples:
echo "$MY_SECRET" | varlock encrypt # Encrypt a value from stdin (non-interactive, agent-friendly)
echo "$MY_SECRET" | varlock encrypt --format raw # Output only varlock("local:...")
varlock encrypt # Prompt interactively for a value
varlock encrypt --file .env.local # Encrypt @sensitive plaintext values in a file in-place
`.trim(),
Expand Down
31 changes: 23 additions & 8 deletions packages/varlock/src/cli/commands/encrypt.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ async function encryptFile(keyId: string, filePath: string) {
}

export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) => {
const filePath = ctx.values.file;
const rawOutput = ctx.values.format === 'raw';
if (filePath && rawOutput) {
throw new CliExitError('--format raw is only available when encrypting a single value');
}
if (rawOutput && process.stdin.isTTY) {
throw new CliExitError('--format raw requires a value on stdin; pipe or redirect one, or omit --format raw to use the interactive prompt');
}

const log = (message?: string) => (rawOutput ? console.error(message) : console.log(message));
const keyId = String(ctx.values['key-id'] || 'varlock-default');
const backend = localEncrypt.getBackendInfo();

Expand All @@ -117,7 +127,7 @@ export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) =
);
}

console.log(`Using ${backend.type} backend (${backend.hardwareBacked ? 'hardware-backed' : 'file-based'})`);
log(`Using ${backend.type} backend (${backend.hardwareBacked ? 'hardware-backed' : 'file-based'})`);

// Hardware-backed but no presence gate → decryption is unattended (headless/CI hosts).
if (backend.hardwareBacked && !backend.biometricAvailable) {
Expand All @@ -127,14 +137,12 @@ export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) =
} else if (process.platform === 'win32' || process.env.WSL_DISTRO_NAME) {
platformHint = '\nConfigure Windows Hello to require fingerprint/PIN on interactive decrypts.';
}
console.log(
log(
'\nNote: no presence gate is configured, so values decrypt unattended (suitable for headless/CI hosts).'
+ `\nThis protects secrets at rest, but not against a process already running as your user.${platformHint}`,
);
}

const filePath = ctx.values.file;

// --file mode: encrypt all sensitive plaintext values in a .env file
if (filePath) {
await encryptFile(keyId, filePath);
Expand All @@ -143,7 +151,7 @@ export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) =

// Single-value mode — read from stdin if piped, otherwise prompt interactively.
// Avoids putting secrets in shell history (e.g. `echo $SECRET | varlock encrypt`).
console.log('');
log('');

let ciphertext: string;

Expand Down Expand Up @@ -175,7 +183,10 @@ export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) =
}
ciphertext = result;
} else {
const prompted = await password({ message: 'Enter the value you want to encrypt', hint: 'for multi-line values, pipe via stdin' });
const prompted = await password({
message: 'Enter the value you want to encrypt',
hint: 'for multi-line values, pipe via stdin',
});
if (isCancel(prompted)) return gracefulExit();
try {
ciphertext = await localEncrypt.encryptValue(prompted, keyId);
Expand All @@ -187,6 +198,10 @@ export const commandFn: TypedGunshiCommandFn<typeof commandSpec> = async (ctx) =
}
}

console.log('\nCopy this into your .env.local file and rename the key appropriately:\n');
console.log(`SOME_SENSITIVE_KEY=varlock("local:${ciphertext}")`);
if (rawOutput) {
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
process.stdout.write(`varlock("local:${ciphertext}")\n`);
} else {
console.log('\nCopy this into your .env.local file and rename the key appropriately:\n');
console.log(`SOME_SENSITIVE_KEY=varlock("local:${ciphertext}")`);
}
};
85 changes: 85 additions & 0 deletions packages/varlock/src/cli/commands/test/encrypt.command.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import {
afterEach, beforeEach, describe, expect, test, vi,
} from 'vitest';
import { Readable } from 'node:stream';

vi.mock('../../../lib/local-encrypt', () => ({
ensureKey: vi.fn(),
encryptValue: vi.fn(async () => 'encrypted-payload'),
getBackendInfo: vi.fn(() => ({
type: 'file-based',
hardwareBacked: false,
biometricAvailable: false,
})),
}));

vi.mock('../../helpers/prompts', () => ({
multiselect: vi.fn(),
password: vi.fn(async (opts: { output?: NodeJS.WritableStream }) => {
(opts.output ?? process.stdout).write('password prompt output');
return 'test-secret';
}),
}));

import { password } from '../../helpers/prompts';
import { commandFn } from '../encrypt.command.js';

const originalStdinDescriptor = Object.getOwnPropertyDescriptor(process, 'stdin')!;
const originalStdin = process.stdin;
const originalStdinIsTTY = process.stdin.isTTY;

describe('encrypt command output format', () => {
beforeEach(() => {
vi.clearAllMocks();
Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true });
});

afterEach(() => {
vi.restoreAllMocks();
Object.defineProperty(originalStdin, 'isTTY', { configurable: true, value: originalStdinIsTTY });
Object.defineProperty(process, 'stdin', originalStdinDescriptor);
});

test('raw format requires piped stdin rather than prompting interactively', async () => {
const stdoutWrite = vi.spyOn(process.stdout, 'write').mockReturnValue(true);

await expect(commandFn({ values: { format: 'raw' } } as any))
.rejects.toThrow('--format raw requires a value on stdin');

expect(stdoutWrite).not.toHaveBeenCalled();
expect(password).not.toHaveBeenCalled();
});

test('raw format writes only the varlock expression to stdout when stdin is piped', async () => {
const stdin = Readable.from([Buffer.from('test-secret')]);
Object.defineProperty(stdin, 'isTTY', { configurable: true, value: false });
Object.defineProperty(process, 'stdin', { configurable: true, value: stdin });
const stdoutWrite = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
const log = vi.spyOn(console, 'log').mockReturnValue(undefined);
const error = vi.spyOn(console, 'error').mockReturnValue(undefined);

await commandFn({ values: { format: 'raw' } } as any);

expect(stdoutWrite).toHaveBeenCalledExactlyOnceWith('varlock("local:encrypted-payload")\n');
expect(log).not.toHaveBeenCalled();
expect(password).not.toHaveBeenCalled();
expect(error).toHaveBeenCalledWith('Using file-based backend (file-based)');
});

test('pretty format keeps the existing copy/paste output', async () => {
const stdoutWrite = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
const log = vi.spyOn(console, 'log').mockReturnValue(undefined);

await commandFn({ values: { format: 'pretty' } } as any);

expect(stdoutWrite).toHaveBeenCalledWith('password prompt output');
expect(stdoutWrite.mock.calls.map(([chunk]) => String(chunk)).join(''))
.toContain('password prompt output');
expect(log).toHaveBeenCalledWith('SOME_SENSITIVE_KEY=varlock("local:encrypted-payload")');
});

test('raw format cannot be combined with --file', async () => {
await expect(commandFn({ values: { format: 'raw', file: '.env.local' } } as any))
.rejects.toThrow('--format raw is only available when encrypting a single value');
});
});