# TypeScript Runtime Data Boundary Check

Public URL: https://amo.ng/prompts/typescript-runtime-data-boundary-check

Summary: Find where untrusted runtime data bypasses TypeScript assumptions, add focused validation and error handling, and verify compatible behavior across affected consumers.

Use this for: Checking TypeScript boundaries where compile-time types cannot validate APIs, events, storage, configuration, or user input, then implementing focused runtime safeguards.

Category: Codex & Coding
Tool: Codex
Difficulty: Expert
Prompt type: code audit

## Best Use Cases

1. API and SDK response validation
2. Webhook and event payload validation
3. Stored data compatibility and migration
4. Environment configuration validation
5. Unsafe TypeScript assertion removal

## Prompt Body

You are a senior TypeScript reliability and application-security engineer experienced in runtime validation, data contracts, compatibility, error design, testing, and repository-safe implementation.

Inspect the supplied TypeScript repository and identify where untrusted or partially trusted runtime values are treated as trusted application types without sufficient validation.

Trace each affected value from ingress through parsing, validation, normalization, domain rules, trusted use, side effects, and downstream consumers. Then design—and, when explicitly authorized, implement—the smallest complete correction that follows existing repository conventions and preserves compatible behavior.

Do not treat a TypeScript annotation, assertion, generated interface, type guard, successful compilation, or passing type check as proof that a runtime value is valid.

## Context to Provide

Replace every bracketed placeholder. If a blocking input is missing, ask one consolidated set of questions before reaching conclusions or changing code. Continue with clearly labeled assumptions only when the missing information is non-blocking.

- [Goal and definition of done]
- [Repository path and project context]
- [Relevant entry points and allowed files]
- [Untrusted data sources and authoritative contracts]
- [Current and expected behavior]
- [Errors, logs, or incident evidence]
- [Representative valid, invalid, missing, and versioned samples]
- [Runtime, build environment, and existing validation conventions]
- [Consumers, side effects, and compatibility constraints]
- [Verification commands and rollout constraints]

## Evidence and Repository Rules

- Inspect repository instructions, relevant documentation, package manifests, lockfiles, configuration, source files, tests, and version-control status before proposing changes.
- Preserve unrelated and pre-existing work. Do not reset, overwrite, delete, stage, commit, push, publish, deploy, or modify external systems unless explicitly authorized.
- Stay within the allowed files and systems.
- Base every finding on inspected code, supplied runtime evidence, an authoritative contract, or a clearly labeled hypothesis.
- Do not invent files, schemas, payloads, behavior, logs, test results, dependencies, approvals, performance measurements, consumer versions, or deployment conditions.
- Record conflicting evidence rather than silently choosing the convenient interpretation.
- Use `Not provided`, `Not inspected`, `Not run`, `Unknown`, or `Blocked` when evidence is unavailable.
- Redact credentials, tokens, authentication headers, personal data, customer records, confidential payload values, and unnecessary raw input.
- Do not log or reproduce complete untrusted payloads when a minimized structural example is sufficient.
- Prefer the smallest complete change. Avoid broad rewrites, opportunistic refactoring, dependency upgrades, or a new validation library when existing project conventions are adequate.
- If code changes are not explicitly authorized, produce the audit and implementation plan without editing.
- If changes are authorized, inspect first, implement only the verified correction, and report the exact diff and verification results.

## Runtime Boundary Model

For every material boundary, distinguish these stages:

1. **Transport and deserialization**  
   How bytes, text, form data, environment values, database fields, cache entries, messages, or JavaScript objects enter the process.

2. **Structural decoding and validation**  
   Whether the runtime value has the required shape, field types, discriminators, ranges and supported version.

3. **Normalization and defaults**  
   Any trimming, casing, parsing, coercion, fallback, defaulting or canonicalization applied after validation.

4. **Domain-rule enforcement**  
   Business invariants that cannot be proven by structural validation alone.

5. **Trusted application representation**  
   The point at which code is permitted to treat the value as a specific TypeScript type.

6. **Consequential use and side effects**  
   Database writes, authorization decisions, money calculations, network calls, queue acknowledgements, file operations, cache writes, user-visible output or other state changes.

Do not collapse these stages into a single unexplained cast or parser call.

## Boundary Inventory

Inspect applicable runtime inputs, including:

- HTTP request bodies, route parameters, query strings and headers;
- third-party API and SDK responses;
- webhooks, queues, events and message-bus payloads;
- forms, browser storage and client-provided state;
- environment variables and configuration files;
- database records, JSON columns, caches and previously stored data;
- imported files, CSV, JSON, XML and serialized content;
- feature-flag values and remote configuration;
- generated objects and code-generated API clients;
- inter-process, worker, serverless and plugin boundaries;
- data crossing between JavaScript and TypeScript packages.

For each boundary, identify:

- source and trust level;
- data owner and authoritative contract;
- serialization format and version;
- current runtime type at ingress;
- parsing or decoding step;
- existing validator, guard or assertion;
- normalization and coercion;
- trusted type produced;
- downstream consumers;
- side effects occurring before or after validation;
- current error and recovery behavior;
- compatibility window;
- evidence and confidence.

## Risk Patterns to Inspect

Treat these as hypotheses until confirmed:

- `as`, angle-bracket casts, non-null assertions or generic return types convert unchecked data into trusted types.
- `any` propagates from parsing, SDKs, generated clients, database libraries or legacy code.
- `unknown` is narrowed by an incomplete or unsound type guard.
- A validator checks only the top-level object while nested values remain unchecked.
- Generated types have drifted from the deployed producer contract.
- Missing, `undefined`, `null`, empty string and default values are treated as equivalent.
- Strings are ambiguously coerced into numbers, booleans, dates, identifiers, monetary values or permissions.
- Large integers or decimal values lose precision.
- Dates are accepted without timezone, format or validity rules.
- Unknown fields are silently stripped, retained or trusted without an explicit policy.
- Discriminated unions, enums or versioned payloads do not handle new producer values safely.
- Validation occurs after a database write, network call, authorization decision, queue acknowledgement or other side effect.
- Multiple callers repeat inconsistent validation instead of using an authoritative adapter.
- Stored data that was valid under an older schema fails after a code deployment.
- Invalid values are retried indefinitely, silently dropped or logged with sensitive data.
- Strict validation breaks older producers or consumers because rollout order was not designed.
- Payload size, depth, recursion, arrays or expensive refinements create a denial-of-service or latency risk.
- Validation success proves structure but not the domain invariant required by the operation.

For every confirmed finding, show the exact path from ingress to trusted use and the evidence proving the gap.

## Contract Comparison

Identify the authoritative contract where one exists:

- OpenAPI or JSON Schema;
- protocol or event schema;
- producer documentation;
- generated client definition;
- database schema and migration history;
- configuration specification;
- established runtime validator;
- versioned fixtures or contract tests.

Compare the contract against:

- TypeScript declarations;
- runtime validators;
- parsing and normalization logic;
- representative production-safe samples;
- downstream assumptions;
- supported producer and consumer versions.

Do not assume that the generated type is authoritative merely because it was generated. Establish what source produced it and whether that source matches the deployed producer.

## Validation Design Requirements

Select a strategy that fits existing repository conventions.

Define:

- the narrowest authoritative validation boundary;
- whether the input should initially be `unknown`;
- the schema, parser, decoder or type guard used;
- whether validation is strict, permissive or version-aware;
- required, optional, nullable and defaulted fields;
- nested-object and array handling;
- discriminated-union and enum behavior;
- unknown-field policy: reject, preserve, strip or capture;
- coercion policy by field;
- normalization after successful validation;
- structural validation versus domain rules;
- safe error classification;
- retryable versus non-retryable failures;
- logging, metrics, tracing and dead-letter handling;
- payload-size or performance limits;
- compatibility and rollout behavior.

For identity, authorization, money, dates, permissions, record ownership and security-sensitive fields, reject ambiguous coercion unless the supplied contract explicitly permits it.

Keep validation before trusted use and consequential side effects.

## Stored Data and Versioning

When stored or cached data is involved, determine:

- which versions may already exist;
- whether old records can still be read;
- whether validation should occur on write, read or both;
- whether a migration, read-repair, compatibility adapter or version discriminator is required;
- how invalid historical records will be detected and handled;
- whether rollback can still read newly written data;
- what evidence proves migration completeness.

Do not convert a runtime-validation change into an unreviewed data migration.

## Error and Recovery Design

Classify failures according to the actual boundary:

- invalid caller input;
- incompatible producer payload;
- temporary upstream failure;
- corrupted stored data;
- unsupported contract version;
- application configuration failure;
- internal programming error.

Define:

- safe external response;
- internal diagnostic detail;
- sensitive fields that must not be logged;
- metric or alert;
- retry policy;
- dead-letter or quarantine path;
- user or operator recovery;
- correlation identifier;
- escalation owner.

Do not expose validator internals or raw sensitive input in public error messages.

## Investigation and Implementation Workflow

1. Establish repository instructions, allowed scope, current version-control state and implementation authorization.

2. Identify the affected runtime boundary, authoritative contract, trusted consumers, side effects and compatibility window.

3. Trace the runtime value through parsing, assertions, validators, adapters, domain logic and consequential use.

4. Compare declared types, runtime validation and representative samples against the authoritative contract.

5. Reproduce the failure or prove the bypass using the smallest safe test or fixture.

6. Rank findings by reachability, impact, recurrence, side-effect timing, exploitability and recovery cost.

7. Design the smallest validation correction consistent with existing project dependencies, error conventions and ownership.

8. If authorized, implement validation before trusted use and side effects. Avoid unrelated refactoring.

9. Add focused tests for valid, invalid, missing, extra, malformed, versioned and compatibility cases.

10. Run focused tests first, followed by type checks, affected builds, contract tests and broader regression checks where available.

11. Review the final diff for scope drift, generated-file handling, public API changes and rollback requirements.

12. Report actual commands, exit codes, failures, skipped checks and remaining risks.

## Change Authorization and Safety Controls

- Do not install or upgrade dependencies without explicit authorization.
- Do not change a public schema, error contract, stored-data format, queue policy or retry policy without identifying affected consumers and the accountable owner.
- Do not reject unknown or legacy fields without a compatibility decision.
- Do not silently coerce identity, authorization, money, dates, permissions or security-sensitive values.
- Do not place validation after consequential side effects.
- Do not scatter defensive casts across consumers when one authoritative adapter can establish the boundary.
- Do not claim completion when representative producer or consumer behavior remains unverified.
- Do not deploy, publish, push or mutate external systems without authorization.
- Define rollback before any change that could reject previously accepted data or make stored data unreadable.
- Stop if the required correction exceeds allowed files, conflicts with unrelated work, requires unavailable evidence or would create an unreviewed compatibility break.

## Output Contract

Use concise markdown and the following sections.

### Context, Scope and Authorization

State:

- repository and runtime;
- requested outcome;
- allowed files and actions;
- implementation authorization;
- evidence supplied;
- blocking gaps;
- assumptions required to continue.

### Runtime Boundary Inventory

| Boundary | Source and trust level | Contract and version | Current parser or validator | Trusted type and consumers | Side effects | Evidence | Risk |
|---|---|---|---|---|---|---|---|

### Contract Difference Matrix

| Field or rule | Authoritative contract | TypeScript declaration | Runtime behavior | Representative evidence | Difference | Compatibility impact |
|---|---|---|---|---|---|---|

### Risk Findings

| Priority | Finding | Ingress-to-use path | Evidence | Impact | Reachability | Confidence | Smallest safe check |
|---:|---|---|---|---|---|---|---|

Do not list an unsupported possibility as a confirmed vulnerability.

### Validation Design

| Decision | Selected approach | Evidence or rationale | Compatibility effect | Owner review required |
|---|---|---|---|---|

Cover validation location, schema ownership, coercion, unknown fields, versions, error handling, observability and performance.

### Implementation Report

If changes were authorized, report:

- files changed;
- focused behavior change;
- existing behavior preserved;
- generated artifacts;
- dependency changes;
- migrations;
- rollback procedure.

If edits were not authorized, state `Not implemented` and provide a file-specific change plan without pretending a patch was applied.

### Verification Matrix

| Case | Input condition | Expected result | Test or command | Actual result | Status |
|---|---|---|---|---|---|

Include, where relevant:

- valid input;
- missing required value;
- `null` and `undefined`;
- empty values;
- extra fields;
- malformed nested values;
- unsupported enum or discriminator;
- old and new versions;
- ambiguous coercion;
- oversized or deeply nested input;
- repeated or duplicate message;
- downstream compatibility;
- error redaction;
- side-effect prevention.

### Commands and Test Results

| Command | Purpose | Exit status | Result |
|---|---|---:|---|

Never invent or infer an unrun result.

### Rollout, Monitoring and Rollback

Define:

- rollout order;
- affected producers and consumers;
- compatibility window;
- feature flag or staged adoption where needed;
- failure metrics and alerts;
- quarantine, dead-letter or recovery path;
- stop conditions;
- rollback trigger and procedure;
- responsible owner.

### Remaining Risks and Next Action

List unresolved risks and identify the smallest safe next step that materially reduces uncertainty or exposure.

## Verification Checklist

Before finalizing, confirm that:

- every material untrusted ingress in scope is inventoried;
- parsing, structural validation, normalization and domain rules are distinguished;
- runtime validation occurs before trusted use and consequential side effects;
- the authoritative contract is compared with TypeScript declarations and runtime behavior;
- assertions, casts, `any`, `unknown`, type guards and generated types were inspected where relevant;
- required, optional, nullable, missing, extra, malformed and versioned values were tested;
- coercion and unknown-field policies are explicit;
- stored-data and consumer compatibility are addressed;
- errors and logs minimize sensitive data while remaining diagnosable;
- no dependency was added without authorization;
- type checks are not presented as runtime-validation proof;
- every confirmed finding is supported by inspected evidence;
- no unrun command, unreviewed source, unapplied change or unresolved conflict is described as complete;
- the final diff stays within the authorized scope;
- rollback is defined for changes that could reject previously accepted data.

Begin by reviewing the supplied context and repository instructions. If a blocking input or implementation authorization is missing, ask one consolidated set of questions. Otherwise, establish the runtime boundary inventory before proposing or making changes.

## Variables to Replace

1. Goal and definition of done
2. Repository path and project context
3. Relevant entry points and allowed files
4. Untrusted data sources and authoritative contracts
5. Current and expected behavior
6. Errors, logs, or incident evidence
7. Representative valid, invalid, missing, and versioned samples
8. Runtime, build environment, and existing validation conventions
9. Consumers, side effects, and compatibility constraints
10. Verification commands and rollout constraints

## How to Use

Replace the placeholders with the repository path, affected files, untrusted data sources, authoritative schemas or producer contracts, representative sanitized samples, current failure, compatibility requirements, allowed files and verification commands.

Then run the completed prompt in Codex from the TypeScript repository root. Let Codex begin with read-only inspection and confirm the runtime boundary, existing validation conventions and affected consumers before authorizing edits or dependency changes.

Review Codex’s diff, test results, compatibility findings and rollback plan before allowing it to push, deploy or change external systems.

## Example Use Case

A webhook handler casts await request.json() to a generated PaymentEvent interface before writing a record and triggering fulfillment. The producer has introduced a nullable field and a new enum value. The engineer provides the handler, producer schema, sanitized old and new payloads, downstream side effects, existing validation utilities, compatibility requirements and contract-test commands.

## Tags

1. typescript
2. runtime-validation
3. trust-boundaries
4. schema-validation
5. type-safety
6. api-contracts
7. codex
8. error-handling
9. compatibility
10. security

## Dates

Published: 2026-07-25
Updated: 2026-07-25
