> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# TLS

> 在 Bun.serve 中启用 TLS

Bun 的 TLS 支持是内置的，由 [BoringSSL](https://boringssl.googlesource.com/boringssl) 提供支持。要启用 TLS，需要同时传递 `key` 和 `cert`。

```ts theme={null}
Bun.serve({
  tls: {
    key: Bun.file("./key.pem"), // [!code ++]
    cert: Bun.file("./cert.pem"), // [!code ++]
  },
});
```

`key` 和 `cert` 字段期望的是 TLS 密钥和证书的**内容**，而不是路径。每个可以是字符串、`BunFile`、`TypedArray` 或 `Buffer`。

```ts theme={null}
Bun.serve({
  tls: {
    key: Bun.file("./key.pem"), // BunFile
    key: fs.readFileSync("./key.pem"), // Buffer
    key: fs.readFileSync("./key.pem", "utf8"), // string
    key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")], // 上述类型的数组
  },
});
```

### 口令

如果你的私钥使用口令加密，请为 `passphrase` 提供一个值来解密它。

```ts theme={null}
Bun.serve({
  tls: {
    key: Bun.file("./key.pem"),
    cert: Bun.file("./cert.pem"),
    passphrase: "my-secret-passphrase", // [!code ++]
  },
});
```

### CA 证书

传递 `ca` 来覆盖受信任的 CA 证书。默认情况下，服务器信任由 Mozilla 策划的知名 CA 列表；设置 `ca` 会替换该列表。

```ts theme={null}
Bun.serve({
  tls: {
    key: Bun.file("./key.pem"), // TLS 密钥路径
    cert: Bun.file("./cert.pem"), // TLS 证书路径
    ca: Bun.file("./ca.pem"), // 根 CA 证书路径  // [!code ++]
  },
});
```

### Diffie-Hellman

要覆盖 Diffie-Hellman 参数：

```ts theme={null}
Bun.serve({
  tls: {
    dhParamsFile: "/path/to/dhparams.pem", // Diffie Hellman 参数路径 // [!code ++]
  },
});
```

***

## 服务器名称指示 (SNI)

要为服务器配置服务器名称指示 (SNI)，在 `tls` 对象中设置 `serverName` 字段。

```ts theme={null}
Bun.serve({
  tls: {
    serverName: "my-server.com", // SNI // [!code ++]
  },
});
```

要允许多个服务器名称，向 `tls` 传递一个对象数组，每个对象带有 `serverName` 字段。

```ts theme={null}
Bun.serve({
  tls: [
    {
      key: Bun.file("./key1.pem"),
      cert: Bun.file("./cert1.pem"),
      serverName: "my-server1.com", // [!code ++]
    },
    {
      key: Bun.file("./key2.pem"),
      cert: Bun.file("./cert2.pem"),
      serverName: "my-server2.com", // [!code ++]
    },
  ],
});
```
