Unknown Input Type Guard Hardening

Validate untrusted JSON with unknown-typed inputs and hand-written type guards so every field is checked before it reaches business logic.

TypescriptSecurity Boundaries

Code

typescriptsnippet
33 lines
interface WebhookEvent {
  id: string;
  action: 'created' | 'deleted';
  payload: { repo: string; stars: number };
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function isWebhookEvent(value: unknown): value is WebhookEvent {
  if (!isRecord(value)) return false;
  if (typeof value.id !== 'string') return false;
  if (value.action !== 'created' && value.action !== 'deleted') return false;
  if (!isRecord(value.payload)) return false;
  if (typeof value.payload.repo !== 'string') return false;
  if (typeof value.payload.stars !== 'number' || !Number.isFinite(value.payload.stars)) {
    return false;
  }
  return true;
}

function handle(raw: unknown): string {
  // 守卫之后 unknown 收窄为 WebhookEvent,业务代码零 as 断言
  if (!isWebhookEvent(raw)) {
    return 'rejected: malformed event';
  }
  return `${raw.id}: ${raw.action} on ${raw.payload.repo} (${raw.payload.stars} stars)`;
}

console.log(handle({ id: 'w1', action: 'created', payload: { repo: 'a/b', stars: 3 } }));
console.log(handle({ id: 'w2', action: 'poked', payload: null }));
console.log(handle('not an object'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

w1: created on a/b (3 stars)
rejected: malformed event
rejected: malformed event

Inside the working code

Unknown Input Type Guard Hardening keeps everything in the functions isRecord, isWebhookEvent and handle.

Watch out for

  • The guard typeof value.id !== 'string' short-circuits the flow with an early return when its condition holds.

Putting it to use

The primary signature is function isRecord(value: unknown)

Core lines

return `${raw.id}: ${raw.action} on ${raw.payload.repo} (${raw.payload.stars} stars)`;
return typeof value === 'object' && value !== null && !Array.isArray(value);
if (value.action !== 'created' && value.action !== 'deleted') return false;

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `isRecord`, `isWebhookEvent`, `handle` at load time.