All files / next-edge index.ts

84.61% Statements 55/65
72.22% Branches 26/36
68.75% Functions 11/16
88.7% Lines 55/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187                                                15x 15x   48x   48x 30x   15x           1x                         13x       13x   13x 81x     13x     13x   13x     41x       41x     41x                   13x 13x 14x   14x 14x 1x     14x   14x 14x   14x       1x 1x     13x         13x 13x 13x     13x                   13x                   13x 271x     13x 13x   13x 13x           13x 41x       13x 7x       7x     13x 13x 13x   13x   13x   13x 13x 13x               13x      
import { SerializeOptions as CookieSerializeOptions, serialize } from "cookie"
import { IncomingHttpHeaders } from "http"
import { isText } from "istextorbinary"
import { NextApiRequest, NextApiResponse } from "next"
import parse, { splitCookiesString } from "set-cookie-parser"
import { CreateApiHandlerOptions } from "../type/create-api-handler-options"
import { getBaseUrl } from "../common/get-base-url"
import { defaultForwardedHeaders } from "../common/default-forwarded-headers"
import { processLocationHeader } from "../common/process-location-header"
import { guessCookieDomain } from "../common/get-cookie-domain"
 
function readRawBody(req: NextApiRequest): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const chunks: Uint8Array[] = []
    req.on("data", (chunk) => chunks.push(chunk))
    req.on("end", () => resolve(Buffer.concat(chunks)))
    req.on("error", (err) => reject(err))
  })
}
 
export function filterRequestHeaders(
  headers: IncomingHttpHeaders,
  forwardAdditionalHeaders?: string[],
): Headers {
  const filteredHeaders = new Headers()
  Object.entries(headers).forEach(([key, value]) => {
    const isValid =
      defaultForwardedHeaders.includes(key) ||
      (forwardAdditionalHeaders ?? []).includes(key)
    if (isValid)
      filteredHeaders.set(key, Array.isArray(value) ? value.join(",") : value)
  })
  return filteredHeaders
}
 
/**
 * The NextJS API configuration
 */
export const config = {
  api: {
    bodyParser: false,
  },
}
 
function processSetCookieHeader(
  protocol: string,
  originalReq: NextApiRequest,
  fetchResponse: Response,
  options: CreateApiHandlerOptions,
) {
  const isTls =
    protocol === "https:" ||
    originalReq.headers["x-forwarded-proto"] === "https"
 
  const secure =
    options.forceCookieSecure === undefined ? isTls : options.forceCookieSecure
 
  const forwarded = originalReq.rawHeaders.findIndex(
    (h) => h.toLowerCase() === "x-forwarded-host",
  )
  const host =
    forwarded > -1
      ? originalReq.rawHeaders[forwarded + 1]
      : originalReq.headers.host
  const domain = guessCookieDomain(host, options)
 
  return parse(
    splitCookiesString(fetchResponse.headers.get("set-cookie") || ""),
  )
    .map((cookie) => ({
      ...cookie,
      domain,
      secure,
      encode: (v: string) => v,
    }))
    .map(({ value, name, ...options }) =>
      serialize(name, value, options as CookieSerializeOptions),
    )
}
 
/**
 * Creates a NextJS / Vercel API Handler
 *
 * For this handler to work, please set the environment variable `ORY_SDK_URL`.
 */
export function createApiHandler(options: CreateApiHandlerOptions) {
  const baseUrl = getBaseUrl(options)
  return async (req: NextApiRequest, res: NextApiResponse<string>) => {
    const { paths, ...query } = req.query
 
    const searchParams = new URLSearchParams()
    Object.keys(query).forEach((key) => {
      searchParams.set(key, String(query[key]))
    })
 
    const path = Array.isArray(paths) ? paths.join("/") : paths
 
    const url = new URL(path, baseUrl)
    url.search = searchParams.toString()
 
    if (path === "ui/welcome") {
      // A special for redirecting to the home page
      // if we were being redirected to the hosted UI
      // welcome page.
      res.redirect(303, "../../../")
      return
    }
 
    const headers = filterRequestHeaders(
      req.headers,
      options.forwardAdditionalHeaders,
    )
 
    headers.set("X-Ory-Base-URL-Rewrite", "false")
    headers.set("Ory-Base-URL-Rewrite", "false")
    headers.set("Ory-No-Custom-Domain-Redirect", "true")
 
    // Only effective in CI.
    Iif (
      process.env.ORY_CI_RATE_LIMIT_HEADER &&
      process.env.ORY_CI_RATE_LIMIT_HEADER_VALUE
    ) {
      headers.set(
        process.env.ORY_CI_RATE_LIMIT_HEADER,
        process.env.ORY_CI_RATE_LIMIT_HEADER_VALUE,
      )
    }
 
    const response = await fetch(url, {
      method: req.method,
      headers,
      body:
        req.method !== "GET" && req.method !== "HEAD"
          ? await readRawBody(req)
          : null,
      redirect: "manual",
    })
 
    for (const [key, value] of response.headers) {
      res.appendHeader(key, value)
    }
 
    res.removeHeader("set-cookie")
    res.removeHeader("location")
 
    Eif (response.headers.get("set-cookie")) {
      const cookies = processSetCookieHeader(
        (req as unknown as { protocol: string }).protocol,
        req,
        response,
        options,
      )
      cookies.forEach((cookie) => {
        res.appendHeader("Set-Cookie", cookie)
      })
    }
 
    if (response.headers.get("location")) {
      const location = processLocationHeader(
        response.headers.get("location"),
        baseUrl,
      )
      res.setHeader("Location", location)
    }
 
    res.removeHeader("transfer-encoding")
    res.removeHeader("content-encoding")
    res.removeHeader("content-length")
 
    res.status(response.status)
 
    const buf = Buffer.from(await response.arrayBuffer())
 
    Eif (buf.byteLength > 0) {
      if (isText(null, buf)) {
        res.send(
          buf.toString("utf-8").replace(new RegExp(baseUrl, "g"), "/api/.ory"),
        )
      } else E{
        res.write(buf)
      }
    }
 
    res.end()
  }
}