慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
火燧之智在客,有四重之卫以安之。
Nimra Abid · 2026-05-24 · via DEV Community

此乃投献于谷歌I/O写作挑战


Firebase AI Logic诚然令人振奋。其于Google I/O 2026年正式发布,汝可直呼Gemini于汝之网页或移动应用:无需后端服务器,无需将API密钥,无需管理基础设施。开发者之体验真切。

然设人工智能之端于互联网,则生攻击之隙。吾所读之文,多仅述谷歌所运之一种安顿之法——此中亦不乏于此挑战之内者。

其法有四,相成相辅。此篇将遍述之。


胁之模型:汝所实御者何

先于码文,当明其可失之所在。

配额耗尽凡得见尔之端点而施用其脚本者,必耗尔之符码之资。每发一智机之呼,皆直抵尔之账目。

提示注入若尔之系统之命在客端之码,则可藉二进制之解构或网路之截获而得之,进而施用。

符码重演 即便短暂之认证令牌,亦可能遭窃取而复用。五分钟之窗口,足令脚本频击吾之端点。

推理之际,有害之内容存焉。 用户所输入,至模型之前,未尝有净化之默认设置。若无推理层之强制执行,敌对之输入可乘隙而入。

吾将示君四层之中,每一层皆可直合此隙之一。


层一:代理之构

闭:因API密钥窃取致配额竭

愚者之法,将Gemini API密钥嵌于应用包中,直呼API,终将败。应用包可反编译。网络之流可察见。

Firebase AI 之理,于架构层面解此难题。凡 SDK 之请,皆由 Firebase 之代理服务器中转。汝之 Gemini API 密钥,存于 Firebase 之基构,未尝传于客户端。

// firebase.ts
import { initializeApp, FirebaseApp } from 'firebase/app';
import { getAI, GoogleAIBackend, AI } from 'firebase/ai';

const firebaseConfig = {
  apiKey: "your-firebase-api-key",            // ✅ Firebase Web API key — safe in client.
  authDomain: "your-project.firebaseapp.com", // This is a project identifier,
  projectId: "your-project-id",               // NOT a billing credential.
  appId: "your-app-id"
};

const app: FirebaseApp = initializeApp(firebaseConfig);

// All requests route through Firebase's proxy.
// Your Gemini API key never leaves Firebase's servers.
const ai: AI = getAI(app, { backend: new GoogleAIBackend() });

export { app, ai };

Enter fullscreen mode Exit fullscreen mode

Firebase Web API之钥非密也——乃项目标识,受安全规则所限。汝之Gemini API钥,具账务之权柄,永不出现在汝之代码中。


第二层:服务器提示模板+仅模板模式

可闭:提示注入与提示提取

若汝之系统指令存于客户端代码,则两事可生:

  1. 凡解汝之应用二进制者,皆可读汝之确凿提示.
  2. 若汝自用户输入动态组构提示,则坚毅之用户可设输入以覆汝之系统指令.服务器提示模板 尽移尔之提示配置——系统指令、模型选择、安全设置、输入模式——于 Firebase 之服务器。客户端仅送模板之 ID 及变量值之类型。

仅模板之模式,于 I/O 2026 年宣告,严行此规:Firebase 之 AI 逻辑,惟执行存于服务器之提示。凡客户端代码直送之定制提示指令,皆尽弃之。

模板于Firebase控制台定义之。点提示语法

---
model: gemini-3.1-flash
config:
  temperature: 0.4
  topP: 0.9
input:
  schema:
    userQuery: string
    userName?: string
---
{{role "system"}}
You are a professional support agent for Acme Corp.
You answer questions about orders, returns, and shipping only.
You do not engage with topics outside these areas.

{{role "user"}}
{{#if userName}}Customer {{userName}} asks:{{/if}}
{{userQuery}}

入全景模式 出全屏模式

凡此以往——模型、配置、系统指令、输入架构——皆存于 Firebase 之服务器。于客户端,当用getTemplateGenerativeModel()如所规定者官方JS SDK参考

// secure-chat.ts
import { getAI, GoogleAIBackend, getTemplateGenerativeModel } from 'firebase/ai';
import { app } from './firebase';

// Typed interface matching the template's input schema.
// Enforced at compile time — no undeclared fields can reach the template.
interface SupportTemplateVariables {
  userQuery: string;
  userName?: string;
}

const ai = getAI(app, { backend: new GoogleAIBackend() });

// Must use getTemplateGenerativeModel() — not ai.templateGenerativeModel()
const templateModel = getTemplateGenerativeModel(ai);

export async function askSupportAgent(
  userInput: string,
  displayName?: string
): Promise<string> {
  const variables: SupportTemplateVariables = {
    userQuery: userInput,
    userName: displayName ?? undefined,
  };

  // Client sends only: template ID + typed variable values.
  // System instructions, model config, and safety settings
  // are composed server-side and never reach the client.
  const result = await templateModel.generateContent(
    'support-agent-v2',
    variables
  );

  return result.response.text();
}

进入全屏模式 退出全屏模式

察其于客之码,无系统之提示,无名之模,无安之配置。此三者,皆不可读,不可改,不可覆。惟启模板之式,此乃 Firebase AI 之智,所纳于尔之应用者,其请唯此而已。

TypeScript之接口,非惟关乎类型之安,更明乎客主之约,由编译器所强。倘开发者欲传非所愿之字段,或泄于提示,编译器必先察之,俟其行也。


第三层:Firebase App Check + 重放攻击防护

禁:非授权之客及令牌重放

模板仅模式,固守汝之提示。应用检验,则辨何人得发请求。

应用检验,取设备认证之供者——安卓之Play Integrity,苹果之DeviceCheck,及网络之reCAPTCHA Enterprise——以生密码之符,证请求自汝之应用真本、未遭修改者出。Firebase,于处理任何人工智能请求之前,必验此符。

// app-check.ts
import { initializeAppCheck, ReCaptchaEnterpriseProvider, AppCheck } from 'firebase/app-check';
import { FirebaseApp } from 'firebase/app';
import { app } from './firebase';

export function initializeSecureAppCheck(app: FirebaseApp): AppCheck {
  return initializeAppCheck(app, {
    provider: new ReCaptchaEnterpriseProvider(
      import.meta.env.VITE_RECAPTCHA_ENTERPRISE_SITE_KEY
    ),
    // The SDK automatically attaches a fresh App Check token
    // to every outgoing Firebase request — no manual token
    // management needed anywhere in your app.
    isTokenAutoRefreshEnabled: true,
  });
}

入全景模式 出全景模式

// main.ts — call this once before any Firebase AI Logic requests
import { initializeSecureAppCheck } from './app-check';
import { app } from './firebase';

initializeSecureAppCheck(app);

入全景模式 出全景模式

重放攻击防护者,五月出焉,遂补其缺。纵令短时之符,App Check已支持五分钟之短,然被截之符,犹可于其效期内复用。至若按符计费之AI端点,此窗可乘。

有重放防护,则每App Check之令牌皆严限单用。首请呈令牌者,即永废之。后请持同令牌者,立拒之。

欲启重放防护,当于Firebase之台,入App Check → [尔之应用] → 限用令牌。除初始化之外,无复需更动客户端之码。


第四层:模型铠甲 — GA与Firebase之合

关闭:推理时之不安全内容

前三层固守认证与提示之构。模型铠甲则御推理时实至模型之物。

Google Model Armor 于 Cloud Next 2026 会中与 Firebase 同步推出。其运作于 Firebase AI Logic 之请与 Gemini API 之间,既检视所送之提示,复审所返之应答。可配置之护栏,覆有害内容、提示注入之尝试、敏感数据之模式,及定制政策之规则。

Firebase 之整合,其要者何?尔之应用代码,无庸更易。 模型铠甲,于谷歌云台之Firebase项目层级而设。尔之SDK调用,乃透明穿行而过。

// Your application code is identical with or without Model Armor.
// Enforcement happens at the Firebase infrastructure layer.

export async function askSupportAgent(
  userInput: string,
  displayName?: string
): Promise<string | null> {
  const variables: SupportTemplateVariables = {
    userQuery: userInput,
    userName: displayName,
  };

  try {
    const result = await templateModel.generateContent(
      'support-agent-v2',
      variables
    );
    return result.response.text();

  } catch (error: unknown) {
    // If Model Armor intercepted the input or output as a policy violation,
    // Firebase returns an error before the model processes it.
    // You handle the error — not the unsafe content.
    if (error instanceof Error) {
      console.error('Request blocked by content policy:', error.message);
    }
    return null;
  }
}

入全景模式 出全景模式

护栏之内容类目、敏感阈值、定制过滤器,皆于谷歌云台管理之。汝可无触客户端代码,亦无须发布应用更新而更之。


全栈之貌,终始如一

User submits input
        │
        ▼ TypeScript interface — typed variables enforced at compile time
        │
        ▼ Firebase SDK — App Check token automatically attached
        │
        ▼ Firebase Proxy — token validated; replay check (single-use)
                         — Gemini API key never leaves server ✓
        │
        ▼ Firebase AI Logic — Template-Only Mode enforced
                            — Server template composed, not client prompt ✓
        │
        ▼ Model Armor — input inspected against guardrails ✓
        │
        ▼ Gemini API — processes sanitized, policy-compliant prompt
        │
        ▼ Model Armor — response inspected before return
        │
        ▼ Your app receives a clean, policy-compliant response ✓

入全景模式 出全景模式

窃汝之码者,不得API之钥,亦无系统之提示。施术者制请求,初用即遭拒其令牌。设敌意之输入者,未及模型,已为所阻。


此四层之防,非全然之策也。

Firestore Security Rules Firebase AI 之逻辑,固守AI推理之途。若于 Firestore 中储藏对话之史或用户之数据,则其安全之规约,主司孰得而窥之。一有防卫之AI功能,置于开放之数据库之前,犹为隐患。

Firebase Authentication 检查应用确认请求源自汝之应用。然不辨何人发之。若汝之AI功能唯应授权于认证之用户,则Firebase认证可设此界限。

汝自处输出之理 模型铠甲于基构之层滤其文。汝之应用仍需慎处模型之应,正其呈示,勿盲从其议,且验AI所生之文,方视之为信实之据。


宏图之象

谷歌于云未来2026及I/O 2026所运之功能,昭然若揭:其筑安全之基,与能力同生,非为事后之补缀。

代理架构、模板独用之模、应用检查之防、模型之铠,非独立之能。乃层层应于单问:何以于客户端应用中运AI之能,使严谨之工程团队可为其背书?

善应其问者,将施四层之制,非惟其速启之教程所及也.

四层俱在尔今.


TemplateGenerativeModel之注:自二零二六年五月之JS SDK参考文始,此类属公预览,其API之形或迁。恒以getTemplateGenerativeModel(ai)之式立之——勿以ai.templateGenerativeModel()之式。察之。官方参考行前。


出处:Firebase AI 逻辑 文档·谷歌I/O 2026年Firebase新动态何在·造船生产之AI功能,速矣——云行至‘26’·服务器提示模板:开始使用·模板生成模型JS API参考