From 8d8aaf5794a4eb006676abca53a563ae8f7eb455 Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Fri, 20 Nov 2026 15:16:13 +0900 Subject: [PATCH] feat(mobile): share history as Markdown or original audio and harden the E2E gate Adds history share (Markdown file / original audio) with 12-locale strings, pins Maestro to the target device with --udid, allows cleartext only for explicit local E2E artifacts, and fixes small-screen scroll/keyboard races in the Maestro flows. Evidence: docs/evidence/2026-11-17-backlog-operations.md. --- apps/mobile-rn/.maestro/README.md | 2 +- .../.maestro/authenticated-parity.yaml | 59 +++++++++- .../.maestro/fresh-install-signup.yaml | 16 ++- .../navigation-shell-search-local.yaml | 3 + ...history-detail-unmount-regression.test.tsx | 109 +++++++++++++++++- .../mobile-rn/__tests__/history-share.test.ts | 92 +++++++++++++++ apps/mobile-rn/ios/D3ROVoice/Info.plist | 1 - apps/mobile-rn/package-lock.json | 2 +- apps/mobile-rn/package.json | 2 +- .../data-portability/portability-types.ts | 2 +- .../data-portability/portable-file.ts | 2 +- .../src/features/history/history-share.ts | 94 +++++++++++++++ .../src/screens/HistoryDetailScreen.tsx | 74 +++++++++++- packages/i18n/src/locales/de.json | 2 + packages/i18n/src/locales/en.json | 2 + packages/i18n/src/locales/es.json | 2 + packages/i18n/src/locales/fr.json | 2 + packages/i18n/src/locales/ja.json | 2 + packages/i18n/src/locales/ko.json | 2 + packages/i18n/src/locales/pt.json | 2 + packages/i18n/src/locales/ru.json | 2 + packages/i18n/src/locales/th.json | 2 + packages/i18n/src/locales/vi.json | 2 + packages/i18n/src/locales/zh-TW.json | 2 + packages/i18n/src/locales/zh.json | 2 + scripts/ci/build-mobile-local-e2e.ps1 | 15 ++- scripts/ci/run-mobile-emulator-gate.sh | 6 +- scripts/ci/verify-android-artifact.mjs | 45 +++++++- scripts/ci/verify-mobile-build-config.mjs | 105 ++++++++++++++++- 29 files changed, 627 insertions(+), 26 deletions(-) create mode 100644 apps/mobile-rn/__tests__/history-share.test.ts create mode 100644 apps/mobile-rn/src/features/history/history-share.ts diff --git a/apps/mobile-rn/.maestro/README.md b/apps/mobile-rn/.maestro/README.md index 90e47146..91dd25ca 100644 --- a/apps/mobile-rn/.maestro/README.md +++ b/apps/mobile-rn/.maestro/README.md @@ -12,7 +12,7 @@ 필수 게이트는 실제 가입, OAuth, 결제, 팀 가입, 서버 데이터 생성을 수행하지 않는다. -CI는 같은 `fresh-install-signup.yaml`을 기본 프로필과 `840x1490` 작은 화면에서 각각 실행하고, 실패 여부와 관계없이 디스플레이 override를 초기화한다. Maestro 실행 전에 debug 앱과 AndroidTest APK를 임시 설치해 `CsprngInstrumentedTest`를 한 번 실행한다. 이 계측 검사는 실제 Android `RNGetRandomValuesModule`에서 16바이트 엔트로피를 두 번 받아 길이, non-zero, 비동일성, UUID v4 version/variant 소비 계약을 확인한 뒤 두 패키지를 제거한다. 이후 검증 대상 E2E APK를 fresh install한다. +CI는 같은 `fresh-install-signup.yaml`을 기본 프로필과 `840x1490` 작은 화면에서 각각 실행하고, 실패 여부와 관계없이 디스플레이 override를 초기화한다. 다중 기기 연결 시 `ANDROID_SERIAL`을 지정하면 runner가 모든 Maestro 호출에 같은 `--udid`를 전달해 다른 기기를 선택하지 않는다. 작은 화면에서는 실제 스크롤 후 컨트롤을 탭한다. Maestro 실행 전에 debug 앱과 AndroidTest APK를 임시 설치해 `CsprngInstrumentedTest`를 한 번 실행한다. 이 계측 검사는 실제 Android `RNGetRandomValuesModule`에서 16바이트 엔트로피를 두 번 받아 길이, non-zero, 비동일성, UUID v4 version/variant 소비 계약을 확인한 뒤 두 패키지를 제거한다. 이후 검증 대상 E2E APK를 fresh install한다. ## 외부 계정 게이트 diff --git a/apps/mobile-rn/.maestro/authenticated-parity.yaml b/apps/mobile-rn/.maestro/authenticated-parity.yaml index 71c32657..7a814598 100644 --- a/apps/mobile-rn/.maestro/authenticated-parity.yaml +++ b/apps/mobile-rn/.maestro/authenticated-parity.yaml @@ -20,6 +20,7 @@ name: Authenticated mobile parity navigation and fail-closed billing direction: DOWN timeout: 15000 visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: onboarding-skip - extendedWaitUntil: @@ -29,6 +30,7 @@ name: Authenticated mobile parity navigation and fail-closed billing - tapOn: id: login-email - inputText: ${MOBILE_E2E_EMAIL} +- hideKeyboard - tapOn: id: login-password - inputText: ${MOBILE_E2E_PASSWORD} @@ -39,6 +41,7 @@ name: Authenticated mobile parity navigation and fail-closed billing direction: DOWN timeout: 15000 visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: login-submit - extendedWaitUntil: @@ -60,8 +63,22 @@ name: Authenticated mobile parity navigation and fail-closed billing id: record-fab-dictation - assertVisible: id: record-screen +- scrollUntilVisible: + element: + id: record-import-file + direction: DOWN + timeout: 15000 + visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - assertVisible: id: record-import-file +- scrollUntilVisible: + element: + id: record-start + direction: DOWN + timeout: 15000 + visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: record-start - tapOn: @@ -74,14 +91,30 @@ name: Authenticated mobile parity navigation and fail-closed billing - setPermissions: permissions: microphone: allow +- scrollUntilVisible: + element: + id: record-start + direction: DOWN + timeout: 15000 + visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: record-start - extendedWaitUntil: visible: id: record-stop timeout: 15000 +- scrollUntilVisible: + element: + id: record-cancel + direction: DOWN + timeout: 15000 + visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: record-cancel + waitToSettleTimeoutMs: 1000 + retryTapIfNoChange: false - extendedWaitUntil: visible: id: record-start @@ -95,6 +128,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-talk direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-talk - assertVisible: @@ -109,6 +143,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: more-open-settings direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: more-open-settings - assertVisible: @@ -118,8 +153,16 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-account direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-account +- scrollUntilVisible: + element: + id: account-logout + direction: DOWN + timeout: 15000 + visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - assertVisible: id: account-logout - pressKey: BACK @@ -128,6 +171,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-paywall direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-paywall - assertVisible: @@ -143,6 +187,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-devices direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-devices - assertVisible: @@ -168,6 +213,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-templates direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-templates - assertVisible: @@ -178,6 +224,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-memos direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-memos - assertVisible: @@ -188,6 +235,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-teams direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-teams - assertVisible: @@ -198,6 +246,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-notifications direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-notifications - assertVisible: @@ -215,6 +264,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-notifications direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-notifications - assertVisible: @@ -227,6 +277,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-data-portability direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-data-portability - assertVisible: @@ -235,8 +286,9 @@ name: Authenticated mobile parity navigation and fail-closed billing - scrollUntilVisible: element: id: open-dictionary - direction: DOWN + direction: UP visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-dictionary - assertVisible: @@ -245,8 +297,9 @@ name: Authenticated mobile parity navigation and fail-closed billing - scrollUntilVisible: element: id: open-commands - direction: DOWN + direction: UP visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-commands - assertVisible: @@ -257,6 +310,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-knowledge direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-knowledge - assertVisible: @@ -267,6 +321,7 @@ name: Authenticated mobile parity navigation and fail-closed billing id: open-actions direction: DOWN visibilityPercentage: 50 + waitToSettleTimeoutMs: 1000 - tapOn: id: open-actions - assertVisible: diff --git a/apps/mobile-rn/.maestro/fresh-install-signup.yaml b/apps/mobile-rn/.maestro/fresh-install-signup.yaml index a576b327..2f5e0a6c 100644 --- a/apps/mobile-rn/.maestro/fresh-install-signup.yaml +++ b/apps/mobile-rn/.maestro/fresh-install-signup.yaml @@ -84,8 +84,8 @@ name: Fresh install complete tutorial and new-account boundary id: onboarding-next - scrollUntilVisible: element: - id: onboarding-step-5 - direction: UP + id: onboarding-theme-dark + direction: DOWN timeout: 10000 visibilityPercentage: 50 - swipe: @@ -130,10 +130,12 @@ name: Fresh install complete tutorial and new-account boundary permissions: microphone: allow notifications: allow -- extendedWaitUntil: - visible: +- scrollUntilVisible: + element: id: login-submit + direction: DOWN timeout: 30000 + visibilityPercentage: 50 - assertNotVisible: id: onboarding-screen - assertNotVisible: @@ -148,6 +150,12 @@ name: Fresh install complete tutorial and new-account boundary permissions: microphone: deny notifications: deny +- scrollUntilVisible: + element: + id: login-submit + direction: DOWN + timeout: 30000 + visibilityPercentage: 50 - assertVisible: id: login-submit - assertNotVisible: diff --git a/apps/mobile-rn/.maestro/navigation-shell-search-local.yaml b/apps/mobile-rn/.maestro/navigation-shell-search-local.yaml index e608c8d6..3b6c92a9 100644 --- a/apps/mobile-rn/.maestro/navigation-shell-search-local.yaml +++ b/apps/mobile-rn/.maestro/navigation-shell-search-local.yaml @@ -29,6 +29,7 @@ name: Mobile shell and unified search local proof - tapOn: id: login-email - inputText: ${MOBILE_E2E_EMAIL} +- hideKeyboard - tapOn: id: login-password - inputText: ${MOBILE_E2E_PASSWORD} @@ -86,6 +87,8 @@ name: Mobile shell and unified search local proof visible: id: history-detail-favorite timeout: 30000 +- assertVisible: + id: history-detail-share-markdown - takeScreenshot: unified-search-record-detail - pressKey: BACK - extendedWaitUntil: diff --git a/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx b/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx index 04605035..60f21c58 100644 --- a/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx +++ b/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx @@ -69,6 +69,28 @@ jest.mock('../src/features/history/history-service', () => { } }) +const mockPrepareTranscriptShareFile = jest.fn() +const mockPrepareAudioShareFile = jest.fn() +const mockSharePreparedPortableFile = jest.fn() +const mockDisposePreparedFile = jest.fn(async () => undefined) +const PREPARED_FILE = { + path: '/cache/portable_exports/transcript.md', + uri: 'file:///cache/portable_exports/transcript.md', + fileName: 'transcript.md', + mimeType: 'text/markdown', + format: 'md', + textContent: 'transcript', + dispose: mockDisposePreparedFile, +} + +jest.mock('../src/features/history/history-share', () => ({ + prepareTranscriptShareFile: (...args: unknown[]) => mockPrepareTranscriptShareFile(...args), + prepareAudioShareFile: (...args: unknown[]) => mockPrepareAudioShareFile(...args), +})) +jest.mock('../src/features/data-portability/portable-file', () => ({ + sharePreparedPortableFile: (...args: unknown[]) => mockSharePreparedPortableFile(...args), +})) + import HistoryDetailScreen from '../src/screens/HistoryDetailScreen' const SAMPLE_DETAIL: HistoryDetail = { @@ -129,7 +151,11 @@ describe('HistoryDetailScreen unmount audio & async cleanup', () => { mockPausePlayer.mockClear() mockResumePlayer.mockClear() mockGetHistoryDetail.mockReset().mockResolvedValue(SAMPLE_DETAIL) - mockCreateAudioPlaybackUrl.mockReset() + mockCreateAudioPlaybackUrl.mockReset().mockResolvedValue('https://storage.example/signed.wav') + mockPrepareTranscriptShareFile.mockReset().mockResolvedValue(PREPARED_FILE) + mockPrepareAudioShareFile.mockReset().mockResolvedValue(PREPARED_FILE) + mockSharePreparedPortableFile.mockReset().mockResolvedValue(undefined) + mockDisposePreparedFile.mockClear() mockGoBack.mockClear() }) @@ -181,4 +207,85 @@ describe('HistoryDetailScreen unmount audio & async cleanup', () => { }) expect(mockStartPlayer).not.toHaveBeenCalled() }) + + test('HistoryDetailScreen_Markdown버튼_파일생성및공유호출', async () => { + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + }) + + await act(async () => { + renderer.root.findByProps({ testID: 'history-detail-share-markdown' }).props.onPress() + await Promise.resolve() + }) + + expect(mockPrepareTranscriptShareFile).toHaveBeenCalledWith( + SAMPLE_DETAIL.entry, + 'md', + 'mobile.hist.summaryLabel', + ) + expect(mockSharePreparedPortableFile).toHaveBeenCalledWith(PREPARED_FILE, 'mobile.hist.shareMarkdown') + act(() => renderer.unmount()) + }) + + test('HistoryDetailScreen_원본오디오버튼_서명URL다운로드후공유', async () => { + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + }) + + await act(async () => { + renderer.root.findByProps({ testID: `history-audio-share-${AUDIO_ID}` }).props.onPress() + await Promise.resolve() + }) + + expect(mockCreateAudioPlaybackUrl).toHaveBeenCalledWith(USER_ID, SAMPLE_DETAIL.audioFiles[0]) + expect(mockPrepareAudioShareFile).toHaveBeenCalledWith( + SAMPLE_DETAIL.audioFiles[0], + 'https://storage.example/signed.wav', + ) + expect(mockSharePreparedPortableFile).toHaveBeenCalledWith(PREPARED_FILE, 'mobile.hist.shareAudio') + act(() => renderer.unmount()) + }) + + test('HistoryDetailScreen_공유준비중언마운트_늦은공유시트를열지않고파일정리', async () => { + let resolvePreparation: (file: typeof PREPARED_FILE) => void = () => undefined + mockPrepareAudioShareFile.mockImplementation( + () => new Promise((resolve) => { + resolvePreparation = resolve + }), + ) + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + }) + + await act(async () => { + renderer.root.findByProps({ testID: `history-audio-share-${AUDIO_ID}` }).props.onPress() + await Promise.resolve() + }) + act(() => renderer.unmount()) + await act(async () => { + resolvePreparation(PREPARED_FILE) + await Promise.resolve() + }) + + expect(mockSharePreparedPortableFile).not.toHaveBeenCalled() + expect(mockDisposePreparedFile).toHaveBeenCalledTimes(1) + }) }) diff --git a/apps/mobile-rn/__tests__/history-share.test.ts b/apps/mobile-rn/__tests__/history-share.test.ts new file mode 100644 index 00000000..ba80f6c2 --- /dev/null +++ b/apps/mobile-rn/__tests__/history-share.test.ts @@ -0,0 +1,92 @@ +import { FileSystem } from 'react-native-file-access'; +import { + MAX_SHARED_AUDIO_BYTES, + prepareAudioShareFile, + prepareTranscriptShareFile, +} from '../src/features/history/history-share'; + +jest.mock('react-native-file-access', () => ({ + Dirs: { CacheDir: '/cache' }, + FileSystem: { + exists: jest.fn(async () => true), + mkdir: jest.fn(async () => undefined), + writeFile: jest.fn(async () => undefined), + stat: jest.fn(async () => ({ size: 1 })), + unlink: jest.fn(async () => undefined), + }, +})); + +const ENTRY = { + title: '주간 회의', + original_text: '원문', + polished_text: '다듬은 전사', + summary_text: '요약 내용', +}; + +describe('기록 파일 공유', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('다듬은 전사와 요약을 Markdown 파일로 저장한다', async () => { + const file = await prepareTranscriptShareFile(ENTRY, 'md', '요약'); + + const write = jest.mocked(FileSystem.writeFile); + expect(file.format).toBe('md'); + expect(file.mimeType).toBe('text/markdown'); + expect(file.fileName.endsWith('.md')).toBe(true); + expect(write.mock.calls[0]?.[1]).toBe('# 주간 회의\n\n다듬은 전사\n\n## 요약\n\n요약 내용'); + }); + + it('다듬은 값이 비어 있으면 원문으로 텍스트 파일을 만든다', async () => { + await prepareTranscriptShareFile({ ...ENTRY, polished_text: ' ' }, 'txt', '요약'); + + expect(jest.mocked(FileSystem.writeFile).mock.calls[0]?.[1]).toBe('주간 회의\n\n원문\n\n요약\n\n요약 내용'); + }); + + it('사용자가 선택한 원본 오디오를 제한 안에서 파일로 준비한다', async () => { + const bytes = new Uint8Array([82, 73, 70, 70]); + const fetchAudio: typeof fetch = async () => new Response(bytes, { + status: 200, + headers: { 'content-length': String(bytes.byteLength) }, + }); + + const file = await prepareAudioShareFile({ + mime_type: 'audio/wav', + original_name: '회의.wav', + size_bytes: bytes.byteLength, + }, 'https://example.com/signed-audio', fetchAudio); + + expect(file).toMatchObject({ + format: 'binary', + mimeType: 'audio/wav', + textContent: null, + }); + expect(jest.mocked(FileSystem.writeFile).mock.calls[0]?.[2]).toBe('base64'); + }); + + it('Content-Length가 50 MiB를 넘으면 본문을 파일에 쓰지 않는다', async () => { + const fetchAudio: typeof fetch = async () => new Response(new Uint8Array([1]), { + status: 200, + headers: { 'content-length': String(MAX_SHARED_AUDIO_BYTES + 1) }, + }); + + await expect(prepareAudioShareFile({ + mime_type: 'audio/wav', + original_name: 'large.wav', + size_bytes: 1, + }, 'https://example.com/signed-audio', fetchAudio)).rejects.toThrow('50 MiB'); + expect(FileSystem.writeFile).not.toHaveBeenCalled(); + }); + + it('다운로드 실패를 공유 성공으로 처리하지 않는다', async () => { + const fetchAudio: typeof fetch = async () => new Response(null, { status: 403 }); + + await expect(prepareAudioShareFile({ + mime_type: 'audio/wav', + original_name: 'private.wav', + size_bytes: 4, + }, 'https://example.com/expired-audio', fetchAudio)).rejects.toThrow('HTTP 403'); + expect(FileSystem.writeFile).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile-rn/ios/D3ROVoice/Info.plist b/apps/mobile-rn/ios/D3ROVoice/Info.plist index d8aa0624..edf50ffa 100644 --- a/apps/mobile-rn/ios/D3ROVoice/Info.plist +++ b/apps/mobile-rn/ios/D3ROVoice/Info.plist @@ -31,7 +31,6 @@ Editor CFBundleURLSchemes - d3ro d3ro-voice diff --git a/apps/mobile-rn/package-lock.json b/apps/mobile-rn/package-lock.json index 73edac53..7c13cb0a 100644 --- a/apps/mobile-rn/package-lock.json +++ b/apps/mobile-rn/package-lock.json @@ -56,7 +56,7 @@ "typescript": "^5.8.3" }, "engines": { - "node": "^22.21.0 || ^24.3.0 || >=25.0.0" + "node": "24.x" } }, "../..": { diff --git a/apps/mobile-rn/package.json b/apps/mobile-rn/package.json index 41326829..ed88fdfa 100644 --- a/apps/mobile-rn/package.json +++ b/apps/mobile-rn/package.json @@ -61,6 +61,6 @@ "typescript": "^5.8.3" }, "engines": { - "node": "^22.21.0 || ^24.3.0 || >=25.0.0" + "node": "24.x" } } diff --git a/apps/mobile-rn/src/features/data-portability/portability-types.ts b/apps/mobile-rn/src/features/data-portability/portability-types.ts index d9c4bbb7..1c8f0f77 100644 --- a/apps/mobile-rn/src/features/data-portability/portability-types.ts +++ b/apps/mobile-rn/src/features/data-portability/portability-types.ts @@ -224,7 +224,7 @@ export interface PreparedPortableFile { uri: string; fileName: string; mimeType: string; - format: PortableTextFormat | MeetingDocumentFormat; + format: PortableTextFormat | MeetingDocumentFormat | 'binary'; textContent: string | null; dispose: () => Promise; } diff --git a/apps/mobile-rn/src/features/data-portability/portable-file.ts b/apps/mobile-rn/src/features/data-portability/portable-file.ts index 60b7be56..5b84f649 100644 --- a/apps/mobile-rn/src/features/data-portability/portable-file.ts +++ b/apps/mobile-rn/src/features/data-portability/portable-file.ts @@ -74,7 +74,7 @@ async function disposeExport(path: string): Promise { if (await FileSystem.exists(path)) await FileSystem.unlink(path); } -async function persistExport(options: { +export async function persistExport(options: { baseName: string; extension: string; mimeType: string; diff --git a/apps/mobile-rn/src/features/history/history-share.ts b/apps/mobile-rn/src/features/history/history-share.ts new file mode 100644 index 00000000..97f1c19d --- /dev/null +++ b/apps/mobile-rn/src/features/history/history-share.ts @@ -0,0 +1,94 @@ +import type { AudioFile, HistoryEntry } from '@d3ro/api-client'; +import { persistExport } from '../data-portability/portable-file'; +import type { PreparedPortableFile } from '../data-portability/portability-types'; + +export const MAX_SHARED_AUDIO_BYTES = 50 * 1024 * 1024; + +export type TranscriptShareFormat = 'txt' | 'md'; + +type TranscriptShareEntry = Pick< + HistoryEntry, + 'title' | 'original_text' | 'polished_text' | 'summary_text' +>; + +export function buildTranscriptShareText( + entry: TranscriptShareEntry, + format: TranscriptShareFormat, + summaryLabel: string, +): string { + const title = entry.title?.replace(/\s*\r?\n\s*/g, ' ').trim() ?? ''; + const transcript = entry.polished_text?.trim() || entry.original_text.trim(); + const summary = entry.summary_text?.trim() ?? ''; + const sections = [ + format === 'md' && title !== '' ? `# ${title}` : title, + transcript, + ]; + if (summary !== '') { + sections.push(`${format === 'md' ? '## ' : ''}${summaryLabel}`, summary); + } + return sections.filter(section => section !== '').join('\n\n'); +} + +export function prepareTranscriptShareFile( + entry: TranscriptShareEntry, + format: TranscriptShareFormat, + summaryLabel: string, +): Promise { + return persistExport({ + baseName: entry.title?.trim() || 'd3ro-transcript', + extension: format, + mimeType: format === 'md' ? 'text/markdown' : 'text/plain', + format, + text: buildTranscriptShareText(entry, format, summaryLabel), + bytes: null, + }); +} + +const AUDIO_EXTENSIONS: Readonly> = { + 'audio/aac': 'aac', + 'audio/flac': 'flac', + 'audio/mp4': 'm4a', + 'audio/mpeg': 'mp3', + 'audio/ogg': 'ogg', + 'audio/wav': 'wav', + 'audio/wave': 'wav', + 'audio/webm': 'webm', + 'audio/x-m4a': 'm4a', + 'audio/x-wav': 'wav', + 'video/mp4': 'mp4', +}; + +export async function prepareAudioShareFile( + audioFile: Pick, + signedUrl: string, + fetchAudio: typeof fetch = fetch, +): Promise { + const mimeType = audioFile.mime_type.toLowerCase().split(';')[0].trim(); + const extension = AUDIO_EXTENSIONS[mimeType]; + if (extension === undefined) throw new Error('Unsupported audio share format'); + if (audioFile.size_bytes > MAX_SHARED_AUDIO_BYTES) throw new Error('Audio share exceeds 50 MiB'); + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 30_000); + try { + const response = await fetchAudio(signedUrl, { signal: controller.signal }); + if (!response.ok) throw new Error(`Audio download failed with HTTP ${response.status}`); + const declaredLength = Number(response.headers.get('content-length')); + if (Number.isFinite(declaredLength) && declaredLength > MAX_SHARED_AUDIO_BYTES) { + throw new Error('Audio share exceeds 50 MiB'); + } + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength === 0) throw new Error('Audio share is empty'); + if (bytes.byteLength > MAX_SHARED_AUDIO_BYTES) throw new Error('Audio share exceeds 50 MiB'); + return await persistExport({ + baseName: audioFile.original_name?.replace(/\.[^.]+$/, '') || 'd3ro-audio', + extension, + mimeType, + format: 'binary', + text: null, + bytes, + }); + } finally { + clearTimeout(timeout); + } +} diff --git a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx index e5fe1b33..d8baa9d2 100644 --- a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx +++ b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx @@ -30,6 +30,14 @@ import { type HistoryDetail, } from '../features/history/history-service' import { loadHistoryCache } from '../features/history/history-cache' +import { + prepareAudioShareFile, + prepareTranscriptShareFile, +} from '../features/history/history-share' +import { + sharePreparedPortableFile, +} from '../features/data-portability/portable-file' +import type { PreparedPortableFile } from '../features/data-portability/portability-types' import { useMobilePreferences } from '../lib/preferences-context' const HISTORY_MODE_KEYS: Record = { @@ -104,6 +112,8 @@ export default function HistoryDetailScreen({ const [activeAudioId, setActiveAudioId] = useState(null) const [paused, setPaused] = useState(false) const [audioBusy, setAudioBusy] = useState(false) + const [sharingFile, setSharingFile] = useState(false) + const [sharingAudioId, setSharingAudioId] = useState(null) useEffect(() => { mountedRef.current = true @@ -306,6 +316,48 @@ export default function HistoryDetailScreen({ } } + const shareTranscriptFile = async (): Promise => { + if (detail === null || sharingFile) return + setSharingFile(true) + setError(null) + let file: PreparedPortableFile | null = null + try { + file = await prepareTranscriptShareFile(detail.entry, 'md', t('mobile.hist.summaryLabel')) + if (!mountedRef.current) { + await file.dispose().catch(() => undefined) + return + } + await sharePreparedPortableFile(file, t('mobile.hist.shareMarkdown')) + } catch { + if (file !== null) await file.dispose().catch(() => undefined) + if (mountedRef.current) setError(t('mobile.hist.shareFailed')) + } finally { + if (mountedRef.current) setSharingFile(false) + } + } + + const shareAudio = async (audioFile: AudioFile): Promise => { + if (user === null || sharingAudioId !== null || offline || audioFile.upload_status !== 'uploaded') return + setSharingAudioId(audioFile.id) + setError(null) + let file: PreparedPortableFile | null = null + try { + const signedUrl = await createAudioPlaybackUrl(user.id, audioFile) + if (!mountedRef.current) return + file = await prepareAudioShareFile(audioFile, signedUrl) + if (!mountedRef.current) { + await file.dispose().catch(() => undefined) + return + } + await sharePreparedPortableFile(file, t('mobile.hist.shareAudio')) + } catch { + if (file !== null) await file.dispose().catch(() => undefined) + if (mountedRef.current) setError(t('mobile.hist.audioError')) + } finally { + if (mountedRef.current) setSharingAudioId(null) + } + } + const controlAudio = async (audioFile: AudioFile): Promise => { if (user === null || audioBusy) return const playbackGeneration = ++playbackGenerationRef.current @@ -478,6 +530,16 @@ export default function HistoryDetailScreen({ > {t('mobile.hist.share')} + { void shareTranscriptFile() }} + style={styles.compactButton} + testID="history-detail-share-markdown" + > + {t('mobile.hist.shareMarkdown')} + @@ -611,6 +673,16 @@ export default function HistoryDetailScreen({ : t('mobile.hist.audioPlay')} + { void shareAudio(audioFile) }} + style={styles.compactButton} + testID={`history-audio-share-${audioFile.id}`} + > + {t('mobile.hist.share')} + ))} {activeAudioId !== null && ( @@ -729,7 +801,7 @@ function createStyles(palette: Palette) { }, inlineButton: { minHeight: 48, justifyContent: 'center' }, primaryCard: { gap: 8 }, - actionRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginBottom: 4 }, + actionRow: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 8, marginBottom: 4 }, compactButton: { minWidth: 48, minHeight: 48, diff --git a/packages/i18n/src/locales/de.json b/packages/i18n/src/locales/de.json index c884a8ed..fd7e8b2c 100644 --- a/packages/i18n/src/locales/de.json +++ b/packages/i18n/src/locales/de.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Markdown-Datei", + "mobile.hist.shareAudio": "Originalaudio teilen", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/en.json b/packages/i18n/src/locales/en.json index f52fecb2..b6731bde 100644 --- a/packages/i18n/src/locales/en.json +++ b/packages/i18n/src/locales/en.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Markdown file", + "mobile.hist.shareAudio": "Share source audio", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/es.json b/packages/i18n/src/locales/es.json index 94706841..1e169cb1 100644 --- a/packages/i18n/src/locales/es.json +++ b/packages/i18n/src/locales/es.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Archivo Markdown", + "mobile.hist.shareAudio": "Compartir audio original", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/fr.json b/packages/i18n/src/locales/fr.json index e311529a..5e50fcd5 100644 --- a/packages/i18n/src/locales/fr.json +++ b/packages/i18n/src/locales/fr.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Fichier Markdown", + "mobile.hist.shareAudio": "Partager l’audio d’origine", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/ja.json b/packages/i18n/src/locales/ja.json index 461e7130..e07fc617 100644 --- a/packages/i18n/src/locales/ja.json +++ b/packages/i18n/src/locales/ja.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Markdownファイル", + "mobile.hist.shareAudio": "元の音声を共有", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/ko.json b/packages/i18n/src/locales/ko.json index b7bd47aa..285f7cc5 100644 --- a/packages/i18n/src/locales/ko.json +++ b/packages/i18n/src/locales/ko.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "완료", "mobile.hist.jobStatus.failed": "실패", "mobile.hist.jobStatus.cancelled": "취소됨", + "mobile.hist.shareMarkdown": "Markdown 파일", + "mobile.hist.shareAudio": "원본 오디오 공유", "mobile.hist.share": "공유", "mobile.hist.shareFailed": "공유 시트를 열지 못했습니다.", "mobile.hist.editFailed": "서버에서 편집을 확정하지 못했습니다.", diff --git a/packages/i18n/src/locales/pt.json b/packages/i18n/src/locales/pt.json index 35cfc140..317b5a32 100644 --- a/packages/i18n/src/locales/pt.json +++ b/packages/i18n/src/locales/pt.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Arquivo Markdown", + "mobile.hist.shareAudio": "Compartilhar áudio original", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/ru.json b/packages/i18n/src/locales/ru.json index 49551c67..3d0073c6 100644 --- a/packages/i18n/src/locales/ru.json +++ b/packages/i18n/src/locales/ru.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Файл Markdown", + "mobile.hist.shareAudio": "Поделиться исходным аудио", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/th.json b/packages/i18n/src/locales/th.json index 06a0c925..4bd9214f 100644 --- a/packages/i18n/src/locales/th.json +++ b/packages/i18n/src/locales/th.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "ไฟล์ Markdown", + "mobile.hist.shareAudio": "แชร์เสียงต้นฉบับ", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/vi.json b/packages/i18n/src/locales/vi.json index 88f511e0..80aeb579 100644 --- a/packages/i18n/src/locales/vi.json +++ b/packages/i18n/src/locales/vi.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Tệp Markdown", + "mobile.hist.shareAudio": "Chia sẻ âm thanh gốc", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/zh-TW.json b/packages/i18n/src/locales/zh-TW.json index 09b169ff..cf43fa59 100644 --- a/packages/i18n/src/locales/zh-TW.json +++ b/packages/i18n/src/locales/zh-TW.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Markdown 檔案", + "mobile.hist.shareAudio": "分享原始音訊", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/packages/i18n/src/locales/zh.json b/packages/i18n/src/locales/zh.json index b8392b72..cce877aa 100644 --- a/packages/i18n/src/locales/zh.json +++ b/packages/i18n/src/locales/zh.json @@ -389,6 +389,8 @@ "mobile.hist.jobStatus.succeeded": "Completed", "mobile.hist.jobStatus.failed": "Failed", "mobile.hist.jobStatus.cancelled": "Cancelled", + "mobile.hist.shareMarkdown": "Markdown 文件", + "mobile.hist.shareAudio": "分享原始音频", "mobile.hist.share": "Share", "mobile.hist.shareFailed": "The share sheet could not be opened.", "mobile.hist.editFailed": "The server did not confirm the edit.", diff --git a/scripts/ci/build-mobile-local-e2e.ps1 b/scripts/ci/build-mobile-local-e2e.ps1 index 461057d5..f0a872c4 100644 --- a/scripts/ci/build-mobile-local-e2e.ps1 +++ b/scripts/ci/build-mobile-local-e2e.ps1 @@ -9,9 +9,22 @@ param( ) $ErrorActionPreference = 'Stop' +if ($PSVersionTable.PSEdition -eq 'Desktop') { + Import-Module (Join-Path $env:SystemRoot 'system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1') -Force +} $root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path $androidRoot = Join-Path $root 'apps\mobile-rn\android' -$status = & supabase status --workdir (Join-Path $root 'server') -o env 2>$null +$previousErrorActionPreference = $ErrorActionPreference +try { + $ErrorActionPreference = 'Continue' + $status = & npx --yes supabase@3.2.0 status --workdir (Join-Path $root 'server') -o env 2>$null + $statusExitCode = $LASTEXITCODE +} finally { + $ErrorActionPreference = $previousErrorActionPreference +} +if ($statusExitCode -ne 0) { + throw "Supabase status failed with exit code $statusExitCode" +} $configuration = @{} foreach ($line in $status) { if ($line -match '^([A-Z_]+)="(.*)"$') { $configuration[$matches[1]] = $matches[2] } diff --git a/scripts/ci/run-mobile-emulator-gate.sh b/scripts/ci/run-mobile-emulator-gate.sh index 9eeaefd9..7879014b 100644 --- a/scripts/ci/run-mobile-emulator-gate.sh +++ b/scripts/ci/run-mobile-emulator-gate.sh @@ -28,6 +28,8 @@ if [[ "$connected_devices" -ne 1 && -z "${ANDROID_SERIAL:-}" ]]; then exit 2 fi adb get-state | grep -Fx 'device' >/dev/null +target_serial="${ANDROID_SERIAL:-$(adb get-serialno)}" +maestro_device_args=(--udid "$target_serial") collect_evidence() { local gate_status="$1" @@ -72,7 +74,7 @@ adb shell pm path "$PACKAGE_NAME" | grep -F "package:" >/dev/null run_flow() { local flow_name="$1" local flow_path="$2" - "$MAESTRO_BIN" test "$flow_path" \ + "$MAESTRO_BIN" test "${maestro_device_args[@]}" "$flow_path" \ --format JUNIT \ --output "apps/mobile-rn/.maestro/${flow_name}.junit.xml" \ --test-output-dir "$OUTPUT_ROOT/$flow_name" @@ -89,7 +91,7 @@ adb shell wm size reset >/dev/null display_override_active='false' if [[ -n "${MOBILE_E2E_EMAIL:-}" && -n "${MOBILE_E2E_PASSWORD:-}" ]]; then - "$MAESTRO_BIN" test 'apps/mobile-rn/.maestro/authenticated-parity.yaml' \ + "$MAESTRO_BIN" test "${maestro_device_args[@]}" 'apps/mobile-rn/.maestro/authenticated-parity.yaml' \ -e MOBILE_E2E_EMAIL="$MOBILE_E2E_EMAIL" \ -e MOBILE_E2E_PASSWORD="$MOBILE_E2E_PASSWORD" \ --format JUNIT \ diff --git a/scripts/ci/verify-android-artifact.mjs b/scripts/ci/verify-android-artifact.mjs index 387c7e1c..a64fffe5 100644 --- a/scripts/ci/verify-android-artifact.mjs +++ b/scripts/ci/verify-android-artifact.mjs @@ -86,6 +86,7 @@ function sameFileSnapshot(left, right) { function parseArguments(argv) { const allowed = new Set([ 'aab', + 'allow-local-cleartext', 'apk', 'bundletool', 'expected-admob-app-id', @@ -706,7 +707,7 @@ function verifyDeepLinkManifest(manifest) { if (!verifiedAppLink) fail('missing_verified_app_link_accept_invite') } -function verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId) { +function verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId, allowLocalCleartext = false) { const packageInfo = badging.match(/package: name='([^']+)' versionCode='([0-9]+)' versionName='([^']+)'/) if (!packageInfo || packageInfo[1] !== EXPECTED_PACKAGE) fail('package_name_mismatch') const versionCode = Number(packageInfo[2]) @@ -719,7 +720,8 @@ function verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId) { if (mode !== 'debug' && debuggable) fail(`${mode}_must_not_be_debuggable`) if (mode === 'debug' && !debuggable) fail('debug_must_be_debuggable') - if (!/android:usesCleartextTraffic[^\n]*0x0\b/.test(manifest) && mode !== 'debug') { + const cleartextAllowed = mode === 'debug' || (mode === 'e2e' && allowLocalCleartext) + if (!/android:usesCleartextTraffic[^\n]*0x0\b/.test(manifest) && !cleartextAllowed) { fail(`${mode}_cleartext_must_be_false`) } const requiredPermissions = [ @@ -747,11 +749,11 @@ function verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId) { return { debuggable, adMobAppId, versionName, versionCode, minSdk, targetSdk } } -function verifyManifest(aapt, archive, mode, expectedAdMobAppId) { +function verifyManifest(aapt, archive, mode, expectedAdMobAppId, allowLocalCleartext = false) { const apkPath = archive.absolute const badging = runArtifact(aapt, ['dump', 'badging', apkPath], 'aapt_badging', archive) const manifest = runArtifact(aapt, ['dump', 'xmltree', apkPath, 'AndroidManifest.xml'], 'aapt_manifest', archive) - return verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId) + return verifyManifestContracts(badging, manifest, mode, expectedAdMobAppId, allowLocalCleartext) } function verifyArchive(archive, mode) { @@ -1114,6 +1116,35 @@ function runSigningPolicySelfTest() { if (!legacyArgumentRejected) fail('self_test_legacy_certificate_argument_not_rejected') const manifestFixture = createManifestContractSelfTestFixture() + const localOptions = parseArguments([ + '--mode', 'e2e', + '--apk', 'local.apk', + '--allow-local-cleartext', 'true', + ]) + if (localOptions['allow-local-cleartext'] !== 'true') fail('self_test_local_cleartext_option') + const localE2eManifest = manifestFixture.manifest + .replace('android:usesCleartextTraffic=(type 0x12)0x0', 'android:usesCleartextTraffic=(type 0x12)0xffffffff') + .replaceAll('ca-app-pub-1234567890123456~1234567890', TEST_ADMOB_APP_ID) + expectSelfTestFailure( + 'manifest_local_e2e_cleartext_default', + () => verifyManifestContracts(manifestFixture.badging, localE2eManifest, 'e2e', null), + 'e2e_cleartext_must_be_false', + ) + verifyManifestContracts(manifestFixture.badging, localE2eManifest, 'e2e', null, true) + expectSelfTestFailure( + 'manifest_release_cleartext_override', + () => verifyManifestContracts( + manifestFixture.badging, + manifestFixture.manifest.replace( + 'android:usesCleartextTraffic=(type 0x12)0x0', + 'android:usesCleartextTraffic=(type 0x12)0xffffffff', + ), + 'release', + 'ca-app-pub-1234567890123456~1234567890', + true, + ), + 'release_cleartext_must_be_false', + ) const manifestEvidence = verifyManifestContracts( manifestFixture.badging, manifestFixture.manifest, @@ -1434,6 +1465,11 @@ if (cliArguments.length === 1 && cliArguments[0] === '--self-test') { const options = parseArguments(cliArguments) const mode = options.mode if (!VALID_MODES.has(mode)) fail(`unknown_mode_${mode}`) +const localCleartextOption = options['allow-local-cleartext'] +if (localCleartextOption !== undefined && (localCleartextOption !== 'true' || mode !== 'e2e')) { + fail('allow_local_cleartext_only_valid_for_local_e2e') +} +const allowLocalCleartext = localCleartextOption === 'true' if (!options.apk) fail('apk_path_required') const apkPath = resolve(options.apk) if (!existsSync(apkPath)) fail(`apk_missing_${apkPath}`) @@ -1462,6 +1498,7 @@ try { archive, mode, options['expected-admob-app-id'], + allowLocalCleartext, ) if (mode !== 'debug') { const expectedVersionName = options['expected-version-name'] diff --git a/scripts/ci/verify-mobile-build-config.mjs b/scripts/ci/verify-mobile-build-config.mjs index 91e19602..1e7be9a4 100644 --- a/scripts/ci/verify-mobile-build-config.mjs +++ b/scripts/ci/verify-mobile-build-config.mjs @@ -4,6 +4,10 @@ import { resolve } from 'node:path' const ROOT = resolve(import.meta.dirname, '../..') const BUILD_GRADLE = resolve(ROOT, 'apps/mobile-rn/android/app/build.gradle') const ROOT_BUILD_GRADLE = resolve(ROOT, 'apps/mobile-rn/android/build.gradle') +const ANDROID_MANIFEST = resolve(ROOT, 'apps/mobile-rn/android/app/src/main/AndroidManifest.xml') +const IOS_PROJECT = resolve(ROOT, 'apps/mobile-rn/ios/D3ROVoice.xcodeproj/project.pbxproj') +const IOS_PLIST = resolve(ROOT, 'apps/mobile-rn/ios/D3ROVoice/Info.plist') +const AUTH_REDIRECT = resolve(ROOT, 'apps/mobile-rn/src/lib/auth-redirect.ts') const PRODUCT_VERSION = resolve(ROOT, 'release/product-version.json') const CONFIG_MODULE = resolve( ROOT, @@ -60,16 +64,48 @@ function parseIntegerConstant(source, name) { } async function readSourceContractFiles() { - const [gradle, rootGradle, configModule, productVersionSource] = await Promise.all([ + const [ + gradle, + rootGradle, + configModule, + productVersionSource, + androidManifest, + iosProject, + iosPlist, + authRedirect, + ] = await Promise.all([ readFile(BUILD_GRADLE, 'utf8'), readFile(ROOT_BUILD_GRADLE, 'utf8'), readFile(CONFIG_MODULE, 'utf8'), readFile(PRODUCT_VERSION, 'utf8'), + readFile(ANDROID_MANIFEST, 'utf8'), + readFile(IOS_PROJECT, 'utf8'), + readFile(IOS_PLIST, 'utf8'), + readFile(AUTH_REDIRECT, 'utf8'), ]) - return { gradle, rootGradle, configModule, productVersion: JSON.parse(productVersionSource) } + return { + gradle, + rootGradle, + configModule, + productVersion: JSON.parse(productVersionSource), + androidManifest, + iosProject, + iosPlist, + authRedirect, + } } -function verifySourceContractSources({ gradle, rootGradle, configModule, productVersion }) { +function verifySourceContractSources(sources) { + const { + gradle, + rootGradle, + configModule, + productVersion, + androidManifest, + iosProject, + iosPlist, + authRedirect, + } = sources if (/gradle\.startParameter\.taskNames/.test(gradle)) { fail('variant_gate_must_not_use_requested_task_name_heuristics') } @@ -78,6 +114,36 @@ function verifySourceContractSources({ gradle, rootGradle, configModule, product } const defaultConfigBlock = extractBlock(gradle, /\bdefaultConfig\s*\{/, 'missing_default_config') + requireMatch( + defaultConfigBlock, + /applicationId\s+"com\.d3ro\.voice"/, + 'android_application_id_must_be_canonical', + ) + const iosBundleIds = [...iosProject.matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*([^;]+);/g)] + .map(match => match[1].trim()) + if (iosBundleIds.length === 0 || iosBundleIds.some(value => value !== 'com.d3ro.voice')) { + fail('ios_bundle_identifier_must_be_canonical') + } + const iosSchemeBlock = iosPlist.match( + /CFBundleURLSchemes<\/key>\s*([\s\S]*?)<\/array>/, + )?.[1] + if (!iosSchemeBlock) fail('ios_url_schemes_missing') + const iosSchemes = [...iosSchemeBlock.matchAll(/([^<]+)<\/string>/g)].map(match => match[1]) + if (iosSchemes.length !== 1 || iosSchemes[0] !== 'd3ro-voice') { + fail('ios_url_scheme_must_be_canonical') + } + requireMatch( + authRedirect, + /AUTH_REDIRECT_URL\s*=\s*'d3ro-voice:\/\/auth-callback'/, + 'oauth_callback_scheme_must_be_canonical', + ) + for (const host of ['auth-callback', 'accept-invite']) { + requireMatch( + androidManifest, + new RegExp(`android:scheme="d3ro-voice"\\s+android:host="${host}"`), + `android_${host}_deep_link_must_be_canonical`, + ) + } const buildTypesBlock = extractBlock(gradle, /\bbuildTypes\s*\{/, 'missing_build_types') const e2eBlock = extractBlock(buildTypesBlock, /\be2e\s*\{/, 'missing_e2e_build_type') const debugBlock = extractBlock(buildTypesBlock, /\bdebug\s*\{/, 'missing_debug_build_type') @@ -269,10 +335,10 @@ async function verifySourceContract() { verifySourceContractSources(await readSourceContractFiles()) } -function expectSourceContractFailure(sources, mutate, expectedMessage) { +function expectSourceContractFailure(sources, mutate, expectedMessage, field = 'gradle') { let failedAsExpected = false try { - verifySourceContractSources({ ...sources, gradle: mutate(sources.gradle) }) + verifySourceContractSources({ ...sources, [field]: mutate(sources[field]) }) } catch (error) { if (!(error instanceof Error) || !error.message.includes(expectedMessage)) throw error failedAsExpected = true @@ -341,6 +407,35 @@ function verifyVariant(variant, buildConfig) { if (process.argv.includes('--self-test')) { const sources = await readSourceContractFiles() verifySourceContractSources(sources) + expectSourceContractFailure( + sources, + (gradle) => gradle.replace('applicationId "com.d3ro.voice"', 'applicationId "invalid.example"'), + 'android_application_id_must_be_canonical', + ) + expectSourceContractFailure( + sources, + (iosProject) => iosProject.replaceAll('PRODUCT_BUNDLE_IDENTIFIER = com.d3ro.voice;', 'PRODUCT_BUNDLE_IDENTIFIER = invalid.example;'), + 'ios_bundle_identifier_must_be_canonical', + 'iosProject', + ) + expectSourceContractFailure( + sources, + (iosPlist) => iosPlist.replace('d3ro-voice', 'd3ro'), + 'ios_url_scheme_must_be_canonical', + 'iosPlist', + ) + expectSourceContractFailure( + sources, + (authRedirect) => authRedirect.replace('d3ro-voice://auth-callback', 'd3ro://auth-callback'), + 'oauth_callback_scheme_must_be_canonical', + 'authRedirect', + ) + expectSourceContractFailure( + sources, + (androidManifest) => androidManifest.replace('android:scheme="d3ro-voice" android:host="auth-callback"', 'android:scheme="d3ro" android:host="auth-callback"'), + 'android_auth-callback_deep_link_must_be_canonical', + 'androidManifest', + ) expectSourceContractFailure( sources, (gradle) => gradle.replace('candidate.name == "preE2eBuild"', 'candidate.name == "preE2eBuildDisabled"'),