Skip to content

TrainLCDをFirebaseからCloudflareへ全面移行 - #6238

Merged
TinyKitten merged 18 commits into
devfrom
feature/cloudflare-migration
Jun 16, 2026
Merged

TinyKitten merged 18 commits into
devfrom
feature/cloudflare-migration

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

概要

Firebase(Cloud Functions・Auth・Firestore・Storage・Remote Config)を Cloudflare(Workers・KV・R2・Queues・Workers AI)へ全面移行しました。TTS 合成は Azure Speech に切り替えています。バックエンド(functions/)、アプリの脱 Firebase、旧ネイティブ設定の撤去までを含みます。

変更の種類

  • バグ修正
  • 新機能
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

  • Phase 1 — バックエンド: functions/ を Firebase Cloud Functions から単一の Cloudflare Worker(fetch/queue/scheduled)へ全面置換。TTS=Azure Speech、フィードバックトリアージ=Workers AI、キャッシュ/設定=KV、音声/画像=R2、フィードバックキュー=Queues、レビュー通知=Cron。認証は Worker 発行のセッション JWT(HS256)。
  • Phase 2 — アプリ脱 Firebase: 匿名認証をインストール ID+セッション JWT に置換。Firestore/Remote Config/Storage をそれぞれ /config/maintenance・/config/remote・/feedback/upload-image に置換し、@react-native-firebase/* を撤去(expo-secure-store 追加)。TTS/フィードバック送信は callable 互換を維持しつつ Worker ベース URL から派生。
  • Phase 3 — 撤去: firebase.json・Android gradle の google-services 参照・Licenses の Firebase 記載を削除(ネイティブ再生成 expo prebuild --clean は別途必要)。
  • TTS キャッシュは Queues の 128KB 上限を避け /tts から R2+KV へ直接書き込み。few-shot は CONFIG_KV へ移動。
  • TTS 品質: Azure の音質(48kHz/192kbit)・話速(既定 -3%)・スタイル/プロソディを env で調整可能化。日本語駅名/路線名に IPA 読み(nameIpa)を導入してイントネーションを改善し、山手線のカナ表記ハックを撤去。
  • CodeRabbit 指摘 15 件を反映: queue 失敗時の再試行、KV/OAuth 応答の検証、レビュー通知 state 更新の成功条件化、引数/例外の厳密化、画像アップロード例外の隔離など。
  • シークレット一括投入スクリプト(put-secrets.sh / put-secrets.ps1)、メンテ CLI(R2+KV 版)、移行プラン・手順 docs を追加。

テスト

  • npm run lint が通ること
  • npm test が通ること
  • npm run typecheck が通ること

関連Issue

スクリーンショット(任意)

Summary by CodeRabbit

リリースノート

  • Refactor

    • バックエンド基盤を大規模に更新し、内部的な信頼性と処理効率を向上
  • New Features

    • 端末ごとの安定した認証ID管理機能を追加
  • Bug Fixes

    • 山手線の列車種別表記を修正

TinyKitten and others added 12 commits June 16, 2026 12:23
匿名認証をインストールID+Worker発行JWTに、Firestore/Storage/RemoteConfigをWorkerエンドポイントに置換し、@react-native-firebaseを撤去。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
firebase.jsonとandroid gradleのgoogle-services参照、LicensesのFirebaseエントリを削除。ネイティブ再生成とプロジェクト撤去の手順をdocsに追加。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
find-tts-cache/find-orphaned-tts を Cloudflare REST(KV)+S3(R2) で再実装。fewshot.example.jsonl と利用手順を追加。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
旧Cloud Functions用の*_TTS_API_URL/*_FEEDBACK_API_URL(と未使用のLOCAL)を廃し、workerUrl()で/tts・/postFeedbackを生成する。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
SESSION_JWT_SECRET未設定を明示し、fetchハンドラ全体をtry/catchでログ+JSON500化。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
DISCORD_REVIEW_WEBHOOK_URL/GOOGLE_SA_KEY 未設定は通知オフ扱いとし、毎時Cronのエラーログを抑止。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
stdinパイプ(Windowsで値が届かず空secretになる)を廃し、Nodeで生成した一時JSONをwrangler secret bulkに渡す方式に。put-secrets.ps1とbuild-secrets-json.mjsを追加、GOOGLE_SA_KEY_FILEは.secrets.env行でも指定可。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Queuesの128KB上限に音声が収まらずPayload Too Largeになるため、tts-cacheキューを撤去し/ttsハンドラからwriteTtsCacheでR2+KVへ直接保存する。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
few-shotはfeedbackトリアージ専用でTTSと無関係なため、設定用KV(config:fewshot)へ移し、変数をFEW_SHOT_KV_KEYに変更。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bc024036-1034-46ce-8c74-732d08c8ef10

📥 Commits

Reviewing files that changed from the base of the PR and between 153afe1 and aa6e968.

📒 Files selected for processing (1)
  • src/hooks/useTTSText.ts

📝 Walkthrough

Walkthrough

Firebase Cloud Functions・Firestore・Storage・Auth・Remote Config・Pub/Sub への依存をすべて除去し、バックエンドを Cloudflare Workers(KV/R2/Queues/Workers AI/Azure Speech)へ完全移行した。アプリ側は installId ベースのセッション JWT 認証と Worker URL を使う形に統一されている。

Changes

Firebase → Cloudflare Workers 全面移行

Layer / File(s) Summary
Worker 基盤型・共有ライブラリ・ビルド設定
functions/src/types.ts, functions/src/lib/callable.ts, functions/src/lib/crypto.ts, functions/tsconfig.json, functions/jest.config.js, functions/package.json, functions/wrangler.jsonc
Env/TtsCachePayload/FeedbackQueueMessage 型定義、callable 互換レスポンスヘルパー、Web Crypto ユーティリティを追加。TypeScript/Jest 設定を ESM・Workers 向けに更新し、wrangler.jsonc で dev/production 環境の bindings/vars/secrets を定義した。
Worker セッション JWT 発行・検証・認証ルート
functions/src/lib/auth/session.ts, functions/src/routes/auth.ts
HMAC-SHA256 で HS256 セッション JWT を発行・検証する issueSessionToken/verifySessionToken を追加。POST /auth/token ルートで installId を受け取り署名済み JWT を返すようにした。
TTS ルート:Azure 合成・voice 解決・KV/R2 キャッシュ
functions/src/lib/azure/tts.ts, functions/src/utils/ttsVoice.ts, functions/src/utils/ssml.ts, functions/src/lib/ttsCache.ts, functions/src/routes/tts.ts, functions/src/utils/ttsVoice.test.ts
Azure Speech 合成、Azure ニューラル voice 解決、SSML 前処理、KV/R2 キャッシュ参照・保存を含む handleTts を実装。旧 Google Cloud TTS と Standard voice ユーティリティを削除した。
フィードバック受付・キュー・AI トリアージ・通知
functions/src/routes/feedback.ts, functions/src/routes/uploadImage.ts, functions/src/consumers/feedbackTriage.ts, functions/src/consumers/feedbackTriage.test.ts, functions/fewshot.example.jsonl
/postFeedback・/feedback/upload-image ルートを追加し、キューメッセージの Workers AI 分類・スパム判定・GitHub Issue 作成・Discord 通知を実装。looksLikeSpam/coerceReport テストを更新した。
Cron スケジューラ:レビュー通知・状態管理
functions/src/scheduled/appStoreReviews.ts, functions/src/scheduled/googlePlayReviews.ts, functions/src/lib/reviewState.ts, functions/src/lib/google/accessToken.ts, functions/src/scheduled/appStoreReviews.test.ts, functions/src/scheduled/googlePlayReviews.test.ts
App Store JSON フィードと Android Publisher REST API からレビューを取得し KV で既読管理して Discord 通知する Cron ジョブを実装。Google SA による OAuth トークン取得と KV 状態管理ユーティリティを追加した。旧 workers/ 配下の Firebase 依存実装を削除した。
Worker エントリポイント・config 配信ルート
functions/src/index.ts, functions/src/routes/config.ts, functions/src/funcs/enqueueFeedback.ts, functions/src/funcs/tts.ts, functions/src/funcs/ttsCachePubSub.ts, functions/src/workers/feedback.ts, functions/src/workers/googlePlayReviews.ts
export default { fetch, queue, scheduled } に統合し、全ルートをディスパッチする構造に変更。KV から設定値を返す /config/maintenance・/config/remote を追加。Firebase 関数の named export 群をすべて削除した。
運用 CLI とシークレット投入導線
functions/scripts/*, functions/src/cli/lib/cloudflare.ts, functions/src/cli/find-tts-cache.ts, functions/src/cli/find-orphaned-tts.ts, functions/.gitignore, functions/.secrets.env.example
KV/R2 操作ヘルパー、TTS キャッシュ探索・孤立検出 CLI、wrangler secret bulk 用スクリプト(sh/ps1/mjs)を追加。.gitignore と secrets テンプレートを Wrangler 前提へ更新した。
アプリ側 ID・セッション・Worker URL 基盤
src/lib/installId.ts, src/lib/session.ts, src/lib/workerApi.ts, src/store/atoms/auth.ts, src/@types/react-native-dotenv.d.ts, .env.example, app.config.ts, package.json, jest.setup.js
expo-secure-store による端末固定 UUID 生成、Worker 発行セッション JWT のキャッシュ、環境別 Worker URL 解決を追加。AppUser 型を導入し Firebase Auth 依存を除去。テストモックを expo-secure-store 前提へ更新した。
アプリ機能の Worker API 切り替え
src/hooks/useAnonymousUser.ts, src/hooks/useCachedAnonymousUser.ts, src/hooks/useTTS.ts, src/hooks/useTTS.test.ts, src/hooks/useFeedback.ts, src/hooks/useUnderMaintenance.ts
TTS・フィードバック・メンテナンス API 呼び出しを Firebase Auth/Firestore/Storage から Worker URL と session token 前提へ変更。匿名認証を getInstallId() ベースに置き換えた。
Remote Config の Worker 経由取得への置換
src/lib/remoteConfig.ts, src/lib/remoteConfig.test.ts, src/constants/location.ts
Firebase Remote Config SDK を除去し、/config/remote を fetch してモジュール内キャッシュする実装に置き換え。テストを workerUrl + global.fetch モック前提に更新した。
移行ドキュメント更新と旧実装削除
docs/cloudflare-migration-plan.md, docs/cloudflare-migration-phase3-checklist.md, functions/README.md, AGENTS.md, android/app/build.gradle, android/build.gradle, firebase.json, src/screens/Licenses.tsx, src/hooks/useTTSText.ts
移行計画・Phase 3 チェックリスト・README を Cloudflare 前提へ更新。firebase.json・Google Services Gradle 設定・Firebase ライセンス表示を削除。山手線 TTS 文言を「山手線内回り/外回り」に修正した。

Sequence Diagram(s)

sequenceDiagram
  participant App as モバイルアプリ
  participant Worker as Cloudflare Worker
  participant KV as KV Namespace
  participant R2 as R2 Bucket
  participant Azure as Azure Speech
  participant Queue as Cloudflare Queue
  participant AI as Workers AI

  rect rgba(59, 130, 246, 0.5)
    note over App,Worker: セッション確立
    App->>Worker: POST /auth/token { installId }
    Worker-->>App: { token, expiresIn }
  end

  rect rgba(34, 197, 94, 0.5)
    note over App,Azure: TTS 取得
    App->>Worker: POST /tts (Bearer, ssmlJa, ssmlEn)
    Worker->>KV: get voice:{id}
    alt キャッシュヒット
      KV-->>Worker: pathJa, pathEn
      Worker->>R2: get audio files
      R2-->>Worker: バイナリ
    else キャッシュミス
      Worker->>Azure: synthesizeSpeech x2
      Azure-->>Worker: SynthesizedAudio
      Worker->>R2: put (waitUntil)
      Worker->>KV: put voice:{id} (waitUntil)
    end
    Worker-->>App: { jaAudio, enAudio }
  end

  rect rgba(168, 85, 247, 0.5)
    note over App,AI: フィードバック送信〜トリアージ
    App->>Worker: POST /postFeedback (Bearer, report)
    Worker->>Queue: send FeedbackQueueMessage
    Worker-->>App: { ok, queued }
    Queue->>Worker: queue consumer
    Worker->>AI: runTriage(few-shot + description)
    AI-->>Worker: AIReport
  end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • TrainLCD/MobileApp#6151: src/lib/remoteConfig.ts の setupRemoteConfig/getMaxPermitAccuracy/isForceNotArrivedOnLowAccuracyEnabled およびキャッシュ挙動を変更しており、本 PR が同じ getter 群を Worker 経由取得へ置き換えた箇所と直接関係する。
  • TrainLCD/MobileApp#6131: Firebase Remote Config から getMaxPermitAccuracy()/isForceNotArrivedOnLowAccuracyEnabled() を参照する実装を追加・利用箇所更新しており、本 PR はその同じ getter 群を /config/remote 経由へ完全置換しているためコードレベルで強く関連する。
  • TrainLCD/MobileApp#6235: src/hooks/useTTS.ts の TTS 処理中核フローを変更しており、本 PR も同ファイルの認証経路・API URL 生成を Worker 前提へ置き換えているため直接関係する。

Poem

🐰 ふわふわ耳でぴょんと跳ねたら
Cloudflare の空へ飛び立った!
Firebase のほこりを払い落として
Workers でキャッシュも JWT も
ぴかぴかレールを駆け抜けるよ 🚃✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/cloudflare-migration

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useAnonymousUser.ts (1)

8-25: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

useRef の更新では再レンダリングされないため、常に null を返す可能性が高い

useRef の .current を更新しても React は再レンダリングをトリガーしません。getInstallId() が完了して userRef.current = { uid } を設定しても、呼び出し側コンポーネントは再レンダリングされず、初回の null のまま使い続けます。

useState を使用するか、コメントにある通り useCachedAnonymousUser の使用を強制する設計に変更すべきです。

🐛 useState を使用した修正案
-import { useEffect, useRef } from 'react';
+import { useEffect, useState } from 'react';
 import { getInstallId } from '../lib/installId';
 import type { AppUser } from '../store/atoms/auth';

 /**
  * Jotaiが使えない環境の時にもユーザーを持ちたい場合に使います。基本的に `useCachedAnonymousUser` を使ってください。
  */
 export const useAnonymousUser = (): AppUser | null => {
-  const userRef = useRef<AppUser | null>(null);
+  const [user, setUser] = useState<AppUser | null>(null);
   useEffect(() => {
     let active = true;
     getInstallId()
       .then((uid) => {
         if (active) {
-          userRef.current = { uid };
+          setUser({ uid });
         }
       })
       .catch(() => undefined);
     return () => {
       active = false;
     };
   }, []);

-  return userRef.current;
+  return user;
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useAnonymousUser.ts` around lines 8 - 25, The useAnonymousUser hook
uses useRef which does not trigger re-renders when its value is updated, causing
the hook to always return null even after getInstallId() completes successfully.
Replace useRef with useState to properly trigger re-renders when the anonymous
user data is fetched. Change useRef<AppUser | null>(null) to useState<AppUser |
null>(null), update the .then() callback to call the state setter instead of
assigning to userRef.current, and return the state value instead of
userRef.current at the end of the hook.
🟡 Minor comments (10)
functions/src/utils/ttsVoice.test.ts-10-14 (1)

10-14: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

en-US-Neural の拒否ケースを回帰テストに追加してください。

isAzureVoiceName の境界条件として、Neural のみ(語幹なし)を明示的に false 固定しておくと、Line 9 の正規表現回帰を防げます。

🔧 追加入力例
   it('rejects non-Azure voice ids', () => {
     expect(isAzureVoiceName('ja-JP-Standard-B')).toBe(false);
     expect(isAzureVoiceName('en-US-Chirp3-HD-Aoede')).toBe(false);
+    expect(isAzureVoiceName('en-US-Neural')).toBe(false);
     expect(isAzureVoiceName('')).toBe(false);
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/utils/ttsVoice.test.ts` around lines 10 - 14, The test for
isAzureVoiceName is missing a boundary condition test case for the string
'en-US-Neural' which should be rejected. Add an expect statement in the 'rejects
non-Azure voice ids' test block to explicitly verify that
isAzureVoiceName('en-US-Neural') returns false, ensuring the regex pattern at
Line 9 correctly handles the case where Neural appears without a stem suffix.
functions/src/routes/tts.ts-70-75 (1)

70-75: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

requireString のエラーメッセージが引数実態と一致していません。

Line 74-75 の "containing the message to add" は /tts の ssmlJa / ssmlEn 契約と不一致で、クライアント側の調査を難しくします。対象パラメータ名に合わせた文言へ更新してください。

🔧 修正案
   if (typeof value !== 'string' || value.length === 0) {
     throw new CallableError(
       'invalid-argument',
-      `The function must be called with one argument "${name}" containing the message to add.`
+      `The function must be called with one argument "${name}" containing a non-empty SSML string.`
     );
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/routes/tts.ts` around lines 70 - 75, The error message in the
`requireString` function (lines 74-75) contains hardcoded text "containing the
message to add" which does not match the actual contract for TTS parameters like
`ssmlJa` and `ssmlEn` that contain SSML content, not generic messages. Update
the error message to be more generic and parameter-agnostic by removing the
assumption about what the parameter contains. Instead, make the message
reference the parameter name (already available via the `name` argument) and
describe the general requirement that it must be a non-empty string, without
prescribing what type of content it should contain.
src/lib/installId.ts-10-25 (1)

10-25: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

初回呼び出し時の競合状態によりIDが重複生成される可能性

getInstallId() が複数箇所から同時に呼ばれた場合、両方が cachedInstallId === null かつ stored === null の状態で randomUUID() を実行し、異なる ID を生成・保存する可能性があります。最初の setItemAsync が完了する前に 2 回目の呼び出しが getItemAsync を実行すると発生します。

また、SecureStore の操作は keychain エラーで例外を投げる可能性がありますが、エラーハンドリングがありません。

🛡️ 競合防止とエラーハンドリングの追加案
 let cachedInstallId: string | null = null;
+let pendingPromise: Promise<string> | null = null;

-export const getInstallId = async (): Promise<string> => {
+export const getInstallId = (): Promise<string> => {
   if (cachedInstallId) {
-    return cachedInstallId;
+    return Promise.resolve(cachedInstallId);
   }
+  if (pendingPromise) {
+    return pendingPromise;
+  }

-  const stored = await SecureStore.getItemAsync(INSTALL_ID_KEY);
-  if (stored) {
-    cachedInstallId = stored;
-    return stored;
-  }
-
-  const generated = Crypto.randomUUID();
-  await SecureStore.setItemAsync(INSTALL_ID_KEY, generated);
-  cachedInstallId = generated;
-  return generated;
+  pendingPromise = (async () => {
+    try {
+      const stored = await SecureStore.getItemAsync(INSTALL_ID_KEY);
+      if (stored) {
+        cachedInstallId = stored;
+        return stored;
+      }
+      const generated = Crypto.randomUUID();
+      await SecureStore.setItemAsync(INSTALL_ID_KEY, generated);
+      cachedInstallId = generated;
+      return generated;
+    } finally {
+      pendingPromise = null;
+    }
+  })();
+  return pendingPromise;
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/installId.ts` around lines 10 - 25, The getInstallId function has a
race condition where multiple simultaneous calls can generate different IDs if
they all execute the randomUUID() before any complete the setItemAsync call, and
it lacks error handling for SecureStore operations that may throw keychain
exceptions. Add a Promise-based locking mechanism to ensure only one concurrent
execution of the ID generation logic (by tracking a pending promise and reusing
it across concurrent calls), and wrap the SecureStore.getItemAsync and
SecureStore.setItemAsync calls in try-catch blocks to properly handle potential
keychain errors.
functions/src/routes/uploadImage.ts-38-41 (1)

38-41: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

不正な base64 入力時のエラーハンドリング

base64ToBytes は不正な base64 文字列を受け取ると予期しない結果やエラーを引き起こす可能性があります。デコード失敗時に明確なエラーを返すことを推奨します。

🛡️ 修正案
-  const bytes = base64ToBytes(imageBase64);
+  let bytes: Uint8Array;
+  try {
+    bytes = base64ToBytes(imageBase64);
+  } catch {
+    throw new CallableError('invalid-argument', 'invalid base64 encoding');
+  }
   if (bytes.byteLength > MAX_IMAGE_BYTES) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/routes/uploadImage.ts` around lines 38 - 41, The base64ToBytes
function call at line 38 in uploadImage.ts does not handle invalid base64 input,
which could cause unexpected errors or results. Wrap the
base64ToBytes(imageBase64) call in a try-catch block to catch any decoding
errors, and throw a CallableError with error code 'invalid-argument' and a clear
message indicating that the image data is not valid base64 when decoding fails.
functions/src/consumers/feedbackTriage.test.ts-1-3 (1)

1-3: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

afterEach で jest.clearAllMocks() を追加してください。

このテストではモックのリセットフックがなく、ガイドライン要件を満たしていません。

💡 修正案
 import { coerceReport, looksLikeSpam } from './feedbackTriage';
+
+afterEach(() => {
+  jest.clearAllMocks();
+});

As per coding guidelines, テストの afterEach で jest.clearAllMocks() を呼び出してください。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/consumers/feedbackTriage.test.ts` around lines 1 - 3, Add an
`afterEach` hook to the describe block in feedbackTriage.test.ts that calls
`jest.clearAllMocks()` to ensure all mocks are properly reset between test
cases. This hook should be placed after the imports and before or after the test
cases to comply with testing guidelines and prevent mock state from leaking
between tests.

Source: Coding guidelines

functions/src/consumers/feedbackTriage.ts-497-498 (1)

497-498: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Discord 通知文言にタイポがあります。

届きまさした は 届きました に修正した方がよいです(両方のメッセージ)。

💡 修正案
-        ? `**🙏アプリから新しいフィードバックが届きまさした‼🙏**\n\`\`\`${description}\`\`\``
-        : `**😭アプリからクラッシュレポートが届きまさした‼😭**\n**${description}**\n\`\`\`${stacktrace
+        ? `**🙏アプリから新しいフィードバックが届きました‼🙏**\n\`\`\`${description}\`\`\``
+        : `**😭アプリからクラッシュレポートが届きました‼😭**\n**${description}**\n\`\`\`${stacktrace
             ?.split('\n')
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/consumers/feedbackTriage.ts` around lines 497 - 498, Fix the
Japanese typo in the Discord notification messages in the feedbackTriage.ts
file. In the ternary operator that constructs the notification message, replace
"届きまさした" with "届きました" in both the feedback message (the first part of the
ternary) and the crash report message (the second part of the ternary) to
correct the grammatical error in both Discord notification strings.
functions/README.md-21-22 (1)

21-22: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

README 内で few-shot の保存先が矛盾しています。

Line 21-22 では few-shot を R2 扱いにしていますが、Line 106-108 では CONFIG_KV(config:fewshot)を参照しています。どちらかに統一しないとセットアップで誤設定が起きます。

Also applies to: 106-108

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/README.md` around lines 21 - 22, The README contains contradictory
information about where few-shot data is stored. In functions/README.md lines
21-22, few-shot data is listed as being stored in R2, but in functions/README.md
lines 106-108, the documentation references CONFIG_KV with config:fewshot,
indicating KV storage instead. Resolve this contradiction by ensuring both
sections consistently describe the same storage location for few-shot data.
Determine the actual storage mechanism used in the codebase and update both
locations to match that single source of truth.
docs/cloudflare-migration-plan.md-49-50 (1)

49-50: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

移行計画の記述が現行アーキテクチャとずれています(TTS キャッシュ経路 / few-shot 保存先)。

この計画書では /tts の Queue 投函・tts-cache consumer・few-shot の R2 保管が前提になっていますが、今回の移行結果は「TTS は /tts から R2+KV へ直接保存」「few-shot は CONFIG_KV」です。運用手順の誤誘導を避けるため、ここを最新版に同期してください。

Also applies to: 73-75, 110-112

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/cloudflare-migration-plan.md` around lines 49 - 50, The migration plan
document in docs/cloudflare-migration-plan.md contains outdated architecture
descriptions across multiple sections. The current implementation stores TTS
cache directly in R2+KV from the `/tts` endpoint (not via Queue with a tts-cache
consumer) and stores few-shot prompts in CONFIG_KV (not R2). Update the table
entries at lines 49-50 (the `/tts` and `/postFeedback` rows) to reflect that TTS
is saved directly to R2+KV without Queue involvement, and update the
corresponding descriptions at lines 73-75 and lines 110-112 to align with the
actual current architecture regarding TTS caching and few-shot storage locations
to prevent operational confusion.
docs/cloudflare-migration-phase3-checklist.md-38-51 (1)

38-51: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

移行後アーキテクチャと手順の記述が一部ずれています。

Line 38 の tts-cache-dev キュー作成と、Line 50 の「R2 に配置」という説明は、同ファイル内のコマンド実体(CONFIG_KV への few-shot投入)および今回の移行方針と不整合です。feedback-triage キュー中心の記述へ修正し、few-shot は KV 配置で統一してください。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/cloudflare-migration-phase3-checklist.md` around lines 38 - 51, The
queue creation command and few-shot deployment description in the checklist are
misaligned with the actual implementation and migration policy. In the wrangler
queues create command, ensure the documentation focuses on the feedback-triage
queue as the primary queue rather than tts-cache-dev. Additionally, update the
comment describing few-shot placement to correctly state that few-shot is being
placed in KV (CONFIG_KV binding) via the wrangler kv key put command, not in R2
as currently described. Align all documentation references to match the actual
command implementations shown in the diff.
functions/src/scheduled/appStoreReviews.test.ts-3-57 (1)

3-57: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

afterEach で jest.clearAllMocks() を追加してください。

このファイルは現在モック未使用ですが、将来のモック追加時にテスト間汚染を防ぐため、共通で afterEach(() => jest.clearAllMocks()) を入れておくべきです。

As per coding guidelines: 「テストの afterEach で jest.clearAllMocks() を呼び出してください」。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/scheduled/appStoreReviews.test.ts` around lines 3 - 57, The
test suite for parseAppStoreJson currently lacks an afterEach hook to clear
mocks, which can cause test pollution when mocks are added in the future. Add an
afterEach hook inside the describe('parseAppStoreJson') block that calls
jest.clearAllMocks() to ensure mocks are properly cleared between test runs,
following the coding guidelines for test cleanup.

Source: Coding guidelines

🧹 Nitpick comments (4)
functions/src/routes/auth.ts (1)

35-38: 💤 Low value

エラーメッセージで内部設定名を露出

SESSION_JWT_SECRET というシークレット名を含むエラーメッセージを返しています。運用上のデバッグには便利ですが、攻撃者にシステム構成のヒントを与える可能性があります。

本番環境では汎用的なメッセージに変更することを検討してください。

     return new Response(
-      JSON.stringify({ error: 'server misconfigured: SESSION_JWT_SECRET' }),
+      JSON.stringify({ error: 'server configuration error' }),
       { status: 500, headers: JSON_HEADERS }
     );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/routes/auth.ts` around lines 35 - 38, The error response in the
SESSION_JWT_SECRET validation block is exposing the internal secret name in the
error message, which reveals system configuration details to potential
attackers. Replace the error message in the JSON response from the current
message that includes "SESSION_JWT_SECRET" with a generic, non-revealing message
such as "Internal server error" or "Authentication service unavailable" that
provides no hints about the internal configuration while maintaining the same
HTTP status code 500 and headers.
functions/src/lib/crypto.ts (1)

40-48: 💤 Low value

長さが異なる場合の早期リターンはタイミング情報を漏洩する可能性あり

timingSafeEqual は長さが異なる場合に即座に false を返すため、長さの違いがタイミングで推測可能です。現在の用途(JWT 署名比較)では署名長が固定のため実害はありませんが、汎用ユーティリティとして公開する場合は注意が必要です。

ドキュメントコメントに用途の制限を明記することを推奨します。

-/** タイミング安全な文字列比較。 */
+/** タイミング安全な文字列比較(同一長の文字列向け。長さが異なる場合は即座に false を返す)。 */
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/lib/crypto.ts` around lines 40 - 48, The timingSafeEqual
function has a documentation comment that does not clarify an important
limitation regarding timing side-channel vulnerabilities. The early length check
in the function (if a.length !== b.length return false) leaks timing information
about whether the input strings have different lengths, which could be exploited
in contexts where this function is used with variable-length inputs. Update the
JSDoc comment for the timingSafeEqual function to document this constraint
explicitly, noting that the function should only be used when comparing strings
of equal or predictable lengths (such as fixed-length JWT signatures), and that
it is not safe for comparing arbitrary-length strings where length differences
might reveal sensitive information.
functions/src/scheduled/googlePlayReviews.test.ts (1)

22-66: 🏗️ Heavy lift

runGooglePlayReviewJob の統合テストを追加して、通知/state 更新契約を固定してください。

現状は純粋関数の単体テストのみで、ジョブ本体の「DRY_RUN 時に state を進めない」「Webhook 失敗時の state 挙動」「ページネーションと dedupe」の互換性が未検証です。fetch・KV・token 取得をモックした統合テストをこのファイルに追加するのが安全です。

As per coding guidelines: **/*.{test,spec}.{ts,tsx,js,jsx,py,java,go,cs}: Test agents in isolation and with integration tests to ensure correctness and compatibility.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/scheduled/googlePlayReviews.test.ts` around lines 22 - 66, The
test file currently contains only unit tests for the pure function toPlayReviews
but lacks integration tests for the main runGooglePlayReviewJob function. Add
integration tests for runGooglePlayReviewJob that mock external dependencies
(fetch calls, KV storage operations, and token acquisition) to verify the actual
job behavior including state management during DRY_RUN mode, state updates after
successful webhook calls, error handling when webhooks fail, and the
compatibility of pagination and deduplication logic. These integration tests
should be added to the same test file alongside the existing unit tests.

Source: Coding guidelines

functions/src/scheduled/appStoreReviews.test.ts (1)

3-57: 🏗️ Heavy lift

ジョブ本体の統合シナリオも追加して回帰検知を強化してください。

今回の主変更は runAppStoreReviewJob の KV 状態遷移・DryRun・Webhookスキップ動作なので、fetch/KV をモックした統合寄りテスト(同時刻ID、投稿失敗時state更新抑止など)を追加すると安全です。

As per coding guidelines: 「Test agents in isolation and with integration tests to ensure correctness and compatibility」。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/scheduled/appStoreReviews.test.ts` around lines 3 - 57, The
current test file focuses only on the parseAppStoreJson utility function. Add
integration test scenarios for the runAppStoreReviewJob function to strengthen
regression detection by testing the actual job behavior with mocked fetch and KV
dependencies. Create test cases that cover KV state transitions, DryRun mode
behavior, Webhook skipping logic, simultaneous review IDs, and state update
suppression when posting fails. This ensures the main job logic (not just the
parsing utility) is properly validated for correctness and compatibility.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@functions/scripts/build-secrets-json.mjs`:
- Around line 30-49: The catch block in the readFileSync error handling is
silently ignoring all exceptions, including permission errors, invalid paths,
and I/O failures, which allows the process to continue with missing secrets.
Modify the catch block to inspect the error code property: only suppress the
error if the code is ENOENT (file not found), and rethrow any other error so
that unexpected failures are properly surfaced instead of being silently ignored
during secret value loading.

In `@functions/scripts/put-secrets.sh`:
- Around line 22-29: The argument parsing in the put-secrets.sh script (around
the WENV and wargs assignment section) currently ignores unknown options and
missing values for --env, risking unintended deployments to the default dev
environment. Add strict argument validation that explicitly checks for unknown
options before the WENV assignment logic and immediately exits with an error
message if any unrecognized arguments are found. Also add validation to ensure
that when --env is provided, it must be followed by a non-empty value, and exit
with an error if the value is missing.

In `@functions/src/cli/find-tts-cache.ts`:
- Around line 107-120: The code in the find-tts-cache.ts file is parsing JSON
records from KV storage and adding them directly to the matches array without
validating that the required id field exists and is a non-empty string. This
causes problems later when the code tries to use rec.id for file operations.
After successfully parsing the JSON into rec (after the JSON.parse call), add a
validation check to ensure rec.id exists and is a non-empty string. Skip the
record (use continue) if this validation fails, so only valid records with a
present and non-empty id field are added to the matches array.

In `@functions/src/consumers/feedbackTriage.ts`:
- Around line 341-342: The try-catch block wrapping the fetch call in
feedbackTriage.ts (around lines 341-342, and also at lines 417-420 and 540-542)
is suppressing exceptions silently, causing the queue handler in index.ts to
acknowledge the message as successfully processed even when the GitHub API call
fails. This results in lost messages that should be retried. Remove the
exception suppression by either re-throwing the caught error or ensuring that
when GitHub API operations fail, the error propagates up to the queue handler so
the message is not acknowledged and can be retried. Apply this same fix to all
affected locations where GitHub API calls are wrapped in try-catch blocks
without proper error propagation.
- Around line 136-145: The `getBool('isSpam')` call uses an un-normalized key
while the `map` object stores all data with normalized keys, causing a mismatch
that prevents the spam flag from being properly detected. Update the
`getBool('isSpam')` call to use the normalized key format (likely 'is_spam' in
snake_case to match the normalization convention used for other map keys like
'title' and 'summary') so that the spam classification from the model output is
correctly read and the triage logic functions as intended.

In `@functions/src/lib/google/accessToken.ts`:
- Around line 81-89: The code uses TypeScript's `as` type assertion to cast the
OAuth response without validating the actual structure, allowing invalid
payloads to be cached if required fields are missing or have incorrect types.
This causes cascading failures in subsequent API calls that rely on the cached
token. Add runtime validation after parsing the response with res.json() to
verify that json.access_token exists and is a string, and json.expires_in exists
and is a number. Throw an error or handle the validation failure appropriately
if these checks fail, before the tokenCache.set() call occurs.

In `@functions/src/lib/reviewState.ts`:
- Around line 7-16: The loadReviewState function lacks schema validation for the
ReviewState object retrieved from KV storage, which can cause downstream
failures when lastIds is stored in an invalid format. After retrieving the json
value from kv.get in the loadReviewState function, normalize and validate the
returned object to ensure lastIds is always an array (or undefined/empty if
missing). This normalization should happen at the read boundary before returning
the ReviewState to prevent exceptions or incorrect behavior in downstream code
that expects lastIds to be an array when used with new Set(state.lastIds ?? []).

In `@functions/src/routes/config.ts`:
- Around line 28-46: The handleMaintenanceConfig and handleRemoteConfig
functions lack error handling for KV store retrieval operations. When
env.CONFIG_KV.get(..., 'json') encounters corrupted JSON or fails, the exception
propagates causing a 500 error instead of gracefully degrading. Wrap both KV.get
calls in try/catch blocks and treat any caught exceptions as undefined, allowing
the code to fall back to default values (the existing logic already handles
undefined stored values appropriately).

In `@functions/src/routes/tts.ts`:
- Around line 89-139: The current validation only checks the byte length of
stripped SSML text (after stripSsml removes tags), which allows raw SSML with
excessive tags and attributes to bypass the byte limit. Add byte length
validation for the raw ssmlJa and ssmlEn strings (after normalization) using the
utf8ByteLength function, before the existing stripped text validation. Insert
these raw byte length checks immediately after the strippedJa and strippedEn
variables are assigned from stripSsml, similar to the existing pattern used for
jaTextBytes and enTextBytes, to ensure both the raw SSML and visible text
respect the TEXT_BYTE_LIMIT constraint.

In `@functions/src/scheduled/appStoreReviews.ts`:
- Around line 166-169: The filter order in the newcomers variable assignment has
a logic issue where items with timestamps equal to lastUpdated are being
excluded even if they have new IDs not in lastIds, defeating the purpose of
tracking lastIds for duplicate detection at the same timestamp. Modify the first
filter condition on dayjs(x.updated) to include items that are either strictly
after lastUpdated (using isAfter) OR have the same timestamp as lastUpdated and
are not in lastIds (using isSame combined with !lastIds.has(x.id)), ensuring
that new items at the same timestamp are not permanently lost.
- Around line 201-204: The state is being saved unconditionally after calling
postToDiscord, even when the Discord posting fails. Since postToDiscord only
logs errors but continues execution on non-2xx responses, failed notifications
still advance the state, causing reviews to be skipped in future runs. Wrap the
saveReviewState call (where lastUpdated and lastIds are persisted) in a
conditional check that only executes when the postToDiscord operation succeeds.
Ensure that if Discord posting fails, the state is not updated so that failed
reviews can be retried in the next job execution.

In `@functions/src/scheduled/googlePlayReviews.ts`:
- Around line 126-130: The `fetch` call to the Discord webhook URL lacks a
timeout mechanism, which could cause the scheduled function to hang indefinitely
if the webhook endpoint is slow or unresponsive. Add an
`AbortSignal.timeout(...)` to the fetch options to set a reasonable timeout
duration (for example, a few seconds). This signal should be added as a new
property in the options object passed to fetch, ensuring that long-running
webhook calls are automatically aborted and the scheduled job can complete or
fail gracefully.
- Around line 212-238: The state is being saved unconditionally after the
DRY_RUN check, which means lastUpdated and lastIds are persisted even when posts
were skipped in DRY_RUN mode or when posting to Discord failed. Move the
state-saving logic (the saveReviewState call and all the preceding state
calculation logic starting with "if (all.length)") from being executed
unconditionally to being executed only when the post was actually successful.
This should be inside the else block where postToDiscord is called, ensuring
state is updated only after confirmed successful notification delivery.

In `@functions/src/utils/ttsVoice.ts`:
- Around line 9-12: The AZURE_VOICE_PATTERN regex in the isAzureVoiceName
function uses [A-Za-z0-9]* which allows zero or more characters before "Neural",
permitting invalid voice names like "en-US-Neural" to pass validation and
subsequently causing Azure synthesis failures. Change the quantifier from * to +
in the AZURE_VOICE_PATTERN to require at least one alphanumeric character before
"Neural", ensuring only properly formatted voice names are accepted.

In `@src/hooks/useFeedback.ts`:
- Around line 89-110: The screenshot upload code in the `if (screenShotBase64)`
block can throw exceptions (from the fetch call or uploadRes.json() parsing)
that propagate to the outer catch handler and prevent the main feedback
submission from completing. Since image upload is auxiliary functionality, wrap
the entire screenshot upload block (the fetch request and json parsing) in a
local try/catch to catch any exceptions locally, log them as warnings, and allow
the feedback submission to continue regardless of whether the image upload
succeeds or fails.

---

Outside diff comments:
In `@src/hooks/useAnonymousUser.ts`:
- Around line 8-25: The useAnonymousUser hook uses useRef which does not trigger
re-renders when its value is updated, causing the hook to always return null
even after getInstallId() completes successfully. Replace useRef with useState
to properly trigger re-renders when the anonymous user data is fetched. Change
useRef<AppUser | null>(null) to useState<AppUser | null>(null), update the
.then() callback to call the state setter instead of assigning to
userRef.current, and return the state value instead of userRef.current at the
end of the hook.

---

Minor comments:
In `@docs/cloudflare-migration-phase3-checklist.md`:
- Around line 38-51: The queue creation command and few-shot deployment
description in the checklist are misaligned with the actual implementation and
migration policy. In the wrangler queues create command, ensure the
documentation focuses on the feedback-triage queue as the primary queue rather
than tts-cache-dev. Additionally, update the comment describing few-shot
placement to correctly state that few-shot is being placed in KV (CONFIG_KV
binding) via the wrangler kv key put command, not in R2 as currently described.
Align all documentation references to match the actual command implementations
shown in the diff.

In `@docs/cloudflare-migration-plan.md`:
- Around line 49-50: The migration plan document in
docs/cloudflare-migration-plan.md contains outdated architecture descriptions
across multiple sections. The current implementation stores TTS cache directly
in R2+KV from the `/tts` endpoint (not via Queue with a tts-cache consumer) and
stores few-shot prompts in CONFIG_KV (not R2). Update the table entries at lines
49-50 (the `/tts` and `/postFeedback` rows) to reflect that TTS is saved
directly to R2+KV without Queue involvement, and update the corresponding
descriptions at lines 73-75 and lines 110-112 to align with the actual current
architecture regarding TTS caching and few-shot storage locations to prevent
operational confusion.

In `@functions/README.md`:
- Around line 21-22: The README contains contradictory information about where
few-shot data is stored. In functions/README.md lines 21-22, few-shot data is
listed as being stored in R2, but in functions/README.md lines 106-108, the
documentation references CONFIG_KV with config:fewshot, indicating KV storage
instead. Resolve this contradiction by ensuring both sections consistently
describe the same storage location for few-shot data. Determine the actual
storage mechanism used in the codebase and update both locations to match that
single source of truth.

In `@functions/src/consumers/feedbackTriage.test.ts`:
- Around line 1-3: Add an `afterEach` hook to the describe block in
feedbackTriage.test.ts that calls `jest.clearAllMocks()` to ensure all mocks are
properly reset between test cases. This hook should be placed after the imports
and before or after the test cases to comply with testing guidelines and prevent
mock state from leaking between tests.

In `@functions/src/consumers/feedbackTriage.ts`:
- Around line 497-498: Fix the Japanese typo in the Discord notification
messages in the feedbackTriage.ts file. In the ternary operator that constructs
the notification message, replace "届きまさした" with "届きました" in both the feedback
message (the first part of the ternary) and the crash report message (the second
part of the ternary) to correct the grammatical error in both Discord
notification strings.

In `@functions/src/routes/tts.ts`:
- Around line 70-75: The error message in the `requireString` function (lines
74-75) contains hardcoded text "containing the message to add" which does not
match the actual contract for TTS parameters like `ssmlJa` and `ssmlEn` that
contain SSML content, not generic messages. Update the error message to be more
generic and parameter-agnostic by removing the assumption about what the
parameter contains. Instead, make the message reference the parameter name
(already available via the `name` argument) and describe the general requirement
that it must be a non-empty string, without prescribing what type of content it
should contain.

In `@functions/src/routes/uploadImage.ts`:
- Around line 38-41: The base64ToBytes function call at line 38 in
uploadImage.ts does not handle invalid base64 input, which could cause
unexpected errors or results. Wrap the base64ToBytes(imageBase64) call in a
try-catch block to catch any decoding errors, and throw a CallableError with
error code 'invalid-argument' and a clear message indicating that the image data
is not valid base64 when decoding fails.

In `@functions/src/scheduled/appStoreReviews.test.ts`:
- Around line 3-57: The test suite for parseAppStoreJson currently lacks an
afterEach hook to clear mocks, which can cause test pollution when mocks are
added in the future. Add an afterEach hook inside the
describe('parseAppStoreJson') block that calls jest.clearAllMocks() to ensure
mocks are properly cleared between test runs, following the coding guidelines
for test cleanup.

In `@functions/src/utils/ttsVoice.test.ts`:
- Around line 10-14: The test for isAzureVoiceName is missing a boundary
condition test case for the string 'en-US-Neural' which should be rejected. Add
an expect statement in the 'rejects non-Azure voice ids' test block to
explicitly verify that isAzureVoiceName('en-US-Neural') returns false, ensuring
the regex pattern at Line 9 correctly handles the case where Neural appears
without a stem suffix.

In `@src/lib/installId.ts`:
- Around line 10-25: The getInstallId function has a race condition where
multiple simultaneous calls can generate different IDs if they all execute the
randomUUID() before any complete the setItemAsync call, and it lacks error
handling for SecureStore operations that may throw keychain exceptions. Add a
Promise-based locking mechanism to ensure only one concurrent execution of the
ID generation logic (by tracking a pending promise and reusing it across
concurrent calls), and wrap the SecureStore.getItemAsync and
SecureStore.setItemAsync calls in try-catch blocks to properly handle potential
keychain errors.

---

Nitpick comments:
In `@functions/src/lib/crypto.ts`:
- Around line 40-48: The timingSafeEqual function has a documentation comment
that does not clarify an important limitation regarding timing side-channel
vulnerabilities. The early length check in the function (if a.length !==
b.length return false) leaks timing information about whether the input strings
have different lengths, which could be exploited in contexts where this function
is used with variable-length inputs. Update the JSDoc comment for the
timingSafeEqual function to document this constraint explicitly, noting that the
function should only be used when comparing strings of equal or predictable
lengths (such as fixed-length JWT signatures), and that it is not safe for
comparing arbitrary-length strings where length differences might reveal
sensitive information.

In `@functions/src/routes/auth.ts`:
- Around line 35-38: The error response in the SESSION_JWT_SECRET validation
block is exposing the internal secret name in the error message, which reveals
system configuration details to potential attackers. Replace the error message
in the JSON response from the current message that includes "SESSION_JWT_SECRET"
with a generic, non-revealing message such as "Internal server error" or
"Authentication service unavailable" that provides no hints about the internal
configuration while maintaining the same HTTP status code 500 and headers.

In `@functions/src/scheduled/appStoreReviews.test.ts`:
- Around line 3-57: The current test file focuses only on the parseAppStoreJson
utility function. Add integration test scenarios for the runAppStoreReviewJob
function to strengthen regression detection by testing the actual job behavior
with mocked fetch and KV dependencies. Create test cases that cover KV state
transitions, DryRun mode behavior, Webhook skipping logic, simultaneous review
IDs, and state update suppression when posting fails. This ensures the main job
logic (not just the parsing utility) is properly validated for correctness and
compatibility.

In `@functions/src/scheduled/googlePlayReviews.test.ts`:
- Around line 22-66: The test file currently contains only unit tests for the
pure function toPlayReviews but lacks integration tests for the main
runGooglePlayReviewJob function. Add integration tests for
runGooglePlayReviewJob that mock external dependencies (fetch calls, KV storage
operations, and token acquisition) to verify the actual job behavior including
state management during DRY_RUN mode, state updates after successful webhook
calls, error handling when webhooks fail, and the compatibility of pagination
and deduplication logic. These integration tests should be added to the same
test file alongside the existing unit tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d107ab2b-8a10-48ed-b510-5dd4eaa4dbe4

📥 Commits

Reviewing files that changed from the base of the PR and between c096cff and d1b9af2.

⛔ Files ignored due to path filters (2)
  • functions/package-lock.json is excluded by !**/package-lock.json
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (70)
  • .env.example
  • AGENTS.md
  • android/app/build.gradle
  • android/build.gradle
  • app.config.ts
  • docs/cloudflare-migration-phase3-checklist.md
  • docs/cloudflare-migration-plan.md
  • firebase.json
  • functions/.gitignore
  • functions/.secrets.env.example
  • functions/README.md
  • functions/fewshot.example.jsonl
  • functions/jest.config.js
  • functions/package.json
  • functions/scripts/build-secrets-json.mjs
  • functions/scripts/put-secrets.ps1
  • functions/scripts/put-secrets.sh
  • functions/src/cli/find-orphaned-tts.ts
  • functions/src/cli/find-tts-cache.ts
  • functions/src/cli/lib/cloudflare.ts
  • functions/src/consumers/feedbackTriage.test.ts
  • functions/src/consumers/feedbackTriage.ts
  • functions/src/funcs/enqueueFeedback.ts
  • functions/src/funcs/tts.ts
  • functions/src/funcs/ttsCachePubSub.ts
  • functions/src/index.ts
  • functions/src/lib/auth/session.ts
  • functions/src/lib/azure/tts.ts
  • functions/src/lib/callable.ts
  • functions/src/lib/crypto.ts
  • functions/src/lib/google/accessToken.ts
  • functions/src/lib/reviewState.ts
  • functions/src/lib/ttsCache.ts
  • functions/src/routes/auth.ts
  • functions/src/routes/config.ts
  • functions/src/routes/feedback.ts
  • functions/src/routes/tts.ts
  • functions/src/routes/uploadImage.ts
  • functions/src/scheduled/appStoreReviews.test.ts
  • functions/src/scheduled/appStoreReviews.ts
  • functions/src/scheduled/googlePlayReviews.test.ts
  • functions/src/scheduled/googlePlayReviews.ts
  • functions/src/types.ts
  • functions/src/utils/ssml.ts
  • functions/src/utils/ttsVoice.test.ts
  • functions/src/utils/ttsVoice.ts
  • functions/src/workers/__tests__/appStoreReviewNotifier.test.ts
  • functions/src/workers/__tests__/googlePlayReviews.test.ts
  • functions/src/workers/feedback.ts
  • functions/src/workers/googlePlayReviews.ts
  • functions/tsconfig.build.json
  • functions/tsconfig.json
  • functions/wrangler.jsonc
  • jest.setup.js
  • package.json
  • src/@types/react-native-dotenv.d.ts
  • src/constants/location.ts
  • src/hooks/useAnonymousUser.ts
  • src/hooks/useCachedAnonymousUser.ts
  • src/hooks/useFeedback.ts
  • src/hooks/useTTS.test.ts
  • src/hooks/useTTS.ts
  • src/hooks/useUnderMaintenance.ts
  • src/lib/installId.ts
  • src/lib/remoteConfig.test.ts
  • src/lib/remoteConfig.ts
  • src/lib/session.ts
  • src/lib/workerApi.ts
  • src/screens/Licenses.tsx
  • src/store/atoms/auth.ts
💤 Files with no reviewable changes (12)
  • functions/src/workers/googlePlayReviews.ts
  • functions/src/workers/feedback.ts
  • functions/src/funcs/enqueueFeedback.ts
  • android/build.gradle
  • functions/src/workers/tests/googlePlayReviews.test.ts
  • functions/src/funcs/tts.ts
  • functions/src/workers/tests/appStoreReviewNotifier.test.ts
  • firebase.json
  • functions/src/funcs/ttsCachePubSub.ts
  • android/app/build.gradle
  • functions/tsconfig.build.json
  • src/screens/Licenses.tsx

Comment thread functions/scripts/put-secrets.sh Resolved
Comment thread functions/src/cli/find-tts-cache.ts Resolved
Comment on lines +136 to +145
const getBool = (...keys: string[]) =>
keys.some((k) => {
const v = map.get(k);
return v === true || v === 'true';
});

let title = getStr('title');
let summary = getStr('summary');
const isSpam = getBool('isSpam');
const rawLabels = map.get('labels');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

isSpam の読み取りがキー正規化と不整合です。

map 側は正規化キーで保持しているのに、getBool('isSpam') が未正規化キーを参照しており、モデル出力の isSpam を取りこぼします。スパム誤判定で triage が崩れます。

💡 修正案
-  const getBool = (...keys: string[]) =>
+  const getBool = (...keys: string[]) =>
     keys.some((k) => {
-      const v = map.get(k);
+      const v = map.get(norm(k));
       return v === true || v === 'true';
     });
@@
-  const isSpam = getBool('isSpam');
+  const isSpam = getBool('isSpam', 'is_spam');
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/consumers/feedbackTriage.ts` around lines 136 - 145, The
`getBool('isSpam')` call uses an un-normalized key while the `map` object stores
all data with normalized keys, causing a mismatch that prevents the spam flag
from being properly detected. Update the `getBool('isSpam')` call to use the
normalized key format (likely 'is_spam' in snake_case to match the normalization
convention used for other map keys like 'title' and 'summary') so that the spam
classification from the model output is correctly read and the triage logic
functions as intended.

Comment on lines +341 to +342
try {
const res = await fetch(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

GitHub 作成失敗が再試行されずに ACK される経路があります。

ここで例外を握りつぶすため、functions/src/index.ts の queue ハンドラでは成功扱いで message.ack() されます。GitHub API 失敗時にメッセージが失われます。

💡 修正案(失敗時のみ再試行へ)
+  let issueCreated = false;
   try {
@@
     if (res.status !== 201) {
       console.error(await res.json());
       throw new Error(`GitHub API failed with status ${res.status}`);
     }
+    issueCreated = true;
@@
   } catch (err) {
     console.error(err);
+    if (!issueCreated) throw err;
   }

Also applies to: 417-420, 540-542

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/consumers/feedbackTriage.ts` around lines 341 - 342, The
try-catch block wrapping the fetch call in feedbackTriage.ts (around lines
341-342, and also at lines 417-420 and 540-542) is suppressing exceptions
silently, causing the queue handler in index.ts to acknowledge the message as
successfully processed even when the GitHub API call fails. This results in lost
messages that should be retried. Remove the exception suppression by either
re-throwing the caught error or ensuring that when GitHub API operations fail,
the error propagates up to the queue handler so the message is not acknowledged
and can be retried. Apply this same fix to all affected locations where GitHub
API calls are wrapped in try-catch blocks without proper error propagation.

Comment thread functions/src/utils/ttsVoice.ts Resolved
Comment thread src/hooks/useFeedback.ts Resolved
出力フォーマット既定を高音質化(48kHz/192kbit)し、mstts:express-asとprosodyをenvで付与可能に。HDボイス名(コロン含む)の検証も許可。

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
functions/src/lib/azure/tts.ts (2)

31-59: ⚡ Quick win

SSML パラメータの入力バリデーションを推奨します。

voiceName, languageCode, opts の各フィールドが検証なしで SSML に直接埋め込まれています。現在の呼び出し側(/tts ルート)では環境変数やバリデーション済みの値を使用していますが、ライブラリ関数としては防御的であるべきです。特殊文字(<, >, ", &)のエスケープまたは許可文字セットの検証を追加することで、将来的な SSML インジェクションリスクを軽減できます。

🛡️ 入力バリデーション例
+/** SSML 属性値として安全な文字列かチェック(XML 特殊文字を含まない) */
+const isValidSsmlAttr = (value: string): boolean => {
+  return !/[<>"&]/.test(value);
+};
+
 const buildAzureSsml = (
   inner: string,
   languageCode: string,
   voiceName: string,
   opts: TtsOptions
 ): string => {
+  if (!isValidSsmlAttr(languageCode) || !isValidSsmlAttr(voiceName)) {
+    throw new Error('Invalid characters in languageCode or voiceName');
+  }
+  if (opts.style && !isValidSsmlAttr(opts.style)) {
+    throw new Error('Invalid characters in style');
+  }
   let content = inner;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/lib/azure/tts.ts` around lines 31 - 59, The buildAzureSsml
function directly embeds parameters (voiceName, languageCode, opts.style,
opts.styleDegree, opts.rate, opts.pitch, and inner content) into SSML XML
without any validation or escaping, creating a potential SSML injection
vulnerability. Add input validation or escaping for special XML characters
(specifically <, >, ", and &) to all user-provided parameters before they are
embedded into the XML string. This should include escaping the inner content and
any option fields that could contain special characters to ensure they are
safely rendered as SSML.

1-100: 🏗️ Heavy lift

ユニットテストの追加を推奨します。

この Azure TTS 実装は新規追加の重要なライブラリ関数ですが、対応するテストファイルが見当たりません。以下のテストケースを含む functions/src/lib/azure/tts.test.ts の追加を検討してください:

  • extractSpeakInner のエッジケース(ネストしたタグ、属性付き <speak>、マッチしない入力)
  • buildAzureSsml の各オプション組み合わせ(rate のみ、pitch のみ、style + styleDegree、すべて組み合わせ)
  • synthesizeSpeech のエラーハンドリング(モック fetch で非 200 レスポンス、タイムアウト、ネットワークエラー)

既存の functions/jest.config.js でテストインフラは整っているため、テストケース作成のみで品質保証を強化できます。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@functions/src/lib/azure/tts.ts` around lines 1 - 100, Create a new test file
at functions/src/lib/azure/tts.test.ts to add unit test coverage for the three
main functions in tts.ts. For extractSpeakInner, write tests covering edge cases
such as SSML with nested tags, speak tags with various attributes, and inputs
that don't match the expected pattern. For buildAzureSsml, write tests for each
option combination: applying rate only, applying pitch only, applying style with
styleDegree, and applying all options together to verify the correct SSML
wrapping. For synthesizeSpeech, write tests that mock the fetch call to simulate
error scenarios: a non-200 HTTP response with detail text, an AbortSignal
timeout, and network failures. Ensure all tests verify both successful cases and
error handling paths using the existing Jest infrastructure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@functions/src/lib/azure/tts.ts`:
- Around line 31-59: The buildAzureSsml function directly embeds parameters
(voiceName, languageCode, opts.style, opts.styleDegree, opts.rate, opts.pitch,
and inner content) into SSML XML without any validation or escaping, creating a
potential SSML injection vulnerability. Add input validation or escaping for
special XML characters (specifically <, >, ", and &) to all user-provided
parameters before they are embedded into the XML string. This should include
escaping the inner content and any option fields that could contain special
characters to ensure they are safely rendered as SSML.
- Around line 1-100: Create a new test file at
functions/src/lib/azure/tts.test.ts to add unit test coverage for the three main
functions in tts.ts. For extractSpeakInner, write tests covering edge cases such
as SSML with nested tags, speak tags with various attributes, and inputs that
don't match the expected pattern. For buildAzureSsml, write tests for each
option combination: applying rate only, applying pitch only, applying style with
styleDegree, and applying all options together to verify the correct SSML
wrapping. For synthesizeSpeech, write tests that mock the fetch call to simulate
error scenarios: a non-200 HTTP response with detail text, an AbortSignal
timeout, and network failures. Ensure all tests verify both successful cases and
error handling paths using the existing Jest infrastructure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c8713ab3-4a56-4739-a304-b71d91fae8fe

📥 Commits

Reviewing files that changed from the base of the PR and between d1b9af2 and c3e8d4f.

📒 Files selected for processing (5)
  • functions/src/lib/azure/tts.ts
  • functions/src/routes/tts.ts
  • functions/src/types.ts
  • functions/src/utils/ttsVoice.ts
  • functions/wrangler.jsonc
🚧 Files skipped from review as they are similar to previous changes (4)
  • functions/src/types.ts
  • functions/wrangler.jsonc
  • functions/src/utils/ttsVoice.ts
  • functions/src/routes/tts.ts

queue失敗時の再試行・KV/OAuth応答検証・通知state更新の成功条件化・引数/例外の厳密化・画像アップロード隔離など。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@TinyKitten
TinyKitten force-pushed the feature/cloudflare-migration branch from c3e8d4f to 9db44d8 Compare June 16, 2026 06:29
TinyKitten and others added 2 commits June 16, 2026 16:27
nameIpaをGraphQLクエリで取得しreplaceJapaneseTextをphoneme優先に拡張。Google TTS向けのやまのて線カナ表記を漢字へ戻す。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously requested changes Jun 16, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/tts/formatters.ts`:
- Around line 68-72: The `nameIpa` variable is being used directly in the
phoneme element without going through the same parenthesis removal normalization
that is applied to `name` and `nameKatakana`, causing sponsor names to be read
aloud in IPA data when they should be omitted. Apply the same parenthesis
removal normalization to `nameIpa` before using it in the escapeXmlAttr call
within the phoneme tag, ensuring consistent behavior across all name variants
regardless of whether IPA data is available.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 57cafd49-6932-4c4c-9c55-33e49d29cf11

📥 Commits

Reviewing files that changed from the base of the PR and between 9db44d8 and 153afe1.

📒 Files selected for processing (6)
  • functions/wrangler.jsonc
  • src/hooks/tts/formatters.test.ts
  • src/hooks/tts/formatters.ts
  • src/hooks/useTTSText.ts
  • src/lib/graphql/queries.ts
  • src/utils/phoneme.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • functions/wrangler.jsonc

Comment thread src/hooks/tts/formatters.ts Resolved
CodeRabbit指摘: スポンサー名等のカッコ書きがIPA経路で読み上げられるのを防ぐためstripParensForTTSを適用。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@TinyKitten
TinyKitten force-pushed the feature/cloudflare-migration branch from 7d36fa8 to 44db8d0 Compare June 16, 2026 08:27
Azureがja-JPのIPA語末撥音(ん)を再生しきれず「〜せ」で切れるため、日本語はnameKatakanaのsub aliasに戻す。英語IPAと山手線の漢字化は維持。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@TinyKitten

Copy link
Copy Markdown
Member Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant