# aws-lockbox

> AWS SSM Parameter Store secrets manager with TypeScript support

Latest version **3.1.0** (published 2025-02-03) · ISC license · 0 weekly downloads

## Install

```sh
npm install aws-lockbox
pnpm add aws-lockbox
yarn add aws-lockbox
bun add aws-lockbox
```

## Health

**Score 35/100 (D)** — status: maintenance-mode.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.1.0 |
| Published | 2025-02-03 |
| First published | 2018-08-22 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >=16 |
| Dependencies | 1 |
| Unpacked size | 23.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Ryan Beck |
| Maintainers | prayjs |
| Keywords | aws, amazon, parameter store, ssm, secrets, environment, environment variables, process.env, parameters, typescript |

## Links

- npm: https://www.npmjs.com/package/aws-lockbox
- npm.io page: https://npm.io/package/aws-lockbox

## Dependencies (1)

- [@aws-sdk/client-ssm](https://npm.io/package/@aws-sdk/client-ssm.md) ^3.0.0

## Alternatives

- [replicas-cli](https://npm.io/package/replicas-cli.md) — 3.0K weekly downloads
- [env-contract](https://npm.io/package/env-contract.md) — 133 weekly downloads
- [@openveo/api](https://npm.io/package/@openveo/api.md) — 61 weekly downloads
- [@ryniaubenpm2/cumque-error-reiciendis](https://npm.io/package/@ryniaubenpm2/cumque-error-reiciendis.md) — 54 weekly downloads
- [ts-global-type-extra](https://npm.io/package/ts-global-type-extra.md) — 11 weekly downloads

## Recent versions

- 3.1.0 (latest) — 2025-02-03
- 2.0.3 — 2019-07-08
- 2.0.2 — 2019-07-08
- 2.0.1 — 2019-07-01
- 2.0.0 — 2019-07-01
- 1.0.4 — 2018-12-02
- 1.0.3 — 2018-11-08
- 1.0.2 — 2018-08-22
- 1.0.1 — 2018-08-22
- 1.0.0 — 2018-08-22

## README

# AWS Lockbox

A TypeScript library for managing AWS Parameter Store (SSM) secrets in Node.js applications. Automatically loads parameters into `process.env` on startup.

> **Note**: Requires Node.js 16 or later.

## Development

### Node.js Version
This project uses Node.js 20.15.0. We recommend using [nvm](https://github.com/nvm-sh/nvm) to manage Node.js versions.

```bash
# Install the correct version
nvm install

# Use the correct version
nvm use
```

## ⚠️ Breaking Changes in Version 3.0.0

This version includes several breaking changes:

1. **AWS SDK v3 Migration**
   - Upgraded from AWS SDK v2 to v3
   - New modular AWS SDK structure
   - Different error handling patterns

2. **TypeScript Support**
   - Package is now written in TypeScript
   - Includes type definitions
   - Better error handling and type safety

### Migration Guide from v2 to v3

#### Installation
```bash
# Remove old version
npm uninstall aws-lockbox

# Install new version
npm install aws-lockbox@3
```

#### Code Changes Required

Old code (v2):
```javascript
const Lockbox = require('aws-lockbox');
const lb = new Lockbox.Lockbox(maxTries);
lb.exec();
lb.wait(maxWaits, waitMS);  // Synchronous wait
```

New code (v3):
```javascript
const { Lockbox } = require('aws-lockbox');  // or import { Lockbox } from 'aws-lockbox';

async function init() {
  try {
    const maxTries = 100;  // Max retries for fetching parameters
    const lb = new Lockbox(maxTries);
    
    // Execute and fetch parameters
    await lb.exec();  // Now returns a Promise
    
    // Wait for parameters to be set (optional)
    const maxWaits = 10;   // Maximum number of retries
    const waitMS = 100;    // Time between retries in milliseconds
    await lb.wait(maxWaits, waitMS);  // Now returns a Promise
    
    console.log('Parameters loaded successfully');
  } catch (err) {
    console.error('Failed to load parameters:', err);
  }
}

init();
```

#### Configuration Changes

Your existing `lockbox` directory structure will continue to work with v3. The main differences are:

1. **Async/Await Support**
   - All operations are now Promise-based
   - Need to use `await` with `exec()` and `wait()`

2. **AWS SDK v3 Error Handling**
   ```javascript
   try {
     const lb = new Lockbox();
     await lb.exec();
   } catch (err) {
     // AWS SDK v3 error format is different
     console.error('Failed to load parameters:', err);
   }
   ```

3. **TypeScript Support (Optional)**
   - If using TypeScript, you can import types:
   ```typescript
   import { Lockbox } from 'aws-lockbox';
   import type { LockboxConfig } from 'aws-lockbox';
   ```

Your existing configuration files in the `lockbox` directory will work without changes:
```
lockbox/
    - production.js
    - development.js
    - default.js
```

## Getting Started

### Installation

```bash
npm install aws-lockbox
```

### Directory Structure

1. Your variables need to be available in AWS Parameter Store (SSM)
2. Create a `lockbox` directory in your project root with the following structure:

```
lockbox/
    - production.js
    - stage.js
    - development.js
    - local.js
    - default.js
```

### Configuration Files

#### default.js
This is where you put the name of the keys that you wish to pull from Parameter Store:

```javascript
module.exports = {
  parameters: [
    "/aws-lockbox/test/secret1",
    "/aws-lockbox/test/secret2",
    "/aws-lockbox/test/api-key"
  ],
  overrides: []
};
```

#### Environment-specific Files (e.g., development.js, production.js)
These files can extend the default configuration and provide environment-specific overrides:

```javascript
const defaultConfig = require('./default.js');

module.exports = {
  parameters: defaultConfig.parameters,
  overrides: [
    {
      Name: "/aws-lockbox/test/secret1",
      Value: "local-development-value"
    }
  ]
};
```

### Initialization

```typescript
import { Lockbox } from 'aws-lockbox';

async function init() {
  // The max number of tries you want to attempt before throwing an error
  const maxTries = 100;
  const lb = new Lockbox(maxTries);
  
  // Execute and fetch parameters
  await lb.exec();
  
  // Optional: Wait for parameters to be set
  const waitMS = 100;    // Time between retries
  const maxWaits = 10;   // Maximum number of retries
  await lb.wait(maxWaits, waitMS);
}
```

## Features

- Written in TypeScript for better type safety and development experience
- Uses AWS SDK v3 for better modularity and performance
- Automatic retries with exponential backoff for throttled requests
- Environment-specific configuration support
- Local parameter overrides for development
- Async/await based API
- Type definitions included

## Configuration Details

### Parameters Array
The `parameters` array in your configuration files defines what parameters to fetch from AWS SSM:

```javascript
module.exports = {
  parameters: [
    "/my-app/database/url",
    "/my-app/api/key",
    "/my-app/secrets/token"
  ]
};
```

### Overrides Array
The `overrides` array allows you to specify local values, particularly useful for development:

```javascript
module.exports = {
  parameters: [...],
  overrides: [
    {
      Name: "/my-app/database/url",
      Value: "localhost:5432"
    }
  ]
};
```

## Environment Selection

The library automatically selects the configuration file based on `NODE_ENV`:
- If `NODE_ENV=production`, it looks for `lockbox/production.js`
- If `NODE_ENV=development`, it looks for `lockbox/development.js`
- If no environment-specific file is found, it falls back to `lockbox/default.js`

## AWS Configuration

The library uses AWS SDK v3's SSMClient. Make sure you have proper AWS credentials configured either through:
- Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
- AWS credentials file
- IAM role (if running on AWS infrastructure)

Your IAM role/user needs permissions to access the AWS Systems Manager Parameter Store:
```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ssm:GetParameters"
      ],
      "Resource": "arn:aws:ssm:region:account-id:parameter/*"
    }
  ]
}
```

## Error Handling

The library includes built-in error handling for common scenarios:
- Throttling: Automatically retries with exponential backoff
- Missing parameters: Returns clear error messages
- Timeout: Configurable timeout with maxTries and waitMS
- Configuration: Validates configuration format and provides clear error messages

## Publishing to npm

For maintainers, there are two ways to publish a new version:

### Option 1: Using the Publish Script (Recommended)

First, make the script executable (one-time setup):
```bash
chmod +x publish.sh
```

Then run the automated publish script:
```bash
./publish.sh
```

The script will:
1. Verify npm login status
2. Verify Node.js version using nvm
3. Clean install dependencies
4. Show current version and optionally update it
   - Choose to keep current version
   - Or update to patch/minor/major version
5. Build and test
6. Preview package contents
7. Confirm before publishing
8. Publish to npm
9. Show git tags that need to be pushed

After publishing, you'll need to manually:
1. Review the generated git tags
2. Push the tags when ready: `git push origin main --tags`

### Option 2: Manual Publishing

Follow these steps to publish manually:

1. Ensure correct Node.js version:
```bash
# Verify and switch to the correct Node.js version
nvm use

# Verify @types/node matches Node.js version
npm run update-types
```

2. Clean install dependencies:
```bash
# Remove existing dependencies
rm -rf node_modules package-lock.json

# Fresh install
npm install
```

3. Update version:
```bash
# For patches (bug fixes)
npm version patch

# For minor releases (new features)
npm version minor

# For major releases (breaking changes)
npm version major
```

4. Build and test:
```bash
# Rebuild the package
npm run rebuild

# Run tests
npm test
```

5. Preview package contents:
```bash
# Create tarball without publishing
npm pack

# Review the contents
tar -tf aws-lockbox-*.tgz
```

6. Publish to npm:
```bash
# Login to npm (if not already logged in)
npm login

# Publish the package
npm publish

# Push git tags
git push origin main --tags
```

### Publishing Checklist

- [ ] Correct Node.js version (check .nvmrc)
- [ ] Dependencies are clean installed
- [ ] Version updated in package.json
- [ ] CHANGELOG.md updated (if exists)
- [ ] All tests pass
- [ ] Build is clean (no warnings)
- [ ] Package contents reviewed
- [ ] Published to npm
- [ ] Git tags pushed
- [ ] TypeScript types verified (@types/node matches Node.js version)

## License

ISC

---
_Source: https://npm.io/package/aws-lockbox · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
