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

# インターネットアクセス

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>Before running the example code in this document, please ensure you have properly configured environment variables. For details, please refer to <a href="/docs/ja/guides/sandbox-your-first-agent-sandbox#configure-environment-variables">Configure Environment Variables</a>.</Note>;
  }
};

すべてのサンドボックスでインターネット接続を利用でき、外部からのアクセスは公開 URL を通じて提供されます。

<SandboxConfigHint />

## インターネットアクセスの切り替え

サンドボックスを作成するときに、`allowInternetAccess` / `allow_internet_access` パラメーターを使用してインターネット接続を設定できます。インターネットアクセスはデフォルトで有効になっていますが、より厳格なセキュリティ要件を持つワークロードでは無効にできます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create sandbox with internet access enabled (default)
  const sandbox = await Sandbox.create({ allowInternetAccess: true })

  // Create sandbox without internet access
  const isolatedSandbox = await Sandbox.create({ allowInternetAccess: false })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create sandbox with internet access enabled (default)
  sandbox = Sandbox.create(allow_internet_access=True)

  # Create sandbox without internet access
  isolated_sandbox = Sandbox.create(allow_internet_access=False)
  ```
</CodeGroup>

インターネットアクセスが無効になっている場合、サンドボックスはアウトバウンドネットワークリクエストを開始できません。これにより、機密性の高いコードを実行する際に保護レイヤーを追加できます。

<Note>
  `allowInternetAccess` / `allow_internet_access` に falsy な値を渡すと、`network.denyOut` / `network.deny_out` に `['0.0.0.0/0']` を追加するのと同じ効果があり、すべての宛先がブロックされます。
</Note>

## きめ細かなネットワーク制御

ネットワーク設定では、許可リストと拒否リストを定義できるため、アウトバウンドトラフィックをより細かく制御できます。

### 許可リストと拒否リスト

サンドボックスからのアクセスを許可する IP アドレス、CIDR ブロック、またはドメイン名を指定できます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Deny all traffic except specific IPs
  const sandbox = await Sandbox.create({
    network: {
      denyOut: ['0.0.0.0/0'],
      allowOut: ['1.1.1.1', '8.8.8.0/24']
    }
  })

  // Deny specific IPs only
  const restrictedSandbox = await Sandbox.create({
    network: {
      denyOut: ['8.8.8.8']
    }
  })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Deny all traffic except specific IPs
  sandbox = Sandbox.create(
      network={
          "deny_out": ["0.0.0.0/0"],
          "allow_out": ["1.1.1.1", "8.8.8.0/24"]
      }
  )

  # Deny specific IPs only
  restricted_sandbox = Sandbox.create(
      network={
          "deny_out": ["8.8.8.8"]
      }
  )
  ```
</CodeGroup>

<Note>
  CIDR `'0.0.0.0/0'` / `"0.0.0.0/0"` は「すべての宛先」を表す省略表現です。リテラルの代わりに名前付きの代替を使いたい場合は、エクスポートされた `ALL_TRAFFIC` 定数が同じ `0.0.0.0/0` 値に解決されます。
</Note>

### ドメインベースのフィルタリング

`allowOut` / `allow_out` にホスト名を指定して、選択したドメインへのアウトバウンドトラフィックを許可できます。ドメインベースのフィルタリングを有効にする場合、残りのすべてのトラフィックは `denyOut` / `deny_out` を通じてブロックする必要があります。ドメインエントリは許可リストでのみサポートされ、拒否リストでは使用できません。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Allow only traffic to google.com
  const sandbox = await Sandbox.create({
    network: {
      allowOut: ['google.com'],
      denyOut: ['0.0.0.0/0']
    }
  })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Allow only traffic to google.com
  sandbox = Sandbox.create(
      network={
          "allow_out": ["google.com"],
          "deny_out": ["0.0.0.0/0"]
      }
  )
  ```
</CodeGroup>

<Note>
  設定内にドメインが含まれる場合は常に、DNS 解決が機能し続けるように、デフォルトのネームサーバー `8.8.8.8` が自動的に許可されます。
</Note>

ワイルドカードを使用して、あるドメインのすべてのサブドメインにマッチさせることもできます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Allow traffic to any subdomain of mydomain.com
  const sandbox = await Sandbox.create({
    network: {
      allowOut: ['*.mydomain.com'],
      denyOut: ['0.0.0.0/0']
    }
  })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Allow traffic to any subdomain of mydomain.com
  sandbox = Sandbox.create(
      network={
          "allow_out": ["*.mydomain.com"],
          "deny_out": ["0.0.0.0/0"]
      }
  )
  ```
</CodeGroup>

ドメイン、IP アドレス、CIDR 範囲は、すべて同じリスト内で混在させることができます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Allow traffic to specific domains and IPs
  const sandbox = await Sandbox.create({
    network: {
      allowOut: ['api.example.com', '*.github.com', '8.8.8.8'],
      denyOut: ['0.0.0.0/0']
    }
  })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Allow traffic to specific domains and IPs
  sandbox = Sandbox.create(
      network={
          "allow_out": ["api.example.com", "*.github.com", "8.8.8.8"],
          "deny_out": ["0.0.0.0/0"]
      }
  )
  ```
</CodeGroup>

<Note>
  ドメインによるフィルタリングは、ポート 80 の HTTP（Host ヘッダーで検査）とポート 443 の TLS（SNI で検査）にのみ適用されます。それ以外のポートは CIDR ベースのマッチングにフォールバックし、QUIC/HTTP3 などの UDP プロトコルはドメインでフィルタリングできません。
</Note>

### ブロックされた TCP 接続の挙動

ファイアウォールのアーキテクチャにより、ブロックされたアウトバウンド接続でも、サンドボックス内からは成功したように見える場合があります。

ファイアウォールは、対象の宛先が許可されているかどうかを評価する前に、まず TCP 接続を受け入れる必要があります。その結果、サンドボックス内で実行されているコードからは、宛先がブロックされている場合でも接続が成功し、ソケットが開いたように見えることがあります。その場合、リモートエンドポイントには実際にはトラフィックは配信されません。

宛先に到達可能であることを確認するには、TCP 接続の成功だけに依存せず、アプリケーションレベルのレスポンスを検証してください。たとえば、HTTP ステータスコード、完了した TLS ハンドシェイク、または想定されるプロトコルレスポンスのバイト列を確認します。

この挙動は、サンドボックスのアウトバウンドトラフィックが当社のファイアウォールを通じてルーティングされる仕組みにおける現在の制限であり、将来的に更新される可能性があります。

### 優先順位ルール

許可ルールと拒否ルールの両方が設定されている場合、**許可ルールが優先されます**。したがって、両方のリストに含まれている IP アドレスは引き続き許可されます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Even though all traffic is denied, 1.1.1.1 and 8.8.8.8 are explicitly allowed
  const sandbox = await Sandbox.create({
    network: {
      denyOut: ['0.0.0.0/0'],
      allowOut: ['1.1.1.1', '8.8.8.8']
    }
  })
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Even though all traffic is denied, 1.1.1.1 and 8.8.8.8 are explicitly allowed
  sandbox = Sandbox.create(
      network={
          "deny_out": ["0.0.0.0/0"],
          "allow_out": ["1.1.1.1", "8.8.8.8"]
      }
  )
  ```
</CodeGroup>

`network` 設定は、サンドボックスの作成時にのみ有効になります。`Sandbox.create` に指定してください。サンドボックスが存在するようになると、これらは固定され、変更できません。

## サンドボックスの公開 URL

サンドボックス内のサービスには、サンドボックスの公開 URL を使用してアクセスできます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // You need to always pass a port number to get the host
  const host = sandbox.getHost(3000)
  console.log(`https://${host}`)
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create()

  # You need to always pass a port number to get the host
  host = sandbox.get_host(3000)
  print(f'https://{host}')
  ```
</CodeGroup>

出力は次のようになります。

<CodeGroup>
  ```bash JavaScript & TypeScript icon="terminal" theme={"system"}
  https://3000-i62mff4ahtrdfdkyn2esc.sandbox.novita.ai
  ```

  ```bash Python icon="terminal" theme={"system"}
  https://3000-i62mff4ahtrdfdkyn2esc.sandbox.novita.ai
  ```
</CodeGroup>

ホスト名の一番左のセグメントは、メソッドに渡したポート番号そのものです。

## サンドボックス内で実行されているサーバーへの接続

前述の方法を使用して、サンドボックス内で実行されているサーバーに接続できます。たとえば、ポート 3000 で軽量 HTTP サーバーを起動し、その起動ディレクトリからファイルを提供します。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // Start a simple HTTP server inside the sandbox.
  const process = await sandbox.commands.run('python -m http.server 3000', { background: true })
  const host = sandbox.getHost(3000)
  const url = `https://${host}`
  console.log('Server started at:', url)

  // Fetch data from the server inside the sandbox.
  const response = await fetch(url);
  const data = await response.text();
  console.log('Response from server inside sandbox:', data);

  // Kill the server process inside the sandbox.
  await process.kill()
  ```

  ```python Python icon="python" theme={"system"}
  import requests
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create()

  # Start a simple HTTP server inside the sandbox.
  process = sandbox.commands.run("python -m http.server 3000", background=True)
  host = sandbox.get_host(3000)
  url = f"https://{host}"
  print('Server started at:', url)

  # Fetch data from the server inside the sandbox.
  response = requests.get(url)
  data = response.text
  print('Response from server inside sandbox:', data)

  # Kill the server process inside the sandbox.
  process.kill()
  ```
</CodeGroup>

この出力は次のようになります。

<CodeGroup>
  ```bash JavaScript & TypeScript icon="terminal" theme={"system"}
  Server started at: https://3000-ip3nfrvajtqu5ktoxugc7.sandbox.novita.ai
  Response from server inside sandbox: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Directory listing for /</title>
  </head>
  <body>
  <h1>Directory listing for /</h1>
  <hr>
  <ul>
  <li><a href=".bash_logout">.bash_logout</a></li>
  <li><a href=".bashrc">.bashrc</a></li>
  <li><a href=".profile">.profile</a></li>
  </ul>
  <hr>
  </body>
  </html>
  ```

  ```bash Python icon="terminal" theme={"system"}
  Server started at: https://3000-ip3nfrvajtqu5ktoxugc7.sandbox.novita.ai
  Response from server inside sandbox: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Directory listing for /</title>
  </head>
  <body>
  <h1>Directory listing for /</h1>
  <hr>
  <ul>
  <li><a href=".bash_logout">.bash_logout</a></li>
  <li><a href=".bashrc">.bashrc</a></li>
  <li><a href=".profile">.profile</a></li>
  </ul>
  <hr>
  </body>
  </html>
  ```
</CodeGroup>

## リクエストの Host ヘッダーのマスク

`maskRequestHost` / `mask_request_host` オプションを使用して、サンドボックス内で実行されているサービスに送信される Host ヘッダーをカスタマイズできます。これは、アプリケーションがリクエストに特定のホスト形式を求める場合に便利です。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create sandbox with custom host masking
  const sandbox = await Sandbox.create({
    network: {
      maskRequestHost: 'localhost:${PORT}'
    }
  })

  // The ${PORT} variable will be replaced with the actual port number
  // Requests to the sandbox will have Host header set to for example: localhost:8080
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create sandbox with custom host masking
  sandbox = Sandbox.create(
      network={
          "mask_request_host": "localhost:${PORT}"
      }
  )

  # The ${PORT} variable will be replaced with the actual port number
  # Requests to the sandbox will have Host header set to for example: localhost:8080
  ```
</CodeGroup>

リクエスト時には、マスク内の `${PORT}` が、アドレス指定されているサービスの実際のポート番号に置換されます。
