@ashkiani/mongo-logger
v1.2.1
Published
Reusable MongoDB request logger with optional API-key and KeyProve authentication.
Maintainers
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-loggerKeyProve 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
