Firebase + Chrome拡張でクラウド同期を実装する ― 認証・Firestore・データ軽量化の実践
Chrome拡張からFirebaseに接続し、Webアプリと同一のFirestoreデータベースでブックマークを同期する仕組みを構築した。認証フロー、データ軽量化、Tombstone同期の実装を詳細に解説する。
構成
Chrome拡張(popup.html)
├── Firebase Auth(launchWebAuthFlow)
├── Firestore(読み書き)
└── chrome.storage.local(ローカルキャッシュ)
Webアプリ(petapeta-space.web.app)
├── Firebase Auth(signInWithPopup)
├── Firestore(読み書き + リアルタイムリスナー)
└── localStorage(ローカルキャッシュ)
Firebase SDKのローカルバンドル
Chrome拡張のCSP(Content Security Policy)により、CDNからのスクリプト読み込みが制限される。Firebase SDK v10.8.0のcompat版をローカルにバンドルした。
chrome-extension/
└── lib/
├── firebase-app-compat.js
├── firebase-auth-compat.js
└── firebase-firestore-compat.js
<!-- popup.html -->
<script src="lib/firebase-app-compat.js"></script>
<script src="lib/firebase-auth-compat.js"></script>
<script src="lib/firebase-firestore-compat.js"></script>
認証: launchWebAuthFlow
chrome.identity.getAuthToken は拡張機能に紐づいた単一のGoogleアカウントしか使えない。複数アカウント対応のため launchWebAuthFlow を採用した。
async function signIn() {
const redirectUrl = chrome.identity.getRedirectURL();
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
`client_id=${OAUTH_CLIENT_ID}` +
`&redirect_uri=${encodeURIComponent(redirectUrl)}` +
`&response_type=token` +
`&scope=email profile`;
const responseUrl = await chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true
});
// アクセストークンを抽出
const token = new URL(responseUrl.replace('#', '?'))
.searchParams.get('access_token');
// Firebase認証
const credential = firebase.auth.GoogleAuthProvider.credential(null, token);
await firebase.auth().signInWithCredential(credential);
}
OAuthクライアントIDは「Web client」タイプを使用する。「Chrome app」タイプだとlaunchWebAuthFlowと互換性がない。
Firestoreデータ軽量化
Firestoreのドキュメントサイズ上限は1MBであるため、保存データを厳密に制御する。
function sanitizeForCloud(collections) {
return collections.map(c => ({
...c,
cards: c.cards.map(card => ({
id: card.id,
title: (card.title || '').substring(0, 200),
url: card.url,
description: (card.description || '').substring(0, 100),
tags: (card.tags || []).slice(0, 10),
color: card.color || 'color1',
createdAt: card.createdAt,
// Base64画像と記事本文はクラウドに送らない
// image: 除外
// articleContent: 除外
}))
}));
}
| フィールド | 制限 | 理由 |
|---|---|---|
| title | 200文字 | 大半のページタイトルは100文字以下 |
| description | 100文字 | OGP descriptionの要約 |
| tags | 10個 | 実用上10個を超えるタグは不要 |
| tombstones | 100件 | 古いものから自動削除 |
| image | 除外 | Base64エンコードで数百KB〜数MBになる |
| articleContent | 除外 | Readability抽出した本文は大きい |
Tombstone同期
複数端末でデータを同期する際、片方で削除したカードがもう片方から復活する問題を解決する。
// 削除時にTombstoneを記録
function deleteCard(collectionId, cardId) {
const tombstone = {
id: cardId,
collectionId: collectionId,
deletedAt: Date.now()
};
tombstones.push(tombstone);
// 100件を超えたら古いものを削除
if (tombstones.length > 100) {
tombstones = tombstones.slice(-100);
}
}
// マージ同期
function mergeData(localData, cloudData) {
const allTombstones = [
...localData.tombstones,
...cloudData.tombstones
];
const deletedIds = new Set(allTombstones.map(t => t.id));
// 両方のカードを統合し、削除済みを除外
const mergedCards = filterAndDedupeCards(
[...localData.cards, ...cloudData.cards],
deletedIds
);
return { cards: mergedCards, tombstones: allTombstones };
}
function filterAndDedupeCards(cards, deletedIds) {
const seen = new Map();
for (const card of cards) {
if (deletedIds.has(card.id)) continue;
// 同一IDは新しい方を採用
const existing = seen.get(card.id);
if (!existing || card.updatedAt > existing.updatedAt) {
seen.set(card.id, card);
}
}
return Array.from(seen.values());
}
Firestoreセキュリティルール
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
各ユーザーは自分のドキュメントのみ読み書きできる。
まとめ
- Chrome拡張のCSP制約により、Firebase SDKはローカルバンドルが必要
launchWebAuthFlowで複数Googleアカウントに対応- Firestoreの1MB制限に対して、画像・本文除外 + フィールド長制限で対処
- Tombstone方式で削除データの復活を防止し、複数端末間の整合性を確保
- undefinedをnull/空文字に変換する前処理がFirestoreでは必須
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。