Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
@biblioteksentralen/cloud-run-core
Advanced tools
Core package for NodeJS services using Cloud Run
This package contains some core functionality for Node.js services running on Google Cloud Run, such as logging and error handling.
parseRequest
▶ pnpm install
▶ pnpm test
Publishing the package:
▶ pn changeset # create a new changeset
▶ pn changeset version # updates version number and changelog
▶ git commit -m "publish vX.X.X"
▶ pn changeset publish
▶ git push --follow-tags
▶ npm install @biblioteksentralen/cloud-run-core
To create an Express-based HTTP service:
// src/start.ts
import { createService } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";
const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });
service.router.get("/", async (req, res) => {
req.log.info(`Hello log!`);
// ...
});
service.start();
The HTTP service comes pre-configured with a logging middleware that sets up Pino to structure logs for Google Cloud Logging with trace context. The logger is added to the Express Request context, so it can be used in all request handlers:
// src/endpoints/funRequestHandler.ts
import { Request, Response } from "@biblioteksentralen/cloud-run-core";
export async function funRequestHandler(req: Request, res: Response): Promise<void> {
req.log.info(`Hello log!`);
}
// src/start.ts
// ...
import { funRequestHandler } from "./endpoints/funRequestHandler.js";
// ...
service.router.get("/", funRequestHandler);
In scripts / GCP Cloud Run Jobs:
import { logger } from "@biblioteksentralen/cloud-run-core"
logger.info({ someProperty: "someValue" }, "Hello world")
The logger is configured so it formats logs as JSON structured for GCP Cloud Logging when running in GCP, or when output is piped to another process (no TTY), and with pino-pretty otherwise.
To manually disable pino-pretty, set the environment variable PINO_PRETTY=false
.
LOG_LEVEL
- Control minimum log levelThe environment variable LOG_LEVEL
can be used to control the minimum log level.
Defaults to debug
.
Use createRouter()
to create modular, mountable route handlers (uses express.Router()
):
// src/start.ts
import { createService, createRouter } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";
const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });
const adminRouter = createRouter()
adminRouter.get("/", async (req, res) => {
req.log.info(`Hello admin`);
// ...
});
service.router.use("/admin", adminRouter);
service.start();
This package provides an error handling middleware that is automatically
attached to the service when you start the service using service.start()
,
inspired by How to Handle Errors in Express with
TypeScript.
AppError
is a base class to be used for all known application errors (that is,
all errors we throw ourselves).
// src/endpoints/funRequestHandler.ts
import { AppError, Request, Response } from "@biblioteksentralen/cloud-run-core";
export async function funRequestHandler(req: Request, res: Response) {
// ...
throw new AppError('🔥 Databasen har brent ned');
// ...
}
As long as errors are thrown before writing the response has started, a JSON error response is produced on the form:
{ "error": "🔥 Databasen har brent ned" }
By default, errors based on AppError
are considered operational and displayed
in responses. If an error should not be displayed, set isOperational: false
when constructing the error:
throw new AppError('🔥 Databasen har brent ned', { isOperational: false });
This results in a generic error response (but the original error is still logged):
{ "error": "Internal server error" }
A generic error response will also be shown for any unknown error, that is,
any error that is not based on AppError
) is thrown. All errors, both known and
unknown, are logged.
By default, errors use status code 500. To use another status code:
throw new AppError('💤 Too early', { httpStatus: 425 });
The package also provides a few subclasses of AppError
for common use cases,
such as ClientRequestError
(yields 400 response) and Unauthorized
(yields
401 response).
throw new Unauthorized('🔒 Unauthorized');
Set sentry.dsn
when creating the client to enable Sentry error reporting and telemetry.
import { createService } from "@biblioteksentralen/cloud-run-core";
const service = createService("fun-service", {
sentry: {
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 0.1,
environment: process.env.NODE_ENV, // or similar
...
},
...
});
parseRequest
The parseRequest
parses a request body using a Zod schema. If the input is
invalid, the request will be logged together with the errors, and an "invalid
request" is returned to the sender.
import { Request, Response, parseRequest } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";
export async function funRequestHandler(req: Request, res: Response) {
const { isbn13 } = parseRequest(req.body, z.object({
"isbn13": z.string().regex(/^978[0-9]{10}$/),
}));
res.json({ status: "ok", isbn13 });
}
The package uses http-terminator to
gracefully terminate the HTTP server when the process exists (on SIGTERM). An
event, shutdown
, is emitted after the server has shut down. You can listen to
this if you want to do additional cleanup, such as closing database connections.
// src/start.ts
import { createService } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";
const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });
service.on("shutdown", async () => {
await db.close()
});
// ...
service.start();
The package provides a helper function to parse and validate Pub/Sub messages delivered through push delivery.
The package is agnostic when it comes to which schema parsing/validation library
to use. We like Zod for its usability, and have added support for it in the
errorHandler, but it's not very performant
(https://moltar.github.io/typescript-runtime-type-benchmarks/), so you might
pick something else if performance is important (if you do, remember to throw
ClientRequestError
when validation fails).
import { z } from "zod";
import {
parsePubSubMessage,
Request,
Response,
} from "@biblioteksentralen/cloud-run-core";
const messageSchema = z.object({
table: z.string(),
key: z.number(),
});
app.post("/", async (req: Request, res: Response) => {
const message = parsePubSubMessage(req, (data) => messageSchema.parse(JSON.parse(data)));
// ...
});
import { isCloudRunEnvironment } from "@biblioteksentralen/cloud-run-core";
isCloudRunEnvironment()
will return true if running as a Cloud Run Service or Job.
We include @types/express
as a dependency, not a devDependency, because we
extend and re-export the Request interface. Initially we kept it under
devDependencies, but then all package consumers would have to install the
package themselves. Not sure what's considered best practice in cases like
this though.
@sentry
-pakkene kan av og til komme ut av sync med hverandre. De jobber med
å redusere mengden pakker for å redusere problemet:
https://github.com/getsentry/sentry-javascript/issues/8965#issuecomment-1709923865
Inntil videre kan en prøve å oppdatere alle pakker og se om en klarer å få
like versjoner fra pn ls --depth 3 @sentry/types
FAQs
Core package for NodeJS services using Cloud Run
The npm package @biblioteksentralen/cloud-run-core receives a total of 173 weekly downloads. As such, @biblioteksentralen/cloud-run-core popularity was classified as not popular.
We found that @biblioteksentralen/cloud-run-core demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.