Security
The backend never trusts editor output. Anything the browser sends can be forged; it may not come from the editor at all. Validate before you store a document, and render stored documents with a function that only emits what the schema allows.
validate() and toSafeHTML()
@writeon/server has both. Give it the same extensions as the editor:
ts
import { advancedSchema } from '@writeon/advanced/schema'
import { basic } from '@writeon/core/presets'
import { toSafeHTML, validate } from '@writeon/server'
// The same extensions as the editor, in one shared array.
// The schema built from it is cached.
const extensions = [...basic(), advancedSchema()]
interface Posts {
save(id: string, doc: unknown, html: string): Promise<void>
}
declare const db: { posts: Posts }
export async function savePost(
id: string,
body: unknown,
): Promise<Response> {
// Never trust what the browser sends.
// It may not come from the editor at all.
const result = validate(body, {
extensions,
limits: { maxBytes: 500_000 },
})
if (!result.ok) {
return Response.json({ errors: result.errors }, { status: 422 })
}
// Save the checked document, not the body.
// result.removed lists what was dropped (unknown nodes,
// javascript: links…).
const html = toSafeHTML(result.doc, { extensions })
await db.posts.save(id, result.doc, html)
return Response.json({ removed: result.removed })
}validate():
- checks the JSON shape and refuses
__proto__,constructorandprototypekeys; - enforces limits: size (1 MB), depth (32) and node count (50 000) by default;
- removes unknown nodes, marks and attributes, invalid attribute values and content the schema does not allow;
- removes links and images whose address is not allowed (
javascript:,data:and so on); - in
'strip'mode (default) returns the cleaned document and what was removed; in'strict'mode refuses the whole document instead.
toSafeHTML() renders only what the schema knows, escapes all text and checks every URL again.
In the browser
- Link and image addresses are checked by the schema, so pasted or typed
javascript:links never enter the document. fromHTML()and paste parse HTML inside an inert<template>: no scripts run and no images load.- Image uploads refuse SVG by default.
Rendering stored documents
Prefer toSafeHTML() on the server. If you render on the client with toHTML(), render documents that were validated when they were saved.