Aller au contenu

Utilitaire Proxy ​

L’utilitaire Proxy fournit des fonctions utiles pour utiliser une application Hono comme proxy, notamment comme proxy inverse.

Importation ​

ts
import { Hono } from 'hono'
import { proxy } from 'hono/proxy'

proxy() ​

proxy() est une enveloppe de l’API fetch() destinée au proxy. Ses paramètres et sa valeur de retour sont les mêmes que ceux de fetch(), à l’exception des options propres au proxy.

L’en-tête Accept-Encoding est remplacé par un encodage pris en charge par l’environnement d’exécution actuel. Les en-têtes de réponse inutiles sont supprimés, et un objet Response pouvant être envoyé par le gestionnaire est renvoyé.

Exemples ​

Utilisation simple :

ts
app.get('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`)
})

Utilisation avancée :

ts
app.get('/proxy/:path', async (c) => {
  const res = await proxy(
    `http://${originServer}/${c.req.param('path')}`,
    {
      headers: {
        ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.
        'X-Forwarded-For': '127.0.0.1',
        'X-Forwarded-Host': c.req.header('host'),
        Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
      },
    }
  )
  res.headers.delete('Set-Cookie')
  return res
})

Vous pouvez aussi passer c.req comme paramètre.

ts
app.all('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`, {
    ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary.
    headers: {
      ...c.req.header(),
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
    },
  })
})

Vous pouvez remplacer la fonction globale fetch par défaut avec l’option customFetch :

ts
app.get('/proxy', (c) => {
  return proxy('https://example.com/', {
    customFetch,
  })
})

Traitement de l’en-tête Connection ​

Par défaut, proxy() ignore l’en-tête Connection afin d’éviter les attaques par injection d’en-têtes hop-by-hop. Vous pouvez activer la conformité stricte à la RFC 9110 avec l’option strictConnectionProcessing :

ts
// Default behavior (recommended for untrusted clients)
app.get('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`, c.req)
})

// Strict RFC 9110 compliance (use only in trusted environments)
app.get('/internal-proxy/:path', (c) => {
  return proxy(`http://${internalServer}/${c.req.param('path')}`, {
    ...c.req,
    strictConnectionProcessing: true,
  })
})

ProxyFetch ​

Le type de proxy() est défini par ProxyFetch comme suit.

ts
interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {
  raw?: Request
  customFetch?: (request: Request) => Promise<Response>
  strictConnectionProcessing?: boolean
  headers?:
    | HeadersInit
    | [string, string][]
    | Record<RequestHeader, string | undefined>
    | Record<string, string | undefined>
}

interface ProxyFetch {
  (
    input: string | URL | Request,
    init?: ProxyRequestInit
  ): Promise<Response>
}

Publié sous licence MIT.