|
| 1 | +/** |
| 2 | + * Schema validation as an *inbound firewall* — with an MQTT 5 reason code |
| 3 | + * instead of a dropped connection. |
| 4 | + * |
| 5 | + * The important detail is WHERE validation runs. The `@mqttkit/aedes` adapter |
| 6 | + * dispatches every inbound PUBLISH inside aedes' `authorizePublish` hook, i.e. |
| 7 | + * BEFORE the broker acknowledges or forwards the message. So a schema failure |
| 8 | + * genuinely rejects the publish: the handler never runs and no subscriber ever |
| 9 | + * sees the bad payload. |
| 10 | + * |
| 11 | + * (If instead you run validation on a `broker.on('publish')` listener — a |
| 12 | + * common mistake in hand-rolled broker wrappers — it fires AFTER the PUBACK and |
| 13 | + * AFTER the message was forwarded, so it can only observe, never block.) |
| 14 | + * |
| 15 | + * On aedes 2.x, when the publisher is an MQTT 5 client, a rejected QoS>0 publish |
| 16 | + * comes back as a PUBACK/PUBREC carrying reason code 0x87 (Not authorized) — the |
| 17 | + * connection stays up, unlike the v3/v4 behaviour which drops the socket. |
| 18 | + * |
| 19 | + * Run: bun run src/index.ts |
| 20 | + */ |
| 21 | +import { AedesBrokerAdapter } from '@mqttkit/aedes' |
| 22 | +import { MqttApp, router, SchemaValidationError, type StandardSchemaV1 } from '@mqttkit/core' |
| 23 | +import mqtt from 'mqtt' |
| 24 | + |
| 25 | +// ---- A tiny Standard Schema: { temperature: number } ---- |
| 26 | +type Reading = { temperature: number } |
| 27 | + |
| 28 | +const readingSchema: StandardSchemaV1<unknown, Reading> = { |
| 29 | + '~standard': { |
| 30 | + version: 1, |
| 31 | + vendor: 'mqttkit-example', |
| 32 | + validate(value) { |
| 33 | + if (typeof value !== 'object' || value === null) { |
| 34 | + return { issues: [{ message: 'expected object', path: [] }] } |
| 35 | + } |
| 36 | + const temperature = (value as Record<string, unknown>).temperature |
| 37 | + if (typeof temperature !== 'number') { |
| 38 | + return { issues: [{ message: 'expected number', path: ['temperature'] }] } |
| 39 | + } |
| 40 | + return { value: { temperature } } |
| 41 | + }, |
| 42 | + types: { input: undefined as unknown, output: undefined as unknown as Reading }, |
| 43 | + }, |
| 44 | +} |
| 45 | + |
| 46 | +const handled: Reading[] = [] |
| 47 | + |
| 48 | +const adapter = new AedesBrokerAdapter<{ uid: string }>({ |
| 49 | + tcp: { port: 0 }, |
| 50 | + ws: false, |
| 51 | + authenticate: ({ clientId }) => ({ uid: clientId }), |
| 52 | +}) |
| 53 | + |
| 54 | +const app = new MqttApp<{ principal?: { uid: string } }>() |
| 55 | + .use({ setup: (a) => { a.broker(adapter) } }) |
| 56 | + // Central place to observe rejections. phase === 'validation' means the schema |
| 57 | + // gate stopped the message before the handler. |
| 58 | + .onError((e) => { |
| 59 | + if (e.phase === 'validation') { |
| 60 | + const detail = e.error instanceof SchemaValidationError ? e.error.message : String(e.error) |
| 61 | + console.log(`❌ [server] rejected publish on "${e.topic}" — ${detail}`) |
| 62 | + } |
| 63 | + }) |
| 64 | + .use( |
| 65 | + router<{ principal?: { uid: string } }>().topic('devices/:uid/reading', { |
| 66 | + publish: true, |
| 67 | + schema: readingSchema, |
| 68 | + validate: 'inbound', |
| 69 | + async onMessage(ctx) { |
| 70 | + // Only ever reached for payloads that passed the schema. |
| 71 | + handled.push(ctx.body as Reading) |
| 72 | + console.log('✅ [server] handler ran, body =', ctx.body) |
| 73 | + }, |
| 74 | + }), |
| 75 | + ) |
| 76 | + |
| 77 | +await app.listen() |
| 78 | +const port = adapter.getTcpAddress()?.port |
| 79 | +console.log(`broker listening on mqtt://127.0.0.1:${port}\n`) |
| 80 | + |
| 81 | +// Connect as an MQTT 5 client so a rejection can carry a reason code. |
| 82 | +const client = await mqtt.connectAsync(`mqtt://127.0.0.1:${port}`, { |
| 83 | + protocolVersion: 5, |
| 84 | + clientId: 'sensor-1', |
| 85 | +}) |
| 86 | + |
| 87 | +async function tryPublish(label: string, payload: unknown) { |
| 88 | + try { |
| 89 | + const ack = (await client.publishAsync( |
| 90 | + 'devices/sensor-1/reading', |
| 91 | + JSON.stringify(payload), |
| 92 | + { qos: 1 }, |
| 93 | + )) as { reasonCode?: number } | undefined |
| 94 | + console.log(`[client] ${label}: PUBACK reasonCode = ${ack?.reasonCode ?? 0}`) |
| 95 | + } catch (err) { |
| 96 | + console.log(`[client] ${label}: rejected — ${(err as Error).message}`) |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +console.log('--- valid payload ---') |
| 101 | +await tryPublish('valid ', { temperature: 21.5 }) |
| 102 | + |
| 103 | +console.log('\n--- invalid payload (temperature is a string) ---') |
| 104 | +await tryPublish('invalid', { temperature: 'hot' }) |
| 105 | + |
| 106 | +// The bad publish did NOT drop the connection — prove the client is still usable. |
| 107 | +await new Promise((r) => setTimeout(r, 50)) |
| 108 | +console.log('\n[client] still connected after the rejected publish?', client.connected) |
| 109 | +console.log('[server] handler ran', handled.length, 'time(s) — only the valid payload got through') |
| 110 | + |
| 111 | +await client.endAsync() |
| 112 | +await app.stop() |
0 commit comments