Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Alagarr is a request-response helper library that removes the boilerplate from your Node.js serverless functions and helps make your code portable.
Alagarr is a request-response helper library for serverless/faas functions* invoked via HTTP events (e.g. via API Gateway). Alagarr makes your code portable: it abstracts the event-context-callback function signatures of various serverless-providers so that you can spend less time writing boring function-as-a-service-related boilerplate.
Alagarr is a higher-order function which abstracts the the programming models of various serverless-cloud providers and adds a standardized request-response model extensible through composable middleware functions. It's API is concise and will be familiar to anyone who's worked with Express.js. It comes with built-in error handling which makes it trivial to implement error-recovery strategies.
*Currently: AWS Lambda/API Gateway. Next: GCP & Azure
Without Alagarr:
// AWS Lambda / API Gateway
module.exports.myHandler = function(event, context, callback) {
callback(null, {
statusCode: 200,
body: JSON.stringify({ foo: 'bar' }),
headers: {
'content-type': 'application/json',
},
})
}
With Alagarr:
const alagarr = require('alagarr')
module.exports.myHandler = alagarr(() => ({ foo: 'bar' }))
Alagarr helps you cut out all the boilerplate involved with handling HTTP requests in serverless functions. Albeit somewhat contrived, here is a before-and-after example of a common pattern frequently found in AWS Lambda function's:
const got = require('got')
module.exports.handler = function(event, context, callback) {
const { queryStringParameters: { currency } } = event
if (!currency) {
callback(null, {
statusCode: 400,
body: JSON.stringify({
message: 'Please provide the "currency" query parameter.',
}),
headers: {
'content-type': 'application/json',
},
})
}
got(`https://api.coinmarketcap.com/v1/ticker/${currency}`)
.then(response => {
callback(null, {
statusCode: 200,
body: JSON.stringify(response),
headers: {
'content-type': 'application/json',
},
})
})
.catch(error => {
callback(null, {
statusCode: error.statusCode,
body: JSON.stringify({
error: error.response,
}),
headers: {
'content-type': 'application/json',
},
})
})
}
const { alagarr, ClientError } = require('alagarr') // @TODO: this require is wrong
const got = require('got')
module.exports.handler = alagarr((request, response) => {
const { query: { currency } } = request
if (!currency) {
throw new ClientError('Please provide the "currency" query parameter.')
}
return got(`https://api.coinmarketcap.com/v1/ticker/${currency}`)
})
There are a few things being handled for you in the above Alagarr example:
callback()
is being handled for you. Alagarr will set the status code, content-type, and body appropriately. More on this behavior here.Install Alagarr with NPM or Yarn:
npm install alagarr
Then include it in your serverless function:
const alagarr = require('alagarr')
module.exports.exampleHandler = alagarr(request => {
const { path, provider } = request
return `You've ended up at ${path} on the ${provider} cloud.`
})
Alagarr ships with default configuration that should work for most use-cases. But, it's possible to pass a configuration object as the second parameter to the alagar() function:
const alagarr = require('alagarr')
module.exports.handler = alagarr(() => 'Hello world!', {
headers: {},
logger: console.log,
})
The available configuration options are outlined here:
Option | Default | Description |
---|---|---|
cspPolicies | [] | List of CSP policies to include in the response headers |
errorHandler | Provide a custom error handler. See the section on Error Handling for more details | |
headers | {} | Headers to include in every response |
logger | Logger to use to log requests. If undefined, Alagarr will use an internal logger. Logging can be disabled by setting to false . See the section on Logging for more details | |
requestMiddleware | Array of custom request middleware to use. See the section on Request Middleware for more details | |
responseMiddleware | Array of custom response middleware to use. See the section on Response Middleware for more details |
request.body
request.context
request.cookies
request.headers
request.hostname
request.meta
request.method
request.path
request.provider
request.query
request.source
request.timestamp
response.json()
response.html()
response.text()
response.svg()
response.png()
response.jpeg()
response.respondTo()
response.raw()
@TODO
const alagarr = require('alagarr')
const configurationOptions = {
logger: false,
}
const handlerFunction = function(request, response) {
const { query: { name } } = request
return response.html(`Hello ${name}.`)
}
module.exports.handler = alagar(handlerFunction, configurationOptions)
The handlerFunction
has a function signature of:
export type HandlerFunction = (
request: any,
response: any,
) => string | object | void | Promise<string | object | void>
If your handlerFunction
returns falsey, then it's your responsibility to call the appropriate response method to end the invocation (e.g. response.json()
). For convenience, if the handlerFunction
returns a string, the result will be passed to response.html()
or response.text()
for you. Alternatively, if the handler returns an object, it will be passed to response.json()
. You may also return a Promise (or make your handler async
).
@TODO
@TODO
@TODO
@TODO
The request body, if any. If using default request middleware, or another body parser, this value will contain the parsed contents of the request body.
readonly body: string | object
The provider context object.
On AWS Lambda this is the second parameter passed to a Lambda function's handler.
readonly context: object
An object containing the cookies included with the request.
readonly cookies: {
readonly [name: string]: string
}
An object containing all of the headers included in the request.
readonly headers: {
readonly [name: string]: string
}
The request's hostname. Derived from the request's Host
header.
readonly hostname: string
An object containing some meta data about the invocation. It includes:
readonly meta: {
readonly coldStart: boolean, // was this a cold start?
readonly invocationCount: number, // number of times this container has been invoked
}
The request HTTP method. E.g GET
or POST
.
readonly method: enum {
'GET',
'POST',
'PATCH',
'DELETE',
}
The request path.
readonly path: string
The name of the current request's provider. Possible values include: aws
readonly provider: enum {
'aws'
}
An object of query parameters included in the request.
Given a request:
GET http://example.com?foo=1&bar=2
request.query
will contain:
{
foo: '1',
bar: '2',
}
readonly query: {
readonly [name: string]: string
}
The name of the current request's invocation source. Possible values include: api-gateway
readonly source: enum {
'api-gateway'
}
Timestamp at the time of the first middleware's execution.
readonly timestamp: number
Respond according to request's Accept header with formats provided in formats
map. Kind of like a Ruby on Rails respond_to do |format|
block.
response.respondTo({
json: {},
html: '<html />',
})
Exposes the underlying callback
method.
response.raw(null, { something: 'custom' })
Throw em. Alagarr will catch them.
@TODO
Yes.
@TODO
Alagarr uses a pipeline of middleware functions to process the incoming request and outgoing response objects. This lets you customize how your requests and responses are handled as well as provide custom middleware in addition to those provided by Alagarr.
Alagarr includes the following request middleware:
Provider | Name | Default | Description |
---|---|---|---|
All | meta | built-in | Adds meta data about the request including whether the invocation is a coldStart, and invocation count |
All | normalize-headers | built-in | Normalizes request headers. |
All | normalize-programming-model | built-in | Normalizes the programming models of different providers. |
All | timestamp | built-in | Adds a request-start timestamp under request.timestamp which can be used to determine the ellapsed duration of the invocation |
Any | cookies | enabled | Parses cookies out of request header and makes them accessible under request.cookies |
Any | hostname | enabled | Sets a convenience hostname property on the request object based on the request headers |
Any | json-body | enabled | Body parser for request bodies with content-type of application/json |
Any | url-encoded-body | enabled | Body parser for request bodies with content-type of application/x-www-form-urlencoded |
AWS | base64-body | enabled | Decodes base64-encoded request bodies when isBase64Encoded on the API Gateway request is truthy |
Alagarr includes the following response middleware:
Provider | Name | Default | Description |
---|---|---|---|
All | enforced-headers | built-in | |
All | log | built-in | |
Any | compress | disabled | Compress response body with deflate or gzip when appropriate |
Any | content-length | enabled | Adds a content-length header to the response |
Any | csp | enabled | Adds Content-Security-Policy headers to the response |
Any | etag | disabled | Adds an Entity Tag (ETag) header to the response |
All middleware are functions. Middleware which is included in Alagarr are all pure, but this is not required for custom middleware. Middleware may return Promises which are resolved before the next middleware is called. Middleware should not mutate state, but instead return new values—but this is not required in custom middleware. However, everytime middleware mutates state, a cute cuddly koala dies somewhere in Australia. So.. Yea.
Request middleware act on a request object and must always return a new request object. Request middleware have the following function signature:
type requestMiddleware = (
request: InterfaceRequest,
options: InterfaceAlagarrOptions,
) => InterfaceRequest
Response middleware act on the response object and must always return a new response object. Response middleware have the following function signature:
type responseMiddleware = (
response: InterfaceResponseData,
request: InterfaceRequest,
options: InterfaceAlagarrOptions,
) => InterfaceResponseData
An example of custom middleware might be middleware which handles user sessions. The request middleware would restore a session from some data store, while the response middleware might ensure a session is updated and a cookie is set.
Request Middleware
module.exports.restoreSession = async function(request) {
const { cookies: { sessionId } } = request
const session = (await getSessionFromDatabase(sessionId)) || undefined
return {
...request,
session,
}
}
Response Middleware
module.exports.saveSession = async function(responsePayload, request) {
const sessionCookie = await saveSessionToDatabase(request.session)
return {
...responsePayload,
headers: {
...responsePayload.headers,
'Set-Cookie': `session=${sessionCookie}`, // @TODO: refactor once #5 is closed.
},
}
}
This custom middleware could then be used with Alagarr in a serverless function handler with:
const handler = require('alagarr')
const { restoreSession, saveSession } = require('./custom-middleware')
const alagarrConfig = {
requestMiddleware: ['default', restoreSession],
responseMiddleware: ['default', saveSession],
}
module.exports.userDashboardHandler = handler((request, response) => {
const session = request.session
if (!session) {
return response.redirect('/login')
}
return `<h1>Welcome back, ${session.username}!</h1>`
}
alagarrConfig,
)
The codebase tries to follow declarative, functional(ish) programming paradigms. Many functional styles are enforced through TSLint linter utilised by the project. These include immutablity rules (no-let
, no-object-mutation
) and rules which prohibit imperative code (no-expression-statement
, no-loop-statement
). Disabling the linter for code should be avoided. Exceptions are made where satisfying a linting rule is impractical or otherwise untenable. In practice, this tends to be areas where the code touches 3rd party modules and in tests due to Jest's imperative-style.
Alagarr © Marco Lüthy. Released under the MIT license.
Authored and maintained by Marco Lüthy with help from contributors.
github.com/adieuadieu · GitHub @adieuadieu · Twitter @adieuadieu · Medium @marco.luethy
FAQs
Alagarr is a request-response helper library that removes the boilerplate from your Node.js serverless functions and helps make your code portable.
The npm package alagarr receives a total of 110 weekly downloads. As such, alagarr popularity was classified as not popular.
We found that alagarr demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.