
Research
/Security News
Critical Vulnerability in NestJS Devtools: Localhost RCE via Sandbox Escape
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
assert-response
Advanced tools
A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.
A lightweight utility library for asserting HTTP response conditions and throwing a Response
with the appropriate HTTP status code, and optional body
and options
.
If the resource is missing, throw a 404 Not Found
response.
import { found } from "assert-response";
function loader() {
const foo = getFoo(); // Foo | undefined
// Throws a 404 response if foo is undefined
found(foo);
foo; // Type is now Foo
// Do something with foo
}
If the user is not authenticated, throw a 401 Unauthorized
response.
import { authorized } from "assert-response";
function action() {
const user = getCurrentUser(); // User | null
// Throws a 401 response if user is null
authorized(user);
user; // Type is now User
// ...
}
If the operation was unsuccessful, throw a 500 Internal Server Error
.
import { noError } from "assert-response";
function action() {
const success = processRequest(); // boolean
// Throws a 500 response if success is false
noError(success);
// Do further actions
}
If the operation was successful, throw a 200 OK
.
import { internalServerError, notOk } from "assert-response";
function action() {
const [error] = processOtherRequest(); // [string | null]
// Throws a 200 response if error is null
notOk(error);
error; // Type is now string
console.error(error);
// Throws a 500 response if error is not null
internalServerError(error);
}
This example ensures:
401 Unauthorized
).403 Forbidden
).400 Bad Request
).404 Not Found
).409 Conflict
).500 Internal Server Error
/ 204 No Content
).import {
authorized,
allowed,
found,
match,
noContent,
valid,
internalServerError,
} from "assert-response";
interface Document {
id: string;
lastModified: number;
}
async function saveAndContinueEditing(doc?: Document) {
const user = getCurrentUser();
// 👋 Throws a 401 response if current user is null
authorized(user, "Authentication required");
user; // Type is now User
// 🔓 Throws a 403 response if not permitted
allowed(
user.permissions.includes("update-document"),
"Permission to update document required"
);
// ✅ Throws a 400 response if missing update document
valid(doc, "Missing document");
doc; // Type is now Document
const prevDoc: Document | undefined = await database.find(doc.id);
// 🔍 Throws a 404 response if the document does not exist
found(prevDoc, "Document not found");
prevDoc; // Type is now Document
// 🤝 Throws a 409 response if the document has been modified since last retrieval
match(prevDoc.lastModified === doc.lastModified, "Conflict detected");
const [error] = await database.put(doc);
// ⚠️ Throws a 500 response if the update failed
internalServerError(error);
// 👌 Throws a 204 response if everything successful
noContent(true);
}
Each assertion function checks a condition and throws a Response
with the corresponding HTTP status code if the condition is truthy.
Negated functions work in reverse: they throw a response when the condition is falsy.
You may also pass an optional body
and options
parameters for Response
as the second and third arguments for the assertion function. These can either be values or functions that return the respective values.
To use these functions:
import { found, ok, redirect, valid } from "assert-response";
// Throws a 200 response if user is truthy, with a dynamic message
ok(
user,
() => JSON.stringify({ message: "Welcome back!" }),
() => ({ headers: { "Content-Type": "application/json" } })
);
// Throws a 302 response with options if redirectURL is set
redirect(redirectURL, undefined, {
headers: {
Location: redirectURL!,
},
});
// Validate user input (Negated function, throws 400 response if condition is falsy)
valid(isValid(input), "Invalid input");
// Ensure item is found (Negated function, throws 404 response if condition is falsy)
found(item, "Item not found");
Each function is mapped to an HTTP status code.
200
–299
)Status Code | Function (Aliases) | Negated Function (Aliases) |
---|---|---|
200 | ok ( successful ) | notOk ( failed ) |
201 | created | notCreated ( creationFailed ) |
202 | accepted | notAccepted ( rejected ) |
203 | nonAuthoritativeInformation | notNonAuthoritativeInformation ( authoritativeInformation ) |
204 | noContent | notNoContent ( content ) |
205 | resetContent | notResetContent |
206 | partialContent | notPartialContent ( entireContent , fullContent ) |
207 | multiStatus | notMultiStatus ( singleStatus ) |
208 | alreadyReported | notAlreadyReported |
226 | imUsed | notImUsed |
300
–399
)Status Code | Function (Aliases) | Negated Function (Aliases) |
---|---|---|
300 | multipleChoices | notMultipleChoices |
301 | movedPermanently | notMovedPermanently |
302 | temporaryFound ( redirect ) | notTemporaryFound ( noRedirect ) |
303 | seeOther | notSeeOther |
304 | notModified | modified |
305 | useProxy ( proxy ) | notUseProxy |
307 | temporaryRedirect | notTemporaryRedirect |
308 | permanentRedirect | notPermanentRedirect |
400
–499
)Status Code | Function (Aliases) | Negated Function (Aliases) |
---|---|---|
400 | badRequest ( invalid ) | goodRequest ( valid , correct ) |
401 | unauthorized | authorized ( authenticated ) |
402 | paymentRequired | paymentNotRequired ( paymentOptional ) |
403 | forbidden | notForbidden ( allowed , permitted ) |
404 | notFound | found |
405 | methodNotAllowed | methodAllowed |
406 | notAcceptable | acceptable |
407 | proxyAuthRequired | proxyAuthNotRequired ( proxyAuthOptional ) |
408 | requestTimeout | notRequestTimeout ( requestFast ) |
409 | conflict | notConflict ( match ) |
410 | gone | notGone ( present ) |
411 | lengthRequired | lengthNotRequired ( lengthOptional ) |
412 | preconditionFailed | preconditionSuccessful ( preconditionMet , preconditionPassed ) |
413 | payloadTooLarge | notPayloadTooLarge ( payloadSmall ) |
414 | uriTooLong | uriNotTooLong ( uriShort ) |
415 | unsupportedMediaType | supportedMediaType |
416 | rangeNotSatisfiable | rangeSatisfiable |
417 | expectationFailed | expectationSuccessful ( expectationMet , expectationPassed ) |
418 | teapot | notTeapot |
421 | misdirectedRequest | correctlyDirectedRequest ( directedRequest ) |
422 | unprocessableEntity | processableEntity |
423 | locked | unlocked ( open ) |
424 | failedDependency | successfulDependency ( dependencyMet , dependencyPassed ) |
425 | tooEarly | notTooEarly ( afterSufficientTime , onTime ) |
426 | upgradeRequired | upgradeNotRequired ( upgradeOptional ) |
428 | preconditionRequired | preconditionNotRequired ( preconditionOptional ) |
429 | tooManyRequests | notTooManyRequests ( fewRequests ) |
431 | requestHeaderFieldsTooLarge | requestHeaderFieldsAcceptable ( requestHeaderFieldsSmall ) |
451 | unavailableForLegalReasons | availableForLegalReasons |
500
–599
)Status Code | Function (Aliases) | Negated Function (Aliases) |
---|---|---|
500 | internalServerError | noError ( notInternalServerError ) |
501 | notImplemented | implemented |
502 | badGateway | goodGateway |
503 | serviceUnavailable | serviceAvailable |
504 | gatewayTimeout | notGatewayTimeout ( gatewayResponsive ) |
505 | httpVersionNotSupported | httpVersionSupported |
506 | variantAlsoNegotiates | notVariantAlsoNegotiates ( variantNotNegotiating ) |
507 | insufficientStorage | sufficientStorage ( storageAvailable ) |
508 | loopDetected | loopNotDetected ( noLoop ) |
509 | bandwidthLimitExceeded | bandwidthLimitNotExceeded ( bandwidthAvailable ) |
510 | notExtended | extended |
511 | networkAuthenticationRequired | networkAuthenticationNotRequired ( networkAuthenticationOptional ) |
0.2.1
successfulPrecondition
to preconditionSuccessful
FAQs
A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.
The npm package assert-response receives a total of 117 weekly downloads. As such, assert-response popularity was classified as not popular.
We found that assert-response 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.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.
Product
Socket now supports Rust and Cargo, offering package search for all users and experimental SBOM generation for enterprise projects.