SYSTEM ARCHITECTURE · ZERO SERVERLESS

前端 GitHub + 後端 Google Apps Script 架構解密

這套架構是專為學生、獨立開發者與教學實戰設計的「完全免費、零維運主機、金鑰永久安全隔離」的現代 AI 全端解決方案。前端部署於 GitHub Pages,後端利用 Google Apps Script (GAS) 充當安全中繼代理,對接 OpenRouter 大模型並在 Google Sheet 寫入即時對話審計日誌。

🌱 零主機費用 ($0 / 月) 🛡️ API Key 絕不落地外洩 ⚡ 免管 Linux & 免維護 Docker 📸 支援多模態圖表截圖問答 📊 Google Sheet 免費試算表日誌庫
🖥️ 系統端到端架構與實時數據傳輸動態圖 (Active Pipeline Architecture)
傳輸模擬控制器:
管線狀態: ● 全鏈路正常 (302 Follow + SSL Keep-Alive)
~/architecture - digital-jitong-bff - zsh (90x36) ■ CLIENT ■ GAS BFF ■ OPENROUTER ■ SHEETS ZONE 1 · 前端與用戶瀏覽端 (GITHUB PAGES) CLIENT BROWSER 學員瀏覽器 (Desktop / Mobile) DOM 視圖 · 圖表渲染 · 提問輸入框 ● 零安裝環境 · 全響應式自適應 STATIC CDN HOSTING GitHub Pages 靜態託管 託管 HTML5 / CSS / Apache ECharts 全球 CDN 邊緣加速 · 永久 0 元維運 🔒 公開 Repo 內絕無任何 API Key AGENT UI · digital_jitong.js 「數位乩童」客服前端模組 1. 對話狀態管理 (Session History) 2. 畫面上下文萃取 (getPageContext) 3. 框選螢幕截圖 (html2canvas to Base64) 4. fetch() 請求送出 (mode: 'cors') redirect: "follow" (處理 302 重導向) CLIENT PAYLOAD PACKER status: READY (截圖 + Prompt) ● 雙向多模態通道待命 ZONE 2 · 無伺服器中繼後端 (GOOGLE APPS SCRIPT) ★ FOCAL GATEWAY · doPost(e) & doGet(e) Google Apps Script Web App 接收前端 POST 請求,充當安全中繼代理 (BFF) 處理 302 跨域跳轉與 CORS 預檢安全機制 以 ContentService 回傳標準 JSON 302 重導向正常通過 · 每日額度 20,000 次 INTERNAL KEY VAULT Script Properties 金鑰保險箱 PropertiesService.getScriptProperties() 🔒 私密變數儲存 OPENROUTER_API_KEY,學生絕不外洩 HTTP DISPATCH ENGINE UrlFetchApp 外部請求引擎 1. 自動附加 Authorization: Bearer Header 2. 將圖表 Base64 轉換為 OpenRouter 多模態格式 3. 呼叫 OpenRouter 進行 Claude Haiku 推論 4. 呼叫 SpreadsheetApp 進行非同步日誌入庫 PROXY THROUGHPUT ENGINE active: HTTPS Keep-Alive Pool SSL 握手完成 · 雙向管線零丟包 ZONE 3 · 雲端 AI 推論與試算表資料庫 LLM INFERENCE · CLOUD GATEWAY OpenRouter API 閘道 Claude Haiku 3.5 / 5.5 高智商推理 · 多輪追問 · 視覺圖表辨識 極低 Token 費率 · 秒級串流/完整解答 STREAMING INFERENCE ENGINE running: 88% (148 tokens/s) FREE DATABASE · GOOGLE SHEETS Google Sheets 對話歷史庫 免安裝 MySQL · 永久免費保存 SpreadsheetApp.appendRow() 日誌寫入欄位: 1. Timestamp (時間戳記) 2. Question (學生提問內容) 3. Answer (AI 回覆開示摘要) 4. Model & HasImage (多模態標記) PERSISTENCE STORAGE TELEMETRY ✓ LOGGED: Row #382 Appended 老師可隨時以試算表篩選分析學員卡點 ● 數據結構化就緒 1. 載入網頁資源 2. POST JSON+截圖 7. 響應 JSON 回傳 3. 讀取 API Key 4. HTTPS Bearer Key 5. 推論 Claude 回覆 6. 記錄 appendRow
── session log · data transmission telemetry ──────────────────────────────────────────────────────── ● STREAMING ACTIVE (LOOP)
07:05:12 browser User prompt + ECharts canvas screenshot attached to digital_jitong.js
07:05:13 fetch-api POST https://script.google.com/.../exec (mode: 'cors', redirect: 'follow')
07:05:14 gas-bff HTTP 302 follow-redirect handled -> ScriptProperties loaded OPENROUTER_API_KEY
07:05:15 openrouter POST /chat/completions (Claude Haiku 5.5 multi-modal vision inferring, 148 tok/s)
07:05:16 sheets-db SpreadsheetApp.appendRow([Timestamp, UserQuery, ReplySummary, HasImage]) saved
07:05:17 response ContentService returned JSON payload -> client rendered AI insight bubble

🛡️ 1. 金鑰安全隔離(絕不外洩原則)

在全端開發中,學生最常犯的重大資安事故,就是把 OpenAI 或 OpenRouter 的 API Key 直接寫進前端 HTML / JS,然後推上公開的 GitHub 倉庫,幾分鐘內就會被自動爬蟲盜刷掏空。

  • 金鑰存於後端保險箱:API Key 儲存在 Google Apps Script 的專案屬性 (Script Properties) 中,只有 Google 伺服端具備讀取權限。
  • 前端靜態碼零暴露:公開在 GitHub Pages 上的代碼只有一個無鑑權的 GAS Web App 呼叫網址,就算任何人「右鍵檢查原始碼」也永遠挖不到金鑰。

🔄 2. 突破跨域阻隔(CORS 與 302 重導向)

當前端網頁 (drchunchihchen.github.io) 嘗試呼叫外部 API 時,瀏覽器會嚴格執行同源政策 (CORS)。此外,Google Apps Script 執行時會將請求從 script.google.com 經由 HTTP 302 重導向至 script.googleusercontent.com。

  • 前端必備參數:呼叫時必須顯式指定 redirect: "follow" 與 mode: "cors",否則請求會在重導向階段被瀏覽器強制中斷。
  • 後端標準回傳:GAS 必須使用 ContentService.createTextOutput() 並設置 MimeType 為 JSON,才能讓瀏覽器安心接收數據。

💰 3. 永久免費與零伺服器維護 ($0/月)

傳統架設後端需要租用 AWS EC2、GCP VM 或 Heroku,每月需支付 150~800 元台幣,還得自己設定 Nginx 反向代理、SSL 憑證定時更新與 Linux 防火牆。

  • GitHub Pages:提供全球邊緣 CDN 免費靜態託管,頻寬充沛、無限流量。
  • Google Apps Script:免費個人 Google 帳號每日可執行高達 20,000 次 URL 轉發,免裝 Node.js、免管 Docker,完全「無伺服器 (Serverless)」。

📊 4. Google Sheets 免費關聯資料庫

不需要再花時間安裝 MySQL 或設定 MongoDB,直接將 Google 試算表當成雲端持久化資料庫使用!

  • 一行程式碼存檔:GAS 原生支援 SpreadsheetApp.openById().appendRow([...]),以超低延遲自動寫入新列。
  • 視覺化與後續分析:老師或專案負責人打開 Google 試算表,就能看到所有學生的即時問答、提問時段與 Token 耗用情況,直接做成統計圖表!

💡 教學重點小提醒(BFF 架構思維):

這種「前端靜態純展示 + 輕量無伺服器做 BFF (Backend For Frontend) + 外部大模型 API」的模式,是目前敏捷開發 AI 應用最精煉的實戰架構。學生學會這套模式後,無論是寫個人履歷網站、期末專題、商業數據儀表板,都能在「0 元成本」的前提下隨插即用!

這是放在 GitHub Pages 靜態網站中(例如 digital_jitong.js)用來向 Google Apps Script 發送請求的精簡程式碼:

// 1. 設定你的 Google Apps Script 部署網址 (Web App URL)
const GAS_BACKEND_URL = "https://script.google.com/macros/s/AKfycbyZJTyyxiK5C_ow8KPRhtCRlxZQOV3sg3vrZPVtTWp6xtjsypbRdm7a_zTgrV3jJAUk/exec";

/**
 * 向 GAS 後端發送對話與截圖資訊
 * @param {string} promptText 學生提問文字
 * @param {string|null} base64Image 多模態截圖 (可選,Base64 字串)
 * @param {string} pageContext 當前頁面圖表與篩選條件上下文
 */
async function askDigitalJitong(promptText, base64Image = null, pageContext = "") {
  const payload = {
    message: promptText,
    context: pageContext,
    imageBase64: base64Image || null,
    timestamp: new Date().toISOString()
  };

  try {
    // 關鍵設定:method 為 POST,mode 為 cors,redirect 必須為 follow!
    const response = await fetch(GAS_BACKEND_URL, {
      method: "POST",
      mode: "cors",
      cache: "no-cache",
      redirect: "follow", // 重要!GAS 執行時會 302 重導向到 script.googleusercontent.com
      headers: {
        "Content-Type": "text/plain;charset=utf-8" // 避免觸發複雜預檢 (preflight)
      },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error(`伺服器回應異常,狀態碼: ${response.status}`);
    }

    const data = await response.json();
    console.log("【數位乩童開示回傳】:", data.reply);
    return data.reply;

  } catch (error) {
    console.error("【連線失敗】:", error);
    throw error;
  }
}
🔍 前端關鍵要點解析:
1. redirect: "follow":這是與 GAS 通訊最關鍵的一行。Google 在執行 Apps Script 時,會先回傳 HTTP 302 狀態碼,告訴瀏覽器真正的執行容器在 googleusercontent.com。如果沒有設定 follow,瀏覽器會直接中斷並拋出 CORS 錯誤。
2. headers: {"Content-Type": "text/plain"}:在簡單 POST 請求中使用純文字或標準 JSON 封裝,能大幅降低瀏覽器觸發 OPTIONS 預檢失敗的機率。

這是部署在 Google Apps Script 中的 Code.gs 核心程式碼:

/**
 * 處理前端 POST 請求 (BFF 安全中繼)
 */
function doPost(e) {
  try {
    // 1. 安全取得儲存在專案屬性中的 API Key (前端完全看不到!)
    const props = PropertiesService.getScriptProperties();
    const apiKey = props.getProperty("OPENROUTER_API_KEY");
    const sheetId = props.getProperty("LOG_SHEET_ID"); // 儲存日誌的 Google Sheet ID
    
    if (!apiKey) {
      return jsonResponse({ error: "尚未設定 OPENROUTER_API_KEY 金鑰" }, 500);
    }

    // 2. 解析前端傳來的 JSON 數據
    const contents = e.postData.contents;
    const requestData = JSON.parse(contents);
    const userMessage = requestData.message || "";
    const pageContext = requestData.context || "";
    const imageBase64 = requestData.imageBase64 || null;

    // 3. 組裝發往 OpenRouter 的 Prompt 與多模態 Payload
    const messages = [
      {
        role: "system",
        content: "你是「數位乩童」,說話靈光四溢、帶有玄學幽默但技術極度扎實的 AI 導師。你的真身是香港中文大學資訊工程系博士陳純質。"
      }
    ];

    // 多模態訊息組裝
    const userContent = [];
    userContent.push({
      type: "text",
      text: (pageContext ? `【學員當前操作畫面上下文】\n${pageContext}\n\n` : "") + userMessage
    });

    if (imageBase64) {
      userContent.push({
        type: "image_url",
        image_url: {
          url: imageBase64.startsWith("data:") ? imageBase64 : `data:image/png;base64,${imageBase64}`
        }
      });
    }

    messages.push({ role: "user", content: userContent });

    // 4. 呼叫 OpenRouter API 進行 Claude Haiku 推論
    const openRouterUrl = "https://openrouter.ai/api/v1/chat/completions";
    const payload = {
      model: "anthropic/claude-3.5-haiku",
      messages: messages,
      temperature: 0.7
    };

    const options = {
      method: "post",
      contentType: "application/json",
      headers: {
        "Authorization": "Bearer " + apiKey,
        "HTTP-Referer": "https://github.com/drchunchihchen/dataviz",
        "X-Title": "Digital Jitong Course Assistant"
      },
      payload: JSON.stringify(payload),
      muteHttpExceptions: true
    };

    const response = UrlFetchApp.fetch(openRouterUrl, options);
    const resJson = JSON.parse(response.getContentText());
    const replyText = resJson.choices[0].message.content;

    // 5. 異步記錄到 Google Sheets 試算表
    if (sheetId) {
      try {
        const sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
        sheet.appendRow([
          new Date(),
          userMessage,
          replyText.substring(0, 500),
          imageBase64 ? "有截圖" : "無截圖",
          "claude-3.5-haiku"
        ]);
      } catch (sheetErr) {
        Logger.log("日誌記錄失敗: " + sheetErr.message);
      }
    }

    // 6. 回傳標準 JSON 格式給前端
    return jsonResponse({
      status: "success",
      reply: replyText
    });

  } catch (err) {
    return jsonResponse({ error: err.message }, 500);
  }
}

/**
 * 輔助函式:建立符合 CORS 規範的 JSON 輸出
 */
function jsonResponse(data, statusCode = 200) {
  const output = ContentService.createTextOutput(JSON.stringify(data));
  output.setMimeType(ContentService.MimeType.JSON);
  return output;
}

/**
 * 支援健康檢查 GET 請求
 */
function doGet(e) {
  return jsonResponse({
    status: "online",
    service: "數位乩童 GAS Backend Gateway",
    time: new Date()
  });
}
🔍 後端關鍵要點解析:
1. PropertiesService.getScriptProperties():將敏感密鑰隔離在雲端環境變數中,即便專案程式碼截圖展示給學生看,金鑰也絕不會外洩。
2. ContentService.createTextOutput().setMimeType(ContentService.MimeType.JSON):GAS 專屬的輸出方式,能正確附帶 JSON MIME 標頭。
3. SpreadsheetApp.appendRow():自動在試算表尾端新增一行,免寫 SQL,天然具備時間戳與資料庫審計功能。

Google Apps Script 3 步驟極速部署指南

1
建立 GAS 專案

前往 script.google.com 點擊「新增專案」,清空原本內容並完整貼上 Tab 2 的 Code.gs 程式碼,命名為「數位乩童後端中繼」。

2
設定金鑰屬性

點選左側齒輪「專案設定」,拉至下方「指令碼屬性」,點擊「新增指令碼屬性」,屬性名稱填 OPENROUTER_API_KEY,值貼上你的 OpenRouter 憑證,儲存完成隔離。

3
部署為 Web 應用程式

點擊右上角「部署」→「新增部署作業」→ 選擇齒輪「網路應用程式」:
• 執行身分:我 (你的 Google 帳號)
• 誰可以存取:任何人 (Anyone)(重要!)
取得 https://script.google.com/macros/s/.../exec 網址即可!

⚠️ 學生常見避坑提示:每次修改 Code.gs 程式碼後,必須點擊「部署」→「管理部署作業」→ 點擊鉛筆圖示編輯 → 選擇「新版本」再點儲存!如果沒有切換成新版本,外面的 Web 網址依舊會執行舊程式碼。