Skip to content
Merged
Show file tree
Hide file tree
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
42 changes: 34 additions & 8 deletions src/lib/download-request.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { Agent as SecretStreamAgent } from 'secret-stream-http'
import { Type as T } from 'typebox'
import { Compile } from 'typebox/compile'

import { TypedEventTarget } from '../lib/event-target.js'
import type { DownloadCreateParams } from '../routes/downloads.js'
import { type DownloadStateUpdate } from '../types.js'
import { StatusError } from './errors.js'
import { errors, jsonError } from './errors.js'
import {
errors,
jsonError,
remoteErrorDetails,
RemoteStatusError,
remoteStatusError,
} from './errors.js'
import { anyFetch } from './secret-stream-fetch.js'
import { StateUpdateEvent } from './state-update-event.js'
import { throttle } from './throttle.js'
Expand All @@ -15,6 +22,11 @@ export type DownloadState = DownloadStateUpdate &

const PROGRESS_THROTTLE_MS = 100

// Only the fields we act on: the sender may be a newer version with statuses we don't know
const CompiledRemoteShareStatus = Compile(
T.Object({ status: T.String(), error: T.Optional(T.Unknown()) }),
)

export class DownloadRequest extends TypedEventTarget<
InstanceType<typeof StateUpdateEvent<DownloadStateUpdate>>
> {
Expand Down Expand Up @@ -64,10 +76,16 @@ export class DownloadRequest extends TypedEventTarget<
async (error) => {
// In case the error happens before we pipe to the stream, we need to abort the stream
await stream.abort().catch(noop)
if (error.name === 'AbortError') {
// instanceof, because an error from the sender can carry any name
if (error instanceof DOMException && error.name === 'AbortError') {
this.#updateState({ status: 'aborted' })
} else if (getErrorCode(error) === 'DOWNLOAD_SHARE_CANCELED') {
this.#updateState({ status: 'canceled' })
} else if (error instanceof RemoteStatusError) {
this.#updateState({
status: 'error',
error: RemoteStatusError.details(error),
})
} else if (getErrorCode(error)) {
// Specific known error from the server
this.#updateState({ status: 'error', error: jsonError(error) })
Expand All @@ -85,10 +103,18 @@ export class DownloadRequest extends TypedEventTarget<
dispatcher: this.#dispatcher,
signal: AbortSignal.timeout(2000),
})
const json: any = await response.json()
if (json.status) {
this.#updateState({ status: json.status, error: json.error })
return
const shareState: unknown = await response.json()
if (CompiledRemoteShareStatus.Check(shareState)) {
if (shareState.status === 'canceled') {
this.#updateState({ status: 'canceled' })
return
} else if (shareState.status === 'error') {
this.#updateState({
status: 'error',
error: remoteErrorDetails(shareState.error),
})
return
}
}
} catch {
// Ignore errors from checking the status and update state with original error
Expand Down Expand Up @@ -146,7 +172,7 @@ export class DownloadRequest extends TypedEventTarget<
})
}
if (!response.ok) {
throw new StatusError(response.status, (await response.json()) as any)
throw await remoteStatusError(response)
}
if (this.#abortController.signal.aborted) {
response.body.cancel().catch(noop)
Expand Down
68 changes: 67 additions & 1 deletion src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,77 @@ export class StatusError extends Error {

constructor(status = 500, body?: StatusErrorObject | string) {
super(typeof body === 'object' ? body.message : body)
if (typeof body === 'object') Object.assign(this, body)
if (typeof body === 'object') {
for (const key of Object.keys(body)) {
// JSON.parse makes "__proto__" an own key, and assigning it would replace the prototype
if (key !== '__proto__') this[key] = body[key]
}
}
this.status = status
}
}

/**
* An error response from another device. The other device may be running a
* different version, so properties we don't know about are kept.
*/
export class RemoteStatusError extends StatusError {
readonly #details: ReturnType<typeof remoteErrorDetails>

constructor(status: number, body: unknown) {
const details = remoteErrorDetails(body)
super(status, details)
this.#details = details
}

/**
* The error as the other device reported it, with a string code and message.
* Static, because the other device's properties are copied onto the instance.
*/
static details(error: RemoteStatusError) {
return error.#details
}
}

export async function remoteStatusError(
response: Response,
): Promise<RemoteStatusError> {
let body: unknown
try {
body = await response.json()
} catch {
// Not JSON, e.g. from a proxy
}
return new RemoteStatusError(
response.status,
isPlainObject(body)
? body
: { message: `Remote device responded with status ${response.status}` },
)
}

/** Error details reported by another device, keeping any extra properties */
export function remoteErrorDetails(value: unknown): {
message: string
code: string
} {
const details = Object.fromEntries(
Object.entries(isPlainObject(value) ? value : {}).filter(
([key]) => key !== '__proto__',
),
)
return {
...details,
message:
typeof details.message === 'string' ? details.message : 'Unknown error',
code: typeof details.code === 'string' ? details.code : 'UNKNOWN_ERROR',
}
}

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

const errorsList = [
// Download errors (receiver-side)
{
Expand Down
4 changes: 2 additions & 2 deletions src/routes/map-shares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Type as T, type Static } from 'typebox'
import { Compile } from 'typebox/compile'

import type { Context } from '../context.js'
import { errors, StatusError } from '../lib/errors.js'
import { errors, remoteStatusError } from '../lib/errors.js'
import { createEventStreamResponse } from '../lib/event-stream-response.js'
import { MapShare } from '../lib/map-share.js'
import { anyFetch } from '../lib/secret-stream-fetch.js'
Expand Down Expand Up @@ -183,7 +183,7 @@ export function MapSharesRouter(
}
if (!response.ok) {
// pass through error from sender
throw new StatusError(response.status, (await response.json()) as any)
throw await remoteStatusError(response)
}
return new Response(null, { status: 204 })
}
Expand Down
85 changes: 85 additions & 0 deletions test/errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, it, expect } from 'vitest'

import {
remoteErrorDetails,
RemoteStatusError,
remoteStatusError,
StatusError,
} from '../src/lib/errors.js'

const withProto = (fields: object) =>
JSON.stringify(fields).replace(/^\{/, '{"__proto__":{"polluted":true},')

describe('remoteStatusError', () => {
it('keeps properties it does not know about', async () => {
const response = new Response(
JSON.stringify({ code: 'NEW_CODE', message: 'From the future', hint: 1 }),
{ status: 409 },
)
const err = await remoteStatusError(response)
expect(err).toBeInstanceOf(StatusError)
expect(err).toMatchObject({
status: 409,
code: 'NEW_CODE',
message: 'From the future',
hint: 1,
})
})

it('keeps a details property', async () => {
const response = Response.json(
{ code: 'X', details: { a: 1 } },
{ status: 409 },
)
const err = await remoteStatusError(response)
expect(err.details).toEqual({ a: 1 })
expect(RemoteStatusError.details(err)).toEqual({
code: 'X',
message: 'Unknown error',
details: { a: 1 },
})
})

it('does not let __proto__ replace the prototype', async () => {
const response = new Response(withProto({ code: 'X' }), { status: 409 })
const err = await remoteStatusError(response)
expect(err).toBeInstanceOf(StatusError)
expect(err.code).toBe('X')
expect(err.polluted).toBeUndefined()
})

it('handles a body that is not a JSON object', async () => {
for (const body of ['<html>Bad Gateway</html>', 'null', '[1]', '"x"', '']) {
const err = await remoteStatusError(new Response(body, { status: 502 }))
expect(err).toBeInstanceOf(StatusError)
expect(err.status).toBe(502)
expect(err.code).toBe('UNKNOWN_ERROR')
expect(err.message).toMatch(/502/)
}
})
})

describe('remoteErrorDetails', () => {
it('keeps extra properties', () => {
expect(
remoteErrorDetails({ code: 'NEW_CODE', message: 'm', hint: 1 }),
).toEqual({ code: 'NEW_CODE', message: 'm', hint: 1 })
})

it('fills in a code and message when they are missing or not strings', () => {
expect(remoteErrorDetails({ code: 42 })).toEqual({
code: 'UNKNOWN_ERROR',
message: 'Unknown error',
})
expect(remoteErrorDetails('oops')).toEqual({
code: 'UNKNOWN_ERROR',
message: 'Unknown error',
})
})

it('drops __proto__', () => {
const details = remoteErrorDetails(JSON.parse(withProto({ code: 'X' })))
expect(Object.keys(details)).not.toContain('__proto__')
expect(Object.getPrototypeOf(details)).toBe(Object.prototype)
})
})
41 changes: 40 additions & 1 deletion test/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { once } from 'node:events'
import nodeFs from 'node:fs'
import fs from 'node:fs/promises'
import { createServer as createHttpServer } from 'node:http'
import type { AddressInfo, Socket } from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { Transform } from 'node:stream'

import { createAdapter } from '@comapeo/node-server'
import bogon from 'bogon'
import ky from 'ky'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { Agent as SecretStreamAgent } from 'secret-stream-http'
import {
Agent as SecretStreamAgent,
createServer as createSecretStreamServer,
} from 'secret-stream-http'
import { vi, type TestContext } from 'vitest'

import type { ServerOptions } from '../src/index.js'
Expand Down Expand Up @@ -262,3 +269,35 @@ export function goOffline(testContext: TestContext) {
server.close()
})
}

/**
* A remote device that answers map share requests with whatever `handler`
* returns, for testing how the receiver copes with other versions or
* misbehaving senders.
*/
export async function startFakeSender(
t: TestContext,
handler: (request: Request) => Response | Promise<Response>,
) {
const keyPair = SecretStreamAgent.keyPair()
const httpServer = createHttpServer(createAdapter(handler))
const server = createSecretStreamServer(httpServer, { keyPair })
const sockets = new Set<Socket>()
server.on('connection', (socket: Socket) => {
sockets.add(socket)
socket.once('close', () => sockets.delete(socket))
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
t.onTestFinished(async () => {
const closed = once(server, 'close')
server.close()
for (const socket of sockets) socket.destroy()
await closed
})
const { port } = server.address() as AddressInfo
return {
deviceId: Buffer.from(keyPair.publicKey).toString('hex'),
shareUrl: `http://127.0.0.1:${port}/mapShares/fake-share`,
}
}
Loading
Loading