Skip to main content
Security guideReviewed

Deserialisation vulnerabilities: the checks that come before bytes become objects

A deserialisation vulnerability starts where an application turns bytes it received or stored back into objects, and lets those bytes decide which objects to build.

This guide explains what serialisation is, where your application does it without anyone calling it that, which formats carry types as well as data, and the checks that belong before any object is built: a size limit, integrity, a depth limit, an allow-list of types and a schema. It comes with a parser-boundary checklist, a reference to what each language's documentation says, and a Node.js lab that sends tampered objects to a careless, a late-check and a careful version of one feature.

Parser-boundary checklist, format reference and tampered-object lab

An illustration written for this page, not client code. A checklist block to fill in for every place your application rebuilds data that crossed a trust boundary, with the basis for each question; a reference to what the Python, PyYAML, PHP, Java, .NET, Ruby and Node.js documentation says each function can construct, its documented restriction and its plain-data alternative, by version; and a Node.js lab that sends eight fixtures, the genuine token and seven tampered ones, to a careless, a late-check and a careful version of one feature, with a regression test that fails on the careless version and passes on the careful one.

How to use it

Recorded on Node.js v26.0.0.

insecure-deserialization.txt

ILLUSTRATION ONLY. The checklist, the reference, the invented garden centre with its classes, keys and tokens, the lab code and the results below were written and recorded for this page. They are not a client's code or a client's result. The lab is an illustration in one language, JavaScript, with a token format invented for it; it does not reproduce the behaviour of any real serialisation library. Its "dangerous" class only adds a line to a list in memory. Run it on your own computer to learn, and use its fixtures only on code you own or are authorised in writing to test.

This asset has three parts:
  PART 1. A parser-boundary checklist: one block for every place your application rebuilds data that crossed a trust boundary.
  PART 2. A format and function reference: what each language's own documentation says a function can construct, the restriction it documents and the plain-data alternative, with the version that documentation covers.
  PART 3. A tampered-object lab in Node.js: a careless, a late-check and a careful way to rebuild a signed token, eight fixtures, the output they produced and a regression test.

==== PART 1. PARSER-BOUNDARY CHECKLIST ====
Fill in one block for every place your application turns bytes from outside into values or objects, including places where a framework or a library does it for you. Each question ends with its basis: the document it comes from, or "this page's advice" where it is a recommendation of this page rather than a documented requirement. Part 2 gives the function-level settings for each language.

PLACES TO LOOK (this page's advice)
  Cookies and tokens: session cookies, "remember me" tokens, signed links, anything the server hands to the browser and reads back later.
  Session stores: server-side sessions kept in files, a database or a cache, written by one request and read by the next.
  Caches: entries written by one process and read by another, including fragments a framework saves for you.
  Queue and job messages: background jobs, scheduled tasks and messages from other services.
  Uploaded and imported files: data exports, backups, saved settings, templates and project files that a feature opens.
  API bodies and webhooks: every route that accepts a body, in any content type, including partner and internal calls.
  Calls between your own services: anything one service sends another, and anything a client app sends back.

---- BLOCK: copy once per place ----
Place, and the code that rebuilds it:
Q1. Which format, and which function rebuilds it?
    Basis: ASVS 5.0 section V1.5 says certain deserialisation methods have been identified by language or framework documentation as insecure and cannot be made safe with untrusted data, and that careful due diligence should be performed for each mechanism in use. Look the function up in Part 2.
Q2. Can the format name a type, so that the bytes decide which class is built?     yes / no
    Basis: Microsoft's BinaryFormatter migration guide says any deserialiser, binary or text, that allows its input to carry information about the objects to be created is a security problem waiting to happen. A JSON reviver or a library setting that reads a type name from the data counts as yes (this page's advice).
Q3. Who could have written these bytes? (the public, signed-in users, a partner, your own staff, another service)
    Basis: Microsoft's BinaryFormatter security guide says the safe input case is true in some rare circumstances, and that it is much more common for a payload to cross a trust boundary without the developer realising it.
Q4. Is integrity checked before parsing?     yes / no
    Key used, where it is kept, and who can read it:
    Basis: OWASP Top 10:2025 A08 asks that unsigned or unencrypted serialised data is not received from untrusted clients and used without some form of integrity check or digital signature. CWE-502 gives a hash-based message authentication code (HMAC) as one way to make sure data has not been modified. ASVS 5.0 requirement 13.3.1 (Level 2) puts backend secrets in a secrets management solution and says they must not be included in source code or build artefacts. Checking before parsing rather than after is this page's advice; Part 3 shows why.
Q5. What are the size and depth limits, and are they enforced before parsing?
    Size:          Depth:          Enforced before parsing?  yes / no
    Basis: CWE-502 lists denial of service through CPU resource consumption among its consequences. Java's pattern-based serialisation filters can limit stream bytes, graph depth, references and array sizes, and PHP's unserialize() takes a max_depth option. The values are yours to set; this page's advice is the smallest the feature needs.
Q6. Which types may be built? Write the allow-list:
    Basis: ASVS 5.0 requirement 1.5.2 (Level 2) asks that deserialisation of untrusted data enforces safe input handling, such as an allowlist of object types or restricting client-defined object types. CWE-502 says to add only acceptable classes to an allowlist, and notes that new gadgets are constantly being discovered, so this alone is not a sufficient mitigation.
Q7. Which schema is the plain data checked against before any object is built?
    Basis: ASVS 5.0 requirement 2.2.1 (Level 1) asks that input is validated either against an allow list of values, patterns and ranges, or against an expected structure and logical limits according to predefined rules, and says that at Level 1 this can focus on input used to make specific business or security decisions, while for Level 2 and up it should apply to all input. CWE-502 suggests populating a new object rather than just deserialising, so the data flows through safe input validation.
Q8. What happens when a check fails?
    Basis: this page's advice. Refuse the whole value, build nothing from it, log which check refused it, and answer with a generic error. Do not fall back to an older, looser reader.
Q9. Which safer format would remove the question, and what would the move take?
    Basis: OWASP's Deserialization Cheat Sheet says a great reduction of risk is achieved by avoiding native serialisation formats and switching to a pure data format like JSON or XML. The pickle, unserialize() and Marshal documentation in Part 2 each point to JSON.
Date checked, and the regression test that keeps these answers true:

WHAT TO AIM FOR (this page's advice, drawn from the documents above)
  A format that cannot name a type (Q2 no), integrity checked before parsing with a key kept outside the code (Q4), limits enforced before parsing (Q5), an allow-list of one type or none (Q6), a schema for every field (Q7) and a refusal that builds nothing (Q8). Where Q2 has to stay yes for now, Q4 to Q6 carry the weight and Q9 is the plan to change it.

---- WORKED EXAMPLE: the lab's careful version (Part 3) ----
Place: the draft-order token the invented garden centre hands the browser and reads back on the next request
Q1. JSON, read with JSON.parse and no reviver, after the checks below
Q2. no: the type field is a name the code looks up in its allow-list, not a class the data chooses
Q3. anyone: the browser holds the token, so it is untrusted
Q4. yes: HMAC-SHA256 from crypto.createHmac, compared with crypto.timingSafeEqual before the payload is decoded. The lab key is an invented value written into service.mjs so the output repeats; a real key would come from a secret store
Q5. size 1024 characters and depth 2, both checked before JSON.parse
Q6. DraftOrder only, in a Map from the name to its schema check and its constructor
Q7. exactly four fields: type, sku (3 to 20 capital letters, digits or hyphens), quantity (a whole number from 1 to 99) and note (text of at most 200 characters)
Q8. a refusal that names the stage, and no object
Q9. already plain JSON
Date checked: 14 November 2026. Regression test: regression.test.mjs

==== PART 2. FORMAT AND FUNCTION REFERENCE ====
Each entry gives what the documentation says the function can construct, the restriction it documents and the plain-data alternative it points to, with the documentation page and the version it covers. Every page below was opened on 14 November 2026. Defaults and support change between versions, so read the documentation for the version you run.

PYTHON: pickle.load() and pickle.loads()
Documentation: the pickle module page in the Python 3.14.10 documentation.
  Can construct: by default, unpickling will import any class or function that it finds in the pickle data. The page warns that the pickle module is not secure, that it is possible to construct malicious pickle data which will execute arbitrary code during unpickling, and never to unpickle data that could have come from an untrusted source or could have been tampered with.
  Documented restriction: subclass Unpickler and override find_class(), which is called whenever a global (a class or a function) is requested, to forbid globals completely or restrict them to a safe subset. The page adds that you have to be careful with what you allow to be unpickled, and that if security is a concern you may want to consider alternatives such as the marshalling API in xmlrpc.client or third-party solutions. It also says to consider signing data with hmac if you need to ensure that it has not been tampered with.
  Plain-data alternative: json. The page says safer serialisation formats such as json may be more appropriate if you are processing untrusted data, that JSON by default can only represent a subset of the Python built-in types and no custom classes, and that, unlike pickle, deserialising untrusted JSON does not in itself create an arbitrary code execution vulnerability.

PYTHON: PyYAML yaml.load(), yaml.unsafe_load() and yaml.safe_load()
Documentation: the PyYAML documentation page on pyyaml.org (it carries no date, and its installation section names PyYAML 5.1), the CHANGES file in the PyYAML repository, and OWASP's Deserialization Cheat Sheet.
  Can construct: the documentation says Loader supports all predefined tags and may construct an arbitrary Python object, so it is not safe to use Loader to load a document received from an untrusted source, and it warns that yaml.load is as powerful as pickle.load and so may call any Python function. OWASP's cheat sheet lists for review uses of PyYAML's unsafe loaders, such as yaml.unsafe_load() or yaml.load() with Loader=yaml.Loader or Loader=yaml.UnsafeLoader.
  Documented restriction: safe_load recognises only standard YAML tags and cannot construct an arbitrary Python object. SafeLoader, in the documentation's words, does not construct class instances and is probably safe to use with documents received from an untrusted source. OWASP adds: do not register custom constructors that allow arbitrary object creation.
  Versions: the CHANGES file's entries about yaml.load() and its loaders include these. Under 5.1 (2019-03-13): "Deprecate yaml.load and add FullLoader and UnsafeLoader classes". Under 5.2 (2019-12-02): "Repair incompatibilities introduced with 5.1. The default Loader was changed, but several methods like add_constructor still used the old default", and "Make FullLoader safer by removing python/object/apply from the default FullLoader". Under 5.3.1 (2020-03-18): "Prevents arbitrary code execution during python/object/new constructor". Under 5.4 (2021-01-19): "Fix for CVE-2020-14343, moves arbitrary python tags to UnsafeLoader". Under 6.0 (2021-10-13): "always require Loader arg to yaml.load()". When the file was opened, its newest dated entry was 6.0.2 (2024-08-06).
  What the documentation page covers: the statements credited to it above, about yaml.load, safe_load, Loader and SafeLoader. It does not mention FullLoader, UnsafeLoader, full_load or unsafe_load, so it says nothing about the two classes the 5.1 entry adds. Reading its warning together with the entries above is this page's advice, not something the documentation page says.
  Plain-data alternative: yaml.safe_load() for YAML you have to accept, or JSON.

PHP: unserialize()
Documentation: the PHP documentation page for unserialize(), whose changelog runs to PHP 8.4.0, and the PHP documentation's page of new features in PHP 7.0.
  Can construct: omitting the allowed_classes option is the same as setting it to true, and PHP will attempt to instantiate objects of any class. After reconstructing an object, PHP will automatically attempt to call its __unserialize() or __wakeup() method, if one exists. The page warns: do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. The warning's next sentence says unserialisation can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this.
  Documented restriction: allowed_classes takes an array of class names to accept, false to accept no classes or true to accept all; an object of a class that is not accepted is instantiated as __PHP_Incomplete_Class instead. max_depth sets the maximum depth of structures, is intended to prevent stack overflows, has a default of 4096 and is disabled by 0.
  Versions: the PHP 7.0 new features page lists filtered unserialize(), with the allowed_classes option. The function page's own changelog starts later: allowed_classes became strictly typed in 7.1.0, max_depth was added in 7.4.0, and from 8.4.0 unserialize() throws TypeError and ValueError if allowed_classes is neither an array of class names nor a bool.
  Plain-data alternative: JSON, through json_decode() and json_encode(). For serialised data stored outside the application, the page suggests hash_hmac() for data validation.

JAVA: ObjectInputStream.readObject() and serialisation filters
Documentation: five pages that Oracle's page metadata places in the Java Core Libraries Developer Guide for Java SE release 27 (Addressing Deserialization Vulnerabilities, Java Serialization Filters, Allow-Lists and Reject-Lists, Creating Pattern-Based Filters and Built-in Filters), JEP 290 and JEP 415.
  Can construct: the guide says deserialising untrusted data is an inherently dangerous activity because the content of the incoming data stream determines the objects that are created, the values of their fields and the references between them, and that deserialisation is code execution because the readObject method of the class being deserialised can contain custom code.
  Documented restriction: a pattern-based filter accepts or rejects class, package and module names, and can limit array sizes (maxarray), graph depth (maxdepth), references (maxrefs) and stream bytes (maxbytes). The Java Serialization Filters page says a JVM-wide, pattern-based filter is specified with the jdk.serialFilter property, and a stream-specific filter is implemented with the ObjectInputFilter API. The Creating Pattern-Based Filters page says that defining the jdk.serialFilter system property on the command line creates a filter that applies only to one application, and only to a single invocation of Java, and that specifying the filter as the jdk.serialFilter Security Property, in the Java runtime's conf/security/java.security file, defines a pattern-based, JVM-wide filter that affects every application run with that Java runtime. It says a system property supersedes a Security Property value. A class name that matches no pattern is allowed, so a filter that allows only the classes it lists ends with !*.
  On by default: the guide says a serialisation filter is not enabled or configured by default. It says the RMI Registry, the RMI Distributed Garbage Collector and JMX have built-in filters, that the two RMI filters include the limits maxarray=1000000;maxdepth=20, and to use the built-in filters as starting points only.
  Versions: JEP 290, Filter Incoming Serialization Data, gives its release as 9. JEP 415, Context-Specific Deserialization Filters, which added a JVM-wide filter factory that selects a filter for each deserialisation, gives its release as 17.
  OWASP adds: filters are not called for strings or primitives encoded concretely in the stream, so bound the serialised input size separately, and filtering does not make arbitrary untrusted deserialisation safe.
  Plain-data alternative: besides filters, the first action the guide lists is not to deserialise untrusted data. OWASP's cheat sheet points to pure data formats such as JSON, and lists JSON libraries by configuration: jackson-databind, for example, can be used safely as long as polymorphism is not used.

.NET: BinaryFormatter and related formatters
Documentation: Microsoft Learn's "Deserialization risks in use of BinaryFormatter and related types", which says it applies to .NET Framework all versions, .NET Core 2.1 to 3.1 and .NET 5 and later, and the BinaryFormatter migration guide.
  Status: starting with .NET 9, the runtime no longer includes an implementation of BinaryFormatter. The APIs are still present, but their implementation always throws a PlatformNotSupportedException, regardless of project type, and the settings that previously enabled its use are removed. The unsupported System.Runtime.Serialization.Formatters NuGet package contains the functioning implementation, including its vulnerabilities and risks.
  Microsoft's wording: the BinaryFormatter type is dangerous and is not recommended for data processing; applications should stop using it as soon as possible, even if they believe the data they're processing to be trustworthy; BinaryFormatter is insecure and can't be made secure. The Deserialize method is never safe when used with untrusted input, and the denial-of-service attacks it allows cannot be mitigated with a SerializationBinder or any other BinaryFormatter configuration switch.
  Related types: SoapFormatter, LosFormatter, NetDataContractSerializer and ObjectStateFormatter, which the guide says all perform unrestricted polymorphic deserialisation and are dangerous, just like BinaryFormatter.
  Plain-data alternative: the migration guide names four serialisers to move to: System.Text.Json (JSON), DataContractSerializer (XML), MessagePack (binary) and protobuf-net (binary). For payloads already stored, it describes reading BinaryFormatter (NRBF) payloads without performing general-purpose and vulnerable deserialisation. OWASP's cheat sheet adds that where JSON.Net is used, TypeNameHandling should be set only to None.

RUBY: Marshal.load and Psych (YAML)
Documentation: the Marshal and Psych pages in the Ruby 4.0 documentation.
  Can construct: by design, Marshal.load can deserialise almost any class loaded into the Ruby process, and in many cases this can lead to remote code execution if the data is loaded from an untrusted source. The page says Marshal.load is not suitable as a general purpose serialisation format and that you should never unmarshal user supplied input or other untrusted data. Psych.unsafe_load, its documentation says, should not be used to parse untrusted documents.
  Documented restriction: for Marshal, the page's answer is a different format (below). Psych.safe_load allows only TrueClass, FalseClass, NilClass, Integer, Float, String, Array and Hash by default; further classes are added with permitted_classes, recursive data structures are not allowed by default, aliases need aliases: true, and a class that is not permitted raises Psych::DisallowedClass. The method documentation for Psych.load says it is similar to safe_load except that Symbol objects are allowed by default, and its source passes the call to safe_load. The same page's overview still shows Psych.load reading a !ruby/range document "from a trusted string" and returning a Range.
  Plain-data alternative: the Marshal page says to use JSON or another serialisation format that is only able to load simple, primitive types such as String, Array and Hash, and never to allow user input to specify arbitrary types to deserialise into.

NODE.JS: JSON.parse() and node:v8 deserialize()
Documentation: MDN's JSON.parse() and Object initializer pages, and the v8 module page in the Node.js v26 documentation (v26.13.1 when it was opened).
  Can construct: MDN says JSON property values can only be strings, numbers, true, false, null, arrays or another JSON object, so JSON cannot express methods or non-plain objects like Map or RegExp, and that in JSON "__proto__" is a normal property key. A reviver changes what comes back: MDN says the reviver is run on the parsed value and all its properties, depth-first, and that because JSON has no syntax space for type metadata, reviving values that are not plain objects means choosing among options that include prefixing the data with a type tag. The Node.js documentation says the v8 serialisation API serialises JavaScript values in a way that is compatible with the HTML structured clone algorithm, and that v8.deserialize() uses a DefaultDeserializer with default options to read a value from a buffer.
  Documented restriction: for v8.deserialize(), none documented: the v8 module page describes its argument only as a buffer returned by serialize(). For JSON.parse(), what follows is this page's own advice, not a documented restriction: without a reviver it needs none, and with a reviver the restriction is whatever the reviver enforces.
  What the lab saw on Node.js v26.0.0 (format-probe.mjs, Part 3): through JSON.stringify and JSON.parse, a class instance and a Map came back as plain objects and a Date as a string. Through v8.serialize and v8.deserialize, the class instance came back as a plain object, while the Date and the Map came back as a Date and a Map.
  Plain-data alternative: JSON.parse() with no reviver, then a schema check, then a constructor your code chooses.

OTHER FORMATS
  OWASP's Deserialization Cheat Sheet lists more Java libraries by configuration. For example, it says SnakeYAML cannot be used safely unless the SafeConstructor class is used. Under a list of libraries that it says are either no longer maintained or cannot be used safely with untrusted input, its entry for XMLDecoder in the JDK is a quotation it credits to the Red Hat Defensive Coding Guide: "close to impossible to securely deserialize Java objects in this format from untrusted inputs". XML parser settings have their own worksheet in the XXE guide in this library.

==== PART 3. TAMPERED-OBJECT LAB ====
WHAT IT IS
An invented garden centre keeps a visitor's draft order in a token between page loads: the order as JSON, encoded in base64url, then a full stop, then an HMAC-SHA256 signature of the encoded part. The next request hands the token back and the service rebuilds the order. The lab has three versions of that rebuild:
  careless    never checks the signature, sets no size or depth limit and checks no schema, and its JSON reviver builds whichever service class the data names. The signature is there for show.
  late check  the careless rebuild, followed by a correct signature check. The check runs after the objects were built.
  careful     a size limit, an integrity check, a depth limit, plain JSON.parse, a type allow-list, a schema check, and then a new DraftOrder built from the checked fields, in that order.
The service defines two classes. DraftOrder is the one a token is meant to hold. ReportJob stands for a class that starts work when it is built; in the lab its constructor only adds a marker line to a list in memory, which is how the output shows that it ran.
The lab is an illustration in one language, with a token format invented for this page. It does not reproduce any real library's behaviour. What it shows is the order of the checks.

WHAT IT NEEDS
Node.js and nothing else. The files import only node:crypto, node:v8, node:test and node:assert/strict, and the lab installs no packages, opens no network port and writes no files. Both keys are invented values in a form no real provider uses, written into service.mjs so the output repeats; a real key is random and kept in a secret store. The results below were recorded on Node.js v26.0.0 on macOS 27.2.1. The Node.js documentation marks node:test as stable from version 20.0.0; this lab has been run only on v26.0.0.

THE FIXTURES (fixtures.mjs)
  F0  the genuine token
  F1  swapped type name: DraftOrder changed to ReportJob
  F2  added field: discountPercent set to 100
  F3  changed field type: quantity sent as the text "3"
  F4  a nested object 100 levels deep in note
  F5  an oversized body: a note of 50000 characters
  F6  the genuine object, signed with another key
  F7  a property named __proto__ added
The careless and late-check versions receive each fixture as an attacker without the key would send it: the payload changed and the genuine token's signature left on it (F6 carries a signature made with the other key). The careful version receives it that way ("key kept secret") and then again re-signed with the lab key ("re-signed with key"), as if the key had leaked, to show what the size, depth, type and schema checks still catch.

SET-UP
Make an empty folder, save the eight files below into it under the names shown, and run the commands under RUN IT from that folder.

==== File 1 of 8: service.mjs ====
// service.mjs: the invented garden centre's classes and token helpers,
// shared by every version of the lab. Nothing here opens a network port.
import { createHmac, timingSafeEqual } from 'node:crypto'

// Invented keys, in a form no real provider uses. A real key is random,
// lives in a secret store and is never written into source code.
export const LAB_KEY = 'LAB-ONLY-HMAC-KEY-not-a-real-secret'
export const OTHER_KEY = 'LAB-ONLY-OTHER-KEY-not-a-real-secret'

// Every marker line the lab records, in memory only.
export const markerLines = []

export function recordMarker(text) {
  markerLines.push('MARKER: ' + text)
}

// The one type a draft-order token is meant to hold.
export class DraftOrder {
  constructor(sku, quantity, note) {
    this.sku = sku
    this.quantity = quantity
    this.note = note
  }
}

// A class the service uses for staff reports. In a real service, building
// one would start a report export. In the lab its constructor only records
// a marker line.
export class ReportJob {
  constructor() {
    recordMarker('ReportJob constructor ran (a real one would start a report export)')
  }
}

// Every class the service defines, by name.
export const SERVICE_CLASSES = { DraftOrder: DraftOrder, ReportJob: ReportJob }

export function toBase64Url(text) {
  return Buffer.from(text, 'utf8').toString('base64url')
}

export function fromBase64Url(part) {
  return Buffer.from(part, 'base64url').toString('utf8')
}

export function signPart(payloadPart, key) {
  return createHmac('sha256', key).update(payloadPart).digest('base64url')
}

// A token is the payload in base64url, a full stop, then its HMAC-SHA256.
export function issueToken(payloadText, key) {
  const payloadPart = toBase64Url(payloadText)
  return payloadPart + '.' + signPart(payloadPart, key)
}

export function signatureMatches(payloadPart, signaturePart, key) {
  const expected = Buffer.from(signPart(payloadPart, key), 'base64url')
  const received = Buffer.from(String(signaturePart), 'base64url')
  if (received.length !== expected.length) return false
  return timingSafeEqual(received, expected)
}
==== File 2 of 8: careless.mjs ====
// careless.mjs: rebuilds a draft order the careless way. It never checks
// the signature, sets no size or depth limit and checks no schema, and its
// reviver builds whichever service class the data names, anywhere in it.
import { SERVICE_CLASSES, fromBase64Url } from './service.mjs'

function reviveAnyNamedClass(key, value) {
  if (value === null || typeof value !== 'object') return value
  const ClassNamedByData = SERVICE_CLASSES[value.type]
  if (typeof ClassNamedByData !== 'function') return value
  return Object.assign(new ClassNamedByData(), value)
}

export function rebuildCareless(token) {
  const payloadPart = token.split('.')[0]
  return JSON.parse(fromBase64Url(payloadPart), reviveAnyNamedClass)
}

export function handleRequest(token) {
  return { refused: false, value: rebuildCareless(token) }
}
==== File 3 of 8: late-check.mjs ====
// late-check.mjs: the careless rebuild followed by a correct signature
// check. The check is sound, but it runs after the objects were built.
import { rebuildCareless } from './careless.mjs'
import { signatureMatches } from './service.mjs'

export function handleRequest(token, key) {
  const value = rebuildCareless(token)
  const parts = token.split('.')
  if (!signatureMatches(parts[0], parts[1], key)) {
    return { refused: true, stageNumber: 0, stage: 'integrity, after parsing', reason: 'signature does not match the payload' }
  }
  return { refused: false, value: value }
}
==== File 4 of 8: careful.mjs ====
// careful.mjs: every check runs before any object is built, in this order:
//   1 size, 2 integrity, 3 depth, 4 parse to plain data,
//   5 type allow-list, 6 schema, 7 construct from the checked fields.
import { DraftOrder, fromBase64Url, signatureMatches } from './service.mjs'

const MAX_TOKEN_LENGTH = 1024
const MAX_DEPTH = 2
const MAX_NOTE_LENGTH = 200
const SKU_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-'
const DRAFT_ORDER_FIELDS = ['type', 'sku', 'quantity', 'note']
const BACKSLASH = String.fromCharCode(92)

function refuse(stageNumber, stage, reason) {
  return { refused: true, stageNumber: stageNumber, stage: stage, reason: reason }
}

// Stage 3: walks the JSON text, skipping strings, and returns the first
// nesting depth over the limit, or 0 if the text stays within it.
function findDepthOverLimit(text, limit) {
  let depth = 0
  let inString = false
  let escaped = false
  for (const character of text) {
    if (inString) {
      if (escaped) escaped = false
      else if (character === BACKSLASH) escaped = true
      else if (character === '"') inString = false
      continue
    }
    if (character === '"') inString = true
    if (character === '{' || character === '[') depth += 1
    if (character === '}' || character === ']') depth -= 1
    if (depth > limit) return depth
  }
  return 0
}

function isSku(value) {
  if (typeof value !== 'string' || value.length < 3 || value.length > 20) return false
  for (const character of value) {
    if (!SKU_CHARACTERS.includes(character)) return false
  }
  return true
}

// Stage 6: the schema for a draft order, written out. Returns a problem,
// or an empty string when the fields are exactly what the type allows.
function checkDraftOrder(fields) {
  for (const name of Object.keys(fields)) {
    if (!DRAFT_ORDER_FIELDS.includes(name)) return 'unexpected field ' + name
  }
  for (const name of DRAFT_ORDER_FIELDS) {
    if (!Object.hasOwn(fields, name)) return 'missing field ' + name
  }
  if (!isSku(fields.sku)) return 'sku must be 3 to 20 capital letters, digits or hyphens'
  const quantity = fields.quantity
  if (!Number.isInteger(quantity) || quantity < 1 || quantity > 99) return 'quantity must be a whole number from 1 to 99'
  if (typeof fields.note !== 'string' || fields.note.length > MAX_NOTE_LENGTH) return 'note must be text of at most 200 characters'
  return ''
}

// Stage 7 builds a new object from the checked fields only.
function buildDraftOrder(fields) {
  return new DraftOrder(fields.sku, fields.quantity, fields.note)
}

// Stage 5: the allow-list. Each type name this endpoint accepts maps to its
// schema check and its constructor. It is a Map, read with get(fields.type).
const ALLOWED_TYPES = new Map([
  ['DraftOrder', { checkFields: checkDraftOrder, construct: buildDraftOrder }],
])

function readPayload(token, key) {
  if (token.length > MAX_TOKEN_LENGTH) {
    return refuse(1, 'size', 'token is ' + token.length + ' characters, over the limit of ' + MAX_TOKEN_LENGTH)
  }
  const parts = token.split('.')
  if (parts.length !== 2 || !signatureMatches(parts[0], parts[1], key)) {
    return refuse(2, 'integrity', 'signature does not match the payload')
  }
  return { refused: false, text: fromBase64Url(parts[0]) }
}

function parsePlainData(text) {
  const depth = findDepthOverLimit(text, MAX_DEPTH)
  if (depth > 0) return refuse(3, 'depth', 'nesting reached depth ' + depth + ', over the limit of ' + MAX_DEPTH)
  let parsed
  try {
    parsed = JSON.parse(text)
  } catch (error) {
    return refuse(4, 'parse', 'not valid JSON')
  }
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
    return refuse(4, 'parse', 'payload is not a JSON object')
  }
  return { refused: false, fields: parsed }
}

export function handleRequest(token, key) {
  const payload = readPayload(token, key)
  if (payload.refused) return payload
  const parsed = parsePlainData(payload.text)
  if (parsed.refused) return parsed
  const fields = parsed.fields
  const allowed = typeof fields.type === 'string' ? ALLOWED_TYPES.get(fields.type) : undefined
  if (!allowed) return refuse(5, 'type allow-list', JSON.stringify(fields.type) + ' is not an allowed type')
  const problem = allowed.checkFields(fields)
  if (problem) return refuse(6, 'schema', problem)
  return { refused: false, value: allowed.construct(fields) }
}
==== File 5 of 8: fixtures.mjs ====
// fixtures.mjs: the genuine token and seven tampered ones. Each fixture
// can be sent two ways:
//   as sent:   the payload was changed by someone without the key, so the
//              signature is the genuine token's (F6 is signed with another key)
//   re-signed: every payload signed with the lab key, as if the key had leaked
import { LAB_KEY, OTHER_KEY, issueToken, signPart, toBase64Url } from './service.mjs'

const GENUINE = '{"type":"DraftOrder","sku":"SEED-TOM-01","quantity":3,"note":"Leave at the side gate"}'
const GENUINE_SIGNATURE = signPart(toBase64Url(GENUINE), LAB_KEY)

function withNote(noteJson) {
  return '{"type":"DraftOrder","sku":"SEED-TOM-01","quantity":3,"note":' + noteJson + '}'
}

function nestedObject(levels) {
  let text = '"bottom"'
  for (let level = 0; level < levels; level += 1) text = '{"n":' + text + '}'
  return text
}

export const FIXTURES = [
  { id: 'F0', label: 'genuine token', payload: GENUINE },
  { id: 'F1', label: 'swapped type name: DraftOrder changed to ReportJob', payload: GENUINE.replace('DraftOrder', 'ReportJob') },
  { id: 'F2', label: 'added field: discountPercent set to 100', payload: GENUINE.replace('}', ',"discountPercent":100}') },
  { id: 'F3', label: 'changed field type: quantity sent as the text "3"', payload: GENUINE.replace('"quantity":3', '"quantity":"3"') },
  { id: 'F4', label: 'nested object 100 levels deep in note', payload: withNote(nestedObject(100)) },
  { id: 'F5', label: 'oversized body: a note of 50000 characters', payload: withNote('"' + 'x'.repeat(50000) + '"') },
  { id: 'F6', label: 'genuine object, signature made with another key', payload: GENUINE, signWith: OTHER_KEY },
  { id: 'F7', label: 'property named __proto__ added', payload: GENUINE.replace('}', ',"__proto__":{"isStaff":true}}') },
]

export function findFixture(id) {
  return FIXTURES.find((fixture) => fixture.id === id)
}

export function tokenAsSent(fixture) {
  if (fixture.id === 'F0') return issueToken(fixture.payload, LAB_KEY)
  if (fixture.signWith) return issueToken(fixture.payload, fixture.signWith)
  return toBase64Url(fixture.payload) + '.' + GENUINE_SIGNATURE
}

export function tokenResigned(fixture) {
  return issueToken(fixture.payload, LAB_KEY)
}
==== File 6 of 8: run-lab.mjs ====
// run-lab.mjs: sends every fixture to every version and prints what was
// built, or which check refused it and at which stage.
import * as careful from './careful.mjs'
import * as careless from './careless.mjs'
import * as lateCheck from './late-check.mjs'
import { FIXTURES, tokenAsSent, tokenResigned } from './fixtures.mjs'
import { DraftOrder, LAB_KEY, ReportJob, markerLines } from './service.mjs'

const CLASS_NAMES = new Map([[DraftOrder.prototype, 'DraftOrder'], [ReportJob.prototype, 'ReportJob'], [Object.prototype, 'plain object']])

function nestingDepth(value) {
  if (value === null || typeof value !== 'object') return 0
  let deepest = 0
  for (const key of Object.keys(value)) deepest = Math.max(deepest, nestingDepth(value[key]))
  return deepest + 1
}

function describeField(value) {
  if (typeof value === 'string' && value.length > 40) return 'text of ' + value.length + ' characters'
  if (value !== null && typeof value === 'object') return 'an object nested ' + nestingDepth(value) + ' levels deep'
  return JSON.stringify(value)
}

// Own fields first, then any field the object inherits from its prototype.
// The type field is left out of the summary.
function describeFields(value) {
  const parts = []
  for (const key of Object.keys(value)) {
    if (key !== 'type') parts.push(key + ' ' + describeField(value[key]))
  }
  for (const key in value) {
    if (!Object.hasOwn(value, key)) parts.push('inherited ' + key + ' ' + describeField(value[key]))
  }
  return parts.join(', ')
}

function describeBuilt(value) {
  const className = CLASS_NAMES.get(Object.getPrototypeOf(value))
  const name = className || 'an object whose prototype came from the token (instanceof DraftOrder: ' + (value instanceof DraftOrder) + ')'
  return 'built ' + name + ': ' + describeFields(value)
}

function describeResult(result) {
  if (!result.refused) return describeBuilt(result.value)
  const where = result.stageNumber > 0 ? 'stage ' + result.stageNumber + ' (' + result.stage + ')' : result.stage
  return 'REFUSED at ' + where + ': ' + result.reason
}

function runOne(version, token) {
  const markersBefore = markerLines.length
  const result = version.handleRequest(token, LAB_KEY)
  const newMarkers = markerLines.slice(markersBefore)
  const markerText = newMarkers.length > 0 ? '  [' + newMarkers.join('; ') + ']' : ''
  return describeResult(result) + markerText
}

function printFixture(fixture) {
  const asSent = tokenAsSent(fixture)
  console.log(fixture.id + ' ' + fixture.label + ' (token ' + asSent.length + ' characters)')
  console.log('  careless                    ' + runOne(careless, asSent))
  console.log('  late check                  ' + runOne(lateCheck, asSent))
  console.log('  careful, key kept secret    ' + runOne(careful, asSent))
  console.log('  careful, re-signed with key ' + runOne(careful, tokenResigned(fixture)))
  console.log('')
}

console.log('Node.js ' + process.version)
console.log('')
for (const fixture of FIXTURES) printFixture(fixture)
console.log('Marker lines recorded in memory during this run: ' + markerLines.length)
console.log('Object.prototype gained an isStaff property: ' + Object.hasOwn(Object.prototype, 'isStaff'))
==== File 7 of 8: format-probe.mjs ====
// format-probe.mjs: what two plain-data round trips give back for a class
// instance, a Date and a Map, and what JSON.parse does with __proto__.
import { deserialize, serialize } from 'node:v8'
import { DraftOrder } from './service.mjs'

function typeName(value) {
  if (value === null || typeof value !== 'object') return typeof value
  return Object.getPrototypeOf(value).constructor.name
}

const samples = [
  ['DraftOrder instance', new DraftOrder('SEED-TOM-01', 3, 'Leave at the side gate')],
  ['Date', new Date(0)],
  ['Map', new Map([['sku', 'SEED-TOM-01']])],
]

console.log('JSON.stringify then JSON.parse, no reviver:')
for (const [label, value] of samples) {
  console.log('  ' + label + ' came back as ' + typeName(JSON.parse(JSON.stringify(value))))
}
console.log('node:v8 serialize then deserialize:')
for (const [label, value] of samples) {
  console.log('  ' + label + ' came back as ' + typeName(deserialize(serialize(value))))
}

const parsed = JSON.parse('{"__proto__":{"isStaff":true}}')
console.log('JSON.parse of {"__proto__":{"isStaff":true}}:')
console.log('  __proto__ is an own key: ' + Object.hasOwn(parsed, '__proto__'))
console.log('  prototype is still Object.prototype: ' + (Object.getPrototypeOf(parsed) === Object.prototype))
console.log('  parsed.isStaff: ' + parsed.isStaff)
==== File 8 of 8: regression.test.mjs ====
// regression.test.mjs: run with: node regression.test.mjs careful
// (or careless, or late-check). With no argument it tests the careful
// version, so node --test can run it in a pipeline.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { FIXTURES, findFixture, tokenAsSent, tokenResigned } from './fixtures.mjs'
import { DraftOrder, LAB_KEY, markerLines } from './service.mjs'

const versionName = process.argv[2] || 'careful'
const version = await import('./' + versionName + '.mjs')
const TAMPERED = FIXTURES.filter((fixture) => fixture.id !== 'F0')
const STILL_REFUSED_WITH_KEY = ['F1', 'F2', 'F3', 'F4', 'F5', 'F7'].map(findFixture)

function send(token) {
  return version.handleRequest(token, LAB_KEY)
}

test('the genuine token rebuilds a DraftOrder with its fields', () => {
  const result = send(tokenAsSent(findFixture('F0')))
  assert.equal(result.refused, false)
  assert.ok(result.value instanceof DraftOrder)
  assert.equal(result.value.sku, 'SEED-TOM-01')
  assert.equal(result.value.quantity, 3)
})

test('no token makes the service build a class it did not ask for', () => {
  markerLines.length = 0
  for (const fixture of FIXTURES) {
    send(tokenAsSent(fixture))
    send(tokenResigned(fixture))
  }
  assert.deepEqual(markerLines, [])
})

test('every tampered token is refused while the key stays secret', () => {
  for (const fixture of TAMPERED) {
    const result = send(tokenAsSent(fixture))
    assert.equal(result.refused, true, fixture.id + ' ' + fixture.label + ' was accepted')
  }
})

test('with the key leaked, the size, depth, type and schema checks still refuse', () => {
  for (const fixture of STILL_REFUSED_WITH_KEY) {
    const result = send(tokenResigned(fixture))
    assert.equal(result.refused, true, fixture.id + ' ' + fixture.label + ' was accepted')
  }
})

test('an oversized token is refused before it is parsed', () => {
  const result = send(tokenAsSent(findFixture('F5')))
  assert.equal(result.stageNumber, 1, 'F5 was not refused at stage 1, the size check')
})
==== RUN IT ====
node run-lab.mjs
node format-probe.mjs
node regression.test.mjs careful
node regression.test.mjs late-check
node regression.test.mjs careless
node --test

==== OUTPUT OF node run-lab.mjs (Node.js v26.0.0, macOS 27.2.1) ====
Node.js v26.0.0

F0 genuine token (token 159 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"
  late check                  built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"
  careful, key kept secret    built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"
  careful, re-signed with key built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"

F1 swapped type name: DraftOrder changed to ReportJob (token 158 characters)
  careless                    built ReportJob: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"  [MARKER: ReportJob constructor ran (a real one would start a report export)]
  late check                  REFUSED at integrity, after parsing: signature does not match the payload  [MARKER: ReportJob constructor ran (a real one would start a report export)]
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key REFUSED at stage 5 (type allow-list): "ReportJob" is not an allowed type

F2 added field: discountPercent set to 100 (token 188 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate", discountPercent 100
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key REFUSED at stage 6 (schema): unexpected field discountPercent

F3 changed field type: quantity sent as the text "3" (token 162 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity "3", note "Leave at the side gate"
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key REFUSED at stage 6 (schema): quantity must be a whole number from 1 to 99

F4 nested object 100 levels deep in note (token 938 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity 3, note an object nested 100 levels deep
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key REFUSED at stage 3 (depth): nesting reached depth 3, over the limit of 2

F5 oversized body: a note of 50000 characters (token 66796 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity 3, note text of 50000 characters
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 1 (size): token is 66796 characters, over the limit of 1024
  careful, re-signed with key REFUSED at stage 1 (size): token is 66796 characters, over the limit of 1024

F6 genuine object, signature made with another key (token 159 characters)
  careless                    built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key built DraftOrder: sku "SEED-TOM-01", quantity 3, note "Leave at the side gate"

F7 property named __proto__ added (token 198 characters)
  careless                    built an object whose prototype came from the token (instanceof DraftOrder: false): sku "SEED-TOM-01", quantity 3, note "Leave at the side gate", inherited isStaff true
  late check                  REFUSED at integrity, after parsing: signature does not match the payload
  careful, key kept secret    REFUSED at stage 2 (integrity): signature does not match the payload
  careful, re-signed with key REFUSED at stage 6 (schema): unexpected field __proto__

Marker lines recorded in memory during this run: 2
Object.prototype gained an isStaff property: false
Exit code: 0

==== OUTPUT OF node format-probe.mjs ====
JSON.stringify then JSON.parse, no reviver:
  DraftOrder instance came back as Object
  Date came back as string
  Map came back as Object
node:v8 serialize then deserialize:
  DraftOrder instance came back as Object
  Date came back as Date
  Map came back as Map
JSON.parse of {"__proto__":{"isStaff":true}}:
  __proto__ is an own key: true
  prototype is still Object.prototype: true
  parsed.isStaff: undefined
Exit code: 0

==== REGRESSION TEST RESULTS ====
The lines below are copied from the test runner's output. Durations change from run to run. In the two failing runs, each stack trace is cut because it names the folder the lab ran in, and the block of error properties that follows it is cut with it; each cut is marked.

Run: node regression.test.mjs careful
✔ the genuine token rebuilds a DraftOrder with its fields (0.855875ms)
✔ no token makes the service build a class it did not ask for (0.986333ms)
✔ every tampered token is refused while the key stays secret (0.134708ms)
✔ with the key leaked, the size, depth, type and schema checks still refuse (0.194625ms)
✔ an oversized token is refused before it is parsed (0.070584ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.290791
Exit code: 0

Run: node regression.test.mjs late-check
✔ the genuine token rebuilds a DraftOrder with its fields (0.775959ms)
✖ no token makes the service build a class it did not ask for (2.166834ms)
✔ every tampered token is refused while the key stays secret (0.246875ms)
✖ with the key leaked, the size, depth, type and schema checks still refuse (0.122917ms)
✖ an oversized token is refused before it is parsed (0.4785ms)
ℹ tests 5
ℹ suites 0
ℹ pass 2
ℹ fail 3
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7.223459

✖ failing tests:

test at regression.test.mjs:26:1
✖ no token makes the service build a class it did not ask for (2.166834ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'MARKER: ReportJob constructor ran (a real one would start a report export)',
  +   'MARKER: ReportJob constructor ran (a real one would start a report export)'
  + ]
  - []
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)

test at regression.test.mjs:42:1
✖ with the key leaked, the size, depth, type and schema checks still refuse (0.122917ms)
  AssertionError [ERR_ASSERTION]: F1 swapped type name: DraftOrder changed to ReportJob was accepted
  
  false !== true
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)

test at regression.test.mjs:49:1
✖ an oversized token is refused before it is parsed (0.4785ms)
  AssertionError [ERR_ASSERTION]: F5 was not refused at stage 1, the size check
  
  0 !== 1
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)
Exit code: 1

Run: node regression.test.mjs careless
✔ the genuine token rebuilds a DraftOrder with its fields (0.825959ms)
✖ no token makes the service build a class it did not ask for (2.250084ms)
✖ every tampered token is refused while the key stays secret (0.101042ms)
✖ with the key leaked, the size, depth, type and schema checks still refuse (0.089417ms)
✖ an oversized token is refused before it is parsed (0.14525ms)
ℹ tests 5
ℹ suites 0
ℹ pass 1
ℹ fail 4
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.076334

✖ failing tests:

test at regression.test.mjs:26:1
✖ no token makes the service build a class it did not ask for (2.250084ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'MARKER: ReportJob constructor ran (a real one would start a report export)',
  +   'MARKER: ReportJob constructor ran (a real one would start a report export)'
  + ]
  - []
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)

test at regression.test.mjs:35:1
✖ every tampered token is refused while the key stays secret (0.101042ms)
  AssertionError [ERR_ASSERTION]: F1 swapped type name: DraftOrder changed to ReportJob was accepted
  
  false !== true
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)

test at regression.test.mjs:42:1
✖ with the key leaked, the size, depth, type and schema checks still refuse (0.089417ms)
  AssertionError [ERR_ASSERTION]: F1 swapped type name: DraftOrder changed to ReportJob was accepted
  
  false !== true
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)

test at regression.test.mjs:49:1
✖ an oversized token is refused before it is parsed (0.14525ms)
  AssertionError [ERR_ASSERTION]: F5 was not refused at stage 1, the size check
  
  undefined !== 1
  
  (stack trace and error properties cut here: the stack trace names the folder the lab ran in)
Exit code: 1

Run: node --test
✔ the genuine token rebuilds a DraftOrder with its fields (0.820041ms)
✔ no token makes the service build a class it did not ask for (1.020166ms)
✔ every tampered token is refused while the key stays secret (0.127625ms)
✔ with the key leaked, the size, depth, type and schema checks still refuse (0.216292ms)
✔ an oversized token is refused before it is parsed (0.076125ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 91.351542
Exit code: 0

==== READING THE RESULTS ====
built followed by a class name: the version returned an object of that class. Fields come from the object itself; "inherited" marks a field the object only has through its prototype.
REFUSED at stage N: the careful version stopped at that check and built nothing. The stages are 1 size, 2 integrity, 3 depth, 4 parse, 5 type allow-list, 6 schema and 7 construct.
REFUSED at integrity, after parsing: the late-check version refused the request, but only after the careless rebuild had run.
A MARKER line in square brackets: the ReportJob constructor ran during that request. In a real service, that is the moment its work would start.
What the run shows: the careless version built something from every fixture. The late-check version refused every tampered token and still ran the ReportJob constructor for F1. The careful version refused every tampered token while the key stayed secret, and with the key leaked its size, depth, type and schema checks still refused F1 to F5 and F7. F6 re-signed with the real key is the genuine token, so it was accepted, as it should be.

==== USING IT ON YOUR OWN CODE ====
1. Fill in a Part 1 block for the boundary you are testing, from the documentation for the version you run.
2. Copy regression.test.mjs into your project and change send() so it calls your real handler, or the function that rebuilds the value, on a test or staging copy.
3. Keep the eight fixtures, rewritten in your own format, and add an added-field and a changed-type case for every field your type has.
4. Give the class you least want built a marker of its own in the test build, as ReportJob has here, so the test can tell whether it ran.
5. Run the test in the pipeline that deploys the application. node --test runs files whose names end in .test.mjs, among other patterns, and sets the exit code to 1 when a test fails. Record the date and the result in the Part 1 block.

What serialisation and deserialisation are

Serialisation turns something a program holds in memory into bytes it can store or send.

Deserialisation turns those bytes back into something the program can use. MITRE's background note for CWE-502 describes the pair as taking program-internal object-related data, packaging it so it can be stored or transferred externally, and then extracting the serialised data to reconstruct the original object. OWASP's Deserialization Cheat Sheet says people often serialise objects to save them for storage, or to send them as part of communications.

This guide is about the second half: the moment bytes that came from outside the code you are reading become values, and sometimes objects, inside it. The boundary is easy to miss, because frameworks and libraries cross it for you all day.

A session read back on the next request is deserialised. So is a "remember me" token, a cache entry written by one process and read by another, a message a background worker picks up, an uploaded settings file, a data import and an API body. Each is a place where someone other than the code may have written the bytes.

OWASP's cheat sheet notes that JSON is now the most popular format for serialising data, that XML was before it, and that many programming languages also have native ways to serialise objects which usually offer more features than JSON or XML, including customisation of the serialisation process.

It says those features can sometimes be repurposed for malicious effect when they operate on untrusted data. That difference between formats is where serialisation security starts, and it is the centre of this guide.

What makes deserialisation a vulnerability

MITRE catalogues the weakness as CWE-502, Deserialization of Untrusted Data: the product deserialises untrusted data without sufficiently ensuring that the resulting data will be valid.

Its listed consequences include attackers modifying unexpected objects or data that were assumed to be safe from modification; denial of service through CPU consumption, because a function that relies on a sentry in a string to know when to terminate could easily never terminate; and consequences that can vary widely, depending on which objects or methods are being deserialised and how they are used.

For the last, it gives as one example attackers using gadget chains to perform unauthorised actions, such as generating a shell.

OWASP's cheat sheet says attacks against deserialisers have been found to allow denial-of-service, access control or remote code execution attacks.

The question underneath is who chooses the type. Oracle's Java documentation says deserialising untrusted data is an inherently dangerous activity because the content of the incoming data stream determines the objects that are created, the values of their fields and the references between them, and that deserialisation is code execution because the readObject method of the class being deserialised can contain custom code.

Microsoft's BinaryFormatter migration guide puts the general rule in one line: any deserialiser, binary or text, that allows its input to carry information about the objects to be created is a security problem waiting to happen.

In plain terms, when the bytes name the class, whoever wrote the bytes chooses which code runs while the object is rebuilt: a constructor, or a hook such as PHP's __wakeup() or Java's readObject(). PHP's documentation says that after it reconstructs an object, it will automatically attempt to call that object's __unserialize() or __wakeup() method if one exists.

Oracle's guide calls classes that can perform arbitrary reflective actions "gadget classes", and says they can be deserialised maliciously to cause a denial of service or remote code execution.

This guide stops at that mechanism. It is enough to know that a class anywhere in your code or its libraries, whose construction does something, can be reached once the sender picks the type.

You will also see this called object injection. CWE-502 lists PHP Object Injection as an alternate term that some PHP application researchers use for attacks on unsafe use of unserialize(), and notes that the term is also used for CWE-915.

Where a rebuilt object leads to code running on your server, the remote code execution guide in this library covers what decides the damage from there: what that process can reach.

What OWASP's standards say

The OWASP Top 10:2025 maps CWE-502 to A08 Software or Data Integrity Failures, which it describes as code and infrastructure that does not protect against invalid or untrusted code or data being treated as trusted and valid. Its fourth example scenario is insecure deserialisation: an application that serialises the user state and passes it back and forth with each request, where an attacker notices the Java object signature and gains remote code execution on the application server.

ASVS 5.0 section V1.5 Safe Deserialization says deserialisation has historically been the cause of various code injection vulnerabilities, and that some deserialisation methods have been identified by language or framework documentation as insecure and cannot be made safe with untrusted data.

Requirement 1.5.2, at Level 2, asks that deserialisation of untrusted data enforces safe input handling, such as using an allowlist of object types or restricting client-defined object types, and that mechanisms explicitly defined as insecure are not used with untrusted input.

Requirement 1.5.3, at Level 3, asks that different parsers used for the same data type, such as JSON parsers, parse consistently and use the same character encoding.

Formats that carry data and formats that carry types

A plain-data format can describe only a fixed set of value types.

MDN says JSON property values can only be strings, numbers, true, false, null, arrays or another JSON object, so JSON cannot express methods or non-plain objects like Map or RegExp. Parsing it gives your code data, and your code decides what to build from that data.

Python's pickle documentation draws the same line from the other side: JSON by default can only represent a subset of the Python built-in types and no custom classes, and unlike pickle, deserialising untrusted JSON does not in itself create an arbitrary code execution vulnerability.

A type-carrying format records which class each value belongs to and builds that class on the way back in. Python's pickle, PHP's serialize() format, Java's Serializable streams, .NET's BinaryFormatter and Ruby's Marshal all work that way, among others. Ruby's documentation states the consequence directly: by design, Marshal.load can deserialise almost any class loaded into the Ruby process, and in many cases this can lead to remote code execution if the data is loaded from an untrusted source.

The line moves with code and configuration. JSON stops being plain data the moment something reads a type name out of it and builds that type. MDN's JSON.parse() page says that because JSON has no syntax space for type metadata, reviving values that are not plain objects means choosing among options, one of which is prefixing the data with a type tag.

OWASP's cheat sheet shows the same thing in libraries: it says jackson-databind can be used safely as long as polymorphism is not used, says json-io's @type property allows deserialisation of any class, and says that where JSON.Net is used, TypeNameHandling should be set only to None.

YAML can move the other way: PyYAML's safe_load and Ruby's Psych.safe_load restrict a format that can name types to plain values and a short list of classes.

The lab's careless version is a small example of JSON turned into a type-carrying format. Its reviver reads a type field and builds whichever of the service's classes it names, so changing one word in the token runs a different constructor.

Files a feature opens after an upload, such as saved projects or backups, cross the same kind of boundary; the file upload security guide in this library covers how the upload itself is checked and stored.

Why signing the bytes is not enough on its own

A signature answers one question: were these bytes produced by someone holding the key?

OWASP Top 10:2025 A08 asks that unsigned or unencrypted serialised data is not received from untrusted clients and used without some form of integrity check or digital signature to detect tampering or replay. OWASP's Deserialization Cheat Sheet says an application that knows before deserialisation which messages it will need to process could sign them, then choose not to deserialise any message without an authenticated signature.

CWE-502 gives a hash-based message authentication code (HMAC) as one way to make sure data has not been modified, and Python's pickle documentation says to consider signing data with hmac if you need to ensure that it has not been tampered with.

Two things undo a signature. The first is order. CWE-502's second example decodes and unpickles a token from a request header and only afterwards checks its HMAC signature; MITRE says the code does not verify that the incoming data is legitimate, and that an attacker can construct a serialised token that executes arbitrary commands.

OWASP's .NET guidance makes the same point about checking an object's type after BinaryFormatter.Deserialize has returned: the check is too late, because execution may already have occurred.

In this page's lab, the late-check version refused every tampered token, and still ran the ReportJob constructor for the token that named it.

The second is the key. A signature proves only that someone with the key made the bytes. If the key turns up in a repository, a log file or an old laptop, anyone holding it can sign whatever they like, and a check that rested on the signature alone has nothing left to stand on.

The PHP documentation gives two pieces of advice in the same warning: not to pass untrusted user input to unserialize() regardless of the options value of allowed_classes, and, if you need to unserialise externally stored serialised data, to consider using hash_hmac() for data validation.

Reading the two together is this page's own step: a signature is one check, and the checks behind it have to hold without it.

ASVS 5.0 requirement 13.3.1, at Level 2, puts backend secrets in a secrets management solution and says they must not be included in source code or build artefacts.

The lab plays out a leaked key by signing every tampered token with the real one. The careful version's size, depth, type and schema checks still refused six of the seven. The seventh, a genuine order signed with the wrong key, was simply the genuine token once the right key signed it, and was accepted.

Why an allow-list of types beats a block-list

A block-list names the classes known to be dangerous and lets the rest through.

An allow-list names the classes this boundary needs and refuses everything else. Oracle's serialisation filtering guide describes both. It calls allow-lists the proactive approach, allowing only class names that are recognised and trusted and rejecting all others, and says this can work very well if your application only deals with a small set of classes. It says reject-lists are usually implemented after an attack reveals that a class is a problem.

One of CWE-502's seven potential mitigations is to avoid having unnecessary types or gadgets available and to add only acceptable classes to an allowlist, and it notes that new gadgets are constantly being discovered, so this alone is not a sufficient mitigation.

That note is the case against relying on a block-list: a list of known-bad classes is out of date the day another one is found. Microsoft says the same of BinaryFormatter from its side: BinaryFormatter.Deserialize might be susceptible to attack categories other than denial of service, such as information disclosure or remote code execution; features such as a custom SerializationBinder might be insufficient to properly mitigate these risks; and the possibility exists that an attacker will discover a novel exploit that bypasses existing mitigations.

An allow-list can still be too generous. OWASP's .NET section warns that some permitted types have risky properties, and gives a type with a property of type Object as its example: if that type is allowed, an attacker can set the property to any object type they choose. Keep the list to the types the feature stores, and keep those types plain.

Check what your platform does when you say nothing. Oracle's guide says a serialisation filter is not enabled or configured by default, and that a class name matching no pattern in a filter is allowed, so a filter meant to allow only listed classes ends with !*.

PHP's documentation says omitting allowed_classes is the same as setting it to true, and PHP will attempt to instantiate objects of any class. Ruby's Psych.safe_load starts from a short list of plain classes and adds only what you name in permitted_classes.

The lab's careful version keeps its allow-list in a Map with one entry, from the name DraftOrder to the code that checks and builds it, and OWASP's Prototype Pollution Prevention Cheat Sheet suggests new Map() or new Set() in place of object literals.

What size and depth limits protect

Integrity and type checks decide what gets built.

Limits decide how much work the parser does before any of those checks has an answer. CWE-502 lists denial of service through CPU resource consumption among its consequences, and Microsoft says BinaryFormatter.Deserialize can be used for denial-of-service attacks that might render an app unresponsive or result in unexpected process termination, and that this category of attack cannot be mitigated with a SerializationBinder or any other BinaryFormatter configuration switch.

Two numbers do most of the work. A size limit caps how many bytes the application will look at, and checked first it protects every later step, including the signature check, which has to read every byte to compute its result. A depth limit caps how far structures can nest.

PHP's documentation describes the max_depth option of unserialize() as intended to prevent stack overflows, gives its default as 4096, and records it arriving in PHP 7.4.0. Oracle's pattern-based filters take maxbytes, maxdepth, maxrefs and maxarray, and the guide says the built-in RMI filters include maxarray=1000000;maxdepth=20.

OWASP's cheat sheet adds that Java filters are not called for strings or primitives encoded concretely in the stream, so the input size needs a bound of its own.

In the lab, the careful version checks the token's length before anything else and the nesting depth before JSON.parse runs, using a short scan written out in careful.mjs. The oversized fixture was refused at stage 1 whether or not it carried a valid signature, and the 100-level fixture, re-signed, was refused at stage 3.

The careless version built both: an order with a 50,000-character note, and an order whose note was an object nested 100 levels deep.

Set the limits from what the feature needs. A draft order has no reason to be longer than a kilobyte or deeper than two levels.

Safe deserialisation: validate before you construct

Validating before you construct means no object of yours exists until the bytes have passed every check that can be made on plain data.

The lab's careful version runs its checks in this order, and each one either passes the value on or refuses it and builds nothing:

  • Size. Refuse a token longer than the feature needs, before reading it.
  • Integrity. Recompute the HMAC over the encoded payload with crypto.createHmac and compare it with crypto.timingSafeEqual, which the Node.js documentation says compares bytes using a constant-time algorithm and is suitable for comparing HMAC digests. It throws when the two values differ in length, so the lab compares the lengths first.
  • Depth. Refuse nesting deeper than the format needs.
  • Parse to plain data. JSON.parse with no reviver, and refuse anything that is not a JSON object.
  • Type allow-list. Look the type name up in the allow-list. A name that is not there is refused.
  • Schema. Require exactly the expected fields, each of the expected type and range. A field the type does not have, such as discountPercent or __proto__, is refused.
  • Construct. Build a new DraftOrder from the checked fields only.

Why the last two steps are separate

The last step follows a CWE-502 mitigation: when deserialising data, populate a new object rather than just deserialising, so the data flows through safe input validation. ASVS 5.0 requirement 2.2.1, at Level 1, asks that input is validated either against an allow list of values, patterns and ranges, or against an expected structure and logical limits according to predefined rules, and says that at Level 1 this can focus on input used to make specific business or security decisions, while for Level 2 and up it should apply to all input.

The V2.2 introduction says schema validation, while not explicitly mandated, may be the most effective mechanism for full validation coverage of HTTP APIs or other interfaces that use JSON or XML.

A schema library can declare the same rules.

Zod's documentation, for example, says z.strictObject() throws an error when unknown keys are found, where z.object() strips them by default. The lab writes its checks out because it installs nothing.

What the lab showed about __proto__

MDN says that in JSON "__proto__" is a normal property key. The lab's format probe matched that on Node.js v26.0.0: JSON.parse kept __proto__ as an own key and left the parsed object's prototype alone. The change came afterwards. In the careless version, copying the parsed fields onto a new instance with Object.assign replaced that instance's prototype with the object from the token, so the result was no longer a DraftOrder and inherited isStaff set to true.

Object.prototype itself did not change in that run.

OWASP's Prototype Pollution Prevention Cheat Sheet describes prototype pollution as a vulnerability that can allow attackers to manipulate an application's JavaScript objects and properties. The careful version never reached a copy: its schema refused __proto__ as an unexpected field.

Moving a feature from a type-carrying format to plain data

Moving a feature off a format that can name types removes the questions above instead of answering them.

OWASP's cheat sheet says a great reduction of risk is achieved by avoiding native deserialisation formats and switching to a pure data format like JSON or XML. It describes the data-transfer object pattern, a separate set of objects created for the explicit purpose of data transfer, and notes that the application can still make security mistakes after a pure data object is parsed. The steps below are this page's advice for making the move without losing data already stored.

  • Write down what the feature really stores: each field, its type and its range. That list becomes the schema, and the classes it needs become an allow-list of one or two entries, or none.
  • Choose the plain format your platform's documentation points to. Python's pickle page points to json, PHP's documentation to json_encode() and json_decode(), and Ruby's Marshal page to JSON or another format that only loads primitive types. Microsoft's migration guide recommends System.Text.Json, DataContractSerializer, MessagePack or protobuf-net in place of BinaryFormatter.
  • Write the new reader first, with the checks in the order above and a test for each tampered case, before anything writes the new format.
  • Decide what happens to data already stored in the old format. Microsoft's migration guide describes reading existing BinaryFormatter payloads without performing general-purpose deserialisation. Elsewhere, convert stored data once, in a job you control, rather than leaving the old reader on a public path. A short-lived session or cache entry can simply be left to expire.
  • Change the signing key when you switch, so tokens issued in the old format stop verifying.
  • Remove the old reader and its settings, and keep a regression test that sends an old-format value and expects a refusal.

While the old format is still in use

Until the move is finished, questions 4 to 6 of the checklist carry the weight: verify before parsing, limit size and depth, and keep the allow-list as short as the feature allows. Java's serialisation filters, Python's find_class(), PHP's allowed_classes and Psych's permitted_classes are the documented places to write the allow-list.

Microsoft's guidance for BinaryFormatter is different: it says the type is insecure and can't be made secure, and that applications should stop using it as soon as possible.

A deserialiser left on its most permissive setting, such as a Java runtime with no filter configured, is the kind of finding the security misconfiguration guide in this library covers.

Deserialisation testing on your own application

Start in the code.

Search for the functions in the reference on this page and for anything that wraps them: pickle.load and pickle.loads, yaml.load with an unsafe loader, unserialize, ObjectInputStream.readObject, BinaryFormatter and its relatives, Marshal.load, and any JSON reviver or library setting that reads a type name. OWASP's cheat sheet lists Java APIs to look for, among them XMLDecoder with external user-defined parameters, XStream's fromXML method, and ObjectInputStream with readObject, and for .NET the terms TypeNameHandling and JavaScriptTypeResolver.

CWE-502 says automated static analysis can find some instances of the weakness, says this is typically done by building a model of data flow and control flow and then searching for potentially vulnerable patterns that connect sources of input with sinks, and rates its effectiveness as High.

Finding every such place, including the ones a library handles, is the reading work the secure code review guide in this library describes.

Then look at what crosses each boundary. OWASP's cheat sheet says captured traffic that contains AC ED 00 05 in hex or rO0 in base64 may suggest data sent in a Java serialisation stream. Under Opaque-box Review in its Python section, it says that if the data is being encoded, it is best to check whether serialisation is likely happening by looking at the starting characters of the parameter value, and gives this example: if data is Base64 encoded, it will most likely start with gASV.

The fourth of A08's four example scenarios has an attacker notice that rO0 signature.

Recognising one is reason enough to fill in a checklist block for that place. Every route that accepts a body belongs in the checklist too, and the API security guide in this library covers keeping an inventory of those routes.

Then test the checks, not the gadgets. On a copy you own or are authorised in writing to test, send harmless tampered values like the lab's fixtures: a changed type name, an extra field, a field of the wrong type, nesting deeper than the format needs, an oversized body, a correct value with a wrong signature and a __proto__ key.

Each should be refused at a named stage, and none should run a constructor you did not intend. A marker of your own in a test build, like the lab's ReportJob, shows whether one ran.

Showing that the sender can choose the type is the whole finding. Nothing on this page builds a chain of classes that does more, and nothing here is for use against someone else's system.

Running the tampered-object lab

The lab in the asset on this page is an illustration: an invented garden centre, one invented token format and JavaScript only.

It does not reproduce any real library. The files import only node:crypto, node:v8, node:test and node:assert/strict, and the lab installs no packages, opens no network port and writes no files. Its two keys are invented values in a form no real provider uses.

The output shown was recorded on Node.js v26.0.0 on macOS 27.2.1. The Node.js documentation marks node:test as stable from version 20.0.0, and the lab has been run only on v26.0.0.

The careless version built something from all eight fixtures: the genuine order, a ReportJob whose constructor recorded the marker line, an order carrying discountPercent 100, an order whose quantity was the text "3", a note nested 100 levels deep, a note of 50,000 characters, an order signed with another key, and an object whose prototype came from the token.

The late-check version refused all seven tampered tokens, but had already built the ReportJob before refusing it. With the key kept secret, the careful version refused all seven: the oversized token at stage 1 and the rest at stage 2.

Re-signed with the lab key, it refused F5 at stage 1, F4 at stage 3, F1 at stage 5 and F2, F3 and F7 at stage 6, and accepted F6, which re-signing had turned into the genuine token.

regression.test.mjs runs five tests: the genuine token still rebuilds, no token runs a class it should not, every tampered token is refused while the key is secret, the size, depth, type and schema checks still refuse with the key leaked, and an oversized token is refused before parsing.

The careful version passed all five and exited with code 0, and so did node --test, which by default runs files whose names end in .test.mjs, among other patterns. The careless version failed four and exited with code 1.

The late-check version failed three, among them the marker test: a correct signature check that runs after the objects were built does not undo a constructor that already ran.

Where an outside review or test fits

The checklist covers the boundaries you already know about, and reading the code finds the ones you do not, such as a library that rebuilds objects from a cache.

Clever Ops reviews code for applications such as Next.js, React and Node with read-only access to the repository. A secure code review follows the paths in scope and looks at untrusted input as it goes; code findings are confirmed against a running build where the scope allows, and the report marks any finding that rests on the code alone.

A Clever Ops web application and API penetration test can add read-only code access to named areas to confirm how a control is enforced. Each finding is confirmed with the least intrusive proof available, and destructive actions are off by default for real people's accounts and for records that existed before the test.

Where a published flaw is known to run code on the server, the version and configuration in the deployed build are confirmed instead, and no exploit payload is sent.

If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

It is a flaw in how an application turns stored or received bytes back into objects. MITRE catalogues it as CWE-502, Deserialization of Untrusted Data: deserialising untrusted data without sufficiently ensuring that the result will be valid. When the format lets the bytes name a class, whoever wrote the bytes chooses which code runs while the object is rebuilt, and CWE-502 says the consequences can vary widely, depending on which objects or methods are being deserialised and how they are used.

It is another name for the same family of flaws. CWE-502 lists PHP Object Injection as an alternate term some PHP application researchers use for attacks on unsafe use of unserialize(), and notes that the term is also used for CWE-915. PHP's documentation says that when allowed_classes is omitted, unserialize() will attempt to instantiate objects of any class, and it warns against passing untrusted user input to unserialize() whatever that option is set to.

Plain JSON.parse with no reviver gives back data, not your classes: MDN says JSON cannot express methods or non-plain objects. The risk returns when code reads a type name from the JSON and builds that type, through a reviver or a library feature. OWASP's cheat sheet says jackson-databind can be used safely as long as polymorphism is not used, and that JSON.Net's TypeNameHandling should be set only to None. Parsed JSON still needs a schema check before you build anything from it.

Not on its own. A signature checked after a type-carrying format has been parsed is too late, because the objects were built during parsing, and a signature made with a leaked key proves nothing. Put a size limit in front of the signature check, check the signature before parsing, keep the key in a secrets store, and keep the depth, type and schema checks behind the signature. In the lab, the size, depth, type and schema checks still refused six of seven tampered tokens after the key was treated as leaked.

Microsoft's migration guide says that starting with .NET 9 the runtime no longer includes an implementation: the APIs are present but always throw a PlatformNotSupportedException. An unsupported compatibility package restores the functioning implementation, including its vulnerabilities and risks. Microsoft's security guide says BinaryFormatter is insecure and can't be made secure, and its migration guide recommends System.Text.Json, DataContractSerializer, MessagePack or protobuf-net instead.

Python's documentation shows overriding Unpickler.find_class() to forbid globals or restrict them to a safe subset, and then says you have to be careful with what you allow to be unpickled and that, if security is a concern, you may want to consider alternatives such as the marshalling API in xmlrpc.client or third-party solutions. Its warning still stands: never unpickle data that could have come from an untrusted source or could have been tampered with. For untrusted input, it points to safer formats such as json.

Find every place the code rebuilds objects from outside data, including inside libraries, and fill in a checklist block for each. Then, on a copy you own or are authorised in writing to test, send harmless tampered values such as a changed type name, an extra field, a wrong signature, deep nesting and an oversized body, and confirm each is refused before any object is built. Keep those cases as regression tests.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.