メインコンテンツまでスキップ

image_generation_plan.role_ts

IDFile NameProposed Image FilenameRelative Link PathPromptInsertion Point
911docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_01_rules_concept.png./picture/firebase_security_role_ts_index_01_rules_concept.pngTheme: Rules as Gatekeeper

Labels to Render:
- User: "Request"
- Gate: "Security Rules 🛡️"
- Castle: "Firestore 🏰"
- Action: "Allow / Deny"

Visual Details:
1. Core Concept: Rules acting as the entry guard.
2. Metaphor: A medieval castle gate with a guard checking a scroll (Request).
3. Action: Guarding.
4. Layout: Gatekeeper scene.
## 第1章:なぜRulesが必要?「公開しちゃった😱」事故の構造を知る💥
912docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_02_access_path.png./picture/firebase_security_role_ts_index_02_access_path.pngTheme: Access Path Logic

Labels to Render:
- Client: "Rules Apply ✅"
- Server: "Rules Bypass ⚠️"
- Admin SDK: "God Mode 👑"

Visual Details:
1. Core Concept: Different rules for different paths.
2. Metaphor: A secure front door (Client) vs a VIP back entrance (Server).
3. Action: Entering.
4. Layout: Comparison.
## 第2章:Firestoreのアクセス経路を整理(Rulesが効く/効かない)🧭
913docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_03_deployment_flow.png./picture/firebase_security_role_ts_index_03_deployment_flow.pngTheme: Rules Deployment Flow

Labels to Render:
- Local: "firestore.rules 📄"
- Tool: "Firebase CLI ⚙️"
- Cloud: "Deploy (Overwrite) ☁️"
- Console: "Old Rules 🗑️"

Visual Details:
1. Core Concept: Local file overwriting cloud settings.
2. Metaphor: Uploading a new blueprint that replaces the old one instantly.
3. Action: Overwriting.
4. Layout: Left-to-right flow.
## 第3章:Rulesの管理とデプロイの基本(Console vs CLI)🧰
914docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_04_user_isolation.png./picture/firebase_security_role_ts_index_04_user_isolation.pngTheme: User Data Isolation

Labels to Render:
- User A: "See A Only 👀"
- User B: "See B Only 👀"
- Pattern: "users/{uid}"

Visual Details:
1. Core Concept: Each user can only access their own data.
2. Metaphor: Private lockers. User A's key only opens Locker A. Locker B is locked.
3. Action: Isolating.
4. Layout: Side-by-side lockers.
## 第7章:ユーザー別データ設計(uid基準の王道)👤📁
915docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_05_write_control.png./picture/firebase_security_role_ts_index_05_write_control.pngTheme: Granular Write Control

Labels to Render:
- Create: "Allow ✅"
- Update: "Deny 🚫"
- Delete: "Admin Only 👑"

Visual Details:
1. Core Concept: Splitting write permissions.
2. Metaphor: A control panel with separate switches for 'Create', 'Update', and 'Delete'.
3. Action: Controlling.
4. Layout: Control panel.
## 第9章:最小権限② “書く”の制御(create/update/deleteを分ける)✍️🧯
916docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_06_input_validation.png./picture/firebase_security_role_ts_index_06_input_validation.pngTheme: Input Validation

Labels to Render:
- Input: "Title (Empty)"
- Rule: "title.size() > 0"
- Result: "Reject 🛑"

Visual Details:
1. Core Concept: Validating data before saving.
2. Metaphor: A shape sorter. A square block (Bad Data) trying to fit in a round hole (Rule). It doesn't fit.
3. Action: Rejecting.
4. Layout: Input check.
## 第11章:入力検証② 文字数・パターン(ユーザー入力の地雷💣)🔤
917docs/firebase_security_role_ts_index.mdfirebase_security_role_ts_index_07_emulator_testing.png./picture/firebase_security_role_ts_index_07_emulator_testing.pngTheme: Emulator Testing

Labels to Render:
- Test 1: "Admin (Pass) ✅"
- Test 2: "User (Pass) ✅"
- Test 3: "Guest (Fail) 🛑"
- Tool: "Emulator 🧪"

Visual Details:
1. Core Concept: Testing different scenarios locally.
2. Metaphor: A crash test dummy running through three different walls.
3. Action: Testing.
4. Layout: Three tracks.
## 第19章:テストが本体!EmulatorでRules単体テスト🧪🧯
918docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_01_direct_access.png./picture/firebase_security_role_ts_study_001_01_direct_access.pngTheme: Firestore Direct Access

Labels to Render:
- Client: "Web App 🌍"
- Path: "Direct SDK"
- Guard: "Rules 🛡️"
- DB: "Firestore"

Visual Details:
1. Core Concept: Clients connect directly to the DB, protected only by Rules.
2. Metaphor: A house with a door opening directly to the street. The lock (Rules) is the only protection.
3. Action: Connecting.
4. Layout: Direct line.
## 1) まず結論:Firestoreは“誰でも叩ける入口”がある🔓🌍
919docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_02_accident_mechanism.png./picture/firebase_security_role_ts_study_001_02_accident_mechanism.pngTheme: Accident Mechanism Flow

Labels to Render:
- Step 1: "Loosen Rules (Debug) 🛠️"
- Step 2: "Deploy (Forget) 📤"
- Step 3: "Leak (Public) 😱"

Visual Details:
1. Core Concept: How accidents happen.
2. Metaphor: Unlocking a door for a friend, forgetting to lock it, and then a thief enters.
3. Action: Leaking.
4. Layout: Timeline.
## 2) 「公開事故😱」が起きる典型パターン(構造で理解)🧠💥
920docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_03_dangerous_rule_a.png./picture/firebase_security_role_ts_study_001_03_dangerous_rule_a.pngTheme: Dangerous Rule: All Public

Labels to Render:
- Rule: "allow read, write: if true"
- Effect: "Open to World 🌏"
- Risk: "Data Loss / Leak 💥"

Visual Details:
1. Core Concept: The danger of if true.
2. Metaphor: A vault with the door wide open and a "Free Money" sign.
3. Action: Leaking.
4. Layout: Warning sign.
## 危険例A:全公開(最悪)☠️
921docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_04_dangerous_rule_b.png./picture/firebase_security_role_ts_study_001_04_dangerous_rule_b.pngTheme: Dangerous Rule: Time Bomb

Labels to Render:
- Rule: "if request.time < ..."
- Clock: "Expired ⏰"
- Effect: "Open -> Closed? (Uncertain)"

Visual Details:
1. Core Concept: Rules expiring without notice.
2. Metaphor: A time bomb ticking. Or a door that was supposed to lock automatically but got stuck.
3. Action: Ticking.
4. Layout: Timer focus.
## 危険例B:期限付き公開(“忘れる”やつ)⏳😇→😱
922docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_05_dangerous_rule_c.png./picture/firebase_security_role_ts_study_001_05_dangerous_rule_c.pngTheme: Dangerous Rule: Login Only

Labels to Render:
- Rule: "if auth != null"
- User A: "Logged In"
- Data B: "User B's Data"
- Access: "Allowed (Bad) 😱"

Visual Details:
1. Core Concept: Login doesn't mean you can see everything.
2. Metaphor: A building badge allows entry to the lobby, but shouldn't open every office door.
3. Action: Accessing unauthorized area.
4. Layout: Scenario.
## 危険例C:「ログインしてれば何でもOK」も実は危ない🔓👤
923docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_06_admin_bypass.png./picture/firebase_security_role_ts_study_001_06_admin_bypass.pngTheme: Admin SDK Bypass

Labels to Render:
- Wall: "Rules 🧱"
- Client: "Blocked 🛑"
- Server (Admin): "Bypass (Fly over) ✈️"

Visual Details:
1. Core Concept: Admin SDK ignores rules.
2. Metaphor: A wall blocking pedestrians (Client). A plane (Admin) flying over the wall.
3. Action: Bypassing.
4. Layout: Comparison.
## 4) 超重要な勘違い:Admin SDKはRulesの対象外⚠️🧱
924docs/firebase_security_role_ts_study_001.mdfirebase_security_role_ts_study_001_07_playground.png./picture/firebase_security_role_ts_study_001_07_playground.pngTheme: Rules Playground UI

Labels to Render:
- UI: "Rules Playground"
- Input: "Simulation Type (get/create)"
- Result: "Request Denied 🛑"

Visual Details:
1. Core Concept: Simulating rules in the console.
2. Metaphor: A flight simulator or a sandbox environment.
3. Action: Simulating.
4. Layout: UI Mockup.
## 5) 手を動かす🧑‍💻:Rules Playgroundで“事故を再現”してみよう🧪🔥
925docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_01_access_map.png./picture/firebase_security_role_ts_study_002_01_access_map.pngTheme: Three Access Paths

Labels to Render:
- Path A: "Client (Rules) ✅"
- Path B: "Server (IAM) 🛡️"
- Path C: "REST (IAM) 🛡️"

Visual Details:
1. Core Concept: The three ways to access Firestore.
2. Metaphor: A map with three roads leading to the same castle (Firestore). Road A has a Gatekeeper (Rules). Roads B and C have ID Scanners (IAM).
3. Action: Routing.
4. Layout: Map view.
## 2) 入口の地図🗺️:Firestoreへ行く“3つの道”🚦
926docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_02_client_vs_server.png./picture/firebase_security_role_ts_study_002_02_client_vs_server.pngTheme: Client vs Server Context

Labels to Render:
- Client: "Untrusted (Hacker) 😈"
- Server: "Trusted (Safe) 😇"
- Defense: "Rules vs IAM"

Visual Details:
1. Core Concept: Clients are hostile environments; Servers are safe.
2. Metaphor: A wild jungle (Client) vs a sterile lab (Server).
3. Action: Comparing.
4. Layout: Split screen.
## 3) ここが超大事💥:「同じ“読む/書く”でも意味が違う」🧠
927docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_03_comparison_table.png./picture/firebase_security_role_ts_study_002_03_comparison_table.pngTheme: Access Path Table

Labels to Render:
- Col 1: "Path"
- Col 2: "Auth"
- Col 3: "Defense"
- Row 1: "Client -> Rules"
- Row 2: "Server -> IAM"

Visual Details:
1. Core Concept: Summarizing the differences.
2. Metaphor: A clean comparison chart or periodic table.
3. Action: Displaying data.
4. Layout: Table view.
## 4) ひと目で分かる表📋✨(これが“事故防止の答え”)
928docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_04_app_map.png./picture/firebase_security_role_ts_study_002_04_app_map.pngTheme: App Access Map Template

Labels to Render:
- Screen: "Post List"
- Path: "Client (Rules)"
- Screen: "Admin Stats"
- Path: "Server (IAM)"

Visual Details:
1. Core Concept: Mapping screens to access methods.
2. Metaphor: Connecting UI screens to their backend pipes.
3. Action: Mapping.
4. Layout: Network diagram.
## 5) 手を動かす🧑‍💻✨:あなたのアプリの“アクセス経路マップ”を作る
929docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_05_server_candidates.png./picture/firebase_security_role_ts_study_002_05_server_candidates.pngTheme: Server-Side Candidates

Labels to Render:
- Task 1: "Aggregation 📊"
- Task 2: "Payment 💳"
- Task 3: "AI Process 🤖"
- Zone: "Server Only 🔒"

Visual Details:
1. Core Concept: Tasks that must be done on the server.
2. Metaphor: High-value items kept in the vault, not on the counter.
3. Action: Securing.
4. Layout: Icon set.
## 6) ミニ課題🎯:サーバー側でやる処理を1つ決める(10分)⏱️
930docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_06_ai_analysis.png./picture/firebase_security_role_ts_study_002_06_ai_analysis.pngTheme: AI Access Analysis

Labels to Render:
- Code: "Source Code"
- AI: "Gemini CLI"
- Output: "Path Analysis Report 📝"

Visual Details:
1. Core Concept: AI analyzing code to find access paths.
2. Metaphor: A robot detective scanning the blueprints of a building.
3. Action: Analyzing.
4. Layout: Process flow.
## 7-1. “アクセス経路の棚卸し”をAIにやらせる🧹
931docs/firebase_security_role_ts_study_002.mdfirebase_security_role_ts_study_002_07_pitfalls.png./picture/firebase_security_role_ts_study_002_07_pitfalls.pngTheme: Common Pitfalls

Labels to Render:
- Trap 1: "Hiding UI != Security 🙈"
- Trap 2: "Server != Rules 🧱"
- Result: "Leak 💥"

Visual Details:
1. Core Concept: Common mistakes to avoid.
2. Metaphor: Warning signs. A person hiding their eyes (Hiding UI) but still being hit.
3. Action: Warning.
4. Layout: Warning icons.
## 8) この章の“落とし穴あるある”😂💥(先に踏んでおこう)
932docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_01_console_cli_conflict.png./picture/firebase_security_role_ts_study_003_01_console_cli_conflict.pngTheme: Console vs CLI Conflict (Data Overwrite Risk)

Labels to Render:
- Console Edit: "一時的な変更"
- CLI Deploy: "強制上書き"
- Result: "変更消失"

Visual Details:
1. Core Concept: The danger of editing in Firebase Console and then deploying from CLI, which overwrites the manual changes.
2. Metaphor: A "Cloud" icon representing Firebase Console with a small "pencil" icon (editing). A "Laptop" icon representing CLI sending a "File" arrow to the Cloud.
3. Action: The file from Laptop (CLI) lands on the Cloud, crushing/replacing the small pencil edits. A "Warning" triangle icon nearby.
4. Layout: Laptop on the left, Cloud on the right. Arrow pointing L -> R.
## 1) Console(Web画面)で編集するメリット / 罠 🖥️🧨
933docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_02_cli_source_of_truth.png./picture/firebase_security_role_ts_study_003_02_cli_source_of_truth.pngTheme: CLI & Git as Source of Truth

Labels to Render:
- Local File: "firestore.rules"
- Version Control: "Git履歴"
- Benefit: "安全・確実"

Visual Details:
1. Core Concept: Managing rules as code in a local file system tracked by Git.
2. Metaphor: A "Document" icon labeled firestore.rules. It is connected to a "Git Branch" icon. A shield icon represents safety.
3. Action: Lines connecting the file to Git, showing it is protected and tracked.
4. Layout: Central document, Git icon above, Shield icon below.
## 2) CLI(ローカルファイル)で管理するメリット / 注意点 💻🧯
934docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_03_firebase_init_files.png./picture/firebase_security_role_ts_study_003_03_firebase_init_files.pngTheme: Firebase Init Generated Files

Labels to Render:
- Config: "firebase.json"
- Rules: "firestore.rules"
- Indexes: "firestore.indexes.json"

Visual Details:
1. Core Concept: The standard file structure created after firebase init.
2. Metaphor: A project folder opening up to reveal three distinct file icons.
3. Action: Static display of the three files, emphasizing their roles.
4. Layout: Folder at top, three files branching out below.
初期化が済むと、だいたいこのへんが増えるよ👇
935docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_04_firebase_json_mapping.png./picture/firebase_security_role_ts_study_003_04_firebase_json_mapping.pngTheme: Firebase JSON Mapping to Rules

Labels to Render:
- Config File: "firebase.json"
- Key: "firestore.rules"
- Target File: "実ファイル"

Visual Details:
1. Core Concept: How firebase.json points to the actual rules file.
2. Metaphor: A JSON code snippet block on the left. An arrow pointing from the "rules": "firestore.rules" line to a file icon on the right.
3. Action: The arrow indicates the reference/linkage.
4. Layout: JSON block left, File icon right.
## 3) firebase.json を理解する(ここが事故防止の心臓❤️)
936docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_05_deploy_command_scope.png./picture/firebase_security_role_ts_study_003_05_deploy_command_scope.pngTheme: Deployment Command Scope

Labels to Render:
- Command: "deploy --only rules"
- Target: "Rulesのみ更新"
- Ignored: "Functions/Hosting等は無視"

Visual Details:
1. Core Concept: The --only firestore:rules command updates only the rules, leaving other resources untouched.
2. Metaphor: A command terminal window executing the command. A laser beam hitting a "Shield" (Rules) while passing by a "Gear" (Functions) and "Globe" (Hosting) without touching them.
3. Action: Selective update.
4. Layout: Terminal at top, resources at bottom. Beam hitting only the Shield.
## 4) まず覚えるべき“安全デプロイ”コマンド3つ🧯
937docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_06_multi_db_config.png./picture/firebase_security_role_ts_study_003_06_multi_db_config.pngTheme: Multiple Database Configuration

Labels to Render:
- JSON Array: "配列設定"
- DB 1: "(default)"
- DB 2: "ecommerce"

Visual Details:
1. Core Concept: Configuring multiple databases in firebase.json using an array.
2. Metaphor: A JSON array bracket [ ... ] containing two blocks. Each block points to a separate Database cylinder icon.
3. Action: Splitting configuration to multiple targets.
4. Layout: JSON array on left, two DB icons on right vertically stacked.
## 5) 複数DBを使うときの firebase.json(超ざっくり最重要形)🧩
938docs/firebase_security_role_ts_study_003.mdfirebase_security_role_ts_study_003_07_safe_workflow.png./picture/firebase_security_role_ts_study_003_07_safe_workflow.pngTheme: Safe Rules Workflow

Labels to Render:
- Step 1: "ローカル編集"
- Step 2: "Gitコミット"
- Step 3: "限定デプロイ"

Visual Details:
1. Core Concept: The three-step cycle for safe rules management.
2. Metaphor: A circular flow chart.
- Top: Laptop (Edit).
- Right: Git Logo (Commit).
- Bottom: Cloud with Shield (Deploy Rules).
3. Action: Arrows connecting them in a clockwise circle.
4. Layout: Circular arrangement.
## ✅ ルール運用の鉄則3つ🛡️
939docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_01_rule_structure.png./picture/firebase_security_role_ts_study_004_01_rule_structure.pngTheme: Firebase Security Rules Structure

Labels to Render:
- Path: "match /users/{uid}"
- Method: "allow read"
- Condition: "if request.auth != null"

Visual Details:
1. Core Concept: The three components of a rule: Path (Where), Method (Action), Condition (Logic).
2. Metaphor: A puzzle with three interlocking pieces labeled Path, Method, and Condition forming a complete "Rule".
3. Action: Static assembly.
4. Layout: Horizontal flow: Path -> Method -> Condition.
## 2) まずこの3つだけ覚えよう 🧠🔑
940docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_02_match_document.png./picture/firebase_security_role_ts_study_004_02_match_document.pngTheme: Match Targets Document

Labels to Render:
- Collection: "cities"
- Match: "match /cities/{city}"
- Target: "Document (SF)"

Visual Details:
1. Core Concept: match syntax specifically targets a document within a collection, not the collection itself.
2. Metaphor: A target reticle (scope) focusing precisely on a single document file named "SF" inside a folder named "cities".
3. Action: The scope highlights the document.
4. Layout: Folder on left, Document inside, Scope over Document.
## ✅ match は「ドキュメントを指す」
941docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_03_allow_logic_or.png./picture/firebase_security_role_ts_study_004_03_allow_logic_or.pngTheme: Allow Rule OR Logic

Labels to Render:
- Rule A: "allow read: if false"
- Rule B: "allow read: if true"
- Result: "Access Granted"

Visual Details:
1. Core Concept: If multiple rules match, access is granted if ANY of them evaluate to true.
2. Metaphor: Two gates. Gate A is locked (red X). Gate B is open (green check). A user walks through Gate B.
3. Action: User bypassing the locked gate via the open one.
4. Layout: Parallel gates. User path going through the open one.
## ✅ allow は「1つでもtrueがあれば勝ち」⚠️
942docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_04_wildcard_variable.png./picture/firebase_security_role_ts_study_004_04_wildcard_variable.pngTheme: Wildcard Variable Capture

Labels to Render:
- Path: "/cities/{city}"
- Actual Data: "cities/SF"
- Variable: "city = 'SF'"

Visual Details:
1. Core Concept: The wildcard {city} captures the actual document ID ("SF") into a variable named city.
2. Metaphor: A "claw machine" claw labeled {city} picking up a ball labeled "SF". The ball is then placed in a box labeled city.
3. Action: Capture and assignment.
4. Layout: Path above, Claw picking "SF", Box with variable below.
## (1) 単一ワイルドカード {id}
943docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_05_subcollection_independence.png./picture/firebase_security_role_ts_study_004_05_subcollection_independence.pngTheme: Subcollection Rules Independence

Labels to Render:
- Parent Match: "match /posts/{id}"
- Subcollection: "comments"
- Status: "No Rules Applied"

Visual Details:
1. Core Concept: Rules defined for a parent document do not automatically apply to its subcollections.
2. Metaphor: An umbrella covering a parent "Post" document. Rain (unauthorized access) is hitting the "Comments" sub-folder underneath, because the umbrella doesn't extend that far.
3. Action: Rain hitting the subcollection.
4. Layout: Umbrella over Parent, Subcollection exposed below.
## (2) サブコレは “自動では守られない” 🧨
944docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_06_recursive_wildcard.png./picture/firebase_security_role_ts_study_004_06_recursive_wildcard.pngTheme: Recursive Wildcard Scope

Labels to Render:
- Syntax: "{document=**}"
- Scope: "Entire Tree"
- Risk: "All Open"

Visual Details:
1. Core Concept: The recursive wildcard matches all documents in the entire subtree.
2. Metaphor: A giant net cast over a complex tree structure of folders and files, capturing everything.
3. Action: Encompassing all nodes.
4. Layout: Tree structure, net overlaying everything.
## (3) 再帰ワイルドカード {path=**} は強い(強すぎる)💥
945docs/firebase_security_role_ts_study_004.mdfirebase_security_role_ts_study_004_07_read_write_granularity.png./picture/firebase_security_role_ts_study_004_07_read_write_granularity.pngTheme: Read/Write Operation Granularity

Labels to Render:
- Read: "get, list"
- Write: "create, update, delete"
- Granularity: "Fine-grained Control"

Visual Details:
1. Core Concept: read is composed of get and list. write is composed of create, update, and delete.
2. Metaphor: A tree diagram.
- Root: Operations.
- Branch 1: Read -> leaves: Get, List.
- Branch 2: Write -> leaves: Create, Update, Delete.
3. Action: Hierarchical breakdown.
4. Layout: Standard tree chart.
## 4) allow の読み方:操作(method)をちゃんと区別する ✍️📖
946docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_01_resource_vs_request.png./picture/firebase_security_role_ts_study_005_01_resource_vs_request.pngTheme: Resource vs Request.Resource

Labels to Render:
- DB (Current): "resource.data"
- Client (New): "request.resource.data"
- Rule: "Compare"

Visual Details:
1. Core Concept: resource represents the existing data in the database. request.resource represents the new data being written.
2. Metaphor: A "Before" and "After" comparison.
- Left: A file icon labeled resource sitting in a database cylinder.
- Right: A file icon labeled request.resource flying in from a computer.
- Center: A scale or comparison symbol <=>.
3. Action: Comparison.
4. Layout: DB on left, Client on right, comparison in middle.
## 1) まずは超重要3点セットを覚える📌😺
947docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_02_request_object.png./picture/firebase_security_role_ts_study_005_02_request_object.pngTheme: Request Object Anatomy

Labels to Render:
- Object: "request"
- Properties: "auth, method, time, resource"

Visual Details:
1. Core Concept: The request object contains critical metadata for security rules.
2. Metaphor: A toolbox labeled request containing specific tools: auth (Key), method (Hammer), time (Clock), resource (File).
3. Action: Static display of tools.
4. Layout: Open toolbox with labeled items inside.
## ✅ request(リクエストの情報)
948docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_03_operation_visibility.png./picture/firebase_security_role_ts_study_005_03_operation_visibility.pngTheme: Data Visibility by Operation

Labels to Render:
- Create: "New Only"
- Update: "Old & New"
- Delete: "Old Only"

Visual Details:
1. Core Concept: What data is available for create, update, and delete.
2. Metaphor: Three windows.
- Window 1 (Create): Shows only the "New" file.
- Window 2 (Update): Shows both "Old" and "New" files side-by-side.
- Window 3 (Delete): Shows only the "Old" file.
3. Action: Static comparison.
4. Layout: Three distinct panels.
## 2) create / update / delete で「見えるもの」が違う⚠️🧠
949docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_04_map_diff.png./picture/firebase_security_role_ts_study_005_04_map_diff.pngTheme: Map Diff Logic

Labels to Render:
- New Data: "request.resource"
- Old Data: "resource"
- Result: "Diff (Changed Keys)"

Visual Details:
1. Core Concept: Calculating the difference between two data sets to identify changed fields.
2. Metaphor: A subtraction equation: New File - Old File = Diff File highlighting specific changes (e.g., changed color).
3. Action: Subtraction leading to result.
4. Layout: Horizontal equation style.
## 3) “差分”を取る最強ワザ:Map.diff() 🧩✨
950docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_05_secure_update.png./picture/firebase_security_role_ts_study_005_05_secure_update.pngTheme: Secure Update Filtering

Labels to Render:
- Input: "Update Request"
- Filter: "allow keys: title, body"
- Blocked: "ownerId change"

Visual Details:
1. Core Concept: Allowing updates only to specific fields while blocking others.
2. Metaphor: A filter funnel.
- Top: Mixed changes (Title, Body, OwnerId).
- Middle: Filter/Sieve.
- Bottom: Allowed changes (Title, Body).
- Side: Rejected change (OwnerId) bouncing off.
3. Action: Filtering.
4. Layout: Vertical funnel.
## 4-2. ルールを書いてみる(差分で update を縛る)🔒✍️
951docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_06_update_checklist.png./picture/firebase_security_role_ts_study_005_06_update_checklist.pngTheme: Update Validation Checklist

Labels to Render:
- Check 1: "Owner?"
- Check 2: "Not Locked?"
- Check 3: "Allowed Keys?"
- Check 4: "Timestamp?"

Visual Details:
1. Core Concept: The sequential checks required for a secure update operation.
2. Metaphor: A clipboard with a checklist. Four items are checked off with green ticks.
3. Action: Verification.
4. Layout: List format.
ポイント解説だよ😊👇
952docs/firebase_security_role_ts_study_005.mdfirebase_security_role_ts_study_005_07_ai_review_workflow.png./picture/firebase_security_role_ts_study_005_07_ai_review_workflow.pngTheme: AI Rules Drafting & Human Review

Labels to Render:
- AI: "Draft Rules"
- Human: "Review & Verify"
- Final: "Deploy"

Visual Details:
1. Core Concept: AI generates the initial rules, human reviews them for safety, then deploys.
2. Metaphor: A robot handing a blueprint to a human engineer holding a magnifying glass. The engineer approves it, leading to a rocket launch (Deploy).
3. Action: Handover and review.
4. Layout: Left to right flow.
## 8-1. “叩き台”はAI、決定は人間🧑‍⚖️✅
953docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_01_auth_check_flow.png./picture/firebase_security_role_ts_study_006_01_auth_check_flow.pngTheme: Authentication Check Flow

Labels to Render:
- User Request: "request.auth"
- Check: "!= null ?"
- True: "Access Granted"
- False: "Permission Denied"

Visual Details:
1. Core Concept: The primary function of request.auth != null is to act as a gatekeeper.
2. Metaphor: A security checkpoint. A user arrives with an ID card (request.auth).
- If ID is present (Not Null), the gate opens.
- If ID is missing (Null), the gate remains closed and a red X appears.
3. Action: Checking ID.
4. Layout: Flowchart style.
## 6-0. まず“脳内モデル”を1枚で🧠🗺️
954docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_02_server_bypass.png./picture/firebase_security_role_ts_study_006_02_server_bypass.pngTheme: Admin SDK Bypasses Rules

Labels to Render:
- Client App: "Rules Apply"
- Server (Admin SDK): "Bypass Rules"
- Firestore: "Database"

Visual Details:
1. Core Concept: Client requests must pass through Security Rules. Server requests (using Admin SDK) bypass them entirely.
2. Metaphor: A castle with a main gate (Rules) and a VIP side entrance.
- Regular users (Client App) line up at the main gate.
- A VIP car (Server/Admin SDK) drives through the open side entrance directly into the castle.
3. Action: Different entry paths.
4. Layout: Castle in center, two paths leading in.
⚠️ 大事:サーバー用ライブラリ(Admin SDK / Server client libraries)は Rules をバイパスします(別の守り=IAM等の世界)🧯
955docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_03_basic_auth_rule.png./picture/firebase_security_role_ts_study_006_03_basic_auth_rule.pngTheme: Basic Auth Rule Syntax

Labels to Render:
- Rule: "allow read, write"
- Condition: "if request.auth != null"
- Meaning: "Login Required"

Visual Details:
1. Core Concept: The syntax if request.auth != null enforces login.
2. Metaphor: A code snippet displayed on a digital lock screen. The lock is closed.
3. Action: Static code display with meaning.
4. Layout: Code block with an arrow pointing to a lock icon.
## 6-1. ルールの最小形:ログイン必須チェック✅🔐
956docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_04_collection_lock.png./picture/firebase_security_role_ts_study_006_04_collection_lock.pngTheme: Specific Collection Locking

Labels to Render:
- Collection: "privateNotes"
- Status: "Login Required"
- Others: "Default Deny"

Visual Details:
1. Core Concept: Applying the login rule specifically to the privateNotes collection.
2. Metaphor: A row of file cabinets. The one labeled privateNotes has a shiny padlock. The others are dark and inaccessible (default deny).
3. Action: Locking specific cabinet.
4. Layout: Row of cabinets.
## 6-2. 手を動かす:privateNotes を“ログイン必須”にする🧑‍💻🧯
957docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_05_default_deny.png./picture/firebase_security_role_ts_study_006_05_default_deny.pngTheme: Default Deny Security

Labels to Render:
- Concept: "Default Deny"
- Explicit Allow: "Only Defined Path"
- Elsewhere: "Blocked"

Visual Details:
1. Core Concept: Unless a rule explicitly allows access, everything is denied by default.
2. Metaphor: A solid brick wall (Firestore). There is only one small door cut into it where the rule is defined. Everywhere else is solid wall.
3. Action: Arrows bouncing off the wall, one arrow passing through the door.
4. Layout: Wall with one door.
// ✅ それ以外は何も書かなければ「全部拒否」になる(デフォルト拒否)
958docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_06_ui_state_transition.png./picture/firebase_security_role_ts_study_006_06_ui_state_transition.pngTheme: UI State based on Auth

Labels to Render:
- State: "Null (Guest)" -> "UI: Login Button"
- State: "User (Auth)" -> "UI: Note Content"

Visual Details:
1. Core Concept: The UI changes based on whether the user state is null or populated.
2. Metaphor: A toggle switch.
- Left position (Guest): Screen shows a "Login" button.
- Right position (User): Screen shows "Notes".
3. Action: State switching.
4. Layout: Split view showing both states.
### ① React側:ログイン状態で画面を切り替える(最小)🪟✨
959docs/firebase_security_role_ts_study_006.mdfirebase_security_role_ts_study_006_07_ux_patterns.png./picture/firebase_security_role_ts_study_006_07_ux_patterns.pngTheme: Authentication UX Patterns

Labels to Render:
- Pattern 1: "Login Prompt"
- Pattern 2: "Freemium"
- Pattern 3: "Private"

Visual Details:
1. Core Concept: Three common ways to handle unauthorized users.
2. Metaphor: Three different door signs.
- Sign 1: "Please Login to Enter".
- Sign 2: "Public Area Open / Private Area Locked".
- Sign 3: "Keep Out / Authorized Personnel Only".
3. Action: Displaying options.
4. Layout: Three distinct panels side-by-side.
## 6-4. 未ログイン時のUXを1行で決めよう🙂📝
960docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_01_user_data_model.png./picture/firebase_security_role_ts_study_007_01_user_data_model.pngTheme: User Data Model Structure

Labels to Render:
- Private: "users/{uid}"
- Subcollection: "users/{uid}/notes"
- Public: "publicProfiles/{uid}"

Visual Details:
1. Core Concept: The recommended Firestore data structure for user data.
2. Metaphor: A file directory tree.
- Root: users. Branch: {uid} (Lock icon). Leaf: notes (Lock icon).
- Root: publicProfiles. Branch: {uid} (Globe icon).
3. Action: Static structure display.
4. Layout: Tree diagram.
## ✅ 王道の設計(超おすすめ)👑
961docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_02_field_id_antipattern.png./picture/firebase_security_role_ts_study_007_02_field_id_antipattern.pngTheme: Vulnerable Field-Based Security

Labels to Render:
- Vulnerable Doc: "ownerUid: 'victim'"
- Attack: "Change ownerUid -> 'hacker'"
- Result: "Access Stolen"

Visual Details:
1. Core Concept: Relying on a mutable field ownerUid for security is risky because it can be changed.
2. Metaphor: A document with a sticky note saying "Owner: Victim". A hacker's hand peels it off and sticks a new note saying "Owner: Hacker".
3. Action: Tampering.
4. Layout: Document being modified.
## ❌ 失敗A:uidを“フィールド”に入れて所有者判定しようとする
962docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_03_auth_only_risk.png./picture/firebase_security_role_ts_study_007_03_auth_only_risk.pngTheme: Auth Only Risk (Too Permissive)

Labels to Render:
- Rule: "auth != null"
- Situation: "Logged In Users"
- Result: "Access Everyone's Data"

Visual Details:
1. Core Concept: Checking only for authentication allows any logged-in user to access any data.
2. Metaphor: A large locker room. The door says "Employees Only" (Auth). Inside, any employee can open ANY locker because there are no individual locks.
3. Action: Chaos / Open access.
4. Layout: Locker room scene.
## ❌ 失敗B:auth != null だけでOKにしちゃう
963docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_04_is_owner_logic.png./picture/firebase_security_role_ts_study_007_04_is_owner_logic.pngTheme: isOwner Security Logic

Labels to Render:
- User ID: "request.auth.uid"
- Path ID: "match /users/{uid}"
- Check: "Match?"
- Result: "Allow Access"

Visual Details:
1. Core Concept: Access is granted only if the requester's UID matches the document path UID.
2. Metaphor: A key and a lock.
- Key: request.auth.uid.
- Lock: {uid} on the door.
- The key shape matches the lock shape perfectly.
3. Action: Unlocking.
4. Layout: Key inserting into lock.
## 4) Rulesを書こう(まずは“最小で強い”やつ)🛡️✨
964docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_05_react_uid_ref.png./picture/firebase_security_role_ts_study_007_05_react_uid_ref.pngTheme: React UID Reference Logic

Labels to Render:
- Code: "doc(db, 'users', user.uid)"
- User Object: "auth.currentUser"
- Firestore: "Path Reference"

Visual Details:
1. Core Concept: Using the authenticated user's UID to construct the Firestore document reference.
2. Metaphor: A bridge construction.
- Side A: User Object (Client).
- Side B: Firestore Document (Server).
- Bridge: user.uid connecting them directly.
3. Action: Linking.
4. Layout: Horizontal connection.
## 5) React(TypeScript)で「自分のusers/{uid}」を触る👆✨
965docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_06_attack_simulation.png./picture/firebase_security_role_ts_study_007_06_attack_simulation.pngTheme: Unauthorized Access Attempt

Labels to Render:
- Attacker: "User A (uid: A)"
- Target: "users/{uid: B}"
- Result: "Permission Denied"

Visual Details:
1. Core Concept: A user trying to access a path that doesn't match their UID is denied.
2. Metaphor: A person (User A) trying to open a door labeled "User B". A red force field or "Access Denied" sign blocks them.
3. Action: Blocking access.
4. Layout: Person facing a closed door.
## 6) “他人のuidで読めない”を確認しよう(ここが本番😤🧪)
966docs/firebase_security_role_ts_study_007.mdfirebase_security_role_ts_study_007_07_unit_test_cases.png./picture/firebase_security_role_ts_study_007_07_unit_test_cases.pngTheme: Unit Test Scenarios

Labels to Render:
- Test 1: "Alice -> users/Alice (OK)"
- Test 2: "Bob -> users/Alice (Block)"
- Concept: "Automated Verification"

Visual Details:
1. Core Concept: Verifying security rules with automated tests for valid and invalid access.
2. Metaphor: A robot testing doors.
- Robot "Alice" opens "Alice's Door" (Green Light).
- Robot "Bob" tries "Alice's Door" (Red Light).
3. Action: Testing.
4. Layout: Split panel showing two test cases.
## Rulesの単体テスト例(Jest想定)🧪
1021docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_01_messy_vs_clean.png./picture/firebase_security_role_ts_study_013_01_messy_vs_clean.pngTheme: Comparison of messy vs clean code structure.

Labels to Render:
- Bad: "コピペ地獄"
- Good: "関数化"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Code organization and safety.
2. Metaphor: Left side shows a tangled mess of wires or scattered papers (Chaos). Right side shows neatly organized, stacked boxes or a clean circuit board (Order).
3. Action: An arrow pointing from Left to Right indicating "Refactoring".
4. Layout: Split composition. Left (Chaotic/Red tint), Right (Clean/Blue tint).
]
Rulesは条件(true/false)で守る世界なので、読みやすさ=安全性に直結します✅ ([Firebase][1])
1022docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_02_copy_paste_leak.png./picture/firebase_security_role_ts_study_013_02_copy_paste_leak.pngTheme: Security risk from copy-paste errors.

Labels to Render:
- Copy: "コピー"
- Leak: "修正漏れ"
- Hole: "脆弱性"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Inconsistency leading to security holes.
2. Metaphor: A wall made of identical bricks (Rules). One brick is missing or cracked, letting water/light leak through.
3. Action: Ten identical items are lined up, but one is highlighted as defective/missing a lock.
4. Layout: Row of items, focus on the defective one.
]
* 1か所だけ修正漏れ → そこが穴になる😱
1023docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_03_function_constraints.png./picture/firebase_security_role_ts_study_013_03_function_constraints.pngTheme: Constraints of Firestore Rules functions.

Labels to Render:
- Max 10: "変数10個"
- Max 20: "深さ20"
- No Loop: "再帰禁止"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Technical limits.
2. Metaphor: A small toolkit box (for let), a stop sign for "Recursion", and a stack of blocks limiting height (Stack depth).
3. Action: Display these constraints as icons or a dashboard.
4. Layout: Horizontal arrangement of 3-4 constraint icons.
]
つまり、関数は「小さく」「浅く」「質問っぽい名前(is~ / can~)」が安全です🙂✨
1024docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_04_function_building_blocks.png./picture/firebase_security_role_ts_study_013_04_function_building_blocks.pngTheme: Building a strong foundation with common functions.

Labels to Render:
- Base: "共通関数"
- Block 1: "isSignedIn"
- Block 2: "isOwner"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Modular code.
2. Metaphor: LEGO-like blocks being assembled to form a strong base structure.
3. Action: Blocks labeled isSignedIn, uid, isOwner are placed at the bottom, supporting the rest of the structure.
4. Layout: Pyramidal or foundational structure.
]
* isSignedIn() / uid() / isOwner() があるだけで、Rulesの可読性が一気に上がります📈✨
1025docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_05_readable_rules.png./picture/firebase_security_role_ts_study_013_05_readable_rules.pngTheme: Code that reads like natural language.

Labels to Render:
- Code: "allow read"
- Meaning: "読む"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Readability.
2. Metaphor: A pair of glasses looking at code. Through the lens, the code allow read: if isOwner transforms into clear text "Owner Only".
3. Action: Translation effect through a lens.
4. Layout: Focus on the code and the lens.
]
* allow read: if isOwner(...) みたいに 一瞬で意味が読める
1026docs/firebase_security_role_ts_study_013.mdfirebase_security_role_ts_study_013_06_ai_assistant.png./picture/firebase_security_role_ts_study_013_06_ai_assistant.pngTheme: AI assisting with security rules.

Labels to Render:
- AI: "Gemini"
- Task: "Rules作成"
- Human: "確認"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: AI-Human collaboration.
2. Metaphor: A robot (AI) handing a blueprint (Rules draft) to a human engineer. The human is holding a stamp marked "Check".
3. Action: Handover process.
4. Layout: Side view of AI and Human interaction.
]
## 4-1. Gemini CLI / Firebase拡張で「叩き台」を作る🧰
1027docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_01_rbac_terms.png./picture/firebase_security_role_ts_study_014_01_rbac_terms.pngTheme: Visual definition of RBAC terms.

Labels to Render:
- Role: "役割"
- Permission: "権限"
- Resource: "リソース"
- Boundary: "境界"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Key definitions for security design.
2. Metaphor: Role=ID Card/Person, Permission=Key, Resource=Treasure Chest, Boundary=Gate/Wall.
3. Action: Arranged as a diagram explaining the relationship.
4. Layout: Grid or flow layout.
]
ポイントはこれ👇
1028docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_02_risk_levels.png./picture/firebase_security_role_ts_study_014_02_risk_levels.pngTheme: Risk levels in operation.

Labels to Render:
- Low: "低"
- Mid: "中"
- High: "高"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Categorizing danger levels.
2. Metaphor: A gauge or thermometer. Low=Blue (Read), Mid=Yellow (Edit Self), High=Red/Fire (Delete/Admin).
3. Action: The gauge needle points to High/Red to emphasize importance.
4. Layout: Vertical or curved gauge.
]
* :他人のデータ変更 / 公開・削除 / 権限変更
1029docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_03_three_roles.png./picture/firebase_security_role_ts_study_014_03_three_roles.pngTheme: The three primary roles.

Labels to Render:
- User: "一般"
- Editor: "運用"
- Admin: "管理者"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Simplified role structure.
2. Metaphor: Three distinct avatars. User=Friendly face, Editor=Holding a pen/clipboard, Admin=Wearing a crown.
3. Action: Standing side by side.
4. Layout: Horizontal lineup.
]
* admin(管理者)👑
1030docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_04_role_matrix.png./picture/firebase_security_role_ts_study_014_04_role_matrix.pngTheme: Access Control Matrix.

Labels to Render:
- Row: "操作"
- Col: "ロール"
- Check: "OK"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Mapping roles to permissions.
2. Metaphor: A grid/spreadsheet. Rows are actions, Columns are roles. Cells have Green Checks or Red Crosses.
3. Action: Highlighting the clear distinction between columns.
4. Layout: Grid view.
]
1031docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_05_role_meaning_anchor.png./picture/firebase_security_role_ts_study_014_05_role_meaning_anchor.pngTheme: Fixing the meaning of roles.

Labels to Render:
- Admin: "権限管理"
- Fixed: "固定"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Immutability of role definitions.
2. Metaphor: An anchor or a heavy lock securing a document labeled "Role Definition".
3. Action: Chains or heavy weight keeping it in place.
4. Layout: Centered heavy object.
]
この「意味の固定」ができたら、Rulesに落とすのが楽になります✅
1032docs/firebase_security_role_ts_study_014.mdfirebase_security_role_ts_study_014_06_token_vs_rules.png./picture/firebase_security_role_ts_study_014_06_token_vs_rules.pngTheme: Location of role data vs enforcement.

Labels to Render:
- Token: "認証トークン"
- Rules: "セキュリティルール"
- Match: "判定"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Authentication vs Authorization.
2. Metaphor: Left: A passport/ticket (Token) with a stamp "Admin". Right: A gatekeeper (Rules) checking the passport.
3. Action: An arrow from Token to Rules.
4. Layout: Left to Right flow.
]
> なので、第14章は「ロールの意味を決める章」
1033docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_01_custom_claims_concept.png./picture/firebase_security_role_ts_study_015_01_custom_claims_concept.pngTheme: Concept of Custom Claims.

Labels to Render:
- ID Token: "IDトークン"
- Stamp: "admin: true"
- Gate: "Rules"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Adding authority to identity.
2. Metaphor: A user holding an ID card. A stamp marked "Admin" is pressed onto it. A gatekeeper checks the stamp and opens the gate.
3. Action: Stamping and Verification flow.
4. Layout: Left to Right flow.
]
Rules側での参照はこんな感じ👇
1034docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_02_client_vs_server.png./picture/firebase_security_role_ts_study_015_02_client_vs_server.pngTheme: Where to apply Custom Claims.

Labels to Render:
- Browser: "クライアント"
- Server: "サーバー (Admin SDK)"
- Result: "OK/NG"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Security restriction on claims.
2. Metaphor: Browser tries to stamp the ID card -> Red X (Fail). Server tries to stamp -> Green Check (Success).
3. Action: Contrast between authorized and unauthorized actions.
4. Layout: Split screen or comparison.
]
つまり、Reactアプリ(ブラウザ)にAdmin SDKを入れて付与みたいなのはNG🙅‍♂️(危険すぎ) ([Firebase][2])
1035docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_03_token_refresh.png./picture/firebase_security_role_ts_study_015_03_token_refresh.pngTheme: The necessity of Token Refresh.

Labels to Render:
- Old: "古いトークン"
- Refresh: "更新"
- New: "新しいトークン"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Data propagation delay.
2. Metaphor: Old token (gray, no stamp) goes into a recycle bin/refresh icon and comes out as New token (shiny, with stamp).
3. Action: Transformation/Update process.
4. Layout: Flow arrow.
]
なので付与直後は、ユーザー側で トークンの強制更新が必要になることが多いです(後で手を動かします) ([Firebase][2])
1036docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_04_size_limit.png./picture/firebase_security_role_ts_study_015_04_size_limit.pngTheme: 1000 Byte Limit on Claims.

Labels to Render:
- Limit: "1000 Byte"
- Data: "プロフィール"
- Flag: "フラグ"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Capacity constraint.
2. Metaphor: A small mailbox (Claims). A large package (Profile data) cannot fit (Red X). A small postcard/letter (Admin Flag) fits perfectly (Green Check).
3. Action: Trying to insert items.
4. Layout: Comparison.
]
「admin: true」みたいな 小さいフラグ向き! ([Firebase][2])
1037docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_06_common_accidents.png./picture/firebase_security_role_ts_study_015_06_common_accidents.pngTheme: Common pitfalls with Custom Claims.

Labels to Render:
- Refresh: "更新忘れ"
- Size: "サイズ超過"
- Name: "名前衝突"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Hazard warning.
2. Metaphor: Three warning road signs. 1. Circular arrow with line through it (No Refresh). 2. Weight limit sign (Overload). 3. Restricted area sign (Reserved Names).
3. Action: Static warning signs.
4. Layout: Horizontal arrangement.
]
## 5) よくある事故パターン集😂💥(先に踏んでおこう)
1038docs/firebase_security_role_ts_study_015.mdfirebase_security_role_ts_study_015_06_common_accidents.png./picture/firebase_security_role_ts_study_015_06_common_accidents.pngTheme: Common pitfalls with Custom Claims.

Labels to Render:
- Refresh: "更新忘れ"
- Size: "サイズ超過"
- Name: "名前衝突"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Hazard warning.
2. Metaphor: Three warning road signs. 1. Circular arrow with line through it (No Refresh). 2. Weight limit sign (Overload). 3. Restricted area sign (Reserved Names).
3. Action: Static warning signs.
4. Layout: Horizontal arrangement.
]
## 5) よくある事故パターン集😂💥(先に踏んでおこう)
1039docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_01_rbac_royal.png./picture/firebase_security_role_ts_study_016_01_rbac_royal.pngTheme: RBAC Concept with Royalty Metaphor.

Labels to Render:
- Admin: "王様 (Admin)"
- User: "市民 (User)"
- Gate: "Rules"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Authority-based access.
2. Metaphor: A King with a Crown ticket and a Citizen with a plain ticket approaching a Castle Gate. The Gatekeeper lets the King pass everywhere.
3. Action: Gatekeeper checking tickets.
4. Layout: Side view of the gate.
]
(サーバー側で“役割”を確定させるからね)
1040docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_02_claims_weight.png./picture/firebase_security_role_ts_study_016_02_claims_weight.pngTheme: Appropriate data for Claims.

Labels to Render:
- Claims: "権限 (Light)"
- DB: "情報 (Heavy)"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Data size and usage separation.
2. Metaphor: A balance scale. One side has a small key (Permissions/Claims) which is light. The other side has a heavy scroll/book (Profile/DB) which is heavy.
3. Action: Weighing the data types.
4. Layout: Centered balance scale.
]
「プロフィール」みたいな頻繁に変わる情報は DBに置くのが正解🧺(claimsは“権限”専用)
1041docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_03_roadmap.png./picture/firebase_security_role_ts_study_016_03_roadmap.pngTheme: Implementation Roadmap.

Labels to Render:
- 1: "Admin化"
- 2: "Func"
- 3: "Rules"
- 4: "UI"
- 5: "Test"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Step-by-step implementation guide.
2. Metaphor: A path with 5 milestones. 1. Crown, 2. Gear, 3. Shield, 4. Screen, 5. Beaker.
3. Action: Progression from start to finish.
4. Layout: S-shaped path or linear steps.
]
5. Emulatorで admin/user/未ログインをテスト 🧪
1042docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_04_set_admin_flow.png./picture/firebase_security_role_ts_study_016_04_set_admin_flow.pngTheme: Flowchart of setAdmin function.

Labels to Render:
- Call: "呼び出し"
- Check: "Admin?"
- Action: "付与"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Logic flow for security check.
2. Metaphor: A flowchart. Start -> Decision Diamond (Is Caller Admin?) -> Yes Path (Grant Claim) -> No Path (Error/Stop).
3. Action: Logical progression.
4. Layout: Top to bottom flowchart.
]
> なので、こういうFunctions経由が王道だよ🙂✨
1043docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_05_rules_gate.png./picture/firebase_security_role_ts_study_016_05_rules_gate.pngTheme: Rules Logic Gate.

Labels to Render:
- Logic: "OR"
- Owner: "本人"
- Admin: "管理者"
- Access: "許可"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Multiple conditions for access.
2. Metaphor: A double-lock gate. Key 1 (Owner) opens it. Key 2 (Admin) also opens it. If either key is present, the gate opens.
3. Action: Unlocking mechanism.
4. Layout: Diagram of the gate and keys.
]
クライアントでURLを書き換えて他人の {uid} を読もうとしても、Rulesが門番して落とす🚪🛡️
1044docs/firebase_security_role_ts_study_016.mdfirebase_security_role_ts_study_016_06_testing_tubes.png./picture/firebase_security_role_ts_study_016_06_testing_tubes.pngTheme: Testing RBAC scenarios.

Labels to Render:
- Anon: "未ログイン"
- User: "一般"
- Admin: "管理者"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Verification of different roles.
2. Metaphor: Three test tubes in a rack. Tube 1 (Anon) is Red (Fail). Tube 2 (User) is Yellow (Restricted). Tube 3 (Admin) is Green (Full Access).
3. Action: Static comparison.
4. Layout: Horizontal rack.
]
await assertSucceeds(setDoc(doc(admin.firestore(), "adminOnlyLogs/log1"), { x: 1 }));
1045docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_01_firestore_vs_claims.png./picture/firebase_security_role_ts_study_017_01_firestore_vs_claims.pngTheme: Comparison of Firestore Roles vs Custom Claims.

Labels to Render:
- Firestore: "頻繁な変更/詳細"
- Claims: "全体/固定"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Choosing the right tool.
2. Metaphor: A scale. Left side (Firestore) holds a stack of changing papers (Dynamic). Right side (Claims) holds a heavy golden key (Static/Global).
3. Action: Balancing the two approaches.
4. Layout: Centered comparison.
]
一方で、**「管理者 / 一般ユーザー」みたいな“全体ロール”**は、Custom Claimsの方が堅くて軽いことが多いです🎫🔐 ([Firebase][1])
1046docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_02_pattern_a.png./picture/firebase_security_role_ts_study_017_02_pattern_a.pngTheme: Pattern A: Roles Document.

Labels to Render:
- Collection: "roles"
- Doc: "{uid}"
- Field: "admin: true"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: User-specific role document.
2. Metaphor: A file cabinet labeled "roles". Inside, a folder for a specific User ID containing a paper that says "Admin: True".
3. Action: Static structure visualization.
4. Layout: Directory structure.
]
* 👎 Rulesの中で get() / exists() 参照が増えがち(=コスト&制限に影響)([Firebase][2])
1047docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_03_pattern_b.png./picture/firebase_security_role_ts_study_017_03_pattern_b.pngTheme: Pattern B: Project Membership.

Labels to Render:
- Project: "Projects/p1"
- Members: "Members"
- User: "{uid}"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Resource-scoped roles.
2. Metaphor: A project folder containing a sub-folder named "Members". A user icon is placed inside the Members folder.
3. Action: Inclusion relationship.
4. Layout: Nested folders.
]
* 👎 設計を雑にすると「membersを書き換えて昇格😱」が起きる
1048docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_04_landmine_client.png./picture/firebase_security_role_ts_study_017_04_landmine_client.pngTheme: Danger of Client-side Role Writing.

Labels to Render:
- Client: "ユーザー"
- DB: "Roles"
- Action: "書き込み"
- Result: "禁止"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Security prohibition.
2. Metaphor: A user holding a pen trying to write "Admin" into the Database. A large red "NO" or "ACCESS DENIED" stamp blocks the hand.
3. Action: Blocking an unauthorized write.
4. Layout: Action scene.
]
Rulesで「rolesは誰も書けない」または「管理者だけ」みたいに固定します。
1049docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_05_landmine_cost.png./picture/firebase_security_role_ts_study_017_05_landmine_cost.pngTheme: Cost of Rules Read Operations.

Labels to Render:
- Op: "get() / exists()"
- Cost: "課金"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Hidden costs in logic.
2. Metaphor: A cash register or meter. Every time the function get() is executed, a coin drops into the slot or the meter counter goes up.
3. Action: Counting cost.
4. Layout: Machine close-up.
]
Rules内で get() / exists() / getAfter() を使うと、Rules評価のための追加Readが発生します(拒否されても発生し得る)😱 ([Firebase][2])
1050docs/firebase_security_role_ts_study_017.mdfirebase_security_role_ts_study_017_06_rules_logic.png./picture/firebase_security_role_ts_study_017_06_rules_logic.pngTheme: Logic of isAdmin function.

Labels to Render:
- 1: "Login?"
- 2: "Exists?"
- 3: "Admin?"
- Result: "OK"

Visual Details:
[CRITICAL: Describe WHAT to draw.
1. Core Concept: Sequential logic checks.
2. Metaphor: A logic circuit with 3 AND gates. 1. Is Signed In? -> 2. Does Doc Exist? -> 3. Is Admin Field True? -> Output: Green Light.
3. Action: Flow of verification.
4. Layout: Circuit diagram or flow.
]
exists() / get() は追加Readになり得る&回数制限もあるので、「isAdmin() を1回で済む形」に寄せるのが大事です💡 ([Firebase][2])
1051docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_01_read_write_trap.png./picture/firebase_security_role_ts_study_018_01_read_write_trap.pngTheme: Read and Write Granularity Trap

Labels to Render:
- Read: "get (1 item) + list (all)"
- Write: "create + update + delete"
- Trap: "Too Wide!"

Visual Details:
1. Core Concept: allow read opens up both get and list. allow write opens up create, update, and delete.
2. Metaphor: Two large doors labeled "Read" and "Write". Behind "Read", a small drawer (get) and a huge archive room (list) are both exposed. Behind "Write", three different control panels (create, update, delete) are accessible.
3. Action: Opening the doors reveals too much.
4. Layout: Two main sections (Read/Write) expanding into their components.
## 0) まず“事故の共通原因”だけ押さえる🧠💡
1052docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_02_open_house.png./picture/firebase_security_role_ts_study_018_02_open_house.pngTheme: Security Rule "if true"

Labels to Render:
- Rule: "allow read, write: if true"
- House: "My App"
- Stranger: "Anyone"

Visual Details:
1. Core Concept: if true allows anyone to access the data.
2. Metaphor: A house with all windows and doors wide open. Strangers are walking in freely.
3. Action: Strangers entering.
4. Layout: House view.
## 事故①:allow read, write: if true;(全開放)🚪💥
1053docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_03_owner_swap.png./picture/firebase_security_role_ts_study_018_03_owner_swap.pngTheme: Owner ID Swap Attack

Labels to Render:
- Attacker: "User B"
- Data: "ownerId: 'User A'"
- Update: "Change to 'User B'"
- Result: "Stolen!"

Visual Details:
1. Core Concept: An attacker changing the ownership field to themselves during an update.
2. Metaphor: A thief peeling off a name tag "User A" from a box and sticking their own name tag "User B" on it.
3. Action: Peeling/Sticking.
4. Layout: Close up of the label swap.
## 事故③:update で「所有者すり替え」🎭🪤
1054docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_04_admin_bypass.png./picture/firebase_security_role_ts_study_018_04_admin_bypass.pngTheme: Admin SDK Bypass

Labels to Render:
- Wall: "Security Rules"
- User: "Blocked"
- Admin SDK: "Bypass (Fly Over)"

Visual Details:
1. Core Concept: Admin SDK ignores security rules.
2. Metaphor: A brick wall blocking normal users. A drone or plane labeled "Admin SDK" flying over the wall effortlessly.
3. Action: Flying over.
4. Layout: Wall with ground and sky.
## 事故⑤:「サーバーはRulesで守られてる」勘違い🧯🤯
1055docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_05_cli_overwrite.png./picture/firebase_security_role_ts_study_018_05_cli_overwrite.pngTheme: CLI Overwriting Console Edits

Labels to Render:
- Console: "Manual Edit (Flower)"
- CLI: "Deploy (Bulldozer)"
- Result: "Crushed"

Visual Details:
1. Core Concept: Local deployment overwrites manual changes made in the console.
2. Metaphor: A small flower (Console Edit) growing on the ground. A bulldozer (CLI Deploy) rolling over it, crushing it.
3. Action: Crushing.
4. Layout: Side view of bulldozer.
## 事故⑥:「Consoleで直したのに、CLIデプロイで戻る」🔁😵
1056docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_06_function_stamp.png./picture/firebase_security_role_ts_study_018_06_function_stamp.pngTheme: Helper Functions in Rules

Labels to Render:
- Function: "signedIn()"
- Code: "if signedIn()"
- Stamp: "Reuse Logic"

Visual Details:
1. Core Concept: Reusing logic with functions.
2. Metaphor: A rubber stamp labeled signedIn() being pressed onto multiple lines of a document (Rules), leaving a clean mark.
3. Action: Stamping.
4. Layout: Document view.
## 3-1) 署名系の関数(読みやすさUP)🙂
1057docs/firebase_security_role_ts_study_018.mdfirebase_security_role_ts_study_018_07_ai_detective.png./picture/firebase_security_role_ts_study_018_07_ai_detective.pngTheme: AI Security Detective

Labels to Render:
- AI: "Gemini / Antigravity"
- Code: "Rules"
- Found: "Bug!"

Visual Details:
1. Core Concept: AI finding security flaws.
2. Metaphor: A robot detective with a magnifying glass examining a blueprint (Rules) and pointing to a red X (Bug).
3. Action: Detecting.
4. Layout: Detective scene.
## 5) AIで“事故を見つける速度”を爆上げする🤖⚡(でも最後は人間チェック✅)
1058docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_01_tdd_traffic_light.png./picture/firebase_security_role_ts_study_019_01_tdd_traffic_light.pngTheme: TDD Workflow for Rules

Labels to Render:
- Start: "Red (Fail) 🛑"
- Edit: "Fix Rules 🛠️"
- Goal: "Green (Pass) ✅"

Visual Details:
1. Core Concept: Writing failing tests first, then fixing rules to make them pass.
2. Metaphor: A traffic light sequence. Red light -> Mechanic fixing it -> Green light.
3. Action: Transition from Red to Green.
4. Layout: Sequence.
## 1) 今日の流れ(最短ルート)🗺️
1059docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_02_json_connection.png./picture/firebase_security_role_ts_study_019_02_json_connection.pngTheme: firebase.json Rules Connection

Labels to Render:
- Config: "firebase.json"
- File: "firestore.rules"
- Result: "Connected 🔗"
- Warning: "Unlinked = Open! ⚠️"

Visual Details:
1. Core Concept: Linking the rules file in the configuration is crucial.
2. Metaphor: A cable connecting a control box (firebase.json) to a security gate (firestore.rules). If disconnected, the gate stays open.
3. Action: Connecting.
4. Layout: Connection diagram.
## 2-1. firebase.json に Rules ファイルを必ず紐づける⚠️
1060docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_03_clean_lab.png./picture/firebase_security_role_ts_study_019_03_clean_lab.pngTheme: Clean Test Environment

Labels to Render:
- Step 1: "clearFirestore() 🧼"
- Step 2: "withSecurityRulesDisabled 🔓"
- Step 3: "Setup Data 📦"

Visual Details:
1. Core Concept: Preparing the database before tests.
2. Metaphor: A scientist wiping a lab bench clean, then putting on special gloves to arrange the test samples.
3. Action: Cleaning/Arranging.
4. Layout: Lab sequence.
## 4) テストを書く(通る✅/弾く❌ をペアで)🧪✨
1061docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_04_assert_pair.png./picture/firebase_security_role_ts_study_019_04_assert_pair.pngTheme: Assert Succeeds/Fails Pair

Labels to Render:
- Test 1: "Authorized ✅"
- Check: "assertSucceeds"
- Test 2: "Unauthorized ❌"
- Check: "assertFails"

Visual Details:
1. Core Concept: Tests must check both positive and negative cases.
2. Metaphor: A coin with two sides. One side says "Pass", the other "Block". Both are needed for currency.
3. Action: Flipping/Showing both sides.
4. Layout: Comparison.
it("未ログインは公開だけ読める✅", async () => {
1062docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_05_exec_pipeline.png./picture/firebase_security_role_ts_study_019_05_exec_pipeline.pngTheme: emulators:exec Pipeline

Labels to Render:
- Command: "emulators:exec"
- Start: "Emulator 🚀"
- Run: "npm test 🧪"
- Stop: "Shutdown 🛑"

Visual Details:
1. Core Concept: One command handling the lifecycle.
2. Metaphor: A seamless conveyor belt. A box enters, gets stamped (tested), and exits automatically.
3. Action: Processing.
4. Layout: Pipeline flow.
## 5) 実行する🏃‍♂️💨(毎回安全に:emulators:exec 推奨)
1063docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_06_sleeping_guard.png./picture/firebase_security_role_ts_study_019_06_sleeping_guard.pngTheme: False Positive Trap

Labels to Render:
- Status: "Tests Passed ✅"
- Reality: "Rules Ignored 😱"
- Cause: "Bad Config"

Visual Details:
1. Core Concept: Tests passing because the rules aren't loaded.
2. Metaphor: A security guard sleeping while people walk past. The counter says "0 Incidents" (Passed), but the reality is "Unsafe".
3. Action: Sleeping.
4. Layout: Irony scene.
## 落とし穴A:テストが全部通るのに、なんか怖い…
1064docs/firebase_security_role_ts_study_019.mdfirebase_security_role_ts_study_019_07_ai_draft.png./picture/firebase_security_role_ts_study_019_07_ai_draft.pngTheme: AI Drafting Rules

Labels to Render:
- AI: "Gemini"
- Output: "Draft Rules 📄"
- Output: "Draft Tests 🧪"
- Human: "Review & Fix 🛠️"

Visual Details:
1. Core Concept: AI generating the starting point.
2. Metaphor: A robot printer churning out a blueprint and a checklist. A human engineer picks them up to refine.
3. Action: Printing/Reviewing.
4. Layout: Production line.
## 7-1. Gemini CLI:Rulesとテストを“自動で叩き台生成”🧠⚡
1065docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_01_ai_vs_human.png./picture/firebase_security_role_ts_study_020_01_ai_vs_human.pngTheme: AI vs Human Roles

Labels to Render:
- AI: "Drafting 🏗️"
- Human: "Safety Check 🛡️"
- Goal: "Secure App"

Visual Details:
1. Core Concept: AI builds the structure, Human ensures it's safe.
2. Metaphor: A robot building a house frame. A human inspector checking the foundation and wearing a safety helmet.
3. Action: Collaboration.
4. Layout: Side-by-side.
## 1) まず大事な前提:AIが得意なこと/苦手なこと 🤝😵‍💫
1066docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_02_ingredients.png./picture/firebase_security_role_ts_study_020_02_ingredients.pngTheme: Inputs for AI

Labels to Render:
- List 1: "Collections 🗂️"
- List 2: "Roles 🎭"
- List 3: "Operations 📝"
- Pot: "AI Context"

Visual Details:
1. Core Concept: Preparing structured information for the AI.
2. Metaphor: A chef (User) putting specific ingredients (Lists) into a pot (AI).
3. Action: Cooking/Preparing.
4. Layout: Ingredients going into a container.
## 2) AIに渡す“材料”を用意しよう 🧠📦(これが8割)
1067docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_03_prompt_card.png./picture/firebase_security_role_ts_study_020_03_prompt_card.pngTheme: Structured Prompt

Labels to Render:
- Card: "Prompt"
- Section 1: "Role Definition"
- Section 2: "Constraints"
- AI: "Gemini"

Visual Details:
1. Core Concept: A well-defined prompt yields better results.
2. Metaphor: Inserting a punched card or detailed instruction sheet into a computer.
3. Action: Inputting.
4. Layout: Close-up of the prompt structure.
## 3) Gemini CLI(Firebase拡張)で叩き台を作る 🧰🤖
1068docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_04_checklist_review.png./picture/firebase_security_role_ts_study_020_04_checklist_review.pngTheme: Review Checklist

Labels to Render:
- Check 1: "No 'if true' 🚫"
- Check 2: "List Closed 🔒"
- Check 3: "Update Limit 🧱"
- Inspector: "Human"

Visual Details:
1. Core Concept: Critical checks for AI-generated rules.
2. Metaphor: An inspector holding a clipboard with red ink, marking a blueprint.
3. Action: Reviewing.
4. Layout: Over-the-shoulder view.
## 5) 人間レビューの“鉄板チェックリスト” ✅🧑‍⚖️
1069docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_05_test_chamber.png./picture/firebase_security_role_ts_study_020_05_test_chamber.pngTheme: Testing AI Rules

Labels to Render:
- Robot: "AI Rules"
- Test: "Unit Tests"
- Result: "Pass ✅ / Fail ❌"

Visual Details:
1. Core Concept: Validating AI output with tests.
2. Metaphor: A robot running an obstacle course (Tests). If it hits a wall, it fails.
3. Action: Testing.
4. Layout: Obstacle course.
## 6) “AIのRules”をテストで縛る 🧪🔒(ここが本番)
1070docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_06_token_refresh.png./picture/firebase_security_role_ts_study_020_06_token_refresh.pngTheme: Token Refresh Delay

Labels to Render:
- Admin: "Grant Role"
- Client: "Old Token (User)"
- Action: "Refresh!"
- Result: "New Token (Admin)"

Visual Details:
1. Core Concept: The need to refresh the token to see new claims.
2. Metaphor: An ID card reader showing "Access Denied" until the user swipes their card at a "Update Station".
3. Action: Updating.
4. Layout: Time sequence.
## 7) Custom Claims(adminフラグ)をRulesで読むときの注意 🎫⚠️
1071docs/firebase_security_role_ts_study_020.mdfirebase_security_role_ts_study_020_07_human_deploy.png./picture/firebase_security_role_ts_study_020_07_human_deploy.pngTheme: Human Deployment Safety

Labels to Render:
- Button: "Deploy to Prod"
- Guard: "Human Only 🛑"
- AI: "No Access"

Visual Details:
1. Core Concept: Preventing AI from deploying to production automatically.
2. Metaphor: A big red launch button protected by a glass case. Only a human hand can lift the case.
3. Action: Protecting.
4. Layout: Control panel.
## 8) ついでに:AIを使う開発の“安全運用”も決めよう 🔐🤖
1072docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_01_black_box.png./picture/firebase_security_role_ts_study_021_01_black_box.pngTheme: Admin Only Collection

Labels to Render:
- Collection: "adminOnlyLogs"
- User: "Invisible 🙈"
- Admin: "Visible 👁️"
- Content: "Audit Log"

Visual Details:
1. Core Concept: A collection that is invisible to normal users.
2. Metaphor: A black box or stealth plane. It's invisible to the "User" radar, but the "Admin" radar sees it clearly.
3. Action: Hiding/Revealing.
4. Layout: Radar screen comparison.
## 1) 今日作る完成品(仕様)🎯
1073docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_02_ai_draft.png./picture/firebase_security_role_ts_study_021_02_ai_draft.pngTheme: AI Drafting Rules

Labels to Render:
- Input: "Prompt"
- AI: "Gemini"
- Output: "Rules Draft 📄"
- Note: "Human Review Required"

Visual Details:
1. Core Concept: AI generating the initial code.
2. Metaphor: A 3D printer (AI) creating a prototype model (Rules) based on a sketch (Prompt).
3. Action: Printing.
4. Layout: Creation process.
## 2) AIを先に味方につける(叩き台づくり)🤖⚡
1074docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_03_admin_gate.png./picture/firebase_security_role_ts_study_021_03_admin_gate.pngTheme: Admin Gatekeeper

Labels to Render:
- Gate: "Security Rules"
- Check: "isAdmin()"
- Pass: "King 👑"
- Block: "Citizen 🧍"

Visual Details:
1. Core Concept: Only admins pass the gate.
2. Metaphor: A golden gate that opens only for someone wearing a crown.
3. Action: Opening/Closing.
4. Layout: Gate interaction.
## 3) 実装パート:Rulesを書こう!🛡️✍️
1075docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_04_emulator_config.png./picture/firebase_security_role_ts_study_021_04_emulator_config.pngTheme: Emulator Configuration

Labels to Render:
- File: "firebase.json"
- Port: "8080"
- Connection: "Rules File"
- Emulator: "Running 🏃"

Visual Details:
1. Core Concept: Setting up the emulator.
2. Metaphor: Connecting wires on a patch panel to route the signal correctly.
3. Action: Patching.
4. Layout: Wiring diagram.
## 4) Emulator準備:firebase.json(Rules読み込み設定)🧪⚙️
1076docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_05_role_masks.png./picture/firebase_security_role_ts_study_021_05_role_masks.pngTheme: Role Testing

Labels to Render:
- Test: "Unit Test"
- Role 1: "Admin (Crown)"
- Role 2: "User (Hat)"
- Role 3: "Anon (Mask)"

Visual Details:
1. Core Concept: Testing with different user roles.
2. Metaphor: A testing robot putting on different hats/masks to test the system response.
3. Action: Changing hats.
4. Layout: Character variation.
## 5) テストが本体:Rules単体テストを書く🧪✅❌
1077docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_06_test_run.png./picture/firebase_security_role_ts_study_021_06_test_run.pngTheme: Test Execution

Labels to Render:
- Command: "npm run test:emu"
- Screen: "All Green ✅"
- Bug: "Caught 🪤"

Visual Details:
1. Core Concept: Running tests and catching bugs.
2. Metaphor: A screen showing a row of green lights. A bug is trapped in a net nearby.
3. Action: Success.
4. Layout: Dashboard view.
## 6) 実行:エミュレータ起動→テスト→自動終了🧪🚀
1078docs/firebase_security_role_ts_study_021.mdfirebase_security_role_ts_study_021_07_deploy_warning.png./picture/firebase_security_role_ts_study_021_07_deploy_warning.pngTheme: Deployment Overwrite Warning

Labels to Render:
- Local: "Repo (Master)"
- Cloud: "Console (Old)"
- Action: "Overwrite"
- Rule: "One Way"

Visual Details:
1. Core Concept: Local deployment replaces cloud version.
2. Metaphor: A large stamp "Repo" stamping over a paper "Console".
3. Action: Stamping/Overwriting.
4. Layout: Impact view.
## 7) デプロイ(本番反映)🔥⚠️
1457docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_01_read_breakdown.png./picture/firebase_security_role_ts_study_008_01_read_breakdown.pngTheme: Read Breakdown

Labels to Render:
- Box: "allow read"
- Item 1: "get (One) 📄"
- Item 2: "list (Many) 📚"

Visual Details:
1. Core Concept: 'read' is a container for both 'get' and 'list'.
2. Metaphor: A large box labeled 'read' containing two smaller packages.
3. Action: Containing.
4. Layout: Nested boxes.
## 1) まず結論:readgetlist のセット📦
1458docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_02_list_risk.png./picture/firebase_security_role_ts_study_008_02_list_risk.pngTheme: List Risk

Labels to Render:
- Attacker: "Script 👾"
- Action: "Dump All 🌪️"
- Collection: "DB 🗃️"

Visual Details:
1. Core Concept: The danger of allowing open list access.
2. Metaphor: A vacuum cleaner (Attacker) sucking up all documents from a collection.
3. Action: Sucking/Dumping.
4. Layout: Action scene.
## 2) “listが怖い”理由:一度開けると吸い出しが速い🚨💨
1459docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_03_get_vs_list.png./picture/firebase_security_role_ts_study_008_03_get_vs_list.pngTheme: Get vs List Code

Labels to Render:
- get: "getDoc(ID) 🤏"
- list: "getDocs(Collection) 👐"
- Result: "1 vs 100"

Visual Details:
1. Core Concept: The difference in scope between get and list.
2. Metaphor: Picking a single apple (get) vs harvesting the whole tree (list).
3. Action: Picking.
4. Layout: Side-by-side.
## 4) React側で“getとlistの違い”を手で確認🖐️⚡
1460docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_04_safe_list.png./picture/firebase_security_role_ts_study_008_04_safe_list.pngTheme: Safe List Strategy

Labels to Render:
- Filter: "published == true 🌍"
- Allowed: "Public Post ✅"
- Blocked: "Draft 🚫"

Visual Details:
1. Core Concept: Filtering list access to only public items.
2. Metaphor: A sieve or filter that lets 'Public' items pass but catches 'Draft' items.
3. Action: Filtering.
4. Layout: Process flow.
## 手札A:公開データだけ一覧OK(published == true)🌍📣
1461docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_05_rules_not_filters.png./picture/firebase_security_role_ts_study_008_05_rules_not_filters.pngTheme: Rules are Not Filters

Labels to Render:
- Query: "Give me ALL 📄"
- Rule: "Only Public! 🛡️"
- Result: "REJECT (Access Denied) 💥"

Visual Details:
1. Core Concept: Rules do not filter data; they reject invalid queries.
2. Metaphor: A gatekeeper rejecting a truck because it might contain contraband, rather than sorting through it.
3. Action: Rejecting.
4. Layout: Interaction.
## 7) “Rulesはフィルタじゃない”をもう一段だけ深掘り🧠💥
1462docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_06_emulator_test.png./picture/firebase_security_role_ts_study_008_06_emulator_test.pngTheme: Emulator Testing

Labels to Render:
- Lab: "Local Emulator 🧪"
- Test: "Try List Drafts"
- Result: "Blocked (Pass) ✅"

Visual Details:
1. Core Concept: Verifying security rules in a safe local environment.
2. Metaphor: A crash test dummy (Test) hitting a wall (Rule) in a lab. The scientist marks it as 'Success'.
3. Action: Testing.
4. Layout: Lab scene.
## 8) Emulatorでテスト(ここで“安心”を作る)🧪✅
1463docs/firebase_security_role_ts_study_008.mdfirebase_security_role_ts_study_008_07_ai_draft.png./picture/firebase_security_role_ts_study_008_07_ai_draft.pngTheme: AI Rules Draft

Labels to Render:
- Input: "Schema Structure 📄"
- AI: "Gemini 🤖"
- Output: "Rules Draft 📝"

Visual Details:
1. Core Concept: Using AI to generate a starting point for security rules.
2. Metaphor: A robot architect drafting a blueprint based on a sketch.
3. Action: Drafting.
4. Layout: Left-to-right flow.
## 9) AI活用:Rules&テストの叩き台を爆速で作る🤖⚡
1464docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_01_three_way_split.png./picture/firebase_security_role_ts_study_009_01_three_way_split.pngTheme: Three ways to write to Firestore (Create, Update, Delete) vs One big 'Write'

Labels to Render:
- Create: "新規作成"
- Update: "更新"
- Delete: "削除"
- Write: "書き込み(危険)"

Visual Details:
1. Show a large, dangerous looking gate labeled 'Write'.
2. Show three smaller, specific gates labeled 'Create', 'Update', 'Delete'.
3. Use a checkmark for the three separate gates and a warning sign for the single big gate.
After: ## 1) まず、ここだけ覚えればOKな結論✨
1465docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_02_risk_types.png./picture/firebase_security_role_ts_study_009_02_risk_types.pngTheme: Different risks for Create, Update, and Delete

Labels to Render:
- Create: "スパム・ゴミデータ"
- Update: "権限昇格・改ざん"
- Delete: "データ消失"

Visual Details:
1. Three icons representing the risks.
2. Create: A pile of junk mail or trash.
3. Update: A hacker changing a badge or ID card.
4. Delete: A file burning or disappearing into a black hole.
After: ## 理由A:操作ごとに“危険の種類”が違う💣
1466docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_03_data_visibility.png./picture/firebase_security_role_ts_study_009_03_data_visibility.pngTheme: Data visibility in Rules (resource.data vs request.resource.data)

Labels to Render:
- Existing Data: "resource.data (元データ)"
- Incoming Data: "request.resource.data (新データ)"
- Delete Operation: "削除操作"

Visual Details:
1. Create/Update: Show access to both 'Existing Data' and 'Incoming Data'.
2. Delete: Show access ONLY to 'Existing Data'.
3. 'Incoming Data' is crossed out or unavailable for Delete.
After: ## 理由B:見えるデータが違う(=検査できる範囲が違う)🔍
1467docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_04_doc_structure.png./picture/firebase_security_role_ts_study_009_04_doc_structure.pngTheme: Document structure for 'posts'

Labels to Render:
- Collection: "posts/{postId}"
- Fields: "uid, title, body, status, updatedAt"

Visual Details:
1. A document card visual.
2. Clearly list the fields with sample values (e.g., status: 'draft').
3. Use icons for user (uid), text (title/body), and clock (updatedAt).
After: ## サンプルのドキュメント構造(例)
1468docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_05_rules_logic.png./picture/firebase_security_role_ts_study_009_05_rules_logic.pngTheme: Security Rules Logic Flow

Labels to Render:
- Create: "自分のみ OK"
- Update: "自分のみ + 変更制限"
- Delete: "管理者のみ OK"

Visual Details:
1. Three distinct gates.
2. Create gate: User ID match check.
3. Update gate: User ID match + Diff check.
4. Delete gate: Admin badge check.
After: ## 4) ルール実装(create / update / delete を分ける)🧩🔐
1469docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_06_verification.png./picture/firebase_security_role_ts_study_009_06_verification.pngTheme: Verifying Rules behavior

Labels to Render:
- User: "一般ユーザー"
- Admin: "管理者"
- Action: "削除 (Delete)"

Visual Details:
1. User tries to delete -> Big Red X (Blocked).
2. Admin tries to delete -> Big Green Check (Allowed).
3. Visual representation of permission denied vs granted.
After: ## 5) 手を動かす(3分で “違い” を体感)🧑‍💻⚡
1470docs/firebase_security_role_ts_study_009.mdfirebase_security_role_ts_study_009_07_testing_arch.png./picture/firebase_security_role_ts_study_009_07_testing_arch.pngTheme: Testing Architecture with Emulator

Labels to Render:
- Tool: "Emulator Suite"
- Code: "Unit Tests"
- Result: "安全確認"

Visual Details:
1. A laptop showing code (Unit Tests) connected to a local server box (Emulator).
2. A shield appearing as the result of the test.
3. Arrows showing the flow from Code -> Emulator -> Verification.
After: ## 6) ルールをテストで固める(ここが一番大事)🧪🧯
1471docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_01_validation_basics.png./picture/firebase_security_role_ts_study_010_01_validation_basics.pngTheme: Three Pillars of Input Validation

Labels to Render:
- Required: "必須項目 (hasAll)"
- Allowed: "許可リスト (hasOnly)"
- Type: "型チェック (is string)"

Visual Details:
1. Three pillars supporting a roof labeled 'Security'.
2. Each pillar represents one validation type.
3. Clean, strong architectural metaphor.
After: ## 1) まずココだけ覚える!🎯(今日の武器🗡️)
1472docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_02_schemaless_risk.png./picture/firebase_security_role_ts_study_010_02_schemaless_risk.pngTheme: Schema-less Risk vs Rules Schema

Labels to Render:
- No Rules: "ルールなし (無法地帯)"
- With Rules: "ルールあり (秩序)"

Visual Details:
1. Left side: Chaos, mixed data types, garbage icons.
2. Right side: Neat, organized rows of data blocks.
3. A barrier (Rules) filtering the chaos into order.
After: Firestoreは“スキーマなし(何でも入る)”だから、Rulesで最低限のスキーマを作るのが超大事🔥 ([Firebase][1])
1473docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_03_data_structure.png./picture/firebase_security_role_ts_study_010_03_data_structure.pngTheme: Data Structure for aiNotes

Labels to Render:
- Note: "aiNotes/{noteId}"
- Fields: "prompt, answer, ownerUid, createdAt"

Visual Details:
1. A clean data card representing an AI note.
2. Icons for prompt (bubble), answer (robot), user (person), time (clock).
3. Highlight the specific fields.
After: ## 2) 例題:AIメモアプリの aiNotes を守る📝🤖
1474docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_04_bad_inputs.png./picture/firebase_security_role_ts_study_010_04_bad_inputs.pngTheme: Blocking Malicious Inputs

Labels to Render:
- Attack: "悪意ある入力"
- Blocked: "拒否"
- Example: "isAdmin: true"

Visual Details:
1. A red data packet labeled 'isAdmin: true' trying to enter.
2. A shield blocking it.
3. Sparks or 'X' mark showing rejection.
After: ここで入力検証を入れないと、悪意ある人が👇みたいな“混入”を狙える😱
1475docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_05_rules_functions.png./picture/firebase_security_role_ts_study_010_05_rules_functions.pngTheme: Modular Rule Functions

Labels to Render:
- Function 1: "hasRequiredFields"
- Function 2: "hasOnlyAllowedFields"
- Function 3: "hasValidTypes"

Visual Details:
1. Three puzzle pieces or building blocks connecting together.
2. Each block represents a validation function.
3. Together they form a 'Safe Create' block.
After: ## 3-2. firestore.rules サンプル🛡️✨
1476docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_06_test_scenarios.png./picture/firebase_security_role_ts_study_010_06_test_scenarios.pngTheme: Failing Test Scenarios

Labels to Render:
- Missing Field: "必須不足"
- Wrong Type: "型ミス"
- Extra Field: "余計な混入"

Visual Details:
1. Three test tubes or indicators turning red.
2. Visual representation of each error type (e.g., missing piece, square peg in round hole, extra piece).
3. All leading to a 'Rejected' status.
After: ## 4) 手を動かす(3分でOK)🧪✨
1477docs/firebase_security_role_ts_study_010.mdfirebase_security_role_ts_study_010_07_ai_workflow.png./picture/firebase_security_role_ts_study_010_07_ai_workflow.pngTheme: AI Workflow with Gemini CLI

Labels to Render:
- User: "開発者"
- Tool: "Gemini CLI"
- Output: "Rules + Tests"

Visual Details:
1. User typing into a terminal.
2. Gemini sparkle icon processing.
3. Output documents (Rules file and Test file) appearing.
After: ## 7-1. Gemini CLIで「Rules+テストの叩き台」を作る🚀
1478docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_01_string_bomb.png./picture/firebase_security_role_ts_study_011_01_string_bomb.pngTheme: User Input as a 'Bomb'

Labels to Render:
- Input: "ユーザー入力"
- Danger: "地雷 (長文/不正文字)"
- Solution: "Rulesで無効化"

Visual Details:
1. A round bomb with a fuse representing 'User Input'.
2. A pair of scissors labeled 'Rules' cutting the fuse.
3. The bomb is labeled with text symbols.
After: ## 1) なぜ文字数とパターンが“地雷”なの?💣😇
1479docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_02_risk_scenarios.png./picture/firebase_security_role_ts_study_011_02_risk_scenarios.pngTheme: Risks of Unvalidated Strings

Labels to Render:
- UI Break: "画面崩壊"
- Pollution: "データ汚染"
- Trouble: "運用トラブル"

Visual Details:
1. Three panels.
2. Panel 1: Phone screen breaking due to long text.
3. Panel 2: A list with empty/blank items.
4. Panel 3: A confused operator looking at weird symbols.
After: たとえば👇
1480docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_03_rules_weapons.png./picture/firebase_security_role_ts_study_011_03_rules_weapons.pngTheme: The Three Weapons of String Validation

Labels to Render:
- size(): "文字数チェック"
- trim(): "空白削除"
- matches(): "パターン一致"

Visual Details:
1. Three icons/tools.
2. Ruler for size().
3. Scissors or Trimmers for trim().
4. A matching puzzle piece or stamp for matches().
After: ## 2) Rulesで使う“武器”🗡️(今日の主役)
1481docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_04_profile_fields.png./picture/firebase_security_role_ts_study_011_04_profile_fields.pngTheme: User Profile Fields

Labels to Render:
- Display Name: "表示名 (自由)"
- Handle: "ID (厳格)"
- Bio: "自己紹介 (文字数制限)"

Visual Details:
1. A profile card layout.
2. Display Name area showing Japanese text.
3. Handle area showing English/Numbers only.
4. Bio area showing a short paragraph.
After: ## 3) 例題:プロフィール更新を安全にする🧑‍💻✨
1482docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_05_validation_logic.png./picture/firebase_security_role_ts_study_011_05_validation_logic.pngTheme: Validation Logic Flow

Labels to Render:
- Input: "入力データ"
- Check 1: "型 (String?)"
- Check 2: "空白 (Trim)"
- Check 3: "文字数 (Size)"

Visual Details:
1. A pipeline or flowchart.
2. Data enters on left.
3. Passes through 3 checkpoints.
4. If any fail, it goes to trash (Reject). If all pass, it goes to DB (Save).
After: ## ステップA:検証用の関数を作る(読みやすさUP✨)
1483docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_06_good_bad_examples.png./picture/firebase_security_role_ts_study_011_06_good_bad_examples.pngTheme: Good vs Bad Input Examples

Labels to Render:
- Good: "OK"
- Bad: "NG"
- Examples: "komiyamma vs User_123"

Visual Details:
1. Split screen.
2. Green side with checkmarks for valid inputs.
3. Red side with crosses for invalid inputs (Caps, Symbols, Too short).
After: ## ステップB:通る例✅ / 弾かれる例❌ をイメージする🧠
1484docs/firebase_security_role_ts_study_011.mdfirebase_security_role_ts_study_011_07_defense_layers.png./picture/firebase_security_role_ts_study_011_07_defense_layers.pngTheme: Layers of Defense

Labels to Render:
- Client: "クライアント (UX)"
- Rules: "Rules (本番防御)"
- Server: "AI Logic (高度な判定)"

Visual Details:
1. Three walls or shields.
2. Client is the first, thin wall.
3. Rules is the main, thick fortress wall.
4. Server is the intelligent tower behind the walls.
After: ## 8) Firebase AI Logic と組み合わせる(“追加の安全装置”)🧠🧯
1485docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_01_hidden_fields.png./picture/firebase_security_role_ts_study_012_01_hidden_fields.pngTheme: Hidden Fields Attack

Labels to Render:
- Visible: "画面の入力 (名前, etc)"
- Hidden: "隠しデータ (role: admin)"
- Attack: "改造リクエスト"

Visual Details:
1. A normal looking envelope (request) but with a hidden dagger or device inside (hidden field).
2. X-ray view revealing the 'role: admin' inside the packet.
After: ## 1) まず怖い話:クライアントは“改造できる前提”😈🪛
1486docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_02_allowlist_logic.png./picture/firebase_security_role_ts_study_012_02_allowlist_logic.pngTheme: Two Types of Allowlists

Labels to Render:
- Create: "Create (All Keys Check)"
- Update: "Update (Changed Keys Only)"

Visual Details:
1. Two different scanners.
2. Create scanner scans the whole box.
3. Update scanner scans only the new parts added/changed.
After: ## 2) この章の結論:allowlistは2種類つくる✌️🔑
1487docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_03_diff_affected_keys.png./picture/firebase_security_role_ts_study_012_03_diff_affected_keys.pngTheme: Understanding diff().affectedKeys()

Labels to Render:
- Before: "変更前"
- After: "変更後"
- Diff: "差分 (affectedKeys)"

Visual Details:
1. Comparison of two documents.
2. Highlight only the field that changed (e.g., displayName).
3. Show 'diff' extracting ONLY that changed field.
After: ## B. update(更新)→ diff(resource.data).affectedKeys().hasOnly(...) ✅✅
1488docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_04_profile_structure.png./picture/firebase_security_role_ts_study_012_04_profile_structure.pngTheme: Editable vs Protected Fields

Labels to Render:
- Editable: "変更OK (displayName, bio)"
- Protected: "変更NG (role, createdAt)"

Visual Details:
1. A document split into two zones.
2. Green zone for Editable fields.
3. Red locked zone for Protected fields.
After: ## 4) 手を動かす:プロフィール更新で「許可キー以外は拒否」を実装🧑‍💻🔥
1489docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_05_attack_simulation.png./picture/firebase_security_role_ts_study_012_05_attack_simulation.pngTheme: Blocking Privilege Escalation

Labels to Render:
- Attack: "role: admin"
- Guard: "affectedKeys check"
- Result: "Blocked"

Visual Details:
1. An arrow labeled 'role: admin' trying to hit the database.
2. A shield labeled 'affectedKeys' bouncing it off.
3. A normal arrow (displayName update) passing through.
After: ## 5) 攻撃ごっこ(わざと悪い更新を投げる)😈➡️🧯
1490docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_06_common_pitfalls.png./picture/firebase_security_role_ts_study_012_06_common_pitfalls.pngTheme: The Pitfall of using keys() in Update

Labels to Render:
- Update: "更新時"
- Mistake: "keys()を使う"
- Consequence: "既存フィールドもチェックされてしまう"

Visual Details:
1. A trap or pitfall.
2. A character falling in because they used 'keys()' on update.
3. Show that existing fields (like createdAt) trip the wire.
After: ## 6) よくある落とし穴(ここで事故る)⚠️😵
1491docs/firebase_security_role_ts_study_012.mdfirebase_security_role_ts_study_012_07_ai_review.png./picture/firebase_security_role_ts_study_012_07_ai_review.pngTheme: Human Review of AI Rules

Labels to Render:
- AI: "AI生成 (Rules)"
- Human: "人間レビュー"
- Goal: "完全な安全"

Visual Details:
1. AI robot handing a document to a human.
2. Human holding a magnifying glass checking the document.
3. A stamp of approval only after human check.
After: ## 7) AIで爆速にする(ただし最後は人間の目👀✅)🤖⚡