Firebase 标志

Firebase

社区
ericrisco
firebase

Use when building on Firebase — Firestore data modeling, Security Rules, Auth and custom claims, Cloud Functions, Storage, modular Web/Admin SDK imports — including symptoms like a database open to the internet, a query rejected by rules, or a doc stuck at ~1 write/sec. NOT managed-Postgres BaaS with SQL and RLS (that is supabase).

概览

发布者ericrisco
代码仓库rsc-harness
技能名称firebase
星标数
239
复刻数
24
附带文件
5
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 5 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 ericrisco 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Firebase AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ericrisco/rsc-harness/tree/main/skills/firebase
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ericrisco/rsc-harness.git /tmp/rsc-harness
mkdir -p .claude/skills
cp -r /tmp/rsc-harness/skills/firebase .claude/skills/firebase
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Firebase,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Firebase。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Firebase 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Firebase — Firestore, Rules, Auth, Functions, Storage

The Firebase product surface that sits on top of GCP, on the modular Web SDK (v12) and the Admin SDK. The whole skill exists to stop two failure modes: dragging relational/SQL habits into a NoSQL document store, and leaving the database open to the internet.

Two facts drive everything below:

  • It is a NoSQL document store, shaped for the read path. No joins, no server-side OR across different fields without a composite index, no SELECT * across collections. Denormalize and fan-out so a screen is one cheap query — reads are what you pay for and what users wait on.
  • Rules ARE the access control. Firestore is reachable directly from untrusted clients. There is no app server in the trust path by default — firestore.rules (CEL) is the only thing between a browser and your data. App Check attests the request even came from your app before Rules evaluate.

Not this skill:

Instead of FirebaseGo to
Relational schema, SQL, EXPLAIN, indexing a SQL engine../postgresdb/SKILL.md
Managed Postgres BaaS (SQL + Postgres RLS + PostgREST) — the most-confused sibling: same "backend-as-a-service" shape, completely different data model and rules languagesupabase
AWS document/key-value store with its own capacity modeldynamodb
Self-hosted Mongo document modelingmongodb
Generic GCP project/IAM/billing not specific to a Firebase productgcp-essentials
React/Next.js component or rendering work that merely calls Firebasereact / ../nextjs/SKILL.md

Data modeling

Firestore charges and waits on reads. Model so the common screen is one query against one collection.

Collection vs subcollection vs root + denormalized field — decide by access pattern:

ShapeUse whenWhy
Subcollection (rooms/{id}/messages)Child list is only ever read inside its parent, can grow unboundedSubcollections don't bloat the parent doc; deleting a parent does NOT delete them (handle that)
Separate root collection + foreign idChild must be queried across all parents (collection-group query)A collectionGroup('messages') query needs the docs in same-named subcollections OR a root collection
Denormalized field on the parentA few values are shown alongside the parent and rarely changeAvoids a second read; you accept writing the copy on every change

Hard limits — design around them, don't discover them in prod:

  • A document maxes out at 1 MiB (1,048,576 bytes). Don't accumulate an unbounded array (chat messages, audit log) inside one doc — it will hit the wall and every read pays for the whole blob. Use a subcollection.
  • A single document tolerates only ~1 sustained write/sec. Monotonic IDs and indexed sequential timestamps create a hotspot on one index range. Use scattered auto-IDs (doc(collection(db,'x'))), and for high-frequency counters use a sharded counter (N shard docs, sum on read).

Query reality: no joins; range/inequality filters on a field plus an orderBy on another field require a composite index; in / array-contains-any are capped (~30 values). If a query needs an index, declare it in firestore.indexes.json — see the emulator gotcha below.

ts
// Bad — unbounded array inside one doc; hits 1 MiB, every read pays for all of it
await setDoc(doc(db, "rooms", roomId), { messages: [...allMessages, newMsg] });

// Good — one doc per message in a subcollection, scattered auto-ID, no hotspot
await addDoc(collection(db, "rooms", roomId, "messages"), {
  text, authorId, createdAt: serverTimestamp(),
});

Denormalization recipes, counter sharding, cursor pagination, getCountFromServer, collection-group queries, and composite-index design live in references/data-modeling.md.

Security Rules — the load-bearing section

Rules are NOT filters. A query is rejected outright unless the rules can guarantee every matched document is readable — Firestore will not silently drop the docs you can't see. So a list rule and the query that runs against it must agree: if the rule allows reading only your own docs, the query must itself be constrained (where("ownerId","==",uid)), or the whole query fails.

javascript
// Bad — the entire database is readable AND writable by anyone on the internet
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} { allow read, write: if true; }
  }
}

// Good — default-deny, ownership-scoped, with create-time validation
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow get:    if resource.data.ownerId == request.auth.uid;
      allow list:   if request.auth != null;            // query MUST add where(ownerId == uid)
      allow create: if request.auth.uid == request.resource.data.ownerId;
      allow update, delete: if resource.data.ownerId == request.auth.uid;
    }
    // everything else: no rule = denied
  }
}

Rules to internalize:

  • Default-deny. No matching allow = denied. Never add a /{document=**} catch-all with if true. That single line is the "open to the internet" headline risk.
  • request.auth is the authenticated identity (null when signed out); request.auth.token carries custom claims for RBAC (e.g. request.auth.token.admin == true).
  • resource.data is the existing doc; request.resource.data is the incoming write. Validate the incoming write on create/update (types, immutable ownerId, no privilege escalation).
  • get() / exists() read another doc for cross-document checks (e.g. role lookup) — each costs a billed read and counts against rule-evaluation limits, so keep them shallow.
  • get vs list are distinct: a single-doc read vs a query. read = both; split them so a query can't leak documents a single get would also have blocked.

Set custom claims with the Admin SDK, never from the client. Add App Check in production so Rules only run for requests that provably came from your real app.

Full CEL patterns — RBAC via claims, ownership, validation functions, time-based throttling, and the complete @firebase/rules-unit-testing recipe — are in references/security-rules.md.

Auth

  • Client sign-in with getAuth() + a provider; the SDK manages the refresh of the ID token.
  • Server-side, verify the ID token with getAuth(adminApp).verifyIdToken(idToken) before trusting any caller. A raw UID from the client is not proof of anything.
  • Custom claims for RBAC: getAuth(adminApp).setCustomUserClaims(uid, { admin: true }). Claims land in request.auth.token in Rules and in the decoded token on the server. They refresh on the client's next token refresh, not instantly — force a refresh if you need it immediately.
  • Session cookies (createSessionCookie) suit SSR / server-rendered apps where you want an httpOnly cookie instead of shipping the ID token to every request — pairs with ../nextjs/SKILL.md.

Cloud Functions (2nd gen)

2nd gen is the default and the only generation that runs Node.js 22. Use firebase-functions v7 modular triggers and firebase-admin.

ts
import { onDocumentWritten } from "firebase-functions/v2/firestore";
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { defineSecret } from "firebase-functions/params";

const STRIPE_KEY = defineSecret("STRIPE_KEY"); // never hard-code secrets

export const onPostWrite = onDocumentWritten(
  { document: "posts/{postId}", region: "europe-west1" },
  async (event) => {
    // Background events deliver AT-LEAST-ONCE — make this idempotent.
    const eventId = event.id; // dedupe on this (e.g. a processed/{eventId} marker doc)
  }
);

export const setAdminClaim = onCall(async (request) => {
  if (request.auth?.token.admin !== true) throw new HttpsError("permission-denied", "admins only");
  // ... verify, then setCustomUserClaims via admin SDK
});
  • Callable (onCall) gives you request.auth already verified; raw onRequest HTTPS does not — you must verify the ID token yourself.
  • Idempotency is mandatory for background triggers (onDocumentWritten etc.): events can fire more than once, so guard side effects with the event id.
  • Pin region, set secrets with defineSecret (not env literals), and tune concurrency for cost.
  • Functions require the Blaze plan; outbound networking from a function also requires Blaze.

Trigger catalogue, callable-vs-HTTPS auth, idempotency keys, cold-start/cost, Auth blocking functions, and region pinning are in references/cloud-functions.md.

Cloud Storage

Storage paths are gated by their own Rules; clients can hit them directly.

javascript
// Bad — any signed-in user can overwrite any other user's avatar
match /avatars/{fileName} { allow write: if request.auth != null; }

// Good — path-scoped to the owner, with a size/type guard
match /avatars/{uid}/{fileName} {
  allow read:  if true;                          // public avatars
  allow write: if request.auth.uid == uid
               && request.resource.size < 5 * 1024 * 1024
               && request.resource.contentType.matches('image/.*');
}

For server-issued time-limited access (private downloads), generate a signed URL from the Admin SDK rather than loosening the Rules.

SDK & project mechanics

Use the modular SDK so the bundler tree-shakes unused Firebase code. The old namespaced firebase.firestore() API is gone in v9+.

ts
// Bad — pulls the entire SDK; defeats tree-shaking (and the compat/namespaced API is legacy)
import firebase from "firebase";
firebase.firestore().collection("posts").get();

// Good — named imports, only what you use ships (Web SDK v12)
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from "firebase/firestore";
const db = getFirestore(initializeApp(config));
const snap = await getDocs(collection(db, "posts"));
  • firebase.json configures emulators, rules/index file paths, and hosting; firestore.indexes.json declares composite indexes.
  • Run the Local Emulator Suite (firebase emulators:start) for local dev and tests.
  • Emulator gotcha: the Firestore emulator does NOT enforce composite indexes — it runs any valid query. So "works in the emulator, fails in prod with requires an index" is expected. Verify index coverage separately by keeping firestore.indexes.json in sync and deploying it.
  • The Firebase API key in client config is not a secret (it identifies the project, not authorizes access — Rules + App Check do that). Service-account JSON keys ARE secrets; keep them server-side.

Anti-patterns

Anti-patternWhy it's wrongDo instead
allow read, write: if true; catch-allWhole DB is open to the internetDefault-deny; scope each match to request.auth + ownership
Treating rules as query filtersQuery is rejected, not filtered — it fails entirelyConstrain the query to match what list allows
Unbounded array in one documentHits the 1 MiB limit; every read pays for the whole blobSubcollection, one doc per item
Monotonic IDs / sequential indexed timestampsIndex hotspot → ~1 write/sec/doc wallScattered auto-IDs; sharded counters for high write rate
Trusting client writes for sensitive fieldsClient can set role: "admin" on itselfValidate request.resource in Rules; set claims via Admin SDK only
No App Check in productionRules run for any caller, including scripts/scrapersEnable App Check (reCAPTCHA / Play Integrity / App Attest)
Service-account key in client / repoFull admin access leaksKeep service-account JSON server-side; client API key is fine
Namespaced/compat SDK (firebase.firestore())Legacy, not tree-shakeable, gone in modularModular named imports from firebase/firestore
No emulator / rules testsOpen or broken rules ship silently@firebase/rules-unit-testing via firebase emulators:exec
Background trigger with non-idempotent side effectsAt-least-once delivery double-charges/double-writesDedupe on event.id

Verify

scripts/verify.sh is read-only and runs from your project root. It locates firestore.rules and fails if a root match /{document=**} carries an allow read, write: if true; catch-all or the rules file is empty; validates firestore.indexes.json parses as JSON; and, when the Firebase CLI is present, points at the firebase emulators:exec rules-test path. It exits 0 and skips cleanly when no Firebase artifacts are in the working directory — not every repo has them.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Firebase AI 技能有什么作用?

Use when building on Firebase — Firestore data modeling, Security Rules, Auth and custom claims, Cloud Functions, Storage, modular Web/Admin SDK imports — including symptoms like a database open to the internet, a query rejected by rules, or a doc stuck at ~1 write/sec. NOT managed-Postgres BaaS with SQL and RLS (that is supabase).

为什么在 TypingMind 中使用 Firebase?

因为您只需安装一次,就能搭配任何模型使用。Firebase 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Firebase?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ericrisco/rsc-harness/tree/main/skills/firebase。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Firebase?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Firebase 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Firebase 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Firebase AI 技能免费吗?

是的。该技能源自 ericrisco 在 GitHub 上以 MIT 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇