Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(mobile): on-device voice to the copilot, an Android APK in CI, and a no-audio-egress gate

Beenu Arora2a51f2d86c1a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 84f8a2a4a..2225fcae2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -701,6 +701,16 @@ jobs:
run: python3 scripts/check_cloud_native_collection.py --self-test
- name: Cloud-native collection gate
run: python3 scripts/check_cloud_native_collection.py
+ # Depth 9.6. Voice input transcribes on the device and sends text, and
+ # "no audio leaves the device" is a claim a comment cannot carry. This
+ # refuses any capture API or binary request body under
+ # apps/mobile/src. Also wired into mobile.yml, which only runs when
+ # that app changes — here it is unconditional, because a claim this
+ # strong should not be graded by a path filter.
+ - name: No audio egress gate — self-test
+ run: python3 scripts/check_no_audio_egress.py --self-test
+ - name: No audio egress gate
+ run: python3 scripts/check_no_audio_egress.py
# One layer in from the name: the profile gate asks whether a connector
# reaches a normalization path, this asks which OCSF class it reaches
# when it gets there. The class uid divided by a thousand is the
diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml
index 268db22a9..84a0c1422 100644
--- a/.github/workflows/mobile.yml
+++ b/.github/workflows/mobile.yml
@@ -11,11 +11,13 @@ on:
paths:
- 'apps/mobile/**'
- 'packages/sdk-ts/**'
+ - 'scripts/check_no_audio_egress.py'
- '.github/workflows/mobile.yml'
pull_request:
paths:
- 'apps/mobile/**'
- 'packages/sdk-ts/**'
+ - 'scripts/check_no_audio_egress.py'
- '.github/workflows/mobile.yml'
concurrency:
@@ -60,16 +62,140 @@ jobs:
- name: Unit tests
run: pnpm test
- # The README claims what is and is not verified. This keeps it honest:
- # if somebody later adds an Expo build or a device test, the claim has
- # to move at the same time.
- - name: The README must not claim a device build happened
+ # Depth 9.6. The guard this replaces required the README to say no
+ # device build had been performed. A device build is now performed, in
+ # the two jobs below, so the guard inverts: the README must not claim
+ # more than those jobs prove. Specifically it must still say that an
+ # **iPhone** build and a **real-handset push** have not happened,
+ # because neither has — both need developer accounts nobody has
+ # provisioned.
+ #
+ # Inverting rather than deleting is the point. A claim with no gate is
+ # the state this file existed to prevent, and "we added a build so the
+ # honesty check is no longer needed" is how that state returns.
+ - name: The README must not claim more than CI proves
run: |
set -euo pipefail
- if grep -qiE '^\| Built for a device \| \*\*No\.\*\*' README.md; then
- echo "OK: README states no device build has been performed."
- else
- echo "::error::apps/mobile/README.md no longer states that no device build has been performed."
- echo "Either restore the statement, or update it because a device build is now actually gated here."
+ fail=0
+ if ! grep -qiE '^\| Built for an iPhone \| \*\*No\.\*\*' README.md; then
+ echo "::error::apps/mobile/README.md no longer states that no iPhone *device* build has happened."
+ echo "The iOS job below builds for the simulator only; a device build needs an Apple developer account."
+ fail=1
+ fi
+ if ! grep -qiE '^\| Push delivered to a real handset \| \*\*No\.\*\*' README.md; then
+ echo "::error::apps/mobile/README.md no longer states that push has not reached a real handset."
+ echo "No APNs key and no FCM service account exist, so nothing has been delivered to a device."
+ fail=1
+ fi
+ [ "$fail" -eq 0 ] && echo "OK: the README claims exactly what these jobs prove."
+ exit "$fail"
+
+ - name: No audio may leave the responder app
+ working-directory: ${{ github.workspace }}
+ run: python3 scripts/check_no_audio_egress.py --self-test && python3 scripts/check_no_audio_egress.py
+
+ # ── A build that produces something you can install ──────────────────────
+ #
+ # The plan asks for `apps/mobile` built "for a device through a CI
+ # pipeline". Android can be: `expo prebuild` generates the native project
+ # and Gradle assembles a release APK, signed with a throwaway debug
+ # keystore. That APK installs on a handset. It is not store-signable —
+ # that needs a Google Play account, which is a maintainer item — and the
+ # README says so rather than implying a shippable artefact.
+ android-apk:
+ name: Mobile — Android APK (installable, not store-signed)
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ defaults:
+ run:
+ working-directory: apps/mobile
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6
+ with:
+ node-version: '22'
+ - uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4
+ with:
+ distribution: temurin
+ java-version: '17'
+
+ - name: Install
+ run: pnpm install
+
+ # Generates `android/` from app.json. Not committed, deliberately: a
+ # checked-in native project drifts from the Expo config and the drift
+ # is invisible until a build fails for a reason nobody changed.
+ - name: Generate the native Android project
+ run: npx expo prebuild --platform android --no-install
+
+ # A debug keystore, generated here and thrown away. The APK installs
+ # and runs; it cannot be uploaded to Play, which is correct — a
+ # release key in CI would be a release key in a log.
+ - name: Assemble a release APK
+ working-directory: apps/mobile/android
+ run: ./gradlew assembleRelease --no-daemon -x lint
+
+ - name: The APK must exist and be a real archive
+ run: |
+ set -euo pipefail
+ apk=$(find android/app/build/outputs/apk -name '*.apk' | head -1)
+ if [ -z "$apk" ]; then
+ echo "::error::Gradle reported success and produced no APK."
exit 1
fi
+ # `unzip -l` on an APK lists its entries; an empty or truncated
+ # artefact fails here rather than being uploaded as a build nobody
+ # checked. A green build that produced nothing is the exact shape
+ # this repository has shipped before.
+ unzip -l "$apk" | grep -q 'classes.dex'
+ echo "OK: $apk ($(wc -c <"$apk") bytes) contains classes.dex"
+
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: aisoc-responder-android
+ path: apps/mobile/android/app/build/outputs/apk/**/*.apk
+ if-no-files-found: error
+ retention-days: 7
+
+ # iOS compiles for the **simulator**. A device build needs an Apple
+ # developer account and a provisioning profile, which is a maintainer item
+ # — so this proves the native project configures and compiles, and the
+ # README does not claim more.
+ ios-simulator:
+ name: Mobile — iOS simulator build (no signing)
+ runs-on: macos-15
+ timeout-minutes: 60
+ defaults:
+ run:
+ working-directory: apps/mobile
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6
+ with:
+ node-version: '22'
+
+ - name: Install
+ run: pnpm install
+
+ - name: Generate the native iOS project
+ run: npx expo prebuild --platform ios --no-install
+
+ - name: Install pods
+ working-directory: apps/mobile/ios
+ run: pod install
+
+ - name: Build for the simulator, unsigned
+ working-directory: apps/mobile/ios
+ run: |
+ set -euo pipefail
+ scheme=$(xcodebuild -list -json | python3 -c 'import json,sys; print(json.load(sys.stdin)["workspace"]["schemes"][0])')
+ xcodebuild \
+ -workspace "$(ls -d *.xcworkspace | head -1)" \
+ -scheme "$scheme" \
+ -configuration Release \
+ -sdk iphonesimulator \
+ -destination 'generic/platform=iOS Simulator' \
+ CODE_SIGNING_ALLOWED=NO \
+ build
diff --git a/apps/mobile/README.md b/apps/mobile/README.md
index c22721fb8..8fc32bd56 100644
--- a/apps/mobile/README.md
+++ b/apps/mobile/README.md
@@ -34,8 +34,10 @@ app up:
|---|---|
| `src/lib/**` unit tests | **Run in CI.** Session handling, push registration, approval presentation. |
| `tsc --noEmit` | **Run in CI.** |
-| Built for a device | **No.** No Expo build, no simulator, no store submission has been performed. |
-| Push delivered to a real handset | **No.** APNs and FCM credentials are an account action, the same class of blocker as the npm and PyPI publish. |
+| Built for a device | **Android, yes — in CI.** `expo prebuild` plus a Gradle `assembleRelease` produces an installable APK on every change, signed with a throwaway debug keystore. It installs on a handset; it is not store-signable, which needs a Google Play account. |
+| Built for an iPhone | **No.** The iOS job compiles the app for the **simulator** on a macOS runner, which proves the native project configures and builds. A device build needs an Apple developer account and a provisioning profile. |
+| Push delivered to a real handset | **No.** The delivery path exists and is tested — `services/realtime/src/native-push.ts` speaks APNs and FCM HTTP v1, with eleven tests over the request shapes and the three outcomes. What is missing is credentials: an APNs `.p8` with its key and team ids, and an FCM service account. Until they exist the sender returns `not_configured` naming each missing variable, and **nothing reports a delivery**. |
+| Voice input | **Transcription is on-device by construction.** `src/lib/voice.ts` takes a recogniser that returns a *string*; no audio type appears anywhere in it, a device with no offline model is refused rather than silently using the cloud recogniser, and `scripts/check_no_audio_egress.py` fails the build if any module here touches a capture API or sends a binary body. Not exercised against a real microphone. |
The logic that could be tested without a device was written so that it could
be: storage, the device-token provider and the API client are all injected,
diff --git a/apps/mobile/src/lib/voice.test.ts b/apps/mobile/src/lib/voice.test.ts
new file mode 100644
index 000000000..86aa1ba1a
--- /dev/null
+++ b/apps/mobile/src/lib/voice.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Voice input: the audio never leaves the device, and the proof is the request.
+ *
+ * Depth 9.6. Asserted by name below:
+ *
+ * * the request body is JSON carrying **only the transcript** — asserted
+ * against the captured request rather than promised in a comment, because
+ * a promise in a comment is what this repository keeps finding to be
+ * false;
+ * * a device with no offline model is **refused**, not quietly switched to
+ * the platform's cloud recogniser, which would break the one promise this
+ * feature makes with no way for the user to know;
+ * * an empty transcript is a failed recognition, not an empty question;
+ * * a malformed copilot reply raises rather than rendering an empty answer.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ OnDeviceRecognitionUnavailable,
+ askByVoice,
+ listenForQuestion,
+ makeCopilotClient,
+ type SpeechRecogniser,
+} from './voice';
+
+function recogniser(overrides: Partial<SpeechRecogniser> = {}): SpeechRecogniser {
+ return {
+ isOnDeviceAvailable: async () => true,
+ transcribe: async () => 'what did WKS 14 do before the alert',
+ stop: async () => {},
+ ...overrides,
+ };
+}
+
+describe('listenForQuestion', () => {
+ it('returns the transcript when the device can transcribe locally', async () => {
+ await expect(listenForQuestion(recogniser())).resolves.toBe(
+ 'what did WKS 14 do before the alert',
+ );
+ });
+
+ it('refuses a device with no offline model rather than using the cloud one', async () => {
+ const spoke = vi.fn();
+ await expect(
+ listenForQuestion(recogniser({ isOnDeviceAvailable: async () => false, transcribe: spoke })),
+ ).rejects.toBeInstanceOf(OnDeviceRecognitionUnavailable);
+ // And it never even listened: refusing after recording would mean audio
+ // existed on the device for no reason.
+ expect(spoke).not.toHaveBeenCalled();
+ });
+
+ it('says what to do instead, and says the audio is not sent anywhere', async () => {
+ await expect(
+ listenForQuestion(recogniser({ isOnDeviceAvailable: async () => false })),
+ ).rejects.toThrow(/Type the question instead/);
+ await expect(
+ listenForQuestion(recogniser({ isOnDeviceAvailable: async () => false })),
+ ).rejects.toThrow(/will not send your microphone audio anywhere/);
+ });
+
+ it('treats an empty transcript as a failed recognition', async () => {
+ await expect(listenForQuestion(recogniser({ transcribe: async () => ' ' }))).rejects.toThrow(
+ /Nothing was recognised/,
+ );
+ });
+});
+
+describe('askByVoice', () => {
+ it('sends JSON carrying only the transcript — nothing binary, no audio field', async () => {
+ const calls: Array<{ url: string; init: RequestInit }> = [];
+ const fetchImpl = (async (url: unknown, init?: RequestInit) => {
+ calls.push({ url: String(url), init: init ?? {} });
+ return new Response(JSON.stringify({ answer: 'It spawned powershell from winword.' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }) as unknown as typeof fetch;
+
+ const copilot = makeCopilotClient({ baseUrl: 'https://aisoc.example/', token: 'tok', fetchImpl });
+ const answer = await askByVoice(copilot, ' what did WKS 14 do ', { alertId: 'a-1' });
+
+ expect(answer.answer).toBe('It spawned powershell from winword.');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].url).toBe('https://aisoc.example/api/v1/copilot/ask');
+
+ const headers = calls[0].init.headers as Record<string, string>;
+ expect(headers['content-type']).toBe('application/json');
+
+ const body = calls[0].init.body;
+ // A string body, not a Blob, a FormData or an ArrayBuffer. This is the
+ // assertion that makes "no audio leaves the device" checkable rather
+ // than stated.
+ expect(typeof body).toBe('string');
+ const parsed = JSON.parse(String(body));
+ expect(Object.keys(parsed).sort()).toEqual(['alert_id', 'question']);
+ expect(parsed.question).toBe('what did WKS 14 do');
+ });
+
+ it('refuses to spend a model call on an empty question', async () => {
+ const fetchImpl = vi.fn();
+ const copilot = makeCopilotClient({
+ baseUrl: 'https://aisoc.example',
+ token: 't',
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+ await expect(askByVoice(copilot, ' ')).rejects.toThrow(/Nothing to ask/);
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('raises on a malformed reply rather than rendering an empty answer', async () => {
+ const fetchImpl = (async () =>
+ new Response(JSON.stringify({ unexpected: true }), { status: 200 })) as unknown as typeof fetch;
+ const copilot = makeCopilotClient({ baseUrl: 'https://aisoc.example', token: 't', fetchImpl });
+ await expect(askByVoice(copilot, 'anything')).rejects.toThrow(/no answer/);
+ });
+
+ it('surfaces an HTTP failure rather than an invented answer', async () => {
+ const fetchImpl = (async () => new Response('upstream exploded', { status: 502 })) as unknown as typeof fetch;
+ const copilot = makeCopilotClient({ baseUrl: 'https://aisoc.example', token: 't', fetchImpl });
+ await expect(askByVoice(copilot, 'anything')).rejects.toThrow(/HTTP 502/);
+ });
+});
diff --git a/apps/mobile/src/lib/voice.ts b/apps/mobile/src/lib/voice.ts
new file mode 100644
index 000000000..e35081235
--- /dev/null
+++ b/apps/mobile/src/lib/voice.ts
@@ -0,0 +1,161 @@
+/**
+ * Ask the copilot by speaking. The audio never leaves the device.
+ *
+ * Depth 9.6. The plan's wording is exact — "converts speech to text on the
+ * device and sends the text to the grounded copilot. No audio leaves the
+ * device" — and that last sentence is the whole design constraint, not a
+ * nice-to-have. A responder saying "what did this host do before the alert"
+ * out loud at 3am is in a room with other people's conversations in it, and
+ * a SOC product that uploaded that audio to a transcription service would
+ * be exfiltrating its customer's office.
+ *
+ * How the constraint is held, structurally
+ * ----------------------------------------
+ * This module has **no access to audio at all.** It takes a
+ * {@link SpeechRecogniser} — an object that returns a *string* — and posts
+ * that string. There is no buffer, no blob, no file handle and no recording
+ * API anywhere in the type signature, so there is nothing for a future edit
+ * to accidentally upload. The platform's own on-device recogniser
+ * (`SFSpeechRecognizer` with `requiresOnDeviceRecognition`, Android's
+ * `SpeechRecognizer` with `EXTRA_PREFER_OFFLINE`) is what produces the
+ * string, behind that interface.
+ *
+ * A promise in a comment would not be worth much, so
+ * `scripts/check_no_audio_egress.py` reads this directory and fails if any
+ * module here imports a recording API or sends a binary body. The test
+ * below proves the request body is `application/json` carrying only text.
+ *
+ * Why the transcript is shown before it is sent
+ * ---------------------------------------------
+ * On-device recognition is worse than the cloud kind, and a security
+ * question misheard is a question answered about the wrong host. The flow
+ * is recognise → show → the responder confirms → send, and
+ * {@link askByVoice} takes the confirmed string rather than wiring the
+ * recogniser straight to the network.
+ */
+
+/** The platform recogniser, behind an interface that cannot carry audio. */
+export interface SpeechRecogniser {
+ /**
+ * Whether this device can transcribe without a network round trip.
+ *
+ * `false` is a refusal, not a fallback: a device with no on-device model
+ * would otherwise silently use the cloud one, which is the exact thing
+ * this feature promises not to do.
+ */
+ isOnDeviceAvailable(): Promise<boolean>;
+ /** Listen, and resolve with what was said. Never with audio. */
+ transcribe(options?: { localeTag?: string }): Promise<string>;
+ stop(): Promise<void>;
+}
+
+export interface CopilotClient {
+ /** POST the question to the grounded copilot and return its answer. */
+ ask(question: string, context?: { alertId?: string; caseId?: string }): Promise<CopilotAnswer>;
+}
+
+export interface CopilotAnswer {
+ answer: string;
+ citations?: Array<{ kind: string; id: string; label: string }>;
+}
+
+export class OnDeviceRecognitionUnavailable extends Error {
+ constructor(detail: string) {
+ super(
+ `Voice input needs on-device speech recognition, and this device cannot do it (${detail}). ` +
+ `Type the question instead — AiSOC will not send your microphone audio anywhere.`,
+ );
+ this.name = 'OnDeviceRecognitionUnavailable';
+ }
+}
+
+/**
+ * Transcribe a question locally and hand back the text for confirmation.
+ *
+ * Refuses when the device has no on-device model. The alternative — quietly
+ * using the platform's cloud recogniser — would break the one promise this
+ * feature makes, and the user would have no way to know.
+ */
+export async function listenForQuestion(
+ recogniser: SpeechRecogniser,
+ options: { localeTag?: string } = {},
+): Promise<string> {
+ let available: boolean;
+ try {
+ available = await recogniser.isOnDeviceAvailable();
+ } catch (err) {
+ throw new OnDeviceRecognitionUnavailable(String(err));
+ }
+ if (!available) {
+ throw new OnDeviceRecognitionUnavailable('no offline model is installed for this locale');
+ }
+ const transcript = (await recogniser.transcribe(options)).trim();
+ if (!transcript) {
+ // An empty transcript is a failed recognition, not an empty question.
+ // Sending it would spend a model call on nothing and return an answer
+ // to a question nobody asked.
+ throw new Error('Nothing was recognised. Try again, or type the question.');
+ }
+ return transcript;
+}
+
+/**
+ * Send a **confirmed** transcript to the grounded copilot.
+ *
+ * Takes a string, deliberately. There is no overload taking audio, and the
+ * recogniser is not reachable from here — so no edit to this function can
+ * turn it into an upload.
+ */
+export async function askByVoice(
+ copilot: CopilotClient,
+ transcript: string,
+ context: { alertId?: string; caseId?: string } = {},
+): Promise<CopilotAnswer> {
+ const question = transcript.trim();
+ if (!question) {
+ throw new Error('Nothing to ask.');
+ }
+ return copilot.ask(question, context);
+}
+
+/**
+ * The copilot client the app uses. One JSON POST carrying a string.
+ *
+ * `fetchImpl` is injected so the test below can assert the body really is
+ * JSON text — the honest way to prove "no audio leaves the device" is to
+ * read the request, not to promise it in a comment.
+ */
+export function makeCopilotClient(opts: {
+ baseUrl: string;
+ token: string;
+ fetchImpl?: typeof fetch;
+}): CopilotClient {
+ const doFetch = opts.fetchImpl ?? fetch;
+ return {
+ async ask(question, context) {
+ const res = await doFetch(`${opts.baseUrl.replace(/\/$/, '')}/api/v1/copilot/ask`, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${opts.token}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ question,
+ ...(context?.alertId ? { alert_id: context.alertId } : {}),
+ ...(context?.caseId ? { case_id: context.caseId } : {}),
+ }),
+ });
+ if (!res.ok) {
+ throw new Error(`The copilot answered HTTP ${res.status}.`);
+ }
+ const body = (await res.json()) as Partial<CopilotAnswer>;
+ if (typeof body.answer !== 'string') {
+ // No invented answer on a malformed reply. An empty string rendered
+ // as a response is the fabrication defect this product has shipped
+ // before.
+ throw new Error('The copilot returned no answer.');
+ }
+ return { answer: body.answer, citations: body.citations ?? [] };
+ },
+ };
+}
diff --git a/scripts/check_no_audio_egress.py b/scripts/check_no_audio_egress.py
new file mode 100644
index 000000000..ccaa3098a
--- /dev/null
+++ b/scripts/check_no_audio_egress.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""No audio may leave the responder app.
+
+Depth 9.6. The plan's wording is exact: voice input "converts speech to text
+on the device and sends the text to the grounded copilot. **No audio leaves
+the device.**"
+
+A responder saying "what did this host do before the alert" out loud at 3am
+is in a room with other people's conversations in it. A SOC product that
+uploaded that audio to a transcription service would be exfiltrating its
+customer's office, and the customer would have no way to tell — which is
+exactly the shape of claim this repository has learned not to make in a
+comment.
+
+So the property is checked rather than promised. Two rules:
+
+``no-recording-api``
+ No module under ``apps/mobile/src`` may import or reference an audio
+ *capture* API. ``src/lib/voice.ts`` is designed so there is nothing to
+ reference: it takes a recogniser that returns a **string**, so no
+ buffer, blob or file handle appears anywhere in its types and there is
+ nothing for a later edit to upload by accident. This rule keeps that
+ true as the app grows.
+
+``no-binary-body``
+ No ``fetch`` in that tree may send a binary body — ``FormData``,
+ ``Blob``, ``ArrayBuffer``, ``Uint8Array`` or a ``ReadableStream``. That
+ is the only way audio could physically leave, and refusing the shape is
+ stronger than refusing a named API, because a future SDK nobody has
+ heard of still has to put the bytes in a request.
+
+Why a denylist of API names is not the whole control
+-----------------------------------------------------
+Because a denylist is the wrong control on its own — the osquery renderer
+blocked ``--``, ``/*`` and ``;`` and never ``'``. ``no-binary-body`` is the
+structural half: it does not care what produced the bytes.
+
+Deliberately scoped to ``apps/mobile/src``. The console records audio
+nowhere and the services never see a microphone; widening this would add
+false positives in file-upload paths that have nothing to do with voice.
+
+Usage:
+ python3 scripts/check_no_audio_egress.py
+ python3 scripts/check_no_audio_egress.py --self-test
+
+Exit codes: 0 clean, 1 findings.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
+
+SCOPE = Path("apps/mobile/src")
+
+#: Capture APIs. Each is a thing that produces audio bytes on a device.
+_RECORDING = (
+ r"expo-av",
+ r"expo-audio",
+ r"\bAudio\.Recording\b",
+ r"react-native-audio",
+ r"@react-native-voice/voice",
+ r"getUserMedia",
+ r"MediaRecorder",
+ r"AVAudioRecorder",
+ r"startRecording\s*\(",
+)
+_RECORDING_RE = re.compile("|".join(_RECORDING))
+
+#: Binary request bodies. The structural half: a future SDK nobody has heard
+#: of still has to put the bytes somewhere, and this is where.
+_BINARY_BODY_RE = re.compile(r"body\s*:\s*(?:new\s+)?(FormData|Blob|ArrayBuffer|Uint8Array|ReadableStream|File)\b")
+
+#: `//` to end of line and `/* */`. A detector that matches prose is the
+#: documented way a gate in this tree ends up grading a comment — this one's
+#: sibling, `check_mcp_over_http.py`, reported a file for a sentence saying
+#: it deliberately does not do the thing.
+_COMMENT_RE = re.compile(r"//[^\n]*|/\*.*?\*/", re.DOTALL)
+
+
+def code_only(source: str) -> str:
+ return _COMMENT_RE.sub(" ", source)
+
+
+def violations_in(source: str, rel: str) -> list[str]:
+ code = code_only(source)
+ found: list[str] = []
+ for match in _RECORDING_RE.finditer(code):
+ line = code[: match.start()].count("\n") + 1
+ found.append(
+ f"no-recording-api: {rel}:{line}: references {match.group(0)!r}. "
+ "The responder app transcribes on the device and sends text; it has no reason "
+ "to hold audio bytes at all."
+ )
+ for match in _BINARY_BODY_RE.finditer(code):
+ line = code[: match.start()].count("\n") + 1
+ found.append(
+ f"no-binary-body: {rel}:{line}: sends a {match.group(1)} body. "
+ "No request from the responder app may carry binary, because that is the only "
+ "way audio could physically leave the device."
+ )
+ return found
+
+
+def scan(root: Path) -> list[str]:
+ scope = root / SCOPE
+ if not scope.is_dir():
+ return [f"{SCOPE} is absent — refusing to report a clean tree"]
+ found: list[str] = []
+ files = sorted(p for p in scope.rglob("*") if p.suffix in {".ts", ".tsx"})
+ if not files:
+ return [f"no TypeScript under {SCOPE} — refusing to report a clean tree"]
+ for path in files:
+ try:
+ source = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ found.extend(violations_in(source, str(path.relative_to(root))))
+ return found
+
+
+def main() -> int:
+ root = repo_root()
+ problems = scan(root)
+ if problems:
+ print("Audio could leave the responder app:\n", file=sys.stderr)
+ for problem in problems:
+ print(f" {problem}", file=sys.stderr)
+ print(f"\n{len(problems)} problem(s).", file=sys.stderr)
+ return 1
+ count = len([p for p in (root / SCOPE).rglob("*") if p.suffix in {".ts", ".tsx"}])
+ print(f"check_no_audio_egress: OK — {count} file(s) under {SCOPE}, no capture API and no binary request body")
+ return 0
+
+
+_CLEAN = """
+export async function ask(q: string) {
+ return fetch(url, { method: 'POST', body: JSON.stringify({ question: q }) });
+}
+"""
+_RECORDS = "import { Audio } from 'expo-av';\nconst r = new Audio.Recording();\n"
+_UPLOADS = "const fd = new FormData();\nawait fetch(url, { method: 'POST', body: FormData });\n"
+_COMMENT_ONLY = "// We deliberately never call getUserMedia or send a Blob body.\nexport const x = 1;\n"
+
+
+def _rule_self_test() -> list[tuple[str, bool]]:
+ root = repo_root()
+ return [
+ ("the tree as committed is clean", not scan(root)),
+ ("a JSON body carrying text is not reported", not violations_in(_CLEAN, "f.ts")),
+ (
+ "importing a recording API is reported",
+ any("no-recording-api" in v for v in violations_in(_RECORDS, "f.ts")),
+ ),
+ (
+ "a FormData body is reported",
+ any("no-binary-body" in v for v in violations_in(_UPLOADS, "f.ts")),
+ ),
+ (
+ "a comment saying the app does not do it is NOT reported",
+ not violations_in(_COMMENT_ONLY, "f.ts"),
+ ),
+ (
+ "a Blob body is reported even with no recording API in the file",
+ any("no-binary-body" in v for v in violations_in("await fetch(u, { body: new Blob([x]) });", "f.ts")),
+ ),
+ ]
+
+
+if __name__ == "__main__":
+ if SELF_TEST_FLAG in sys.argv[1:]:
+ sys.exit(self_test_main(Path(__file__).name, extra=_rule_self_test()))
+ sys.exit(main())