🚇

VPN不要!Cloudflare TunnelでMacへのリモートSSH環境を構築する

に公開

はじめに

Claude CodeやCodex CLIなどのAI CLIツールを使って開発していると、AIがコードを生成している間、数分〜数時間の待ち時間が発生することがあります。

「コーヒーを淹れに行きたいけど、進捗が気になる」
「外出先からちょっとだけ状況を確認したい」
「待っている間に別のタスクを投げたい」

こんな経験ありますよね?

本記事では、外部端末やブラウザからMacのAI CLI環境にリモートアクセスする仕組みを構築します。Cloudflare Tunnelを使うことで、VPNアプリ不要・ドメイン不要で試すことができます。

構成

iPhoneもしくはMac (ブラウザ)
├── WebSocket (wss://)
Cloudflare Tunnel (TryCloudflare)
│
Mac
├── cloudflared (トンネル)
├── ws-ssh-bridge (WebSocket → SSH変換)
└── SSH → tmux → Claude Code / Codex CLI

なぜこの構成か?

方式 メリット デメリット
Tailscale 設定が簡単 iPhone側にもアプリが必要
直接SSH + ポート開放 シンプル セキュリティリスク
Cloudflare Tunnel アプリ単体で完結可能、セキュア 中継サーバーの実装が必要

ユーザーが別途VPNアプリをインストールする必要がない構成を採用しました。

前提条件

  • macOS(SSHが有効化されていること)
  • Node.js(v18以上推奨)
  • Homebrew
  • Claude Code / Codex CLI(任意)

Cloudflare Tunnelの2つの方式

Cloudflare Tunnelには2つの利用方法があります。

A. TryCloudflare(クイックトンネル)

# これだけでトンネル作成
cloudflared tunnel --url http://localhost:8765
項目 内容
Cloudflareアカウント 不要
ログイン 不要
URL 毎回ランダム(例: random-words.trycloudflare.com)
設定ファイル 不要
用途 検証、個人利用、開発

B. 正式なトンネル(Named Tunnel)

# 初回のみ:ログインしてトンネル作成
cloudflared tunnel login
cloudflared tunnel create my-tunnel
cloudflared tunnel route dns my-tunnel terminal.yourdomain.com

# 起動
cloudflared tunnel run my-tunnel
項目 内容
Cloudflareアカウント 必要
ログイン 必要(初回のみ)
URL 固定(自分のドメイン)
設定ファイル ~/.cloudflared/config.yml
用途 本番運用、チーム利用
追加機能 Cloudflare Accessで認証追加可能

今回の選択

本記事では A. TryCloudflare を使用します。

理由:

  • アカウント作成・ログイン不要ですぐに試せる
  • 個人利用・検証目的には十分
  • 本番運用時に正式トンネルへ移行すればよい

手順

1. cloudflaredのインストール

brew install cloudflared

2. SSHの有効化

SSHが有効になっているか確認します。

sudo systemsetup -getremotelogin

Remote Login: Off と表示された場合は有効化が必要です。

方法1: コマンドで有効化

sudo systemsetup -setremotelogin on

方法2: GUIから有効化(コマンドでエラーが出る場合)

macOSのセキュリティ制限により、コマンドから設定できない場合があります。

setremotelogin: Turning Remote Login on or off requires Full Disk Access privileges.

このエラーが出た場合は、システム設定から有効化してください:

  1. システム設定 を開く
  2. 一般 → 共有 を選択
  3. リモートログイン をONにする

再度確認:

sudo systemsetup -getremotelogin
# → Remote Login: On と表示されればOK

3. tmuxのインストール

tmuxを使うことで、SSH接続が切れてもプロセスを維持できます。

brew install tmux

4. WebSocket→SSH中継サーバーの作成

Cloudflare TunnelはHTTPS/WebSocketベースのため、通常のSSHクライアントでは直接接続できません。WebSocketをSSHに変換する中継サーバーを作成します。

mkdir -p ~/ai-cli-bridge
cd ~/ai-cli-bridge
npm init -y
npm install ws ssh2

server.js を作成:

server.js
const WebSocket = require('ws');
const { Client } = require('ssh2');

const PORT = 8765;
const PING_INTERVAL = 30000; // 30秒ごとにping

const wss = new WebSocket.Server({ port: PORT });

console.log(`WebSocket-SSH Bridge running on port ${PORT}`);

wss.on('connection', (ws) => {
  console.log('Client connected');
  
  const ssh = new Client();
  let stream = null;
  
  // Keep-alive: 30秒ごとにpingを送信
  const pingInterval = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.ping();
    }
  }, PING_INTERVAL);
  
  ws.on('pong', () => {
    // クライアントからのpong応答(接続維持確認)
  });

  ws.on('message', (message) => {
    const data = JSON.parse(message);
    
    if (data.type === 'auth') {
      ssh.connect({
        host: 'localhost',
        port: 22,
        username: data.username,
        password: data.password
      });
    } else if (data.type === 'input' && stream) {
      stream.write(data.content);
    } else if (data.type === 'resize' && stream) {
      stream.setWindow(data.rows, data.cols, 0, 0);
    }
  });

  ssh.on('ready', () => {
    console.log('SSH connected');
    ws.send(JSON.stringify({ type: 'connected' }));
    
    ssh.shell({ term: 'xterm-256color' }, (err, s) => {
      if (err) {
        ws.send(JSON.stringify({ type: 'error', message: err.message }));
        return;
      }
      stream = s;
      
      stream.on('data', (data) => {
        ws.send(JSON.stringify({ type: 'output', content: data.toString('base64') }));
      });
      
      stream.on('close', () => {
        ws.send(JSON.stringify({ type: 'closed' }));
        ws.close();
      });
    });
  });

  ssh.on('error', (err) => {
    console.error('SSH error:', err.message);
    ws.send(JSON.stringify({ type: 'error', message: err.message }));
  });

  ws.on('close', () => {
    console.log('Client disconnected');
    clearInterval(pingInterval); // pingを停止
    ssh.end();
  });
});

5. サーバーの起動

ターミナルを2つ開きます。

ターミナル1: 中継サーバー起動

cd ~/ai-cli-bridge
node server.js

出力:

WebSocket-SSH Bridge running on port 8765

ターミナル2: Cloudflareトンネル起動

cloudflared tunnel --url http://localhost:8765

以下のようなログが出力されます:

2025-12-31T04:43:48Z INF Requesting new quick Tunnel on trycloudflare.com...
2025-12-31T04:43:52Z INF +--------------------------------------------------------------------------------------------+
2025-12-31T04:43:52Z INF |  Your quick Tunnel has been created! Visit it at (it may take some time to be reachable):  |
2025-12-31T04:43:52Z INF |  https://fifty-connectivity-tuning-narrow.trycloudflare.com                                |
2025-12-31T04:43:52Z INF +--------------------------------------------------------------------------------------------+
2025-12-31T04:43:52Z INF Cannot determine default configuration path. No file [config.yml config.yaml] in [~/.cloudflared ~/.cloudflare-warp ~/cloudflare-warp /etc/cloudflared /usr/local/etc/cloudflared]

表示されたURL(この例では https://fifty-connectivity-tuning-narrow.trycloudflare.com)のドメイン部分をメモしてください。

テスト時には wss:// の後にこのドメインを貼り付けます:

wss://fifty-connectivity-tuning-narrow.trycloudflare.com

6. 動作確認

動作確認用のHTMLファイルを作成します。

nano ~/ai-cli-bridge/test.html
test.html
<!DOCTYPE html>
<html>
<head>
  <title>WebSocket SSH Test</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      max-width: 800px;
      margin: 40px auto;
      padding: 20px;
    }
    .input-group {
      margin-bottom: 15px;
    }
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
    input[type="text"] {
      width: 100%;
      padding: 10px;
      font-size: 14px;
      border: 1px solid #ccc;
      border-radius: 4px;
      box-sizing: border-box;
    }
    .button-group {
      margin: 20px 0;
    }
    button {
      padding: 10px 20px;
      font-size: 14px;
      margin-right: 10px;
      margin-bottom: 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    button.primary {
      background-color: #0070f3;
      color: white;
    }
    button.secondary {
      background-color: #eee;
      color: #333;
    }
    button.danger {
      background-color: #e00;
      color: white;
    }
    #output {
      background-color: #1e1e1e;
      color: #0f0;
      padding: 20px;
      border-radius: 4px;
      font-family: 'Monaco', 'Menlo', monospace;
      font-size: 13px;
      height: 400px;
      overflow-y: auto;
      white-space: pre-wrap;
    }
    .status {
      padding: 10px;
      border-radius: 4px;
      margin-bottom: 15px;
    }
    .status.disconnected {
      background-color: #fee;
      color: #c00;
    }
    .status.connected {
      background-color: #efe;
      color: #0a0;
    }
    .command-input {
      display: flex;
      gap: 10px;
      margin-top: 15px;
    }
    .command-input input {
      flex: 1;
    }
  </style>
</head>
<body>
  <h1>WebSocket SSH Test</h1>
  
  <div id="statusBar" class="status disconnected">● Disconnected</div>
  
  <div class="input-group">
    <label for="wsUrl">WebSocket URL:</label>
    <input type="text" id="wsUrl" placeholder="wss://xxxxx.trycloudflare.com">
  </div>
  
  <div class="input-group">
    <label for="username">Username:</label>
    <input type="text" id="username" placeholder="your-mac-username">
  </div>
  
  <div class="button-group">
    <button class="primary" onclick="connect()" id="connectBtn">Connect</button>
    <button class="danger" onclick="disconnect()" id="disconnectBtn" disabled>Disconnect</button>
  </div>
  
  <div class="button-group">
    <button class="secondary" onclick="sendCommand('whoami\n')">whoami</button>
    <button class="secondary" onclick="sendCommand('pwd\n')">pwd</button>
    <button class="secondary" onclick="sendCommand('ls -la\n')">ls -la</button>
    <button class="secondary" onclick="sendCommand('tmux ls\n')">tmux ls</button>
    <button class="secondary" onclick="sendCommand('claude --version\n')">claude --version</button>
  </div>
  
  <div class="command-input">
    <input type="text" id="commandInput" placeholder="Enter command..." 
           onkeypress="if(event.key==='Enter')sendCustomCommand()">
    <button class="primary" onclick="sendCustomCommand()">Send</button>
  </div>
  
  <h3>Output:</h3>
  <pre id="output"></pre>
  
  <button class="secondary" onclick="clearOutput()">Clear Output</button>

  <script>
    let ws;
    const output = document.getElementById('output');
    const statusBar = document.getElementById('statusBar');
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    
    function log(msg) {
      output.textContent += msg + '\n';
      output.scrollTop = output.scrollHeight;
    }
    
    function setStatus(connected) {
      if (connected) {
        statusBar.textContent = '● Connected';
        statusBar.className = 'status connected';
        connectBtn.disabled = true;
        disconnectBtn.disabled = false;
      } else {
        statusBar.textContent = '● Disconnected';
        statusBar.className = 'status disconnected';
        connectBtn.disabled = false;
        disconnectBtn.disabled = true;
      }
    }

    function connect() {
      const wsUrl = document.getElementById('wsUrl').value.trim();
      const username = document.getElementById('username').value.trim();
      
      if (!wsUrl || !username) {
        alert('Please enter WebSocket URL and username');
        return;
      }
      
      log('Connecting to ' + wsUrl + '...');
      ws = new WebSocket(wsUrl);
      
      ws.onopen = () => {
        log('WebSocket connected, authenticating...');
        const password = prompt('Enter Mac password for ' + username + ':');
        if (!password) {
          ws.close();
          return;
        }
        ws.send(JSON.stringify({
          type: 'auth',
          username: username,
          password: password
        }));
      };
      
      ws.onmessage = (e) => {
        const data = JSON.parse(e.data);
        if (data.type === 'output') {
          log(atob(data.content));
        } else if (data.type === 'connected') {
          log('SSH connected successfully!');
          setStatus(true);
        } else if (data.type === 'error') {
          log('Error: ' + data.message);
        } else {
          log(JSON.stringify(data));
        }
      };
      
      ws.onerror = (e) => setStatus(false);
      ws.onclose = () => {
        log('Disconnected');
        setStatus(false);
      };
    }
    
    function sendCommand(cmd) {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'input', content: cmd }));
      }
    }
    
    function sendCustomCommand() {
      const input = document.getElementById('commandInput');
      if (input.value) {
        sendCommand(input.value + '\n');
        input.value = '';
      }
    }
    
    function disconnect() {
      if (ws) ws.close();
    }
    
    function clearOutput() {
      output.textContent = '';
    }
  </script>
</body>
</html>

ブラウザで開きます:

open ~/ai-cli-bridge/test.html

7. 接続テスト

  1. WebSocket URL に wss:// + ドメイン名を入力
    • 例: wss://fifty-connectivity-tuning-narrow.trycloudflare.com
    • ログに表示された https:// を wss:// に変えて入力
  2. Username にMacのユーザー名を入力
  3. Connect をクリック
  4. パスワードを入力
  5. 「SSH connected successfully!」と表示されれば成功

接続後、各種コマンドボタンやカスタムコマンド入力欄から操作できます。

動作確認の結果

実際に接続してClaude Codeのヘルプを表示した様子:

  • ステータスが「Connected」(緑)に変化
  • claude -h コマンドでClaude Codeのヘルプが表示される
  • ターミナルエスケープシーケンス([?2004h 等)が含まれるが、コマンドは正常に実行されている

今回はローカル環境のブラウザで確認しましたが、test.htmlをCloudflareの静的サイトとして公開して外出先で静的サイトを開いて使用することもできます。

tmuxの重要性

この構成でtmuxが重要な役割を果たします。

tmuxなしの場合

iPhone接続 → SSHセッション開始 → Claude Code実行
│
iPhone切断 → SSHセッション終了 → Claude Codeも終了 ❌

tmuxありの場合

iPhone接続 → tmuxセッション → Claude Code実行
│
iPhone切断 → tmuxは生き続ける → Claude Codeも継続 ✅
│
PC接続 → tmux attach → 続きから確認可能 ✅

基本的なtmuxコマンド

# 新しいセッション作成
tmux new -s ai-work

# セッションから抜ける(プロセスは継続)
# キーボード: Ctrl+b → d
# または
tmux detach

# セッション一覧
tmux ls

# セッションに再接続
tmux attach -t ai-work

今回は詳細な実行方法は記載しませんが、Mac上でCLI実行した場合、クライアント端末で実行した場合もセッションを作成していれば復帰可能です。

常時稼働のための設定

外出先からMacに接続するには、Macがスリープしていない必要があります。

なぜスリープだとダメなのか

設定 役割
リモートログイン ON SSH接続を受け付ける許可
スリープ状態 Mac自体が休止(ネットワークも停止)

「リモートログイン」をONにしていても、Macがスリープするとネットワーク自体が停止するため、外部からの接続を受け付けられません。

caffeinate コマンドでスリープ防止

caffeinate コマンドを使うと、指定したプロセスが動いている間スリープを防止できます。

# ターミナル1: スリープ防止でserver.js起動
caffeinate -i node server.js

# ターミナル2: スリープ防止でcloudflared起動
caffeinate -i cloudflared tunnel --url http://localhost:8765
オプション 効果
-i アイドルスリープを防止
-d ディスプレイスリープを防止
-s AC電源接続時のシステムスリープを防止

推奨のシステム設定

「スクリーンセーバーは動くが、スリープはしない」状態にします。

システム設定:
├── ロック画面
│   ├── スクリーンセーバー開始: 5分後
│   └── スクリーンセーバー開始後にパスワードを要求: ON
├── ディスプレイ
│   └── ディスプレイをオフにする: 10分後
└── バッテリー / 省エネルギー
    └── スリープ: しない(caffeinateを使う場合は自動で防止される)

運用上の注意点

観点 問題ある?
電力消費 微増(ディスプレイオフなら最小限)
セキュリティ スクリーンセーバーにパスワード設定でOK
Macへの負荷 ほぼなし(idle状態)
長期運用 問題なし(サーバー的な使い方として一般的)

セキュリティに関する注意

この構成はあくまで検証・個人利用目的です。本番運用する場合は以下を検討してください:

  1. TryCloudflareではなく正式なトンネルを使用

    • 固定ドメインでCloudflare Accessによる認証を追加
  2. パスワード認証ではなく公開鍵認証

    • server.jsを修正して秘密鍵ベースの認証に変更
  3. トークンベースの認証追加

    • WebSocket接続時に独自のトークン検証を実装

まとめ

  • Cloudflare Tunnel(TryCloudflare)でドメイン不要・VPN不要のリモートアクセス環境を構築
  • WebSocket→SSH中継サーバーにより、ブラウザ/アプリからSSH接続が可能
  • tmuxと組み合わせることで、接続が切れてもAI CLIのプロセスを維持

AIエージェントが自律的に動く時代、人間の役割は変わりつつあります。AIへの指示をどこからでもでき、実行過程やログを確認できる環境をぜひ試してみてください。

参考リンク

Discussion