Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate request #443

Merged
merged 1 commit into from
Oct 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions packages/chopsticks/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { z } from 'zod'
import WebSocket, { AddressInfo, WebSocketServer } from 'ws'

import { ResponseError, SubscriptionManager } from './rpc/shared'
import { defaultLogger, truncate } from './logger'

const logger = defaultLogger.child({ name: 'ws' })

const requestSchema = z.object({
id: z.number(),
jsonrpc: z.literal('2.0'),
method: z.string(),
params: z.array(z.any()).default([]),
})

export type Handler = (
data: { method: string; params: string[] },
subscriptionManager: SubscriptionManager,
Expand Down Expand Up @@ -103,8 +111,8 @@ export const createServer = async (handler: Handler, port?: number) => {
})

ws.on('message', async (message) => {
const req = parseRequest(message.toString())
if (!req || req.id == null || req.method == null) {
const parsed = await requestSchema.safeParseAsync(parseRequest(message.toString()))
if (!parsed.success) {
logger.info('Invalid request: %s', message)
send({
id: null,
Expand All @@ -117,6 +125,7 @@ export const createServer = async (handler: Handler, port?: number) => {
return
}

const { data: req } = parsed
logger.trace(
{
id: req.id,
Expand Down