npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ashkiani/mongo-logger

v1.2.1

Published

Reusable MongoDB request logger with optional API-key and KeyProve authentication.

Readme

@ashkiani/mongo-logger

MongoDB request logging and optional authorization for Node.js applications. The original API-key method remains the default; KeyProve (RFC 9421 proof of possession) is an additional, opt-in method.

Install

npm install @ashkiani/mongo-logger

KeyProve is included automatically as a regular dependency of @ashkiani/mongo-logger. No separate installation step is required. The existing API-key authentication remains the default; KeyProve is loaded only when createKeyproveAuth() is called.

Existing API (unchanged function signatures)

const mongoLogger = require('@ashkiani/mongo-logger');
const logEntry = await mongoLogger.createLogEntryObj(req, dbClient.get(), '/some/api');
if (!logEntry.user.authorized) return res.status(403).send(logEntry.user.issue);
await mongoLogger.writeLogObj(logEntry, dbClient.get(), process.env.DB_NAME, process.env.COL_LOGS);

API keys are read from req.body.key and verified against hashed entries in the MongoDB keys collection, with the existing environment checks. Configure DB_NAME and api_env as before. Set ALLOWED_ORIGINS only if an application explicitly enables origin-keyless access.

By default, keyless access is disabled. Applications that deliberately permit it must pass { allowOriginKeyless: true } to createLogEntryObj(). When allowOriginKeyless is enabled and the request's origin is on ALLOWED_ORIGINS in a supported environment (dev, test, or prod), that request is authorized without hashing or looking up an API key, even if a key was supplied. Otherwise, if a key is supplied, normal API-key verification is performed. allowOriginKeyless: false enforces credential verification regardless of origin. Origin is a client-controlled header and must not be treated as reliable authentication for sensitive routes.

Logging: writeLogObj() redacts API keys for authorized requests and for rejected requests where a valid key might have been supplied (including environment denials and database errors). It retains a submitted key only when an actual MongoDB key lookup completes and returns no matching record (user.apiKeyLookup === 'not_found'), for diagnostics. Invalid keys may still contain sensitive data; restrict log access and retention. Logging does not modify the original request body.

KeyProve integration

The application provides storage callbacks (or uses the MongoDB adapter below), its trusted externally visible request URL, and the exact raw request-body bytes. Mongo-logger uses @ashkiani/keyprove/server internally and returns the KeyProve workflow instance.

const keyprove = await mongoLogger.createKeyproveAuth({
  storage: { save, get, consume }, // as defined by KeyProve v1
  adminToken: process.env.KEYPROVE_ADMIN_TOKEN,
  expectedOrigin: 'https://api.example.com' // optional in KeyProve
});

const logEntry = await mongoLogger.createLogEntryObj(req, dbClient.get(), '/some/api', {
  authMode: 'both',
  keyprove,
  targetUri: 'https://api.example.com' + req.originalUrl,
  rawBody: req.rawBody ?? Buffer.alloc(0),
  allowOriginKeyless: false, // default; explicitly opt in only if required
  invalidSignatureFallback: 'reject'
});

targetUri must be reconstructed from trusted server configuration and the original request URL, never blindly from incoming Host or X-Forwarded-* headers. In Express, capture raw bytes with express.json({ verify: (req, res, bytes) => { req.rawBody = Buffer.from(bytes); } }). Do this before signing verification or application handlers.

| Option | Meaning | |---|---| | authMode: 'legacy' (default) | API-key authentication; allowed-origin keyless access only if explicitly enabled | | authMode: 'both' | Accept signed requests and legacy authentication per the settings below | | authMode: 'keyprove' | Only valid KeyProve signatures authenticate | | allowOriginKeyless (default false) | Explicitly opt into allowed-origin keyless access; when true, an allowlisted origin bypasses key lookup even if a key is supplied | | invalidSignatureFallback (default 'reject') | In both mode, either reject invalid supplied signatures, or explicitly set 'legacy' to try the legacy method |

If a valid signature is supplied, the stored public key and its associated account supply the identity. The result includes user.authorized, user.authenticated, user.authMethod, user.subject, and user.keyId. Stored environments permissions, if present, are checked against api_env. Public-key registration requires administrator authorization; it must not be granted by possession of an Origin header.

For complete invitation creation, enrollment, and optional login/registration pages, use the KeyProve workflow instance returned by createKeyproveAuth():

const result = await keyprove.handle('challenge', {
  readRequest: () => ({ method: req.method, headers: req.headers, body: JSON.stringify(req.body) }),
  sendResponse: result => res.status(result.status).set(result.headers).send(result.body)
});

The host selects the route and maps it to KeyProve's admin-invite, registration-start, registration-finish, challenge, page, and asset actions. KeyProve itself remains database-independent; the application may choose Mongo Logger's optional MongoDB storage adapter.

storage.consume(type, id) must be atomic across all server instances, and storage.save must enforce unique IDs. In-memory KeyProve storage is appropriate only for a single-process demonstration. See KeyProve for the full workflow.

Reusable MongoDB storage and expiration (v1.2.0)

Applications can reuse the existing legacy keys collection for KeyProve records:

const storage = mongoLogger.createMongoKeyproveStorage(dbClient.db(process.env.DB_NAME), {
  collectionName: process.env.COL_KEYS || 'keys'
});
const keyprove = await mongoLogger.createKeyproveAuth({
  adminToken: process.env.KEYPROVE_ADMIN_TOKEN,
  invitationTtlMs: mongoLogger.invitationTtlMsFromEnv(),
  storage
});

Records use prefixed string _id values (e.g. invitation:..., publicKey:...) distinct from legacy API keys. Records also contain native MongoDB createdAtDate and optional expiresAtDate fields for Atlas display. The unchanged value object retains numeric timestamps for KeyProve. consume uses MongoDB's atomic findOneAndDelete, which requires remove permission on the collection. No TTL deletion index is added; old records are not migrated. COL_KEYS is optional and defaults to keys. Note that the legacy API-key lookup still uses keys.

invitationTtlMsFromEnv() reads KEYPROVE_INVITATION_TTL_HOURS (24 hours by default, from 1 second up to 720 hours; fractions accepted) and rejects invalid values. Expiration only affects newly issued invitations.

Reusable response compaction and admin audit (v1.2.0)

compactLogEntry(logEntry, { maxResponseBytes }) limits logged response.data to a 20-character serialized preview when it exceeds the limit, annotating response.truncation with a reason and size. It does not change the original log entry or client response. The default is 8192 bytes; LOG_RESPONSE_MAX_BYTES overrides it. Call this helper explicitly before writeLogObj when desired; existing logger callers are not automatically truncated.

await mongoLogger.writeLogObj(mongoLogger.compactLogEntry(logEntry),
  dbClient, process.env.DB_NAME, process.env.COL_LOGS);

adminAuditMiddleware({ action, path, writeLog }) is an Express-compatible callback middleware that logs an admin page view or invitation attempt after the response completes. Use action: 'admin_page_view' or action: 'invitation_attempt'. The writeLog callback can call writeLogObj. Audit entries record status, outcome, duration, user agent, remote address, and an unverified forwarded-IP hint; invitation attempts include target email. No admin secret, invitation token, request body, or response body is logged. makeAdminAuditRecord is also exported for tests or custom transports.

Environment variables

The application, not this package, chooses whether to enable KeyProve and how to mount its routes. These variables are used by the library or by its shared helpers:

| Variable | Purpose | |---|---| | DB_NAME | Database for legacy API-key lookups and storage supplied by the host | | api_env | Environment used for existing key authorization | | ALLOWED_ORIGINS | Comma-separated origins for legacy keyless access (only where enabled) | | COL_KEYS | Optional name passed by the host to createMongoKeyproveStorage; default keys | | KEYPROVE_ADMIN_TOKEN | Host passes secret to createKeyproveAuth for invitation authorization | | KEYPROVE_INVITATION_TTL_HOURS | Optional invitation lifetime; default 24 | | LOG_RESPONSE_MAX_BYTES | Optional log response-size limit; default 8192 when calling compactLogEntry |

The host must also configure its database connection, trusted public API origin, and log destination as appropriate. The package does not read an application's KEYPROVE_ENABLED flag or KEYPROVE_PUBLIC_ORIGIN automatically.

Logging

writeLogObj(logEntry, dbClient, dbName, collectionName) writes the structured entry to MongoDB. Consider log retention, sensitive request fields, and database access controls before deploying.

License

MIT © Siavash Ashkiani