Compare commits

..

No commits in common. "eedd127ea7a1d612f1e42187f61800f4c4948d75" and "db8d9448a38c670ceca1cea383bb70e518538da7" have entirely different histories.

247 changed files with 11903 additions and 5404 deletions

View file

@ -207,22 +207,11 @@ git 충돌 + 의도 분리 불가. **R3 위반**.
### P9. lint 게이트의 pre-existing 부채 — "내 영역 errors 0"으로 재해석
codebase가 원래 lint GREEN이 아닌 경우가 많음(루트 `eslint .`가 다른 앱의 config 문제로 붕괴, pre-existing errors 다수). "통합 후 lint GREEN"(R7 원문)이 비현실적. 게이트는 **"내가 건드린 영역의 lint errors 0"** + "pre-existing은 별도 wave로 분리"로 재해석. (검증 팁: `git diff --name-only HEAD`로 변경 파일만 lint → 내 책임 분리.)
### P10. "실행되지 않는 사본"과 "운영 서버 사본"도 중복 감사 대상 (Wave 3)
- 워크플로·스크립트는 원격·러너 기준으로 **실제로 실행되는지** 먼저 본다. `.github`는 GitHub 원격이 없어 한 번도 안 돌았고, 그 안의 Payple 갱신 cron 때문에 정기 결제가 멈춰 있었다.
- 배포 전 운영 서버의 설정 파일(NAS compose·.env 키 이름)과 저장소를 diff한다. 저장소를 그대로 덮으면 필수 변수 누락으로 서비스가 내려간다.
### P11. 직접 import할 수 없는 런타임은 "생성 사본 + --check"로만 복제 (Wave 3)
Deno Edge Function처럼 공유 패키지를 번들할 수 없으면 손으로 옮겨 적지 말고 생성 스크립트(`contract:sync`)와 CI 게이트(`contract:check`)를 둔다. `version:sync`와 같은 패턴.
### P12. 데스크톱 테스트는 Electron 런타임으로 (Wave 3)
Node로 vitest를 돌리면 better-sqlite3 ABI 불일치로 수백 건이 가짜 실패한다. `ELECTRON_RUN_AS_NODE=1 <electron.exe> <vitest.mjs> run --config vitest.config.ts`로 돌리고, 남는 실패만 회귀 후보로 본다.
## 누적 wave 인덱스
| Wave | 일시 | 산출 커밋 | 보고서 |
|------|------|-----------|--------|
| Wave 1 | 2026-07-22 | b820c78(WS1)·aef4428(WS2)·078304d(WS3)·87f2dac(WS4) | `docs/REFACTOR_WAVE1_REPORT.md` |
| Wave 2 | 2026-07-22 | efac690(AMBER)·660e622(NATIVE)·00a99e4(POPUP)·4c25620(DEPS)·5b6e7aa(PATTERN) | `docs/REFACTOR_WAVE2_REPORT.md` |
| Wave 3 | 2026-09-26 | 88f24d8(WS-A 계약)·b6fe588(WS-B 웹앱)·cd9d199(WS-C 중복 삭제)·dc43884(WS-D CI)·9297860(사이트) | `docs/REFACTOR_WAVE3_REPORT.md` |
다음 wave 추가 시 본 표 갱신.

View file

@ -26,7 +26,3 @@ obj/
*.db-wal
.env
.env.local
# 앱별 로컬 환경 파일(비밀값)이 이미지 빌드 컨텍스트에 들어가지 않게 한다.
**/.env
**/.env.*

View file

@ -1,12 +1,13 @@
# Copy this file to .env for local operations only. Never commit populated values.
# NAS deployment target (scripts/deploy-nas.ps1, scripts/deploy-nas.sh)
NAS_HOST=
NAS_USER=
NAS_SSH_PORT=22
NAS_DEPLOY_PATH=/volume1/docker/d3ro
# NAS deployment target
DSM_HOST=
DSM_SSH_PORT=22
DSM_SSH_USER=
DSM_SSH_PASSWORD=
NAS_DEPLOY_ROOT=/volume1/docker/d3ro-voice
NAS_ADMIN_PORT=5000
NAS_LANDING_PORT=4321
# Git/Forgejo operations
GIT_SERVER_URL=https://git.example.invalid
@ -17,8 +18,9 @@ FORGEJO_TOKEN=
FORGEJO_USERNAME=
FORGEJO_PASSWORD=
# Public service addresses. The canonical values live in packages/core/src/web-urls.ts;
# the NAS compose needs API_SERVER_URL for the admin login backend (https only).
# Public service addresses
APP_DOMAIN=voice.example.invalid
ADMIN_DOMAIN=admin.voice.example.invalid
API_SERVER_URL=https://voice.example.invalid
SITE_URL=https://voice.example.invalid
CORS_ALLOWED_ORIGINS=https://voice.example.invalid,https://admin.voice.example.invalid
@ -91,21 +93,3 @@ D3RO_WORKER_PUSH_DRAIN_BATCH_LIMIT=20
# Optional authenticated mobile E2E account, stored only in CI secrets or local .env.
MOBILE_E2E_EMAIL=
MOBILE_E2E_PASSWORD=
# Web app image build (apps/web/Dockerfile build args; public values baked into the bundle)
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
NEXT_PUBLIC_PAYPLE_CLIENT_KEY=
# Supabase management (CLI / Management API without an interactive login)
SUPABASE_PROJECT_REF=
SUPABASE_ACCESS_TOKEN=
# Payple renewal cron: same value as the Supabase function secret and the Forgejo secret
CRON_SECRET=
# Cloudflare (tunnel ingress, DNS, Pages and the site bridge worker)
CLOUDFLARE_API_TOKEN=
CLOUDFLARE_ACCOUNT_ID=
CLOUDFLARE_ZONE_ID=
CLOUDFLARE_TUNNEL_ID=

View file

@ -1,188 +0,0 @@
name: ci
# 브랜치·PR 검증. 예전 .github/workflows/ci.yml(GitHub 원격이 없어 한 번도 실행되지 않음)에서
# 자체 호스팅 linux-builder 러너로 돌릴 수 있는 잡만 옮겼다.
#
# 옮기지 않은 잡:
# - test-matrix의 windows/macos 칸: macOS 러너가 없고, windows 러너는 태그 릴리스 전용으로 둔다.
# - mobile-android APK 빌드 / mobile-emulator-e2e: Android SDK + KVM 에뮬레이터가 필요하다.
# GitLab 미러(.gitlab-ci.yml mobile-android, mobile-emulator-e2e)가 계속 담당한다.
#
# 러너 관례: actions/checkout·setup-* 없이 github.token으로 직접 fetch 한다(다른 .forgejo 워크플로와 동일).
# Deno/.NET은 scripts/ci/bootstrap-linux-toolchain.sh 가 체크섬 검증 후 설치한다.
# git clean -fdx 로 지워지지 않도록 도구 캐시는 체크아웃 밖(CI_PROJECT_DIR)에 둔다.
#
# 필요한 시크릿: 없음 (github.token 만 사용)
on:
push:
branches:
- main
- develop
- "feature/**"
- "fix/**"
pull_request:
branches:
- main
- develop
workflow_dispatch:
jobs:
quality:
name: 정본·보안·린트·타입·테스트
runs-on: linux-builder
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
proto="${GITHUB_SERVER_URL%%://*}"; host="${GITHUB_SERVER_URL#*://}"
url="$proto://actions:${CI_TOKEN}@${host%/}/${GITHUB_REPOSITORY}.git"
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: 도구 버전
run: |
echo "node $(node --version) (.nvmrc $(cat .nvmrc)) / npm $(npm --version)"
- name: 의존성 설치
run: npm ci
- name: 버전·계약 정본 대조
run: |
npm run version:check
npm run contract:check
npm run release:metadata:test
- name: 하드코딩 자격증명 검사
run: |
npm run security:secrets:test
npm run security:secrets
- name: 모바일 릴리스 경계·설정 계약
run: |
npm run release:mobile:boundary:test
npm run release:mobile:config:test
npm run release:mobile:build-config:test
npm run release:play:assets
- name: 린트
run: npm run lint
- name: 타입 검사
run: npm run typecheck
- name: 테스트 (Vitest)
run: npm test
build-validation:
name: 워크스페이스 빌드 검증
needs: quality
runs-on: linux-builder
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
proto="${GITHUB_SERVER_URL%%://*}"; host="${GITHUB_SERVER_URL#*://}"
url="$proto://actions:${CI_TOKEN}@${host%/}/${GITHUB_REPOSITORY}.git"
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: 의존성 설치
run: npm ci
- name: 데스크톱 번들 빌드 + 렌더러 번들 검증
run: |
npm run build --workspace=@d3ro/desktop
node scripts/ci/verify-desktop-renderer-bundles.mjs
- name: 어드민 빌드
run: npm run build --workspace=@d3ro/admin
mobile-quality:
name: 모바일 린트·타입·Jest
runs-on: linux-builder
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
proto="${GITHUB_SERVER_URL%%://*}"; host="${GITHUB_SERVER_URL#*://}"
url="$proto://actions:${CI_TOKEN}@${host%/}/${GITHUB_REPOSITORY}.git"
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: 의존성 설치
run: |
npm ci
npm --prefix apps/mobile-rn ci --workspaces=false
- name: 모바일 검사
run: |
npm --prefix apps/mobile-rn run lint
npm --prefix apps/mobile-rn run typecheck
npm --prefix apps/mobile-rn run test:ci
edge-functions:
name: Supabase Edge Functions + Cloudflare Worker
runs-on: linux-builder
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
proto="${GITHUB_SERVER_URL%%://*}"; host="${GITHUB_SERVER_URL#*://}"
url="$proto://actions:${CI_TOKEN}@${host%/}/${GITHUB_REPOSITORY}.git"
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: Deno 2.8.1 설치 후 검사·테스트
shell: bash
run: |
set -euo pipefail
export CI_PROJECT_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/d3ro-ci"
. scripts/ci/bootstrap-linux-toolchain.sh deno
for entrypoint in server/supabase/functions/*/index.ts; do
deno check --config server/supabase/functions/deno.json "$entrypoint"
done
deno test --config server/supabase/functions/deno.json --allow-read --allow-env server/supabase/functions
deno check --no-config server/cloudflare-worker/src/push-drain.ts
deno test --no-config --allow-read server/cloudflare-worker/src/push-drain.test.ts
api-server-tests:
name: .NET API 서버 테스트
runs-on: linux-builder
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
proto="${GITHUB_SERVER_URL%%://*}"; host="${GITHUB_SERVER_URL#*://}"
url="$proto://actions:${CI_TOKEN}@${host%/}/${GITHUB_REPOSITORY}.git"
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: .NET 10.0.302 설치 후 테스트
shell: bash
run: |
set -euo pipefail
export CI_PROJECT_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/d3ro-ci"
. scripts/ci/bootstrap-linux-toolchain.sh dotnet
dotnet restore apps/api-server.Tests/D3ROVoice.Api.Tests.csproj
dotnet test apps/api-server.Tests/D3ROVoice.Api.Tests.csproj --configuration Release --no-restore -p:StaticWebAssetsEnabled=false

View file

@ -0,0 +1,34 @@
name: deploy-site-windows
on:
workflow_dispatch:
jobs:
deploy-win:
runs-on: windows
defaults: { run: { shell: pwsh } }
steps:
- name: checkout
env: { CI_TOKEN: "${{ github.token }}" }
run: |
$u = [Uri]$env:GITHUB_SERVER_URL
$url = "$($u.Scheme)://actions:$($env:CI_TOKEN)@$($u.Authority)/$($env:GITHUB_REPOSITORY).git"
if (-not (Test-Path .git)) { git init -q . }
if (git remote | Select-String -Quiet '^origin$') { git remote set-url origin $url } else { git remote add origin $url }
git fetch -q --depth 1 origin $env:GITHUB_REF
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: 사이트 빌드
run: |
npm ci --prefix site
npm run build --prefix site
- name: Cloudflare Pages 배포
env:
CLOUDFLARE_API_TOKEN: "${{ secrets.CF_API_TOKEN || secrets.CLOUDFLARE_API_TOKEN }}"
CLOUDFLARE_ACCOUNT_ID: "${{ secrets.CF_ACCOUNT_ID || secrets.CLOUDFLARE_ACCOUNT_ID }}"
run: |
if ($env:CLOUDFLARE_API_TOKEN) {
npx --yes wrangler@latest pages deploy site/dist --project-name d3ro --branch main --commit-dirty=true
}

View file

@ -1,14 +1,5 @@
name: deploy-site
# 사이트(site/) 배포의 유일한 경로: Cloudflare Pages `d3ro` (d3ro.chanpaca.net).
# 예전 deploy-site-windows.yml(수동 전용·배포 검증 없음)과 .github/workflows/deploy-site.yml
# (GitHub Pages, 실행된 적 없음)을 이 파일로 합쳤다.
#
# site/는 저장소 루트의 packages/core/src/*.ts 를 상대 import 하므로 전체 트리를 체크아웃한다
# (sparse checkout 금지).
#
# 필요한 시크릿: CF_API_TOKEN(또는 CLOUDFLARE_API_TOKEN), CF_ACCOUNT_ID(또는 CLOUDFLARE_ACCOUNT_ID)
on:
push:
branches: [main]
@ -30,9 +21,6 @@ jobs:
git checkout -q -f FETCH_HEAD
git clean -qfdx
- name: 모바일 릴리스 공개 경계 검사
run: node scripts/ci/verify-mobile-release-boundary.mjs --self-test
- name: 의존성 설치 및 사이트 빌드
run: |
npm ci --prefix site

View file

@ -1,47 +0,0 @@
name: payple-renew
# Payple 정기결제 자동 갱신 트리거. 매일 한 번 Supabase Edge Function `payple-renew`를 호출한다.
# 예전 .github/workflows/payple-renew.yml은 GitHub 원격이 없어 한 번도 실행되지 않았다.
#
# 주의:
# - Forgejo schedule은 기본 브랜치(main)에 이 파일이 있을 때만 등록된다.
# - cron 시각은 Forgejo 서버 기준으로 해석된다. 서버가 UTC면 01:00 UTC = 10:00 KST.
#
# 필요한 시크릿:
# SUPABASE_URL — https://<project-ref>.supabase.co (끝 슬래시 없이)
# CRON_SECRET — Supabase Function 시크릿 CRON_SECRET 과 같은 값
on:
schedule:
- cron: "0 1 * * *"
workflow_dispatch:
jobs:
renew:
runs-on: linux-builder
steps:
- name: payple-renew Edge Function 호출
env:
SUPABASE_URL: "${{ secrets.SUPABASE_URL }}"
CRON_SECRET: "${{ secrets.CRON_SECRET }}"
run: |
set -eu
if [ -z "${SUPABASE_URL:-}" ] || [ -z "${CRON_SECRET:-}" ]; then
echo "SUPABASE_URL / CRON_SECRET 시크릿이 없습니다." >&2
exit 1
fi
response=$(curl --silent --show-error --max-time 300 -w "\n%{http_code}" -X POST \
"${SUPABASE_URL%/}/functions/v1/payple-renew" \
-H "Authorization: Bearer ${CRON_SECRET}" \
-H "Content-Type: application/json")
http_code=$(printf '%s\n' "$response" | tail -n 1)
body=$(printf '%s\n' "$response" | sed '$d')
echo "HTTP $http_code"
printf '%s\n' "$body" | jq . 2>/dev/null || printf '%s\n' "$body"
if [ "$http_code" -ge 400 ]; then
echo "갱신 실패: HTTP $http_code" >&2
exit 1
fi

View file

@ -1,8 +1,9 @@
name: release
# Canonical tag-triggered desktop release built and published on Forgejo.
# GitLab CI (.gitlab-ci.yml) is the legacy mirror builder; both converge on
# publish-forgejo-release.mjs so the Forgejo feed is the single update source.
# GitLab CI (.gitlab-ci.yml) and GitHub Actions (.github/workflows/release.yml)
# remain alternate builders; all three converge on publish-forgejo-release.mjs
# so the Forgejo feed is the single update source.
#
# Required repository secrets:
# FORGEJO_TOKEN — PAT with write:package + write:repository

91
.github/workflows/build-mac.yml vendored Normal file
View file

@ -0,0 +1,91 @@
name: Build macOS
on:
workflow_dispatch:
inputs:
notarize:
description: 'Apple Notarization 활성화'
required: false
default: 'false'
type: choice
options:
- 'false'
- 'true'
jobs:
build:
name: Build & Package (macOS)
runs-on: macos-14 # arm64 (Apple Silicon)
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
arch: [arm64, x64]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Setup Python (sidecar 빌드용)
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install system deps (sox)
run: brew install sox
- name: Install npm dependencies
run: npm install
- name: Bundle SoX into resources
working-directory: apps/desktop
run: bash scripts/install-sox.sh
- name: Build STT sidecar (PyInstaller)
working-directory: apps/desktop
run: |
# 로컬 전사는 사이드카 번들에 의존한다. 누락된 채 패키징하면 설치본에서
# 전사가 전혀 동작하지 않으므로 빌드 후 반드시 검증한다.
npm run sidecar:setup
npm run sidecar:build
node ../../scripts/ci/verify-sidecar-bundle.mjs
- name: Rebuild native modules for Electron
run: npx --yes @electron/rebuild@3 --version=33.4.11
- name: Build renderer/preload/main
run: npm run build
- name: electron-builder dist (mac, ${{ matrix.arch }})
working-directory: apps/desktop
env:
# Apple 서명/공증 (notarize=true일 때만 사용)
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
CSC_LINK: ${{ secrets.MAC_CERT_P12_BASE64 }}
CSC_KEY_PASSWORD: ${{ secrets.MAC_CERT_P12_PASSWORD }}
NOTARIZE: ${{ inputs.notarize || 'false' }}
run: |
if [ "$NOTARIZE" = "true" ] && [ -n "$APPLE_ID" ]; then
npx electron-builder --mac --${{ matrix.arch }} -c.mac.notarize=true
else
npx electron-builder --mac --${{ matrix.arch }} -c.mac.notarize=false
fi
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: d3ro-voice-mac-${{ matrix.arch }}
path: |
apps/desktop/release/*.dmg
apps/desktop/release/*.zip
if-no-files-found: error
retention-days: 7

333
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,333 @@
# .github/workflows/ci.yml
# Continuous Integration Pipeline for D3RO Voice Monorepo
name: CI Pipeline
on:
push:
branches:
- main
- develop
- 'feature/**'
- 'fix/**'
pull_request:
branches:
- main
- develop
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# ──────────────────────────────────────────────────────────────────
# 1. Code Quality, Linting & Typecheck
# ──────────────────────────────────────────────────────────────────
code-quality:
name: Code Quality & Typecheck
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Credential Scanner Self-Test
run: npm run security:secrets:test
- name: Hard-Coded Credential Scan
run: npm run security:secrets
- name: Mobile Release Boundary Self-Test
run: npm run release:mobile:boundary:test
- name: Mobile Release Configuration Self-Test
run: npm run release:mobile:config:test
- name: Mobile Build Configuration Self-Test
run: npm run release:mobile:build-config:test
- name: Play Store Asset Contract
run: npm run release:play:assets
- name: Lint Check
run: npm run lint
- name: Typecheck All Workspaces
run: npm run typecheck
api-server-tests:
name: .NET API Server Tests
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup .NET 10
uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.302'
- name: Restore API Test Dependencies
run: dotnet restore apps/api-server.Tests/D3ROVoice.Api.Tests.csproj
- name: Run API Authorization and Gateway Tests
run: dotnet test apps/api-server.Tests/D3ROVoice.Api.Tests.csproj --configuration Release --no-restore -p:StaticWebAssetsEnabled=false
edge-functions-quality:
name: Supabase Edge Functions Typecheck & Tests
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Deno 2.8.1
uses: denoland/setup-deno@v2
with:
deno-version: v2.8.1
- name: Check Every Edge Function Entrypoint
shell: bash
run: |
set -euo pipefail
for entrypoint in server/supabase/functions/*/index.ts; do
deno check --config server/supabase/functions/deno.json "$entrypoint"
done
- name: Run Edge Function Contract Tests
run: deno test --config server/supabase/functions/deno.json --allow-read --allow-env server/supabase/functions
- name: Check Cloudflare Worker Drain
run: deno check --no-config server/cloudflare-worker/src/push-drain.ts
- name: Run Cloudflare Worker Tests
run: deno test --no-config --allow-read server/cloudflare-worker/src/push-drain.test.ts
# ──────────────────────────────────────────────────────────────────
# 2. Automated Test Matrix (Windows / macOS / Ubuntu)
# ──────────────────────────────────────────────────────────────────
test-matrix:
name: Test Suite (${{ matrix.os }})
needs: code-quality
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Run Monorepo Test Suites (Vitest)
run: npm test
# ──────────────────────────────────────────────────────────────────
# 3. Build Validation for All Workspaces
# ──────────────────────────────────────────────────────────────────
build-validation:
name: Build Validation (${{ matrix.target }})
needs: code-quality
strategy:
matrix:
include:
- target: desktop
os: windows-latest
cmd: npm run build --workspace=@d3ro/desktop
- target: admin
os: ubuntu-latest
cmd: npm run build --workspace=@d3ro/admin
runs-on: ${{ matrix.os }}
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build Target Workspace
run: ${{ matrix.cmd }}
- name: Verify Desktop Renderer Bundles
if: matrix.target == 'desktop'
run: node scripts/ci/verify-desktop-renderer-bundles.mjs
# ──────────────────────────────────────────────────────────────────
# 4. Android x86_64 artifacts and native dependency gate
# ──────────────────────────────────────────────────────────────────
mobile-android:
name: Mobile Android (universal debug + bundled universal E2E)
needs: code-quality
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v4
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
cache-provider: basic
- name: Install Dependencies
run: |
npm ci
npm --prefix apps/mobile-rn ci --workspaces=false
- name: Prepare Verified Whisper Model
run: node scripts/ci/prepare-whisper-model.mjs
- name: Test Mobile TypeScript and Jest
run: |
npm --prefix apps/mobile-rn run lint
npm --prefix apps/mobile-rn run typecheck
npm --prefix apps/mobile-rn run test:ci
- name: Build Universal Debug, CSPRNG Test, and Bundled Universal E2E APKs
working-directory: apps/mobile-rn/android
env:
D3RO_VERSION_NAME: 0.0.0-e2e.${{ github.run_number }}
D3RO_VERSION_CODE: ${{ github.run_number }}
run: ./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:assembleE2e -PreactNativeArchitectures=arm64-v8a,x86_64 --no-daemon
- name: Verify BuildConfig and APK Runtime Contracts
env:
D3RO_VERSION_NAME: 0.0.0-e2e.${{ github.run_number }}
D3RO_VERSION_CODE: ${{ github.run_number }}
run: |
set -euo pipefail
DEBUG_APK=apps/mobile-rn/android/app/build/outputs/apk/debug/app-debug.apk
E2E_APK=apps/mobile-rn/android/app/build/outputs/apk/e2e/app-e2e.apk
test -f "$DEBUG_APK"
test -f "$E2E_APK"
node scripts/ci/verify-mobile-build-config.mjs debug \
| tee apps/mobile-rn/android/app/build/outputs/debug-build-config.json
node scripts/ci/verify-mobile-build-config.mjs e2e \
| tee apps/mobile-rn/android/app/build/outputs/e2e-build-config.json
node scripts/ci/verify-android-artifact.mjs --mode debug --apk "$DEBUG_APK" \
| tee apps/mobile-rn/android/app/build/outputs/debug-artifact-evidence.json
node scripts/ci/verify-android-artifact.mjs \
--mode e2e \
--apk "$E2E_APK" \
--expected-version-name "$D3RO_VERSION_NAME" \
--expected-version-code "$D3RO_VERSION_CODE" \
| tee apps/mobile-rn/android/app/build/outputs/e2e-artifact-evidence.json
node scripts/ci/verify-android-app-links.mjs \
| tee apps/mobile-rn/android/app/build/outputs/app-links-evidence.json
sha256sum "$DEBUG_APK" "$E2E_APK" | tee apps/mobile-rn/android/app/build/outputs/android-ci.sha256
- name: Upload Universal Android Artifacts
uses: actions/upload-artifact@v4
with:
name: d3ro-mobile-android-universal-e2e
path: |
apps/mobile-rn/android/app/build/outputs/apk/debug/app-debug.apk
apps/mobile-rn/android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
apps/mobile-rn/android/app/build/outputs/apk/e2e/app-e2e.apk
apps/mobile-rn/android/app/build/outputs/android-ci.sha256
apps/mobile-rn/android/app/build/outputs/*-build-config.json
apps/mobile-rn/android/app/build/outputs/*-artifact-evidence.json
apps/mobile-rn/android/app/build/outputs/app-links-evidence.json
if-no-files-found: error
# ──────────────────────────────────────────────────────────────────
# 5. Installed bundled APK on a clean API 35 x86_64 emulator
# ──────────────────────────────────────────────────────────────────
mobile-emulator-e2e:
name: Mobile Emulator E2E (API 35)
needs: mobile-android
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v4
- name: Download Bundled Android Artifact
uses: actions/download-artifact@v4
with:
name: d3ro-mobile-android-universal-e2e
path: mobile-artifact
- name: Install Verified Maestro CLI 2.7.0
run: |
curl -fsSL https://github.com/mobile-dev-inc/maestro/releases/download/cli-2.7.0/maestro.zip -o /tmp/maestro.zip
echo 'a4ccab6b604617e7aef6db4f885666056eabe5cfa32befaa3bc994041b8fcbb5 /tmp/maestro.zip' | sha256sum -c -
unzip -q /tmp/maestro.zip -d "$RUNNER_TEMP/maestro"
echo "$RUNNER_TEMP/maestro/maestro/bin" >> "$GITHUB_PATH"
- name: Run Mandatory Clean-room and Optional External-account Journeys
uses: reactivecircus/android-emulator-runner@v2
env:
MOBILE_E2E_EMAIL: ${{ secrets.MOBILE_E2E_EMAIL }}
MOBILE_E2E_PASSWORD: ${{ secrets.MOBILE_E2E_PASSWORD }}
with:
api-level: 35
target: google_apis
arch: x86_64
profile: pixel_6
disable-animations: true
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
script: |
set -euo pipefail
DEBUG_APK="$(find mobile-artifact -path '*/apk/debug/app-debug.apk' -print -quit)"
TEST_APK="$(find mobile-artifact -name app-debug-androidTest.apk -print -quit)"
E2E_APK="$(find mobile-artifact -name app-e2e.apk -print -quit)"
test -n "$DEBUG_APK"
test -n "$TEST_APK"
test -n "$E2E_APK"
maestro --version
bash scripts/ci/run-mobile-csprng-instrumentation.sh "$DEBUG_APK" "$TEST_APK"
bash scripts/ci/run-mobile-emulator-gate.sh "$E2E_APK"
- name: Upload Emulator Evidence
if: always()
uses: actions/upload-artifact@v4
with:
name: d3ro-mobile-emulator-e2e
path: |
apps/mobile-rn/.maestro/*.junit.xml
apps/mobile-rn/.maestro-output/
if-no-files-found: warn

53
.github/workflows/deploy-site.yml vendored Normal file
View file

@ -0,0 +1,53 @@
name: Deploy Landing Page
on:
push:
branches: [main]
paths: ['site/**']
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: site/package-lock.json
- name: Install dependencies
working-directory: site
run: npm ci
- name: Verify Mobile Release Publication Boundary
run: node scripts/ci/verify-mobile-release-boundary.mjs --self-test
- name: Build
working-directory: site
run: npm run build
- uses: actions/upload-pages-artifact@v3
with:
path: site/dist
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- id: deployment
uses: actions/deploy-pages@v4

29
.github/workflows/payple-renew.yml vendored Normal file
View file

@ -0,0 +1,29 @@
name: Payple Subscription Renewal
on:
schedule:
# 매일 01:00 UTC (KST 10:00)
- cron: '0 1 * * *'
workflow_dispatch: {}
jobs:
renew:
runs-on: ubuntu-latest
steps:
- name: Trigger payple-renew Edge Function
run: |
response=$(curl -s -w "\n%{http_code}" -X POST \
"${{ secrets.SUPABASE_URL }}/functions/v1/payple-renew" \
-H "Authorization: Bearer ${{ secrets.CRON_SECRET }}" \
-H "Content-Type: application/json")
http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | head -n -1)
echo "HTTP $http_code"
echo "$body" | jq . 2>/dev/null || echo "$body"
if [ "$http_code" -ge 400 ]; then
echo "::error::Renewal failed with HTTP $http_code"
exit 1
fi

101
.github/workflows/release-signing-ca.yml vendored Normal file
View file

@ -0,0 +1,101 @@
name: Release & Code Signing CA Pipeline
on:
workflow_dispatch:
jobs:
build-and-sign-windows:
runs-on: windows-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Typecheck & Test
run: |
npm run typecheck
npm run test --workspace=@d3ro/api-client
# Azure Trusted Signing (Artifact Signing) for SmartScreen Reputation
- name: Setup Azure Trusted Signing
if: env.AZURE_CLIENT_ID != ''
uses: azure/trusted-signing-action@v0.4.1
with:
azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }}
azure-client-id: ${{ secrets.AZURE_CLIENT_ID }}
azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }}
endpoint: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
trusted-signing-account-name: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
certificate-profile-name: ${{ secrets.AZURE_CERT_PROFILE }}
- name: Build STT Sidecar (local transcription engine)
run: |
# Without this bundle the packaged app cannot transcribe at all.
npm run sidecar:setup --workspace=@d3ro/desktop
npm run sidecar:build --workspace=@d3ro/desktop
node scripts/ci/verify-sidecar-bundle.mjs
- name: Build and Package Windows (NSIS + RFC 3161 TSA)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RFC3161_TSA_SERVER: "http://timestamp.digicert.com"
run: |
npm run build --workspace=@d3ro/desktop
npx electron-builder --win --config apps/desktop/electron-builder.yml
- name: Upload Windows Artifacts
uses: actions/upload-artifact@v4
with:
name: d3ro-voice-windows
path: apps/desktop/release/*/*.exe
build-and-sign-macos:
runs-on: macos-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js 22
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup Apple Developer ID Certificate
if: env.APPLE_CERTIFICATE != ''
env:
APPLE_CERTIFICATE: ${{ secrets.MAC_CSC_LINK }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CSC_KEY_PASSWORD }}
run: |
echo "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12
security create-keychain -p "" build.keychain
security default-keychain -s build.keychain
security unlock-keychain -p "" build.keychain
security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple: -s -k "" build.keychain
- name: Build, Sign, and Notarize macOS (Gatekeeper CA)
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
npm run build --workspace=@d3ro/desktop
npx electron-builder --mac --config apps/desktop/electron-builder.yml
- name: Upload macOS Artifacts
uses: actions/upload-artifact@v4
with:
name: d3ro-voice-macos
path: apps/desktop/release/*/*.dmg

612
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,612 @@
# .github/workflows/release.yml
# Multi-Platform Automated Release Pipeline for D3RO Voice Desktop & Admin
name: Release & Packaging Pipeline
on:
push:
tags:
- 'v*.*.*'
workflow_dispatch:
inputs:
version:
description: 'Release version (e.g. 1.0.0)'
required: true
default: '1.1.0'
permissions:
contents: write
packages: write
jobs:
release-preflight:
name: Release Preflight
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Setup .NET 10
uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.302'
- name: Setup Deno 2.8.1
uses: denoland/setup-deno@v2
with:
deno-version: v2.8.1
- name: Install JavaScript Dependencies
run: |
npm ci
npm --prefix apps/mobile-rn ci --workspaces=false
- name: Verify Source, Security, Tests, and Play Assets
run: |
npm run version:check
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
node scripts/ci/sync-version.mjs --check --tag "$GITHUB_REF_NAME"
fi
npm run release:metadata:test
npm run security:secrets:test
npm run security:secrets
npm run release:mobile:boundary:test
npm run release:mobile:config:test
npm run release:mobile:build-config:test
npm run release:play:assets
npm run lint
npm run typecheck
npm test
npm --prefix apps/mobile-rn run lint
npm --prefix apps/mobile-rn run typecheck
npm --prefix apps/mobile-rn run test:ci
- name: Check and Test Every Supabase Edge Function
shell: bash
run: |
set -euo pipefail
for entrypoint in server/supabase/functions/*/index.ts; do
deno check --config server/supabase/functions/deno.json "$entrypoint"
done
deno test --config server/supabase/functions/deno.json --allow-read --allow-env server/supabase/functions
- name: Test .NET API Authorization and Gateway Boundaries
run: |
dotnet restore apps/api-server.Tests/D3ROVoice.Api.Tests.csproj
dotnet test apps/api-server.Tests/D3ROVoice.Api.Tests.csproj --configuration Release --no-restore -p:StaticWebAssetsEnabled=false
# ──────────────────────────────────────────────────────────────────
# 1. Package Windows Installer (.exe & .blockmap & latest.yml)
# ──────────────────────────────────────────────────────────────────
package-windows:
name: Package Windows Desktop App
needs: release-preflight
runs-on: windows-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build All Workspaces
run: |
npm run version:check
npm run typecheck
npm run build --workspace=@d3ro/desktop
- name: Verify Desktop Renderer Bundles
run: node scripts/ci/verify-desktop-renderer-bundles.mjs
- name: Build STT Sidecar (local transcription engine)
run: |
# Local transcription depends on the faster-whisper sidecar; a release
# that ships without it cannot transcribe at all, so build and verify
# the bundle before packaging.
npm run sidecar:setup --workspace=@d3ro/desktop
npm run sidecar:build --workspace=@d3ro/desktop
node scripts/ci/verify-sidecar-bundle.mjs
- name: Package with Electron Builder (NSIS x64)
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($env:CSC_LINK)) {
throw 'WIN_CSC_LINK must contain the production code-signing PFX path, URL, or base64 payload.'
}
if ([string]::IsNullOrWhiteSpace($env:CSC_KEY_PASSWORD)) {
throw 'WIN_CSC_KEY_PASSWORD is required.'
}
if ([string]::IsNullOrWhiteSpace($env:WIN_CSC_EXPECTED_SIGNER_SUBJECT)) {
throw 'WIN_CSC_EXPECTED_SIGNER_SUBJECT is required.'
}
if ($env:WIN_CSC_EXPECTED_SIGNER_SUBJECT -match '(?i)Everything2EverythingDev') {
throw 'The local Everything2EverythingDev certificate is not a production signing identity.'
}
$releaseVersion = node -p "require('./release/product-version.json').version"
Push-Location apps/desktop
try {
npx electron-builder --win --x64 --config electron-builder.yml
node scripts/ci/verify-native-abi.mjs
if ($LASTEXITCODE -ne 0) { throw "electron-builder failed with exit code $LASTEXITCODE." }
}
finally {
Pop-Location
}
& scripts/ci/verify-windows-release-artifact.ps1 `
-ExpectedVersion $releaseVersion `
-ExpectedSignerSubject $env:WIN_CSC_EXPECTED_SIGNER_SUBJECT `
-ReleaseDirectory "apps/desktop/release/$releaseVersion"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CSC_LINK: ${{ secrets.WIN_CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}
WIN_CSC_EXPECTED_SIGNER_SUBJECT: ${{ secrets.WIN_CSC_EXPECTED_SIGNER_SUBJECT }}
- name: Upload Windows Build Artifacts
uses: actions/upload-artifact@v4
with:
name: windows-release-assets
path: |
apps/desktop/release/*/*.exe
apps/desktop/release/*/*.blockmap
apps/desktop/release/*/latest.yml
# ──────────────────────────────────────────────────────────────────
# 2. Package macOS Desktop App (.dmg & .zip & latest-mac.yml)
# ──────────────────────────────────────────────────────────────────
package-macos:
name: Package macOS Desktop App
needs: release-preflight
runs-on: macos-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build All Workspaces
run: |
npm run version:check
npm run typecheck
npm run build --workspace=@d3ro/desktop
- name: Verify Desktop Renderer Bundles
run: node scripts/ci/verify-desktop-renderer-bundles.mjs
- name: Build STT Sidecar (local transcription engine)
run: |
# Local transcription depends on the faster-whisper sidecar; a release
# that ships without it cannot transcribe at all, so build and verify
# the bundle before packaging.
npm run sidecar:setup --workspace=@d3ro/desktop
npm run sidecar:build --workspace=@d3ro/desktop
node scripts/ci/verify-sidecar-bundle.mjs
- name: Package with Electron Builder (DMG & ZIP arm64)
run: |
cd apps/desktop
npx electron-builder --mac --arm64 --config electron-builder.yml
node scripts/ci/verify-native-abi.mjs
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CSC_LINK: ${{ secrets.MAC_CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.MAC_CSC_KEY_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- name: Upload macOS Build Artifacts
uses: actions/upload-artifact@v4
with:
name: macos-release-assets
path: |
apps/desktop/release/*/*.dmg
apps/desktop/release/*/*.zip
apps/desktop/release/*/*.blockmap
apps/desktop/release/*/latest-mac.yml
# ──────────────────────────────────────────────────────────────────
# 3. Package signed Android APK/AAB (arm64, production-only config)
# ──────────────────────────────────────────────────────────────────
package-android:
name: Package Android Mobile App
needs: release-preflight
runs-on: ubuntu-latest
environment: mobile-production-release
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Establish Trusted Mobile Release Identity
id: android-version
shell: bash
env:
DISPATCH_VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
git fetch --no-tags origin main
if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then
test "$GITHUB_REF" = "refs/heads/main"
test "$GITHUB_SHA" = "$(git rev-parse origin/main)"
VERSION_NAME="$DISPATCH_VERSION"
RELEASE_TAG="v$VERSION_NAME"
else
[[ "$GITHUB_REF" == refs/tags/v* ]]
VERSION_NAME="${GITHUB_REF_NAME#v}"
RELEASE_TAG="$GITHUB_REF_NAME"
git merge-base --is-ancestor "$GITHUB_SHA" origin/main
fi
SSOT_VERSION="$(node -p "require('./release/product-version.json').version")"
VERSION_CODE="$(node -p "require('./release/product-version.json').androidVersionCode")"
[[ "$VERSION_NAME" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
test "$VERSION_NAME" = "$SSOT_VERSION"
test "$RELEASE_TAG" = "v$VERSION_NAME"
[[ "$VERSION_CODE" =~ ^[1-9][0-9]{0,9}$ ]]
test "$VERSION_CODE" -le 2100000000
printf 'name=%s\n' "$VERSION_NAME" >> "$GITHUB_OUTPUT"
printf 'code=%s\n' "$VERSION_CODE" >> "$GITHUB_OUTPUT"
printf 'tag=%s\n' "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
- name: Verify Immutable Checkout Identity
shell: bash
run: |
set -euo pipefail
test "$GITHUB_SHA" = "$(git rev-parse HEAD)"
test -z "$(git status --porcelain --untracked-files=all)"
git rev-parse "${GITHUB_SHA}^{tree}"
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Verify Mobile Release Boundary Source Contract
run: node scripts/ci/verify-mobile-release-boundary.mjs --self-test
- name: Verify Mobile Release Configuration Contract
run: npm run release:mobile:config:test
- name: Verify Mobile Build Configuration Contract
run: npm run release:mobile:build-config:test
- name: Verify Play Store Asset Contract
run: npm run release:play:assets
- name: Require Restricted AAB Handoff Visibility
shell: bash
env:
REPOSITORY_VISIBILITY: ${{ github.event.repository.visibility }}
run: |
set -euo pipefail
test "$REPOSITORY_VISIBILITY" = "private"
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v4
- name: Install Pinned Official Bundletool
shell: bash
run: |
set -euo pipefail
curl --fail --silent --show-error --location \
--output "$RUNNER_TEMP/bundletool-all-1.18.3.jar" \
https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar
printf '%s %s\n' \
a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29 \
"$RUNNER_TEMP/bundletool-all-1.18.3.jar" | sha256sum --check --strict
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
cache-provider: basic
- name: Install Dependencies
run: |
npm ci
npm --prefix apps/mobile-rn ci --workspaces=false
- name: Materialize Release-only Configuration
shell: bash
env:
ANDROID_RELEASE_KEYSTORE_B64: ${{ secrets.ANDROID_RELEASE_KEYSTORE_B64 }}
ANDROID_GOOGLE_SERVICES_JSON_B64: ${{ secrets.ANDROID_GOOGLE_SERVICES_JSON_B64 }}
run: |
set -euo pipefail
umask 077
test -n "$ANDROID_RELEASE_KEYSTORE_B64"
test -n "$ANDROID_GOOGLE_SERVICES_JSON_B64"
printf '%s' "$ANDROID_RELEASE_KEYSTORE_B64" | base64 --decode > apps/mobile-rn/android/app/release.keystore
printf '%s' "$ANDROID_GOOGLE_SERVICES_JSON_B64" | base64 --decode > apps/mobile-rn/android/app/google-services.json
test -s apps/mobile-rn/android/app/release.keystore
test -s apps/mobile-rn/android/app/google-services.json
- name: Prepare Verified Whisper Model
run: node scripts/ci/prepare-whisper-model.mjs
- name: Verify Production Firebase and AdMob Configuration
env:
D3RO_FIREBASE_EXPECTED_PROJECT_ID: ${{ secrets.FIREBASE_PROJECT_ID }}
D3RO_FIREBASE_EXPECTED_PROJECT_NUMBER: ${{ secrets.FIREBASE_PROJECT_NUMBER }}
D3RO_FIREBASE_EXPECTED_MOBILESDK_APP_ID: ${{ secrets.FIREBASE_MOBILESDK_APP_ID }}
run: |
export D3RO_ADMOB_APP_ID="$(node -p "require('./release/android-release-identity.json').adMobAppId")"
export D3RO_ADMOB_BANNER_UNIT_ID="$(node -p "require('./release/android-release-identity.json').adMobBannerUnitId")"
export D3RO_ADMOB_REWARDED_UNIT_ID="$(node -p "require('./release/android-release-identity.json').adMobRewardedUnitId")"
npm run release:mobile:config
- name: Test Mobile TypeScript and Jest
run: |
npm --prefix apps/mobile-rn run lint
npm --prefix apps/mobile-rn run typecheck
npm --prefix apps/mobile-rn run test:ci
- name: Build Signed arm64 APK and AAB
working-directory: apps/mobile-rn/android
env:
D3RO_RELEASE_STORE_FILE: ${{ github.workspace }}/apps/mobile-rn/android/app/release.keystore
D3RO_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }}
D3RO_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }}
D3RO_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }}
D3RO_VERSION_NAME: ${{ steps.android-version.outputs.name }}
D3RO_VERSION_CODE: ${{ steps.android-version.outputs.code }}
run: |
export D3RO_ADMOB_APP_ID="$(node -p "require('../../../release/android-release-identity.json').adMobAppId")"
export D3RO_ADMOB_BANNER_UNIT_ID="$(node -p "require('../../../release/android-release-identity.json').adMobBannerUnitId")"
export D3RO_ADMOB_REWARDED_UNIT_ID="$(node -p "require('../../../release/android-release-identity.json').adMobRewardedUnitId")"
./gradlew :app:assembleRelease :app:bundleRelease -PreactNativeArchitectures=arm64-v8a --no-daemon
- name: Materialize Release Evidence Signing Key
shell: bash
env:
ANDROID_RELEASE_EVIDENCE_PRIVATE_KEY_B64: ${{ secrets.ANDROID_RELEASE_EVIDENCE_PRIVATE_KEY_B64 }}
run: |
set -euo pipefail
umask 077
test -n "$ANDROID_RELEASE_EVIDENCE_PRIVATE_KEY_B64"
printf '%s' "$ANDROID_RELEASE_EVIDENCE_PRIVATE_KEY_B64" | base64 --decode > apps/mobile-rn/android/app/release-evidence-private.pem
test -s apps/mobile-rn/android/app/release-evidence-private.pem
- name: Verify Release BuildConfig, Signature, ABI, Bundle, Ads, and Offline Model
shell: bash
env:
D3RO_VERSION_NAME: ${{ steps.android-version.outputs.name }}
D3RO_VERSION_CODE: ${{ steps.android-version.outputs.code }}
run: |
set -euo pipefail
D3RO_ADMOB_APP_ID="$(node -p "require('./release/android-release-identity.json').adMobAppId")"
D3RO_ADMOB_BANNER_UNIT_ID="$(node -p "require('./release/android-release-identity.json').adMobBannerUnitId")"
D3RO_ADMOB_REWARDED_UNIT_ID="$(node -p "require('./release/android-release-identity.json').adMobRewardedUnitId")"
ANDROID_UPLOAD_CERT_SHA256="$(node -p "require('./release/android-release-identity.json').uploadCertificateSha256")"
PLAY_APP_SIGNING_CERT_SHA256="$(node -p "require('./release/android-release-identity.json').playAppSigningCertificateSha256")"
APK=apps/mobile-rn/android/app/build/outputs/apk/release/app-release.apk
AAB=apps/mobile-rn/android/app/build/outputs/bundle/release/app-release.aab
test -f "$APK"
test -f "$AAB"
node scripts/ci/verify-mobile-build-config.mjs release \
| tee apps/mobile-rn/android/app/build/outputs/release-build-config.json
node scripts/ci/create-mobile-release-evidence.mjs \
--apk "$APK" \
--aab "$AAB" \
--bundletool "$RUNNER_TEMP/bundletool-all-1.18.3.jar" \
--repository "$GITHUB_REPOSITORY" \
--commit-sha "$GITHUB_SHA" \
--tree-sha "$(git rev-parse "${GITHUB_SHA}^{tree}")" \
--git-ref "$GITHUB_REF" \
--workflow-identity "$GITHUB_WORKFLOW_REF" \
--run-id "$GITHUB_RUN_ID" \
--run-attempt "$GITHUB_RUN_ATTEMPT" \
--runner-identity "$RUNNER_NAME:$RUNNER_OS:$RUNNER_ARCH" \
--expected-admob-app-id "$D3RO_ADMOB_APP_ID" \
--expected-upload-cert-sha256 "$ANDROID_UPLOAD_CERT_SHA256" \
--expected-version-name "$D3RO_VERSION_NAME" \
--expected-version-code "$D3RO_VERSION_CODE" \
--private-key apps/mobile-rn/android/app/release-evidence-private.pem \
--snapshot-dir apps/mobile-rn/android/app/build/outputs/release-snapshot
VERIFIER_SHA256="$(sha256sum scripts/ci/verify-android-artifact.mjs | awk '{print $1}')"
BUNDLETOOL_SHA256="a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29"
node scripts/ci/prepare-mobile-release-publication.mjs \
--source-root apps/mobile-rn/android/app/build/outputs/release-snapshot \
--apk apps/mobile-rn/android/app/build/outputs/release-snapshot/app-release.apk \
--aab apps/mobile-rn/android/app/build/outputs/release-snapshot/app-release.aab \
--evidence apps/mobile-rn/android/app/build/outputs/release-snapshot/release-artifact-evidence.json \
--public-key release/mobile-release-evidence-public.pem \
--destination-dir apps/mobile-rn/android/app/build/outputs/release-publication \
--expected-admob-app-id "$D3RO_ADMOB_APP_ID" \
--expected-upload-cert-sha256 "$ANDROID_UPLOAD_CERT_SHA256" \
--expected-version-name "$D3RO_VERSION_NAME" \
--expected-version-code "$D3RO_VERSION_CODE" \
--expected-repository "$GITHUB_REPOSITORY" \
--expected-commit-sha "$GITHUB_SHA" \
--expected-tree-sha "$(git rev-parse "${GITHUB_SHA}^{tree}")" \
--expected-git-ref "$GITHUB_REF" \
--expected-workflow-identity "$GITHUB_WORKFLOW_REF" \
--expected-run-id "$GITHUB_RUN_ID" \
--expected-run-attempt "$GITHUB_RUN_ATTEMPT" \
--expected-runner-identity "$RUNNER_NAME:$RUNNER_OS:$RUNNER_ARCH" \
--expected-verifier-sha256 "$VERIFIER_SHA256" \
--expected-bundletool-sha256 "$BUNDLETOOL_SHA256"
node scripts/ci/verify-android-app-links.mjs \
--expected-play-app-signing-cert-sha256 "$PLAY_APP_SIGNING_CERT_SHA256" \
--forbidden-upload-cert-sha256 "$ANDROID_UPLOAD_CERT_SHA256" \
| tee apps/mobile-rn/android/app/build/outputs/release-app-links-evidence.json
sha256sum apps/mobile-rn/android/app/build/outputs/release-publication/app-release.apk \
apps/mobile-rn/android/app/build/outputs/release-publication/app-release.aab \
| tee apps/mobile-rn/android/app/build/outputs/release-publication/SHA256SUMS.txt
- name: Remove Materialized Release Secrets
if: always()
shell: bash
run: rm -f apps/mobile-rn/android/app/release.keystore apps/mobile-rn/android/app/google-services.json apps/mobile-rn/android/app/release-evidence-private.pem
- name: Upload Restricted Play Console AAB Handoff
uses: actions/upload-artifact@v4
with:
name: android-play-console-handoff
path: |
apps/mobile-rn/android/app/build/outputs/release-publication/app-release.aab
apps/mobile-rn/android/app/build/outputs/release-publication/android-release-evidence.json
apps/mobile-rn/android/app/build/outputs/release-publication/android-publication-manifest.json
apps/mobile-rn/android/app/build/outputs/release-publication/SHA256SUMS.txt
apps/mobile-rn/android/app/build/outputs/release-snapshot/release-artifact-verification.json
apps/mobile-rn/android/app/build/outputs/release-build-config.json
apps/mobile-rn/android/app/build/outputs/release-app-links-evidence.json
retention-days: 7
if-no-files-found: error
# ──────────────────────────────────────────────────────────────────
# 4. Build & Containerize Admin Dashboard
# ──────────────────────────────────────────────────────────────────
package-admin-docker:
name: Build & Publish Admin Docker Image
needs: release-preflight
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: actions/setup-buildx-action@v3
- name: Log in to GitHub Container Registry (GHCR)
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}/admin-console
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./apps/admin/Dockerfile
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# ──────────────────────────────────────────────────────────────────
# 5. Create GitHub Release & Upload Checksums
# ──────────────────────────────────────────────────────────────────
publish-release:
name: Publish Official GitHub Release
needs: [package-windows, package-macos, package-android, package-admin-docker]
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Re-establish Trusted Release Identity
id: release-identity
shell: bash
env:
DISPATCH_VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
git fetch --no-tags origin main
if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then
test "$GITHUB_REF" = "refs/heads/main"
test "$GITHUB_SHA" = "$(git rev-parse origin/main)"
VERSION_NAME="$DISPATCH_VERSION"
RELEASE_TAG="v$VERSION_NAME"
else
[[ "$GITHUB_REF" == refs/tags/v* ]]
VERSION_NAME="${GITHUB_REF_NAME#v}"
RELEASE_TAG="$GITHUB_REF_NAME"
git merge-base --is-ancestor "$GITHUB_SHA" origin/main
fi
SSOT_VERSION="$(node -p "require('./release/product-version.json').version")"
[[ "$VERSION_NAME" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
test "$VERSION_NAME" = "$SSOT_VERSION"
test "$RELEASE_TAG" = "v$VERSION_NAME"
printf 'name=%s\n' "$VERSION_NAME" >> "$GITHUB_OUTPUT"
printf 'tag=%s\n' "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
- name: Download Windows Artifacts
uses: actions/download-artifact@v4
with:
name: windows-release-assets
path: release-dist/
- name: Download macOS Artifacts
uses: actions/download-artifact@v4
with:
name: macos-release-assets
path: release-dist/
- name: Generate SHA-256 Checksums
run: |
set -euo pipefail
find release-dist -type f ! -name SHA256SUMS.txt -print0 \
| sort -z \
| xargs -0 sha256sum > release-dist/SHA256SUMS.txt
cat release-dist/SHA256SUMS.txt
- name: Extract Canonical Release Notes
run: >-
node scripts/ci/extract-release-notes.mjs
--version "${{ steps.release-identity.outputs.name }}"
--output release-notes.md
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: |
release-dist/*
draft: false
prerelease: false
body_path: release-notes.md
generate_release_notes: false
tag_name: ${{ steps.release-identity.outputs.tag }}
fail_on_unmatched_files: true
overwrite_files: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish to Forgejo Release and Update Feed
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_RELEASE_TAG: ${{ steps.release-identity.outputs.tag }}
FORGEJO_RELEASE_DIR: release-dist
run: node scripts/ci/publish-forgejo-release.mjs

16
.gitignore vendored
View file

@ -118,13 +118,9 @@ apps/mobile-rn/android/app/src/main/res/drawable-*/node_modules_*
/supabase/.branches/
/supabase/.temp/
# Release binaries are never committed: the only distribution channel is the
# Forgejo update feed (release/update-policy.json). Landing/download/legal/invite
# pages live only in site/, so the API server has no wwwroot at all.
/site/public/releases/
/apps/web/public/releases/
/apps/api-server/wwwroot/
*.apk
*.aab
*.blockmap
D3RO-Voice-Setup-*.exe
# Release binaries are not committed: the canonical distribution channel is the
# Forgejo update feed, and none of these trees are part of a build graph.
# Historical 1.0.0 copies stay tracked until they are retired.
/site/public/releases/*/
/apps/web/public/releases/*/
/apps/api-server/wwwroot/releases/*/

View file

@ -7,38 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **Live captions stream as you listen.** Words appear about a second after they are
spoken and keep updating while the sentence is in progress; the part that is no
longer changing is shown solid and the rest dimmed. A pause finishes the line, and
long unbroken speech is split at natural boundaries instead of waiting six seconds.
- **Captions are polished in context.** Each finished line is corrected by the local
model using the lines before it (spacing, punctuation, misheard words); rewrites
that change too much are ignored. It can be turned off in Settings.
- **Live captions can use their own speech model.** Settings > STT now has a separate
live-caption model, loaded next to the dictation model, so captions can run on a
faster or more accurate model without changing dictation. The local speech engine
is updated for this and is downloaded again once.
### Changed
- **Suggestions page with Up/Down only.** Moving past the third candidate turns the
page by itself, and at the last candidate the selection waits while more are still
being generated. The separate Ctrl+Alt+Left/Right page shortcuts are gone; they also
collided with the display-rotation shortcut of Intel graphics drivers.
- The live-caption model is chosen next to the other caption settings in the General
tab.
### Fixed
- **Accepting a suggestion with Ctrl+Alt+Enter did not paste.** The paste was sent
while Ctrl+Alt were still held, so the app received Ctrl+Alt+V. The panel now closes
at once and the text is pasted as soon as the keys are released.
- **Clicking a suggestion did nothing** when a new candidate arrived between pressing
and releasing the mouse button; a candidate is now accepted on press.
- **Suggestions rarely appeared in chat boxes that grow as you type.** The growing box
was taken for a different field on every keystroke, which kept blocking suggestions
as "not typing". Fields are now told apart by window and control, and a mouse click
re-checks whether you have typed since.
### Planned
- macOS / Linux support
- Additional Whisper model management UI

47
Dockerfile.admin Normal file
View file

@ -0,0 +1,47 @@
# Dockerfile.admin
# Multi-stage production build for @d3ro/admin Next.js App
FROM node:24.19.0-alpine AS deps
WORKDIR /app
RUN apk add --no-cache libc6-compat
COPY package.json package-lock.json ./
COPY packages ./packages
COPY apps/admin ./apps/admin
COPY apps/desktop/package.json ./apps/desktop/package.json
COPY apps/web/package.json ./apps/web/package.json
RUN npm ci
FROM node:24.19.0-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/packages ./packages
COPY --from=deps /app/apps ./apps
COPY package.json package-lock.json ./
ENV NEXT_TELEMETRY_DISABLED 1
ENV NODE_ENV production
RUN npm run build --workspace=@d3ro/admin
FROM node:24.19.0-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
ENV PORT 3001
ENV HOSTNAME "0.0.0.0"
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/apps/admin/public ./apps/admin/public
COPY --from=builder --chown=nextjs:nodejs /app/apps/admin/.next ./apps/admin/.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/apps/admin/package.json ./apps/admin/package.json
USER nextjs
EXPOSE 3001
CMD ["npm", "run", "start", "--workspace=@d3ro/admin"]

View file

@ -22,12 +22,11 @@ export default async function AdminOverviewPage(): Promise<React.ReactElement> {
}
}
const krw = new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 })
const revenueCards = revenue
? [
{
title: 'Annual Recurring Revenue',
value: krw.format(revenue.arrKrw),
value: `$${revenue.arrUsd.toLocaleString()}`,
subtext: 'Active subscriptions × 12 months',
color: 'green' as const,
badge: 'ARR',
@ -35,7 +34,7 @@ export default async function AdminOverviewPage(): Promise<React.ReactElement> {
},
{
title: 'Monthly Recurring Revenue',
value: krw.format(revenue.mrrKrw),
value: `$${revenue.mrrUsd.toLocaleString()}`,
subtext: `Pro ${revenue.tierBreakdown.pro.toLocaleString()} · Pro+ ${revenue.tierBreakdown.pro_plus.toLocaleString()}`,
color: 'blue' as const,
badge: 'MRR',
@ -209,7 +208,7 @@ export default async function AdminOverviewPage(): Promise<React.ReactElement> {
>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
<StatRing color={card.color} size={46}>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '13px', fontWeight: 500 }}>₩</Typography>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '13px', fontWeight: 500 }}>$</Typography>
</StatRing>
<Box component="span" sx={statusBadgeSx(card.badgeColor)}>
{card.badge}

View file

@ -3,7 +3,6 @@
import { Box, Typography, Button } from '@mui/material'
import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds'
import { SITE_URLS } from '@d3ro/core/web-urls'
import { C, FONT_SANS, FONT_MONO, panelSx, tableSx, statusBadgeSx } from '@/lib/console-theme'
import { requireManager } from '@/lib/admin-guard'
import { fetchReleaseHub, type ReleaseAssetPlatform, type ReleaseHub } from '@/lib/forgejo-releases'
@ -108,7 +107,7 @@ function HeaderBar({ feedLive, repoHtmlUrl }: { feedLive: boolean; repoHtmlUrl:
Forgejo Releases ↗
</Button>
<Button
href={SITE_URLS.download}
href="https://d3ro.chanpaca.net/download.html"
target="_blank"
variant="outlined"
sx={{

View file

@ -20,12 +20,9 @@ import {
Alert
} from '@mui/material'
import type { LicenseTier } from '@d3ro/core/types'
import { PLAN_PRICE_KRW } from '@d3ro/core/plan-catalog'
import { d3roPalette, d3roFontMono, d3roRadius } from '@d3ro/ui/theme'
import { C, FONT_SANS, FONT_MONO, primaryButtonSx } from '@/lib/console-theme'
const krw = new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 })
interface LicenseIssuerDialogProps {
open: boolean
onClose: () => void
@ -153,9 +150,9 @@ export function LicenseIssuerDialog({ open, onClose }: LicenseIssuerDialogProps)
<FormControl fullWidth sx={inputSx}>
<InputLabel>Plan / Tier</InputLabel>
<Select value={tier} onChange={(e) => setTier(e.target.value as LicenseTier)} label="Plan / Tier">
<MenuItem value="pro">Pro ({krw.format(PLAN_PRICE_KRW.pro)} / month)</MenuItem>
<MenuItem value="pro_plus">Pro+ ({krw.format(PLAN_PRICE_KRW.pro_plus)} / month)</MenuItem>
<MenuItem value="team">Team</MenuItem>
<MenuItem value="pro">Pro ($9.9 / ₩12,900)</MenuItem>
<MenuItem value="pro_plus">Pro+ ($19.9 / ₩24,900)</MenuItem>
<MenuItem value="team">Team ($25 / ₩32,000)</MenuItem>
<MenuItem value="enterprise">Enterprise (Custom)</MenuItem>
</Select>
</FormControl>

View file

@ -1,12 +1,17 @@
import 'server-only'
import { PLAN_PRICE_KRW } from '@d3ro/core/plan-catalog'
import { getSupabaseAdminClient } from './supabase-admin'
/** Monthly list price per tier, in USD. */
const TIER_MONTHLY_USD: Record<'pro' | 'pro_plus' | 'free', number> = {
pro: 9.9,
pro_plus: 19.9,
free: 0,
}
export interface SubscriptionRevenue {
/** Monthly list-price revenue in KRW (PLAN_PRICE_KRW; provider currency is not tracked per row). */
mrrKrw: number
arrKrw: number
mrrUsd: number
arrUsd: number
activeCount: number
tierBreakdown: { pro: number; pro_plus: number; free: number }
}
@ -14,7 +19,7 @@ export interface SubscriptionRevenue {
/**
* Aggregates real subscription revenue from Supabase.
* Only status === 'active' subscriptions contribute to MRR/ARR.
* MRR = Σ(PLAN_PRICE_KRW of each active subscription's tier); ARR = MRR * 12.
* MRR = Σ(monthly price of each active subscription's tier); ARR = MRR * 12.
*/
export async function fetchSubscriptionRevenue(): Promise<SubscriptionRevenue> {
const supabase = await getSupabaseAdminClient('manager')
@ -32,7 +37,7 @@ export async function fetchSubscriptionRevenue(): Promise<SubscriptionRevenue> {
}
const tierBreakdown = { pro: 0, pro_plus: 0, free: 0 }
let mrrKrw = 0
let mrrUsd = 0
let activeCount = 0
for (const row of rows) {
@ -41,9 +46,12 @@ export async function fetchSubscriptionRevenue(): Promise<SubscriptionRevenue> {
const tier = row.tier
if (tier === 'pro' || tier === 'pro_plus' || tier === 'free') {
tierBreakdown[tier] += 1
mrrKrw += PLAN_PRICE_KRW[tier]
mrrUsd += TIER_MONTHLY_USD[tier]
}
}
return { mrrKrw, arrKrw: mrrKrw * 12, activeCount, tierBreakdown }
mrrUsd = Math.round(mrrUsd * 100) / 100
const arrUsd = Math.round(mrrUsd * 12 * 100) / 100
return { mrrUsd, arrUsd, activeCount, tierBreakdown }
}

View file

@ -7,6 +7,14 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<!-- Retained legacy binaries are not static assets and must never publish. -->
<Content Remove="wwwroot\releases\**\*" />
<Content Remove="wwwroot\index.html" />
<Content Remove="wwwroot\assets\index-D7M5UQvT.js" />
<Content Remove="wwwroot\assets\index-JlYFxlAJ.js" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />

View file

@ -393,9 +393,65 @@ if (app.Environment.IsDevelopment())
}
app.UseCors("ConfiguredOrigins");
// The API serves no static pages. Landing, download, legal, invite and
// assetlinks pages live only in site/ (Cloudflare Pages); the admin UI is
// apps/admin. Installers are published only through the Forgejo update feed.
app.Use(async (context, next) =>
{
var isInvitePage =
context.Request.Path.StartsWithSegments("/accept-invite")
|| context.Request.Path.Equals("/accept-invite.html");
if (isInvitePage)
{
context.Response.OnStarting(() =>
{
// The invite token lives in the query string. Do not cache the page and
// prevent CDN HTML transforms (including analytics script injection).
context.Response.Headers["Cache-Control"] = "no-store, no-transform";
context.Response.Headers["Content-Security-Policy"] =
"default-src 'self'; base-uri 'none'; connect-src 'none'; font-src 'self'; " +
"form-action 'none'; frame-ancestors 'none'; img-src 'self' data:; " +
"object-src 'none'; script-src 'self'; style-src 'self'";
context.Response.Headers["Permissions-Policy"] =
"camera=(), microphone=(), geolocation=(), payment=(), usb=()";
context.Response.Headers["Referrer-Policy"] = "no-referrer";
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
context.Response.Headers["X-Frame-Options"] = "DENY";
return Task.CompletedTask;
});
}
if (context.Request.Path.Equals("/accept-invite"))
{
context.Response.StatusCode = StatusCodes.Status308PermanentRedirect;
context.Response.Headers.Location = $"/accept-invite/{context.Request.QueryString}";
return;
}
await next();
});
app.UseDefaultFiles();
// Historical mobile binaries remain in the checkout for forensics only. They
// are not official releases and must never be reachable through StaticFiles.
app.Use(async (context, next) =>
{
var requestPath = context.Request.Path.Value ?? string.Empty;
var fileName = Path.GetFileName(requestPath);
var legacyMarketingAsset = requestPath.Equals("/assets/index-D7M5UQvT.js", StringComparison.OrdinalIgnoreCase)
|| requestPath.Equals("/assets/index-JlYFxlAJ.js", StringComparison.OrdinalIgnoreCase);
var mobileReleasePath = requestPath.StartsWith("/releases/", StringComparison.OrdinalIgnoreCase)
&& (fileName.EndsWith(".apk", StringComparison.OrdinalIgnoreCase)
|| fileName.EndsWith(".aab", StringComparison.OrdinalIgnoreCase)
|| (fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)
&& (fileName.Contains("android", StringComparison.OrdinalIgnoreCase)
|| fileName.Contains("signed", StringComparison.OrdinalIgnoreCase))));
if (mobileReleasePath || legacyMarketingAsset)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
await next();
});
app.UseStaticFiles();
app.UseRateLimiter();
app.UseAuthentication();
@ -424,6 +480,10 @@ app.MapGet("/api/health", () => Results.Ok(new
app.MapControllers();
app.MapFallbackToFile("/accept-invite", "accept-invite.html");
// Fallback to Admin BackOffice UI index.html
app.MapFallbackToFile("/admin/{*path}", "admin/index.html");
app.Run();
public partial class Program { }

View file

@ -0,0 +1,12 @@
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.d3ro.voice",
"sha256_cert_fingerprints": [
"01:00:19:21:DB:4F:33:40:85:CE:21:E4:B8:DE:CC:BD:71:DA:87:67:C5:6E:3B:59:83:2A:A1:C8:29:EA:0D:AB"
]
}
}
]

View file

@ -0,0 +1,345 @@
:root {
--ink: #08090c;
--panel: #11141c;
--panel-raised: #171b25;
--line: #303647;
--line-soft: rgba(255, 255, 255, 0.07);
--text: #f4f4f5;
--muted: #a1a1aa;
--faint: #71717a;
--accent: #f25b29;
--accent-hot: #ff7342;
--success: #4ade80;
--danger: #fb7185;
font-family: "Pretendard Variable", Pretendard, Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
background: var(--ink);
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
margin: 0;
}
body {
background:
linear-gradient(var(--line-soft) 1px, transparent 1px),
linear-gradient(90deg, var(--line-soft) 1px, transparent 1px),
radial-gradient(circle at 72% 18%, rgba(242, 91, 41, 0.13), transparent 34rem),
var(--ink);
background-size: 40px 40px, 40px 40px, auto, auto;
}
button,
a {
font: inherit;
}
a {
color: inherit;
}
.shell {
min-height: 100vh;
display: grid;
place-items: center;
padding: 32px 18px;
}
.invite-panel {
width: min(100%, 720px);
overflow: hidden;
border: 1px solid var(--line);
border-radius: 18px;
background: linear-gradient(145deg, rgba(23, 27, 37, 0.96), rgba(12, 14, 20, 0.98));
box-shadow: 0 28px 90px rgba(0, 0, 0, 0.48), inset 0 1px rgba(255, 255, 255, 0.06);
}
.brand-row,
.copy-block,
.token-card,
.actions,
.support-row,
.error {
margin-inline: clamp(22px, 7vw, 64px);
}
.brand-row {
min-height: 76px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
border-bottom: 1px solid var(--line-soft);
}
.brand,
.protocol,
.eyebrow,
.token-card dt,
.token-card dd {
font-family: "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
}
.brand {
color: var(--text);
font-size: 14px;
font-weight: 800;
letter-spacing: 0.16em;
text-decoration: none;
}
.protocol {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
}
.signal {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--success);
box-shadow: 0 0 12px rgba(74, 222, 128, 0.72);
}
.route-line {
height: 54px;
display: grid;
grid-template-columns: auto 1fr auto 1fr auto;
align-items: center;
padding-inline: clamp(22px, 7vw, 64px);
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid var(--line-soft);
}
.route-node {
width: 9px;
height: 9px;
border: 1px solid var(--line);
border-radius: 50%;
background: var(--panel);
}
.route-node--active {
border-color: var(--accent-hot);
background: var(--accent);
box-shadow: 0 0 18px rgba(242, 91, 41, 0.72);
}
.route-track {
height: 1px;
background: linear-gradient(90deg, var(--accent), var(--line));
}
.copy-block {
padding-top: clamp(42px, 8vw, 72px);
}
.eyebrow {
margin: 0 0 16px;
color: var(--accent-hot);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.15em;
}
h1 {
max-width: 600px;
margin: 0;
font-size: clamp(34px, 7.2vw, 60px);
font-weight: 790;
letter-spacing: -0.045em;
line-height: 1.08;
text-wrap: balance;
}
.description {
max-width: 590px;
margin: 26px 0 0;
color: #d4d4d8;
font-size: 16px;
line-height: 1.72;
word-break: keep-all;
}
.description--en {
margin-top: 8px;
color: var(--faint);
font-size: 13px;
}
.token-card {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
margin-top: 38px;
padding: 1px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--line);
overflow: hidden;
}
.token-card div {
min-width: 0;
padding: 18px;
background: var(--panel-raised);
}
.token-card dt {
color: var(--faint);
font-size: 9px;
letter-spacing: 0.13em;
}
.token-card dd {
margin: 8px 0 0;
overflow: hidden;
color: var(--text);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.token-card dd[data-state="valid"] {
color: var(--success);
}
.token-card dd[data-state="invalid"] {
color: var(--danger);
}
.error {
margin-top: 18px;
padding: 13px 14px;
border: 1px solid rgba(251, 113, 133, 0.35);
border-radius: 8px;
color: #fecdd3;
background: rgba(251, 113, 133, 0.08);
font-size: 14px;
line-height: 1.5;
}
.actions {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 12px;
margin-top: 24px;
}
.button {
min-height: 52px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid transparent;
border-radius: 8px;
padding: 0 18px;
font-weight: 750;
text-align: center;
text-decoration: none;
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease, color 160ms ease, transform 160ms ease;
}
.button--primary {
color: #fff;
background: var(--accent);
box-shadow: 0 10px 30px rgba(242, 91, 41, 0.2);
}
.button--primary:hover {
background: var(--accent-hot);
transform: translateY(-1px);
}
.button--secondary {
color: var(--text);
border-color: var(--line);
background: rgba(255, 255, 255, 0.035);
}
.button--secondary:hover {
border-color: #535f7f;
background: rgba(255, 255, 255, 0.06);
}
.button[aria-disabled="true"],
.button:disabled {
opacity: 0.42;
cursor: not-allowed;
pointer-events: none;
transform: none;
}
.button:focus-visible,
.brand:focus-visible,
.support-row a:focus-visible {
outline: 3px solid rgba(255, 115, 66, 0.78);
outline-offset: 3px;
}
.support-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
margin-top: 38px;
padding-block: 22px 28px;
border-top: 1px solid var(--line-soft);
color: var(--faint);
font-size: 13px;
}
.support-row a {
color: #d4d4d8;
font-weight: 650;
text-underline-offset: 4px;
}
@media (max-width: 560px) {
.shell {
align-items: start;
padding: 12px;
}
.invite-panel {
border-radius: 12px;
}
.brand-row {
min-height: 66px;
}
.protocol {
font-size: 8px;
}
.token-card,
.actions {
grid-template-columns: 1fr;
}
.support-row {
align-items: flex-start;
flex-direction: column;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
}
}

View file

@ -0,0 +1,76 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark" />
<meta name="theme-color" content="#08090c" />
<meta name="robots" content="noindex,nofollow" />
<meta name="referrer" content="no-referrer" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; base-uri 'none'; connect-src 'none'; font-src 'self'; form-action 'none'; img-src 'self' data:; object-src 'none'; script-src 'self'; style-src 'self'"
/>
<title>D3RO Voice — 팀 초대 열기</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="stylesheet" href="/accept-invite.css" />
</head>
<body>
<main class="shell">
<section class="invite-panel" aria-labelledby="invite-title">
<header class="brand-row">
<a class="brand" href="/" aria-label="D3RO Voice 홈">D3RO VOICE</a>
<span class="protocol"><span class="signal" aria-hidden="true"></span>SECURE INVITE</span>
</header>
<div class="route-line" aria-hidden="true">
<span class="route-node route-node--active"></span>
<span class="route-track"></span>
<span class="route-node"></span>
<span class="route-track"></span>
<span class="route-node"></span>
</div>
<div class="copy-block">
<p class="eyebrow">TEAM ACCESS / MOBILE HANDOFF</p>
<h1 id="invite-title">D3RO Voice 앱에서<br />팀 초대를 확인해.</h1>
<p class="description">
초대 수락은 로그인한 계정과 서버 권한을 확인한 뒤에만 완료돼. 이 페이지는 초대 토큰을
저장하거나 수락 결과를 만들지 않아.
</p>
<p class="description description--en" lang="en">
Acceptance is completed only after the app verifies your signed-in account and server permissions.
</p>
</div>
<dl class="token-card" aria-label="초대 링크 상태">
<div>
<dt>LINK STATUS</dt>
<dd id="invite-status" aria-live="polite">검증 중</dd>
</div>
<div>
<dt>TOKEN FINGERPRINT</dt>
<dd id="token-fingerprint">—</dd>
</div>
</dl>
<p id="invite-error" class="error" role="alert" hidden></p>
<div class="actions">
<a id="open-app" class="button button--primary" href="#" aria-disabled="true">
D3RO Voice 앱 열기
</a>
<button id="copy-link" class="button button--secondary" type="button" disabled>
초대 링크 복사
</button>
</div>
<footer class="support-row">
<span>앱이 설치되지 않았어?</span>
<a href="/download.html">안전한 설치 파일 받기</a>
</footer>
</section>
</main>
<script src="/accept-invite.js" defer></script>
</body>
</html>

View file

@ -0,0 +1,37 @@
(() => {
'use strict'
const tokenPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const status = document.getElementById('invite-status')
const fingerprint = document.getElementById('token-fingerprint')
const error = document.getElementById('invite-error')
const openApp = document.getElementById('open-app')
const copyLink = document.getElementById('copy-link')
const token = new URLSearchParams(window.location.search).get('token')?.trim() ?? ''
if (!tokenPattern.test(token)) {
status.textContent = '사용할 수 없는 링크'
status.dataset.state = 'invalid'
error.textContent = '초대 링크가 없거나 형식이 올바르지 않아. 새 초대 링크를 요청해.'
error.hidden = false
return
}
status.textContent = '형식 검증 완료 · 서버 확인 대기'
status.dataset.state = 'valid'
fingerprint.textContent = `${token.slice(0, 8)}…${token.slice(-4)}`
openApp.href = `d3ro-voice://accept-invite?token=${encodeURIComponent(token)}`
openApp.removeAttribute('aria-disabled')
copyLink.disabled = false
copyLink.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(window.location.href)
copyLink.textContent = '복사했어'
window.setTimeout(() => { copyLink.textContent = '초대 링크 복사' }, 1800)
} catch {
error.textContent = '브라우저가 복사를 허용하지 않았어. 주소 표시줄에서 링크를 직접 복사해.'
error.hidden = false
}
})
})()

View file

@ -0,0 +1,76 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark" />
<meta name="theme-color" content="#08090c" />
<meta name="robots" content="noindex,nofollow" />
<meta name="referrer" content="no-referrer" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; base-uri 'none'; connect-src 'none'; font-src 'self'; form-action 'none'; img-src 'self' data:; object-src 'none'; script-src 'self'; style-src 'self'"
/>
<title>D3RO Voice — 팀 초대 열기</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="stylesheet" href="/accept-invite.css" />
</head>
<body>
<main class="shell">
<section class="invite-panel" aria-labelledby="invite-title">
<header class="brand-row">
<a class="brand" href="/" aria-label="D3RO Voice 홈">D3RO VOICE</a>
<span class="protocol"><span class="signal" aria-hidden="true"></span>SECURE INVITE</span>
</header>
<div class="route-line" aria-hidden="true">
<span class="route-node route-node--active"></span>
<span class="route-track"></span>
<span class="route-node"></span>
<span class="route-track"></span>
<span class="route-node"></span>
</div>
<div class="copy-block">
<p class="eyebrow">TEAM ACCESS / MOBILE HANDOFF</p>
<h1 id="invite-title">D3RO Voice 앱에서<br />팀 초대를 확인해.</h1>
<p class="description">
초대 수락은 로그인한 계정과 서버 권한을 확인한 뒤에만 완료돼. 이 페이지는 초대 토큰을
저장하거나 수락 결과를 만들지 않아.
</p>
<p class="description description--en" lang="en">
Acceptance is completed only after the app verifies your signed-in account and server permissions.
</p>
</div>
<dl class="token-card" aria-label="초대 링크 상태">
<div>
<dt>LINK STATUS</dt>
<dd id="invite-status" aria-live="polite">검증 중</dd>
</div>
<div>
<dt>TOKEN FINGERPRINT</dt>
<dd id="token-fingerprint">—</dd>
</div>
</dl>
<p id="invite-error" class="error" role="alert" hidden></p>
<div class="actions">
<a id="open-app" class="button button--primary" href="#" aria-disabled="true">
D3RO Voice 앱 열기
</a>
<button id="copy-link" class="button button--secondary" type="button" disabled>
초대 링크 복사
</button>
</div>
<footer class="support-row">
<span>앱이 설치되지 않았어?</span>
<a href="/download.html">안전한 설치 파일 받기</a>
</footer>
</section>
</main>
<script src="/accept-invite.js" defer></script>
</body>
</html>

View file

@ -0,0 +1,730 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3RO Voice — Admin BackOffice</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/lucide@latest/dist/umd/lucide.min.js"></script>
<style>
:root {
--bg-gradient: radial-gradient(circle at 50% 0%, #171b26 0%, #0b0d13 100%);
--card-bg: rgba(22, 27, 38, 0.7);
--card-border: rgba(255, 255, 255, 0.08);
--accent: #6366f1;
--accent-hover: #4f46e5;
--accent-glow: rgba(99, 102, 241, 0.35);
--text-main: #f3f4f6;
--text-muted: #9ca3af;
--success: #10b981;
--danger: #ef4444;
--warning: #f59e0b;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Inter', sans-serif;
background: var(--bg-gradient);
color: var(--text-main);
min-height: 100vh;
display: flex;
flex-direction: column;
}
/* Layout Header */
header {
border-bottom: 1px solid var(--card-border);
backdrop-filter: blur(12px);
background: rgba(11, 13, 19, 0.8);
position: sticky;
top: 0;
z-index: 100;
}
.header-inner {
max-width: 1400px;
margin: 0 auto;
padding: 16px 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
font-family: 'Outfit', sans-serif;
font-weight: 700;
font-size: 20px;
letter-spacing: -0.5px;
}
.brand-badge {
background: linear-gradient(135deg, #6366f1, #8b5cf6);
color: #fff;
font-size: 11px;
padding: 2px 8px;
border-radius: 20px;
font-family: 'Inter', sans-serif;
font-weight: 600;
}
nav {
display: flex;
gap: 8px;
}
.nav-btn {
background: transparent;
border: none;
color: var(--text-muted);
padding: 8px 16px;
border-radius: 8px;
font-weight: 500;
font-size: 14px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.2s;
}
.nav-btn:hover, .nav-btn.active {
color: #fff;
background: rgba(255, 255, 255, 0.06);
}
.nav-btn.active {
border: 1px solid var(--accent-glow);
color: var(--accent);
}
/* Main Container */
main {
flex: 1;
max-width: 1400px;
margin: 0 auto;
width: 100%;
padding: 32px 24px;
}
.page-section { display: none; }
.page-section.active { display: block; animation: fadeIn 0.3s ease-out; }
@keyframes fadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
/* Metric Cards Grid */
.grid-4 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 20px;
margin-bottom: 32px;
}
.card {
background: var(--card-bg);
border: 1px solid var(--card-border);
border-radius: 16px;
padding: 24px;
backdrop-filter: blur(12px);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}
.card-title {
font-size: 13px;
color: var(--text-muted);
font-weight: 500;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.card-value {
font-family: 'Outfit', sans-serif;
font-size: 32px;
font-weight: 700;
color: #fff;
}
.card-sub {
font-size: 12px;
color: var(--text-muted);
margin-top: 6px;
}
/* Data Tables */
.table-container {
width: 100%;
overflow-x: auto;
margin-top: 16px;
}
table {
width: 100%;
border-collapse: collapse;
text-align: left;
font-size: 14px;
}
th {
padding: 14px 16px;
background: rgba(255, 255, 255, 0.03);
color: var(--text-muted);
font-weight: 600;
border-bottom: 1px solid var(--card-border);
}
td {
padding: 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
color: var(--text-main);
}
tr:hover td {
background: rgba(255, 255, 255, 0.02);
}
.badge {
display: inline-block;
padding: 3px 10px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.badge-success { background: rgba(16, 185, 129, 0.15); color: var(--success); }
.badge-danger { background: rgba(239, 68, 68, 0.15); color: var(--danger); }
.badge-warning { background: rgba(245, 158, 11, 0.15); color: var(--warning); }
.badge-primary { background: rgba(99, 102, 241, 0.15); color: var(--accent); }
/* Action Buttons */
.btn {
background: var(--accent);
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 8px;
font-weight: 600;
font-size: 14px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 8px;
transition: all 0.2s;
}
.btn:hover { background: var(--accent-hover); box-shadow: 0 0 16px var(--accent-glow); }
.btn-sm { padding: 6px 12px; font-size: 12px; }
.btn-danger { background: rgba(239, 68, 68, 0.2); color: var(--danger); border: 1px solid rgba(239, 68, 68, 0.4); }
.btn-danger:hover { background: var(--danger); color: #fff; }
/* Section Headers */
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.section-title {
font-family: 'Outfit', sans-serif;
font-size: 22px;
font-weight: 700;
}
/* Modal Form */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(8px);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-overlay.active { display: flex; }
.modal-box {
background: #131722;
border: 1px solid var(--card-border);
border-radius: 20px;
width: 100%;
max-width: 540px;
padding: 32px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.form-group {
margin-bottom: 18px;
}
.form-group label {
display: block;
font-size: 13px;
color: var(--text-muted);
margin-bottom: 6px;
}
.form-control {
width: 100%;
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--card-border);
color: #fff;
padding: 10px 14px;
border-radius: 8px;
font-size: 14px;
outline: none;
}
.form-control:focus {
border-color: var(--accent);
box-shadow: 0 0 8px var(--accent-glow);
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
</style>
</head>
<body>
<header>
<div class="header-inner">
<div class="brand">
<i data-lucide="shield-check" style="color: var(--accent);"></i>
<span>D3RO VOICE</span>
<span class="brand-badge">BackOffice API Server</span>
</div>
<nav>
<button class="nav-btn active" onclick="showTab('dashboard')"><i data-lucide="layout-dashboard"></i> 대시보드</button>
<button class="nav-btn" onclick="showTab('users')"><i data-lucide="users"></i> 사용자 관리</button>
<button class="nav-btn" onclick="showTab('endpoints')"><i data-lucide="cpu"></i> 서비스 모델 리스트</button>
<button class="nav-btn" onclick="showTab('usage')"><i data-lucide="bar-chart-3"></i> 상세 Usage & 비용</button>
</nav>
</div>
</header>
<main>
<!-- 1. DASHBOARD -->
<section id="dashboard" class="page-section active">
<div class="section-header">
<h2 class="section-title">백엔드 서버 대시보드</h2>
<button class="btn btn-sm" onclick="loadStats()"><i data-lucide="refresh-cw"></i> 새로고침</button>
</div>
<div class="grid-4">
<div class="card">
<div class="card-title">서버 상태 & 업타임 <i data-lucide="activity" style="color: var(--success);"></i></div>
<div class="card-value" id="val-uptime">0s</div>
<div class="card-sub" id="val-health"><span class="badge badge-success">정상 작동 중</span></div>
</div>
<div class="card">
<div class="card-title">총 사용자 수 <i data-lucide="user-check" style="color: var(--accent);"></i></div>
<div class="card-value" id="val-users">0</div>
<div class="card-sub" id="val-active-today">오늘 접속: 0명</div>
</div>
<div class="card">
<div class="card-title">API 요청 처리량 <i data-lucide="zap" style="color: var(--warning);"></i></div>
<div class="card-value" id="val-requests">0</div>
<div class="card-sub">누적 AI API 호출 수</div>
</div>
<div class="card">
<div class="card-title">총 사용량 & 예상 비용 <i data-lucide="dollar-sign" style="color: var(--success);"></i></div>
<div class="card-value" id="val-cost">$0.0000</div>
<div class="card-sub">실시간 토큰 비용 계산</div>
</div>
</div>
<div class="card">
<div class="card-title" style="font-size: 16px; font-weight: 700; color: #fff;">운영 에러 & 서비스 로그</div>
<div class="table-container">
<table>
<thead>
<tr>
<th>ID</th>
<th>에러 유형</th>
<th>메시지</th>
<th>엔드포인트</th>
<th>발생 일시</th>
</tr>
</thead>
<tbody id="tbody-errors">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted);">로그 데이터를 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- 2. USERS -->
<section id="users" class="page-section">
<div class="section-header">
<h2 class="section-title">가입 사용자 목록</h2>
</div>
<div class="card">
<div class="table-container">
<table>
<thead>
<tr>
<th>ID</th>
<th>이메일</th>
<th>권한</th>
<th>상태</th>
<th>가입 일시</th>
<th>최근 로그인</th>
</tr>
</thead>
<tbody id="tbody-users">
<tr><td colspan="6" style="text-align: center; color: var(--text-muted);">사용자 목록을 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- 3. MODEL ENDPOINTS -->
<section id="endpoints" class="page-section">
<div class="section-header">
<h2 class="section-title">서비스 제공 모델 & 엔드포인트 설정</h2>
<button class="btn" onclick="openModelModal()"><i data-lucide="plus"></i> 모델 엔드포인트 추가</button>
</div>
<div class="card">
<div class="table-container">
<table>
<thead>
<tr>
<th>모델 ID</th>
<th>모델 이름</th>
<th>제공자</th>
<th>엔드포인트 URL</th>
<th>입력 토큰 비용 ($/1k)</th>
<th>출력 토큰 비용 ($/1k)</th>
<th>상태</th>
<th>관리</th>
</tr>
</thead>
<tbody id="tbody-endpoints">
<tr><td colspan="8" style="text-align: center; color: var(--text-muted);">모델 엔드포인트 데이터를 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- 4. USAGE & COST -->
<section id="usage" class="page-section">
<div class="section-header">
<h2 class="section-title">상세 Usage & 비용 분석 (BE Home)</h2>
</div>
<div class="grid-4" style="margin-bottom: 24px;">
<div class="card">
<div class="card-title">총 프롬프트 토큰</div>
<div class="card-value" id="val-p-tokens">0</div>
</div>
<div class="card">
<div class="card-title">총 완성 토큰</div>
<div class="card-value" id="val-c-tokens">0</div>
</div>
<div class="card">
<div class="card-title">총 토큰 합계</div>
<div class="card-value" id="val-t-tokens">0</div>
</div>
<div class="card">
<div class="card-title">누적 과금 금액</div>
<div class="card-value" id="val-total-cost">$0.0000</div>
</div>
</div>
<div class="card" style="margin-bottom: 24px;">
<div class="card-title" style="font-size: 16px; font-weight: 700; color: #fff;">사용자별 사용량 및 비용</div>
<div class="table-container">
<table>
<thead>
<tr>
<th>사용자 ID</th>
<th>이메일</th>
<th>호출 횟수</th>
<th>사용 토큰</th>
<th>계산 비용 ($)</th>
</tr>
</thead>
<tbody id="tbody-user-usage">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted);">사용량 리포트를 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-title" style="font-size: 16px; font-weight: 700; color: #fff;">모델 엔드포인트별 사용량</div>
<div class="table-container">
<table>
<thead>
<tr>
<th>모델 ID</th>
<th>모델 이름</th>
<th>호출 횟수</th>
<th>총 토큰</th>
<th>계산 비용 ($)</th>
</tr>
</thead>
<tbody id="tbody-model-usage">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted);">사용량 리포트를 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
</section>
</main>
<!-- ADD / EDIT ENDPOINT MODAL -->
<div class="modal-overlay" id="modelModal">
<div class="modal-box">
<div class="modal-header">
<h3 style="font-family: 'Outfit', sans-serif; font-size: 20px;">서비스 모델 엔드포인트 추가</h3>
<button onclick="closeModelModal()" style="background:none; border:none; color:var(--text-muted); cursor:pointer;"><i data-lucide="x"></i></button>
</div>
<form id="endpointForm" onsubmit="handleSaveEndpoint(event)">
<div class="form-group">
<label>모델 ID (영문 식별자)</label>
<input type="text" id="m-id" class="form-control" placeholder="예: d3ro-custom-model" required>
</div>
<div class="form-group">
<label>모델 Display 이름</label>
<input type="text" id="m-name" class="form-control" placeholder="예: D3RO Premium Custom LLM" required>
</div>
<div class="form-row">
<div class="form-group">
<label>제공자 (Provider)</label>
<input type="text" id="m-provider" class="form-control" placeholder="OpenAI / Custom" required>
</div>
<div class="form-group">
<label>API Key (선택)</label>
<input type="password" id="m-key" class="form-control" placeholder="sk-...">
</div>
</div>
<div class="form-group">
<label>엔드포인트 URL</label>
<input type="url" id="m-url" class="form-control" placeholder="https://api.openai.com/v1/chat/completions" required>
</div>
<div class="form-row">
<div class="form-group">
<label>입력 토큰 비용 ($/1k)</label>
<input type="number" step="0.000001" id="m-cost-p" class="form-control" value="0.000150" required>
</div>
<div class="form-group">
<label>출력 토큰 비용 ($/1k)</label>
<input type="number" step="0.000001" id="m-cost-c" class="form-control" value="0.000600" required>
</div>
</div>
<div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
<button type="button" class="btn" style="background: transparent; border: 1px solid var(--card-border);" onclick="closeModelModal()">취소</button>
<button type="submit" class="btn"><i data-lucide="check"></i> 저장하기</button>
</div>
</form>
</div>
</div>
<script>
lucide.createIcons();
function showTab(tabId) {
document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.page-section').forEach(sec => sec.classList.remove('active'));
event.currentTarget.classList.add('active');
document.getElementById(tabId).classList.add('active');
if (tabId === 'dashboard') loadStats();
if (tabId === 'users') loadUsers();
if (tabId === 'endpoints') loadEndpoints();
if (tabId === 'usage') loadUsageReport();
}
async function loadStats() {
try {
const res = await fetch('/api/admin/stats');
if (!res.ok) return;
const data = await res.json();
document.getElementById('val-uptime').innerText = Math.floor(data.serverUptimeSeconds) + '초';
document.getElementById('val-users').innerText = data.totalUsers;
document.getElementById('val-active-today').innerText = '오늘 접속: ' + data.activeUsersToday + '명';
document.getElementById('val-requests').innerText = data.totalRequests;
document.getElementById('val-cost').innerText = '$' + data.totalCost.toFixed(4);
const tbody = document.getElementById('tbody-errors');
if (data.recentErrors.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--success);">에러 로그 없음 (시스템 정상)</td></tr>';
} else {
tbody.innerHTML = data.recentErrors.map(e => `
<tr>
<td>${e.id}</td>
<td><span class="badge badge-danger">${e.errorType}</span></td>
<td>${e.message}</td>
<td>${e.endpoint || '-'}</td>
<td>${new Date(e.createdAt).toLocaleString()}</td>
</tr>
`).join('');
}
} catch (err) {
console.error(err);
}
}
async function loadUsers() {
try {
const res = await fetch('/api/admin/users');
if (!res.ok) return;
const users = await res.json();
const tbody = document.getElementById('tbody-users');
if (users.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: var(--text-muted);">가입된 사용자가 없습니다.</td></tr>';
} else {
tbody.innerHTML = users.map(u => `
<tr>
<td>${u.id}</td>
<td style="font-weight: 600;">${u.email}</td>
<td><span class="badge ${u.role === 'Admin' ? 'badge-primary' : 'badge-warning'}">${u.role}</span></td>
<td><span class="badge ${u.isActive ? 'badge-success' : 'badge-danger'}">${u.isActive ? '활성' : '비활성'}</span></td>
<td>${new Date(u.createdAt).toLocaleString()}</td>
<td>${u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '미접속'}</td>
</tr>
`).join('');
}
} catch (err) {
console.error(err);
}
}
async function loadEndpoints() {
try {
const res = await fetch('/api/admin/endpoints');
if (!res.ok) return;
const endpoints = await res.json();
const tbody = document.getElementById('tbody-endpoints');
if (endpoints.length === 0) {
tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: var(--text-muted);">등록된 서비스 모델 엔드포인트가 없습니다.</td></tr>';
} else {
tbody.innerHTML = endpoints.map(e => `
<tr>
<td><code>${e.modelId}</code></td>
<td style="font-weight:600;">${e.modelName}</td>
<td><span class="badge badge-primary">${e.provider}</span></td>
<td style="font-size:12px; color:var(--text-muted);">${e.endpointUrl}</td>
<td>$${e.costPer1kPromptTokens.toFixed(6)}</td>
<td>$${e.costPer1kCompletionTokens.toFixed(6)}</td>
<td><span class="badge ${e.isActive ? 'badge-success' : 'badge-danger'}">${e.isActive ? '제공중' : '중지'}</span></td>
<td>
<button class="btn btn-sm btn-danger" onclick="deleteEndpoint(${e.id})">삭제</button>
</td>
</tr>
`).join('');
}
} catch (err) {
console.error(err);
}
}
async function loadUsageReport() {
try {
const res = await fetch('/api/admin/usage');
if (!res.ok) return;
const report = await res.json();
document.getElementById('val-p-tokens').innerText = report.totalPromptTokens.toLocaleString();
document.getElementById('val-c-tokens').innerText = report.totalCompletionTokens.toLocaleString();
document.getElementById('val-t-tokens').innerText = (report.totalPromptTokens + report.totalCompletionTokens).toLocaleString();
document.getElementById('val-total-cost').innerText = '$' + report.totalCost.toFixed(4);
const tbodyUser = document.getElementById('tbody-user-usage');
if (report.userSummaries.length === 0) {
tbodyUser.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted);">사용 이력이 없습니다.</td></tr>';
} else {
tbodyUser.innerHTML = report.userSummaries.map(u => `
<tr>
<td>${u.userId}</td>
<td>${u.email}</td>
<td>${u.totalRequests}회</td>
<td>${u.totalTokens.toLocaleString()}</td>
<td style="font-weight:700; color:var(--success);">$${u.totalCost.toFixed(6)}</td>
</tr>
`).join('');
}
const tbodyModel = document.getElementById('tbody-model-usage');
if (report.modelSummaries.length === 0) {
tbodyModel.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted);">모델 사용 이력이 없습니다.</td></tr>';
} else {
tbodyModel.innerHTML = report.modelSummaries.map(m => `
<tr>
<td><code>${m.modelId}</code></td>
<td>${m.modelName}</td>
<td>${m.totalRequests}회</td>
<td>${m.totalTokens.toLocaleString()}</td>
<td style="font-weight:700; color:var(--success);">$${m.totalCost.toFixed(6)}</td>
</tr>
`).join('');
}
} catch (err) {
console.error(err);
}
}
function openModelModal() {
document.getElementById('modelModal').classList.add('active');
}
function closeModelModal() {
document.getElementById('modelModal').classList.remove('active');
}
async function handleSaveEndpoint(e) {
e.preventDefault();
const payload = {
modelId: document.getElementById('m-id').value,
modelName: document.getElementById('m-name').value,
provider: document.getElementById('m-provider').value,
apiKey: document.getElementById('m-key').value,
endpointUrl: document.getElementById('m-url').value,
costPer1kPromptTokens: parseFloat(document.getElementById('m-cost-p').value),
costPer1kCompletionTokens: parseFloat(document.getElementById('m-cost-c').value)
};
try {
const res = await fetch('/api/admin/endpoints', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
closeModelModal();
loadEndpoints();
document.getElementById('endpointForm').reset();
} else {
const err = await res.json();
alert(err.message || '저장 실패');
}
} catch (err) {
alert('에러 발생: ' + err.message);
}
}
async function deleteEndpoint(id) {
if (!confirm('이 서비스 모델 엔드포인트를 삭제하시겠습니까?')) return;
try {
const res = await fetch('/api/admin/endpoints/' + id, { method: 'DELETE' });
if (res.ok) loadEndpoints();
} catch (err) {
alert('삭제 실패: ' + err.message);
}
}
// Initialize
loadStats();
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="refresh" content="0; url=https://d3ro.chanpaca.net/#download" />
<link rel="canonical" href="https://d3ro.chanpaca.net/#download" />
<title>D3RO Voice 릴리스 준비</title>
</head>
<body>
<main>
<h1>D3RO Voice 릴리스 준비</h1>
<p>설치 파일은 서명과 업데이트 경로 검증이 끝난 뒤 공식 페이지에서 제공합니다.</p>
<p><a href="https://d3ro.chanpaca.net/#download">공식 릴리스 준비 페이지로 이동</a></p>
</main>
</body>
</html>

View file

@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#19191b"/>
<circle cx="32" cy="28" r="8" fill="none" stroke="#f25b29" stroke-width="3"/>
<rect x="29" y="36" width="6" height="10" rx="3" fill="#f25b29"/>
<path d="M20 32 Q20 44 32 44 Q44 44 44 32" fill="none" stroke="#f25b29" stroke-width="2.5" stroke-linecap="round"/>
<line x1="32" y1="44" x2="32" y2="52" stroke="#f25b29" stroke-width="2.5" stroke-linecap="round"/>
<line x1="26" y1="52" x2="38" y2="52" stroke="#f25b29" stroke-width="2.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 592 B

View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="refresh" content="0; url=https://d3ro.chanpaca.net/#download" />
<link rel="canonical" href="https://d3ro.chanpaca.net/#download" />
<title>D3RO Voice 릴리스 준비</title>
</head>
<body>
<main>
<h1>D3RO Voice 릴리스 준비</h1>
<p>설치 파일은 서명과 업데이트 경로 검증이 끝난 뒤 공식 페이지에서 제공합니다.</p>
<p><a href="https://d3ro.chanpaca.net/#download">공식 릴리스 준비 페이지로 이동</a></p>
</main>
</body>
</html>

View file

@ -0,0 +1,8 @@
version: 1.0.0
files:
- url: D3RO-Voice-Setup-1.0.0-x64.exe
sha512: Ae4ZDaqL6mtkpyGsX9rna6WT3hhtChiEF4hl+Yx1CQvjCPwTq7LmhcBEm40TvRHOVtjQSASsCTs1wxVgSRo1Ow==
size: 102123822
path: D3RO-Voice-Setup-1.0.0-x64.exe
sha512: Ae4ZDaqL6mtkpyGsX9rna6WT3hhtChiEF4hl+Yx1CQvjCPwTq7LmhcBEm40TvRHOVtjQSASsCTs1wxVgSRo1Ow==
releaseDate: '2026-08-20T01:56:59.299Z'

View file

@ -0,0 +1,8 @@
version: 1.0.0
files:
- url: D3RO-Voice-Setup-1.0.0-x64.exe
sha512: Ae4ZDaqL6mtkpyGsX9rna6WT3hhtChiEF4hl+Yx1CQvjCPwTq7LmhcBEm40TvRHOVtjQSASsCTs1wxVgSRo1Ow==
size: 102123822
path: D3RO-Voice-Setup-1.0.0-x64.exe
sha512: Ae4ZDaqL6mtkpyGsX9rna6WT3hhtChiEF4hl+Yx1CQvjCPwTq7LmhcBEm40TvRHOVtjQSASsCTs1wxVgSRo1Ow==
releaseDate: '2026-08-20T01:56:59.299Z'

View file

@ -61,8 +61,6 @@ logger = logging.getLogger("sidecar")
_model: "WhisperModel | None" = None
_model_id: str | None = None
# 보조 모델 (실시간 자막 등 받아쓰기와 다른 모델). 최대 1개.
_aux_models: "dict[str, WhisperModel]" = {}
_gpu_available: bool = False
_server: uvicorn.Server | None = None
_models_dir: Path | None = None
@ -324,33 +322,12 @@ async def health() -> JSONResponse:
"status": "ready" if _model is not None else "no_model",
"model": _model_id,
"model_loaded": _model is not None,
"aux_models": list(_aux_models.keys()),
"gpu": _gpu_available,
"device": "cuda" if _gpu_available else "cpu",
}
)
def _create_model(model_id: str) -> "WhisperModel":
"""모델을 올린다. /download 로 받아 둔 로컬 디렉토리가 있으면 그것을 쓴다."""
from faster_whisper import WhisperModel
device = "cuda" if _gpu_available else "cpu"
compute_type = "float16" if _gpu_available else "int8"
local_dir = _local_model_dir(model_id)
model_source = str(local_dir) if local_dir else model_id
if local_dir:
logger.info("로컬 모델 디렉토리 사용: %s", local_dir)
logger.info("모델 생성: %s (device=%s, compute=%s)", model_id, device, compute_type)
return WhisperModel(
model_source,
device=device,
compute_type=compute_type,
cpu_threads=_cpu_threads(),
num_workers=1,
)
@app.post("/load")
async def load_model(body: dict) -> JSONResponse: # noqa: ANN001
"""Whisper 모델을 로딩한다.
@ -364,14 +341,12 @@ async def load_model(body: dict) -> JSONResponse: # noqa: ANN001
global _model, _model_id
model_id: str = body.get("model_id", "large-v3-turbo")
# primary = 받아쓰기(기본) 모델, aux = 실시간 자막처럼 따로 고른 보조 모델.
slot: str = body.get("slot", "primary")
logger.info("모델 로딩 시작: %s (slot=%s)", model_id, slot)
logger.info("모델 로딩 시작: %s", model_id)
start_time = time.monotonic()
# 같은 모델이 이미 로딩되어 있으면 재사용 (재로딩은 수초 지연을 만든다)
if (_model is not None and _model_id == model_id) or (slot == "aux" and model_id in _aux_models):
if _model is not None and _model_id == model_id:
logger.info("이미 로딩된 모델 재사용: %s", model_id)
return JSONResponse(
content={
@ -383,20 +358,38 @@ async def load_model(body: dict) -> JSONResponse: # noqa: ANN001
)
try:
if slot == "aux":
# 보조 자리는 하나만 둔다 — 다른 보조 모델은 내려 VRAM 을 돌려받는다.
_aux_models.clear()
_aux_models[model_id] = _create_model(model_id)
else:
from faster_whisper import WhisperModel
device = "cuda" if _gpu_available else "cpu"
compute_type = "float16" if _gpu_available else "int8"
# /download로 미리 받아둔 로컬 디렉토리가 있으면 우선 사용.
# 없으면 faster-whisper의 HF 자동 다운로드 경로로 폴백.
local_dir = _local_model_dir(model_id)
model_source = str(local_dir) if local_dir else model_id
if local_dir:
logger.info("로컬 모델 디렉토리 사용: %s", local_dir)
# 모델 교체 시 이전 모델을 먼저 해제해 VRAM/RAM을 회수한다.
_model = None
_model = _create_model(model_id)
_model = WhisperModel(
model_source,
device=device,
compute_type=compute_type,
cpu_threads=_cpu_threads(),
num_workers=1,
)
_model_id = model_id
# 기본 모델이 된 모델은 보조 자리에 중복으로 들고 있지 않는다.
_aux_models.pop(model_id, None)
load_time_ms = int((time.monotonic() - start_time) * 1000)
logger.info("모델 로딩 완료: %s (slot=%s, %dms)", model_id, slot, load_time_ms)
logger.info(
"모델 로딩 완료: %s (device=%s, compute=%s, %dms)",
model_id,
device,
compute_type,
load_time_ms,
)
return JSONResponse(
content={
@ -421,7 +414,6 @@ async def transcribe(
vad_filter: str = Form("true"),
initial_prompt: str = Form(""),
partial: str = Form("false"),
model_id: str = Form(""),
) -> JSONResponse:
"""오디오 파일을 전사한다.
@ -431,18 +423,8 @@ async def transcribe(
vad_filter - VAD 필터 활성화 ('true' / 'false')
initial_prompt - 초기 프롬프트 (컨텍스트 힌트)
partial - 녹음 중 미리보기 모드 ('true'면 greedy 디코딩 + 컨텍스트 미사용)
model_id - 쓸 모델 (비우면 기본 모델). 올라가 있지 않으면 409
"""
if model_id and model_id != _model_id:
model = _aux_models.get(model_id)
if model is None:
return JSONResponse(
status_code=409,
content={"status": "error", "code": "model_not_loaded", "message": f"모델이 로딩되지 않았습니다: {model_id}"},
)
else:
model = _model
if model is None:
if _model is None:
return JSONResponse(
status_code=503,
content={"status": "error", "message": "모델이 로딩되지 않았습니다"},
@ -484,12 +466,12 @@ async def transcribe(
# VAD가 전체 오디오를 제거하면 max() 에러 발생 → VAD 없이 재시도
try:
segments_iter, info = model.transcribe(audio_array, **transcribe_kwargs)
segments_iter, info = _model.transcribe(audio_array, **transcribe_kwargs)
except ValueError as ve:
if "empty sequence" in str(ve) and transcribe_kwargs.get("vad_filter"):
logger.warning("VAD가 전체 오디오를 제거함 → VAD 없이 재시도")
transcribe_kwargs["vad_filter"] = False
segments_iter, info = model.transcribe(audio_array, **transcribe_kwargs)
segments_iter, info = _model.transcribe(audio_array, **transcribe_kwargs)
else:
raise

View file

@ -7,7 +7,6 @@ import { initLoggerService, getLogger } from './services/LoggerService'
import { initConfigService, configGet, configSet } from './services/ConfigService'
import { getKeyBindingService, uiohookCodeToVk } from './services/KeyBindingService'
import { acquireGlobalInputHook } from './services/global-input-hook'
import { trackModifierKeys } from './services/modifier-state'
import { getVoiceModeService } from './services/VoiceModeService'
import { startLocalLLMAvailability, getLocalLLMService } from './services/LocalLLMService'
import { getHistoryService } from './services/HistoryService'
@ -211,12 +210,14 @@ async function initInputIntelligence(): Promise<void> {
sendToMainWindow(IPC_CHANNELS.SUGGESTION.STATE_CHANGED, state)
)
// 제안 수락/순환/닫기는 전역 키바인딩으로만 들어온다 — 오버레이는 포커스를 갖지 않는다.
// 제안 수락/순환/페이지/닫기는 전역 키바인딩으로만 들어온다 — 오버레이는 포커스를 갖지 않는다.
getKeyBindingService().on('triggered', (payload) => {
if (payload.type !== 'pressed') return
if (payload.actionId === 'suggestion-accept') void suggestion.accept()
else if (payload.actionId === 'suggestion-next') suggestion.next()
else if (payload.actionId === 'suggestion-prev') suggestion.previous()
else if (payload.actionId === 'suggestion-page-next') suggestion.pageNext()
else if (payload.actionId === 'suggestion-page-prev') suggestion.pagePrev()
else if (payload.actionId === 'suggestion-dismiss') suggestion.dismiss('dismissed')
})
@ -225,8 +226,6 @@ async function initInputIntelligence(): Promise<void> {
// KeyBindingService 의 등록 바인딩 경로로는 절대 들어오지 않는다 — 원본 keydown을
// 직접 듣는다(InputTelemetryService/KeyBindingService 가 이미 쓰는 것과 같은 패턴).
acquireGlobalInputHook()
// 단축키로 수락할 때 Ctrl/Alt 를 뗄 때까지 기다리려면 누른 순간부터 추적해야 한다.
trackModifierKeys()
uIOhook.on('keydown', (event: UiohookKeyboardEvent) => {
if (uiohookCodeToVk(event.keycode) !== VK.Escape) return
const shouldDismiss = shouldDismissOnEscape(suggestion.isPresentationActive, {

View file

@ -28,6 +28,7 @@ import { registerMeetingDocTemplateHandlers } from './meeting-doc-template-handl
import { registerCloudSyncHandlers } from './cloud-sync-handlers'
import { registerAdsHandlers } from './ads-handlers'
import { registerSupportHandlers } from './support-handlers'
import { registerPaymentHandlers } from './payment-handlers'
import { registerInputTelemetryHandlers } from './input-telemetry-handlers'
import { registerSuggestionHandlers } from './suggestion-handlers'
import { getLogger } from '../services/LoggerService'
@ -63,6 +64,7 @@ export function registerAllIpcHandlers(): void {
registerCloudSyncHandlers()
registerAdsHandlers()
registerSupportHandlers()
registerPaymentHandlers()
registerInputTelemetryHandlers()
registerSuggestionHandlers()
logger.info('All IPC handlers registered')

View file

@ -11,10 +11,6 @@ import type {
LicenseInfo,
} from '@d3ro/core/types'
import { Feature } from '@d3ro/core/types'
import { billingUrl, PUBLIC_SITE_ORIGIN } from '@d3ro/core/web-urls'
/** 개발 빌드는 로컬 웹앱(`npm run dev --workspace=@d3ro/web`)의 결제 페이지를 연다. */
const DEV_WEB_ORIGIN = 'http://localhost:3000'
/** 업그레이드 유도 이벤트를 모든 렌더러에 broadcast */
function broadcastUpgradePrompt(event: UpgradePromptEvent): void {
@ -104,8 +100,9 @@ export function registerLicenseHandlers(): void {
ipcMain.handle(IPC_CHANNELS.LICENSE.OPEN_BILLING, async (_event, params: { tier: 'pro' | 'pro_plus' }) => {
try {
const url = billingUrl({ tier: params.tier })
await shell.openExternal(app.isPackaged ? url : url.replace(PUBLIC_SITE_ORIGIN, DEV_WEB_ORIGIN))
const baseUrl = app.isPackaged ? 'https://d3ro.dev' : 'http://localhost:3000'
const billingUrl = `${baseUrl}/billing?tier=${params.tier}`
await shell.openExternal(billingUrl)
return ipcSuccess(undefined)
} catch (err) {
return ipcError(ErrorCode.UnknownError, `Failed to open billing: ${err}`)

View file

@ -0,0 +1,246 @@
// apps/desktop/src/main/ipc/payment-handlers.ts
// Authenticated, server-authoritative checkout and subscription IPC handlers.
import { randomUUID } from 'node:crypto'
import { ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ErrorCode, ipcError, ok, type IPCResult } from '@d3ro/core/errors'
import type { CheckoutSessionParams, CheckoutSessionResult } from '@d3ro/core/types'
import { getCloudSyncService } from '../services/CloudSyncService'
const CHECKOUT_FUNCTION = 'stripe-checkout'
const SUBSCRIPTION_FUNCTION = 'payple-manage'
const CHECKOUT_SUCCESS_URL = 'https://d3ro.chanpaca.net/billing?desktop_checkout=success'
const CHECKOUT_CANCEL_URL = 'https://d3ro.chanpaca.net/billing?desktop_checkout=cancelled'
const STRIPE_CHECKOUT_ORIGIN = 'https://checkout.stripe.com'
const STRIPE_CHECKOUT_PATH_PREFIX = '/c/pay/'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const SERVER_ENTITLED_STATUSES = new Set([
'active',
'trialing',
'past_due',
'canceled',
'cancelled'
])
export const PAYMENT_REQUEST_TIMEOUT_MS = 15_000
const CHECKOUT_IDEMPOTENCY_TTL_MS = 5 * 60_000
type PaidTier = 'pro' | 'pro_plus'
type CloudSyncService = ReturnType<typeof getCloudSyncService>
interface CheckoutAttempt {
idempotencyKey: string
expiresAt: number
inFlight?: Promise<IPCResult<CheckoutSessionResult>>
result?: CheckoutSessionResult
}
interface SubscriptionStatus {
tier: 'free' | PaidTier
valid: boolean
expiresAt: number | null
}
class PaymentTimeoutError extends Error {}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function parseCheckoutParams(value: unknown): { tier: PaidTier } | null {
if (!isRecord(value)) return null
if (value.provider !== 'stripe') return null
if (value.tier !== 'pro' && value.tier !== 'pro_plus') return null
return { tier: value.tier }
}
function getAuthenticatedCloud(): { cloud: CloudSyncService; userId: string } | null {
const cloud = getCloudSyncService()
const user = cloud.getUser()
if (!cloud.isAuthenticated() || !user || !UUID_PATTERN.test(user.id)) return null
return { cloud, userId: user.id }
}
async function invokeWithDeadline(
cloud: CloudSyncService,
name: string,
body: Record<string, unknown>
): Promise<{ data: unknown; error: { message: string } | null }> {
const controller = new AbortController()
let timeout: ReturnType<typeof setTimeout> | undefined
const deadline = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
controller.abort()
reject(new PaymentTimeoutError('Payment server request timed out'))
}, PAYMENT_REQUEST_TIMEOUT_MS)
})
try {
return await Promise.race([
cloud.invokeFunction(name, body, {
signal: controller.signal,
timeoutMs: PAYMENT_REQUEST_TIMEOUT_MS
}),
deadline
])
} finally {
if (timeout !== undefined) clearTimeout(timeout)
}
}
function parseTrustedCheckoutUrl(value: unknown): string | null {
if (!isRecord(value) || typeof value.url !== 'string') return null
try {
const url = new URL(value.url)
if (
url.protocol !== 'https:' ||
url.origin !== STRIPE_CHECKOUT_ORIGIN ||
url.username !== '' ||
url.password !== '' ||
!url.pathname.startsWith(STRIPE_CHECKOUT_PATH_PREFIX) ||
url.pathname.length <= STRIPE_CHECKOUT_PATH_PREFIX.length
)
return null
return url.toString()
} catch {
return null
}
}
function parseServerSubscription(value: unknown, now = Date.now()): SubscriptionStatus | null {
if (!isRecord(value)) return null
if (value.tier !== 'free' && value.tier !== 'pro' && value.tier !== 'pro_plus') return null
if (typeof value.status !== 'string' || value.status.length === 0) return null
let expiresAt: number | null = null
if (value.current_period_end !== null && value.current_period_end !== undefined) {
if (typeof value.current_period_end !== 'string') return null
const parsed = Date.parse(value.current_period_end)
if (!Number.isFinite(parsed)) return null
expiresAt = parsed
}
const paidTier = value.tier === 'pro' || value.tier === 'pro_plus'
const valid =
paidTier &&
SERVER_ENTITLED_STATUSES.has(value.status) &&
(expiresAt === null || expiresAt > now)
return {
tier: valid ? value.tier : 'free',
valid,
expiresAt
}
}
async function readServerSubscription(cloud: CloudSyncService): Promise<SubscriptionStatus> {
const response = await invokeWithDeadline(cloud, SUBSCRIPTION_FUNCTION, { action: 'info' })
if (response.error) throw new Error('subscription_provider_error')
const status = parseServerSubscription(response.data)
if (!status) throw new Error('subscription_response_invalid')
return status
}
function paymentFailure<T>(error: unknown, fallback: string): IPCResult<T> {
if (error instanceof PaymentTimeoutError) {
return ipcError(ErrorCode.UnknownError, 'Payment server request timed out')
}
return ipcError(ErrorCode.UnknownError, fallback)
}
export function registerPaymentHandlers(): void {
const attempts = new Map<string, CheckoutAttempt>()
ipcMain.handle(
IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION,
async (_event, rawParams: CheckoutSessionParams) => {
const params = parseCheckoutParams(rawParams)
if (!params) {
return ipcError(ErrorCode.UnknownError, 'Invalid checkout request')
}
const authenticated = getAuthenticatedCloud()
if (!authenticated) {
return ipcError(ErrorCode.UnknownError, 'Sign in is required for checkout')
}
const now = Date.now()
for (const [key, attempt] of attempts) {
if (!attempt.inFlight && attempt.expiresAt <= now) attempts.delete(key)
}
const fingerprint = `${authenticated.userId}:stripe:${params.tier}`
let attempt = attempts.get(fingerprint)
if (!attempt || attempt.expiresAt <= now) {
attempt = {
idempotencyKey: `desktop:stripe-checkout:${randomUUID()}`,
expiresAt: now + CHECKOUT_IDEMPOTENCY_TTL_MS
}
attempts.set(fingerprint, attempt)
}
if (attempt.result) return ok(attempt.result)
if (attempt.inFlight) return attempt.inFlight
const currentAttempt = attempt
const operation = (async (): Promise<IPCResult<CheckoutSessionResult>> => {
try {
const response = await invokeWithDeadline(authenticated.cloud, CHECKOUT_FUNCTION, {
tier: params.tier,
success_url: CHECKOUT_SUCCESS_URL,
cancel_url: CHECKOUT_CANCEL_URL,
idempotency_key: currentAttempt.idempotencyKey
})
if (response.error) {
return ipcError(ErrorCode.UnknownError, 'Checkout service rejected the request')
}
const checkoutUrl = parseTrustedCheckoutUrl(response.data)
if (!checkoutUrl) {
return ipcError(ErrorCode.UnknownError, 'Checkout service returned an invalid URL')
}
const result: CheckoutSessionResult = {
checkoutUrl,
provider: 'stripe',
status: 'pending'
}
currentAttempt.result = result
return ok(result)
} catch (error) {
return paymentFailure(error, 'Checkout service is unavailable')
} finally {
currentAttempt.inFlight = undefined
}
})()
currentAttempt.inFlight = operation
return operation
}
)
ipcMain.handle(IPC_CHANNELS.PAYMENT.VERIFY_PAYMENT, async () => {
const authenticated = getAuthenticatedCloud()
if (!authenticated) {
return ipcError(ErrorCode.UnknownError, 'Sign in is required to verify a subscription')
}
try {
const status = await readServerSubscription(authenticated.cloud)
return ok({ success: status.valid, activeTier: status.tier })
} catch (error) {
return paymentFailure(error, 'Subscription status is unavailable')
}
})
ipcMain.handle(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS, async () => {
const authenticated = getAuthenticatedCloud()
if (!authenticated) {
return ipcError(ErrorCode.UnknownError, 'Sign in is required to read a subscription')
}
try {
return ok(await readServerSubscription(authenticated.cloud))
} catch (error) {
return paymentFailure(error, 'Subscription status is unavailable')
}
})
}

View file

@ -93,7 +93,7 @@ export function registerSupportHandlers(): void {
const result: RefundEligibilityResult = {
eligible: true,
reason: '결제일로부터 7일 이내이며 클라우드 AI 정제 쿼터를 10% 미만 사용하셨습니다. (100% 전액 환불 가능)',
refundMethod: 'Payple 카드 결제 즉시 취소',
refundMethod: 'Toss Payments / Stripe 결제 즉시 취소',
estimatedRefundKrw: 229000,
}
return ok(result)

View file

@ -1,8 +1,6 @@
// src/main/services/CaptionService.ts
// Phase 10.1: Live Caption — 실시간 자막 서비스
// 스트리밍 전사: 1초마다 중간 결과를 갱신하고, 말이 멈추면 문장을 확정한다
// (StreamingCaptionTrack). 확정된 줄은 로컬 LLM이 문맥에 맞게 다듬는다.
// 싱글톤 + EventEmitter 패턴.
// 3초 청크 기반 스트리밍 전사. 싱글톤 + EventEmitter 패턴.
import { EventEmitter } from 'events'
import { app } from 'electron'
@ -10,12 +8,9 @@ import { getLogger } from './LoggerService'
import { getAudioCaptureService, calculateRMS } from './AudioCaptureService'
import { getSoundEffectService } from './SoundEffectService'
import { getLocalSTTService } from './LocalSTTService'
import { getLocalLLMService } from './LocalLLMService'
import { getSTTManager } from './stt/STTManager'
import { getHistoryService } from './HistoryService'
import { configGet } from './ConfigService'
import { buildCaptionRefinePrompt } from './llm-prompts'
import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack'
import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming'
import {
showCaptionOverlay,
hideCaptionOverlay,
@ -33,16 +28,17 @@ import { getMainWindow } from '../windows/WindowManager'
const logger = getLogger('CaptionService')
/** 트랙 판단 주기 (ms) — 인식 주기는 트랙이 정한다(중간 결과 1초) */
const TICK_INTERVAL_MS = 250
/** 청크 수집 간격 (ms) — 6초로 충분한 컨텍스트 확보 */
const CHUNK_INTERVAL_MS = 6000
/** RMS 무음 임계값 — 이하면 무음으로 판정 (SoX 캡처 레벨이 낮으므로 0.003 사용) */
const SILENCE_RMS_THRESHOLD = 0.003
/** 문맥 다듬기 대기열 상한 — 밀리면 오래된 줄은 다듬지 않고 넘긴다 */
const REFINE_QUEUE_LIMIT = 3
const REFINE_TIMEOUT_MS = 6000
const REFINE_KEEP_ALIVE = '10m'
/** 유성음 프레임 비율 — 이 비율 미만이면 청크 스킵 (환각 방지) */
const VOICED_FRAME_RATIO = 0.03
/** initialPrompt 컨텍스트 윈도우 (자) */
const CONTEXT_WINDOW_SIZE = 300
/** 기본 자막 설정 */
const DEFAULT_CONFIG: CaptionConfig = {
@ -67,20 +63,21 @@ class CaptionService extends EventEmitter {
private _sessionId: string | null = null
private _sessionStartedAt: number | null = null
private _segments: CaptionSegment[] = []
private _tickTimer: ReturnType<typeof setInterval> | null = null
private _audioBuffers: Buffer[] = []
private _chunkTimer: ReturnType<typeof setInterval> | null = null
private _isProcessingChunk = false
private _previousContext = ''
private _disposed = false
/** 마이크 트랙 (audioSource='mic' 또는 'both') */
private _micTrack: StreamingCaptionTrack | null = null
/** 시스템 소리 트랙 (audioSource='system' 또는 'both') */
private _systemTrack: StreamingCaptionTrack | null = null
/** 'auto' 언어일 때 첫 확정 결과로 고정한다 — 중간 결과마다 언어가 흔들리지 않게 */
private _sessionLanguage: string | null = null
/** 자막 전용 모델 (null 이면 받아쓰기 모델) */
private _captionModelId: string | null = null
private _refineQueue: CaptionSegment[] = []
private _refining = false
/** 현재 청크 내 유성음 프레임 수 */
private _voicedFrameCount = 0
/** 현재 청크 내 총 프레임 수 */
private _totalFrameCount = 0
private _audioDataHandler: ((payload: { buffer: Buffer; timestamp: number }) => void) | null = null
/** 시스템 오디오용 별도 버퍼 (audioSource='system' 또는 'both') */
private _systemAudioBuffers: Buffer[] = []
private _systemVoicedFrameCount = 0
private _systemTotalFrameCount = 0
// ── 공개 접근자 ──
@ -128,19 +125,18 @@ class CaptionService extends EventEmitter {
// STT 초기화 (모델 로딩 — 시간 소요)
const sttService = getLocalSTTService()
await sttService.initialize()
// 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리).
this._captionModelId = configGet('captionSttModelId') ?? null
if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId)
// 세션 초기화
this._sessionId = crypto.randomUUID()
this._sessionStartedAt = Date.now()
this._segments = []
this._refineQueue = []
this._sessionLanguage = null
this._audioBuffers = []
// 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지
const lang = configGet('sttLanguage') as string | undefined
const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : ''
this._previousContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : ''
this._isProcessingChunk = false
this._voicedFrameCount = 0
this._totalFrameCount = 0
// ConfigService에서 저장된 오디오 소스 읽기
const savedSource = configGet('captionAudioSource' as keyof import('@d3ro/core/types').AppConfig) as unknown as string
@ -152,7 +148,6 @@ class CaptionService extends EventEmitter {
// 마이크 캡처 (mic 또는 both)
if (audioSource === 'mic' || audioSource === 'both') {
this._micTrack = this._createTrack('mic', initialContext)
const audioCaptureService = getAudioCaptureService()
this._audioDataHandler = (payload) => {
this._onAudioData(payload.buffer)
@ -163,26 +158,45 @@ class CaptionService extends EventEmitter {
// 시스템 오디오 캡처 요청 (system 또는 both) — 렌더러에 시작 요청
if (audioSource === 'system' || audioSource === 'both') {
this._systemTrack = this._createTrack('system', initialContext)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.START_SYSTEM_AUDIO, {})
this._systemAudioBuffers = []
this._systemVoicedFrameCount = 0
this._systemTotalFrameCount = 0
}
// 트랙 판단 타이머 — 각 트랙은 한 번에 인식 한 건만 돌린다
this._tickTimer = setInterval(() => {
void this._micTrack?.tick()
void this._systemTrack?.tick()
}, TICK_INTERVAL_MS)
// 청크 타이머 시작
this._chunkTimer = setInterval(() => {
const promises: Promise<void>[] = []
// 마이크 청크 처리
if (audioSource === 'mic' || audioSource === 'both') {
promises.push(
this._processChunk().catch((err: unknown) => {
logger.error(`마이크 청크 처리 실패: ${err instanceof Error ? err.message : String(err)}`)
})
)
}
// 시스템 오디오 청크 처리
if (audioSource === 'system' || audioSource === 'both') {
promises.push(
this._processSystemChunk().catch((err: unknown) => {
logger.error(`시스템 오디오 청크 처리 실패: ${err instanceof Error ? err.message : String(err)}`)
})
)
}
Promise.all(promises).catch(() => { /* 개별 에러는 이미 로깅됨 */ })
}, CHUNK_INTERVAL_MS)
this._setState('active')
getSoundEffectService().play('recording-start')
logger.info(`Live Caption 시작: sessionId=${this._sessionId}`)
} catch (err) {
if (this._tickTimer) {
clearInterval(this._tickTimer)
this._tickTimer = null
if (this._chunkTimer) {
clearInterval(this._chunkTimer)
this._chunkTimer = null
}
this._micTrack = null
this._systemTrack = null
if (this._audioDataHandler) {
const audioCaptureService = getAudioCaptureService()
audioCaptureService.off('audio-data', this._audioDataHandler)
@ -214,15 +228,19 @@ class CaptionService extends EventEmitter {
this._setState('stopping')
// 타이머 정리
if (this._tickTimer) {
clearInterval(this._tickTimer)
this._tickTimer = null
if (this._chunkTimer) {
clearInterval(this._chunkTimer)
this._chunkTimer = null
}
// 잔여 오디오 처리 — 말하던 중이면 마지막 문장을 확정한다
await Promise.all([this._micTrack?.flush(), this._systemTrack?.flush()])
this._micTrack = null
this._systemTrack = null
// 잔여 오디오 처리
try {
await this._processChunk()
} catch (err) {
logger.warn(
`잔여 오디오 처리 실패: ${err instanceof Error ? err.message : String(err)}`,
)
}
// 마이크 캡처 정리
if (this._audioDataHandler) {
@ -234,6 +252,7 @@ class CaptionService extends EventEmitter {
// 시스템 오디오 캡처 중지 요청
this._sendToMainWindow(IPC_CHANNELS.CAPTION.STOP_SYSTEM_AUDIO, {})
this._systemAudioBuffers = []
// 오버레이 숨김
hideCaptionOverlay()
@ -243,8 +262,8 @@ class CaptionService extends EventEmitter {
this._sessionId = null
this._sessionStartedAt = null
this._refineQueue = []
this._sessionLanguage = null
this._audioBuffers = []
this._previousContext = ''
this._setState('inactive')
getSoundEffectService().play('recording-stop')
@ -274,7 +293,14 @@ class CaptionService extends EventEmitter {
private _onAudioData(buffer: Buffer): void {
if (this._state !== 'active') return
this._micTrack?.push(buffer)
this._audioBuffers.push(buffer)
// RMS 기반 유성음 감지 (환각 방지)
this._totalFrameCount++
const rms = calculateRMS(buffer)
if (rms >= SILENCE_RMS_THRESHOLD) {
this._voicedFrameCount++
}
}
/**
@ -283,129 +309,147 @@ class CaptionService extends EventEmitter {
*/
onSystemAudioData(buffer: Buffer): void {
if (this._state !== 'active') return
this._systemTrack?.push(buffer)
this._systemAudioBuffers.push(buffer)
this._systemTotalFrameCount++
const rms = calculateRMS(buffer)
if (rms >= SILENCE_RMS_THRESHOLD) {
this._systemVoicedFrameCount++
}
}
// ── 내부: 스트리밍 트랙 ──
// ── 내부: 3초 청크 처리 ──
private _createTrack(source: 'mic' | 'system', initialContext: string): StreamingCaptionTrack {
return new StreamingCaptionTrack(
{
transcribe: (audio, opts) => this._transcribe(audio, opts),
isVoiced: (chunk) => calculateRMS(chunk) >= SILENCE_RMS_THRESHOLD,
onPartial: (text, stable) => this._emitPartial(text, stable),
onFinal: (text) => this._emitFinal(text, source),
onError: (err) => {
private async _processChunk(): Promise<void> {
if (this._audioBuffers.length === 0) return
if (this._isProcessingChunk) return
this._isProcessingChunk = true
// VAD 카운터 리셋 (로깅용)
const voicedRatio = this._totalFrameCount > 0
? this._voicedFrameCount / this._totalFrameCount
: 0
this._voicedFrameCount = 0
this._totalFrameCount = 0
logger.debug(`청크 처리: 유성음 비율 ${(voicedRatio * 100).toFixed(1)}%`)
// VAD 필터링은 faster-whisper 사이드카에서 처리 (vadFilter: true)
// SoX의 마이크 캡처 레벨이 매우 낮아 로컬 RMS 게이트는 신뢰 불가
try {
const merged = Buffer.concat(this._audioBuffers)
this._audioBuffers = []
// 최소 오디오 크기 확인 (100ms 분량 이상)
const minBytes = 16000 * 2 * 0.1 // 100ms @ 16kHz 16bit mono
if (merged.length < minBytes) {
return
}
const sttService = getSTTManager()
const language = configGet('sttLanguage') as string | undefined
const result = await sttService.transcribe(merged, {
language: language ?? 'auto',
initialPrompt: this._previousContext,
vadFilter: true,
})
if (!result.text || result.text.trim().length === 0) {
return
}
const segment: CaptionSegment = {
id: crypto.randomUUID(),
text: result.text.trim(),
timestamp: Date.now(),
isFinal: true,
}
this._segments.push(segment)
// 다음 청크를 위한 컨텍스트 업데이트 (연속성 유지)
this._previousContext = result.text.trim().slice(-CONTEXT_WINDOW_SIZE)
// 이벤트 emit
this.emit('segment', segment)
// 오버레이 윈도우에 전송
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT, segment)
// 메인 윈도우에 전송 (Dashboard 등에서 사용)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT, segment)
logger.debug(`자막 세그먼트: "${segment.text.substring(0, 50)}"`)
} catch (err) {
const d3roErr =
err instanceof D3ROError
? err
: new D3ROError(
ErrorCode.CaptionSTTFailed,
`자막 전사 실패(${source}): ${err instanceof Error ? err.message : String(err)}`,
`자막 전사 실패: ${err instanceof Error ? err.message : String(err)}`,
)
logger.error(d3roErr.message)
logger.error(`자막 전사 에러: ${d3roErr.message}`)
this.emit('error', d3roErr)
},
},
initialContext,
)
} finally {
this._isProcessingChunk = false
}
}
/** 자막은 항상 로컬 엔진으로 인식한다 — 1초마다 다시 인식하므로 클라우드로는 보낼 수 없다. */
private async _transcribe(
audio: Buffer,
opts: { initialPrompt: string; partial: boolean },
): Promise<CaptionTranscription> {
const configured = (configGet('sttLanguage') as string | undefined) ?? 'auto'
const language = configured === 'auto' ? (this._sessionLanguage ?? 'auto') : configured
const result = await getLocalSTTService().transcribe(audio, {
language,
initialPrompt: opts.initialPrompt,
// ── 내부: 시스템 오디오 청크 처리 ──
private async _processSystemChunk(): Promise<void> {
if (this._systemAudioBuffers.length === 0) return
// VAD 게이트
const voicedRatio = this._systemTotalFrameCount > 0
? this._systemVoicedFrameCount / this._systemTotalFrameCount
: 0
this._systemVoicedFrameCount = 0
this._systemTotalFrameCount = 0
if (voicedRatio < VOICED_FRAME_RATIO) {
this._systemAudioBuffers = []
logger.debug(`시스템 오디오 청크 스킵: 유성음 비율 ${(voicedRatio * 100).toFixed(1)}%`)
return
}
const merged = Buffer.concat(this._systemAudioBuffers)
this._systemAudioBuffers = []
const minBytes = 16000 * 2 * 0.1
if (merged.length < minBytes) return
try {
const sttService = getLocalSTTService()
const language = configGet('sttLanguage') as string | undefined
const result = await sttService.transcribe(merged, {
language: language ?? 'auto',
initialPrompt: this._previousContext,
vadFilter: true,
partial: opts.partial,
modelId: this._captionModelId ?? undefined,
})
if (!opts.partial && configured === 'auto' && !this._sessionLanguage && result.text.trim() && result.language) {
this._sessionLanguage = result.language
}
return {
text: result.text,
segments: result.segments.map((segment) => ({
text: segment.text,
start: segment.start,
end: segment.end,
})),
}
}
private _emitPartial(text: string, stable: string): void {
if (this._state !== 'active') return
const delta = { text, stable, isFinal: false }
this.emit('delta', delta)
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.DELTA, delta)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.DELTA, delta)
}
if (!result.text || result.text.trim().length === 0) return
private _emitFinal(text: string, source: 'mic' | 'system'): void {
const segment: CaptionSegment = {
id: crypto.randomUUID(),
text,
text: result.text.trim(),
timestamp: Date.now(),
isFinal: true,
}
this._segments.push(segment)
this._previousContext = result.text.trim().slice(-CONTEXT_WINDOW_SIZE)
this.emit('segment', segment)
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT, segment)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT, segment)
logger.debug(`자막 확정(${source}): "${segment.text.substring(0, 50)}"`)
this._enqueueRefine(segment)
}
// ── 내부: 문맥 다듬기 ──
private _enqueueRefine(segment: CaptionSegment): void {
if (configGet('captionRefineEnabled') === false) return
if (!getLocalLLMService().isAvailable()) return
this._refineQueue.push(segment)
// 모델이 밀리면 오래된 줄은 포기한다 — 이미 지나간 자막을 늦게 고쳐 봐야 소용없다.
while (this._refineQueue.length > REFINE_QUEUE_LIMIT) this._refineQueue.shift()
if (!this._refining) void this._drainRefineQueue()
}
private async _drainRefineQueue(): Promise<void> {
this._refining = true
try {
for (let next = this._refineQueue.shift(); next; next = this._refineQueue.shift()) {
await this._refine(next)
}
} finally {
this._refining = false
}
}
private async _refine(segment: CaptionSegment): Promise<void> {
const index = this._segments.findIndex((item) => item.id === segment.id)
if (index === -1) return
const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text)
const { systemPrompt, text } = buildCaptionRefinePrompt({ text: segment.text, previous })
try {
const result = await getLocalLLMService().generate(text, {
systemPrompt,
temperature: 0,
maxTokens: Math.min(256, segment.text.length * 2 + 32),
timeoutMs: REFINE_TIMEOUT_MS,
keepAlive: REFINE_KEEP_ALIVE,
})
const refined = acceptCaptionRefinement(segment.text, result.text)
if (!refined) return
const current = this._segments.find((item) => item.id === segment.id)
if (!current) return
current.text = refined
const update = { id: segment.id, text: refined }
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
logger.debug(`시스템 자막: "${segment.text.substring(0, 50)}"`)
} catch (err) {
logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`)
logger.error(`시스템 오디오 전사 실패: ${err instanceof Error ? err.message : String(err)}`)
}
}

View file

@ -6,6 +6,7 @@ import type { AppConfig, ConfigChangedEvent, KeyBinding, KeyBindingActionId, Key
import {
bindingsEqual,
createDefaultBindingMap,
detectBindingConflicts,
findActionSpec,
kb,
normalizeBinding,
@ -75,12 +76,14 @@ function bindingListEquals(a: readonly KeyBinding[], b: readonly KeyBinding[]):
}
/**
* 다음 문장 제안 단축키를 1.6.0 배치로 옮긴다.
* 다음 문장 페이지 넘기기(최대 12개 순차 생성) 도입에 맞춰 제안 단축키를 옮긴다.
*
* - 수락은 화살표(→)에서 Enter 로, 닫기는 화살표(←)에서 Backspace 로 옮긴다
* (평범한 Esc 가 주 수단이 됐다).
* - 수락은 화살표(→)에서 Enter 로 옮긴다 — 화살표를 페이지 이동에 내주기 위해서다.
* - 닫기는 화살표(←)에서 Backspace 로 옮긴다(평범한 Esc 가 주 수단이 됐다).
* - 사용자가 정확히 옛 기본값 그대로일 때만 옮긴다. 다른 키로 커스터마이즈했다면
* 절대 건드리지 않는다.
* 절대 건드리지 않는다(설계 요구사항).
* - 새 페이지 이동 액션(suggestion-page-next/prev)의 기본값은, 위 이관 뒤에도 다른
* 액션과 충돌하지 않을 때만 켠다. 충돌하면 바인딩 없이 두고 경고를 남긴다.
*/
function migrateSuggestionOverlayBindings(activeStore: ElectronStore<AppConfig>): void {
const raw = activeStore.store as unknown as Record<string, unknown>
@ -96,6 +99,19 @@ function migrateSuggestionOverlayBindings(activeStore: ElectronStore<AppConfig>)
migrateIfOldDefault('suggestion-accept', OLD_SUGGESTION_ACCEPT_DEFAULT)
migrateIfOldDefault('suggestion-dismiss', OLD_SUGGESTION_DISMISS_DEFAULT)
for (const actionId of ['suggestion-page-next', 'suggestion-page-prev'] as const) {
const candidate = bindings[actionId] ?? []
const hasConflict = candidate.some(
(binding) => detectBindingConflicts(actionId, binding, bindings).length > 0
)
if (hasConflict) {
logger.warn(
`${actionId} 기본 바인딩이 다른 액션과 충돌해 바인딩 없이 둔다 (사용자가 설정에서 직접 지정할 수 있다)`
)
bindings[actionId] = []
}
}
activeStore.set('keyBindings', bindings)
}
@ -170,8 +186,6 @@ const CONFIG_DEFAULTS: AppConfig = {
activeChainId: null,
captionAudioSource: 'mic',
captionOverlayPosition: null,
captionRefineEnabled: true,
captionSttModelId: null,
updateChannel: 'latest',
updateDeviceId: '',
skippedUpdateVersion: null,

View file

@ -165,8 +165,6 @@ class InputTelemetryService extends EventEmitter {
private _lastFocusKey = ''
/** 현재 포커스에 들어왔을 때의 텍스트 (비밀번호는 저장하지 않는다) — 편집 여부 판정 기준선. */
private _textAtFocus = ''
/** 클릭 뒤 첫 스냅샷에서 기준선을 다시 잡는다 */
private _rebaseFocusText = false
private _lastActiveTickAt = 0
private _lastMouse: { x: number; y: number } | null = null
private _lastClickAt = 0
@ -409,8 +407,6 @@ class InputTelemetryService extends EventEmitter {
this._lastClickAt = now
this._lastClickButton = button
this._lastClickPos = position
// 클릭은 다른 칸으로 옮겨 갔을 수 있다 — 다음 스냅샷의 텍스트를 새 기준으로 삼는다.
this._rebaseFocusText = true
}
private _handleMouseUp(event: UiohookMouseEvent): void {
@ -611,16 +607,15 @@ class InputTelemetryService extends EventEmitter {
: tail
this._caretFallback = !caretKnown
// 포커스 식별: 칸이 바뀌었거나 클릭이 있었으면 그 시점 텍스트를 기준선으로 저장한다
// (비밀번호는 비운다). 마우스로 칸에 들어오기만 하고 아무것도 안 쳤으면 기준선과
// 현재 텍스트가 같아 editedSinceFocus 가 false 로 남는다(실측: YouTube 검색창 클릭만
// 했는데 옛 검색어로 제안이 뜸).
const focusKey = computeFocusKey(this._foreground.hwnd, snapshot.controlType ?? null, snapshot.controlName ?? null)
// 포커스 식별: 바뀌었으면 그 시점 텍스트를 기준선으로 저장한다(비밀번호는 비운다).
// 마우스로 필드에 들어오기만 하고 아무것도 안 쳤으면, 이 기준선과 현재 텍스트가
// 같아 editedSinceFocus 가 false 로 남는다(실측: YouTube 검색창 클릭만 했는데
// 옛 검색어로 제안이 뜸).
const focusKey = computeFocusKey(this._foreground.hwnd, snapshot.controlType ?? null, snapshot.elementRect)
const textForFocus = snapshot.isPassword ? '' : snapshot.text
if (focusKey !== this._lastFocusKey || this._rebaseFocusText) {
if (focusKey !== this._lastFocusKey) {
this._lastFocusKey = focusKey
this._textAtFocus = textForFocus
this._rebaseFocusText = false
}
context.editedSinceFocus = textForFocus !== this._textAtFocus
@ -1390,14 +1385,16 @@ function lastLineOf(text: string): string {
}
/**
* 포커스된 컨트롤 식별 키 — 창(hwnd) + 컨트롤 종류 + 컨트롤 이름.
* 포커스된 컨트롤 식별 키 — 창(hwnd) + 컨트롤 종류 + 위치.
*
* 위치·크기는 쓰지 않는다 — 채팅 입력창은 글이 늘면 자라고 움직여, 넣으면 같은 칸인데도
* 칠 때마다 "새 칸" 으로 오인돼 기준선이 리셋되고 제안이 거의 막혔다(실측: Agent
* Switchboard 에서 not-typing 반복). 같은 창 안의 칸 이동은 클릭 재기준으로 잡는다.
* 높이는 뺀다 — 여러 줄 입력창은 타이핑에 따라 높이가 자라, 높이를 포함하면
* 같은 필드인데도 칠 때마다 "새 포커스" 로 오인돼 기준선이 계속 리셋된다.
*/
function computeFocusKey(hwnd: number | null, controlType: string | null, controlName: string | null): string {
return `${hwnd ?? ''}|${controlType ?? ''}|${controlName ?? ''}`
function computeFocusKey(hwnd: number | null, controlType: string | null, elementRect: UiRect | null): string {
const rect = elementRect
? `${Math.round(elementRect.x)},${Math.round(elementRect.y)},${Math.round(elementRect.width)}`
: 'none'
return `${hwnd ?? ''}|${controlType ?? ''}|${rect}`
}
function formatLocalDate(date: Date): string {

View file

@ -20,7 +20,6 @@ import type {
} from '@d3ro/core/types'
import { Feature } from '@d3ro/core/types'
import { normalizeEntitlementTier } from '@d3ro/core/entitlement'
import { PLAN_QUOTA } from '@d3ro/core/plan-catalog'
import { verifySignedLicenseKey, createDefaultTrialPayload } from '@d3ro/core/utils/crypto-license'
const logger = getLogger('license')
@ -57,22 +56,20 @@ function generateMachineId(): string {
// 클라이언트에서는 PREMIUM_LLM feature로 묶어서 canUse() 체크하고,
// 실제 모델별 세분화는 서버 llm-proxy가 담당.
// 여기의 값은 Settings UI 표시용 + upgrade 유도 시점 판단용.
// 값의 정본은 @d3ro/core PLAN_QUOTA. PREMIUM_LLM은 모델별 한도의 합으로 표시하고,
// 한 모델이라도 무제한이면 한도를 두지 않는다(Free는 Haiku 주 250회).
function premiumLlmLimit(tier: LicenseTier): number | undefined {
const quota = PLAN_QUOTA[tier]
const models = [quota.llm_haiku, quota.llm_sonnet, quota.llm_opus].filter((q) => q.limit !== 0)
if (models.some((q) => q.limit < 0)) return undefined
return models.reduce((sum, q) => sum + q.limit, 0)
const QUOTA_LIMITS: Record<LicenseTier, Partial<Record<Feature, number>>> = {
free: {
// Haiku만, 250/주간. 클라이언트에서는 대략적 일환산(~36/일)으로 표시.
[Feature.PREMIUM_LLM]: 250,
},
pro: {
// 모델별: Haiku 1500 + Sonnet 300 + Opus 50 = 합산 표시
[Feature.PREMIUM_LLM]: 1850,
},
pro_plus: {},
team: {},
enterprise: {},
}
const QUOTA_LIMITS: Record<LicenseTier, Partial<Record<Feature, number>>> = Object.fromEntries(
(['free', 'pro', 'pro_plus', 'team', 'enterprise'] as const).map((tier) => {
const limit = premiumLlmLimit(tier)
return [tier, limit === undefined ? {} : { [Feature.PREMIUM_LLM]: limit }]
}),
) as Record<LicenseTier, Partial<Record<Feature, number>>>
// ── 기능별 최소 필요 티어 ──────────────────────────────────
// 빅뱅 Phase 4: 모든 로컬 기능을 'free'로 해방.
// 클라우드 기능(PREMIUM_LLM, CLOUD_SYNC)만 로그인 요구 + 티어 gate.

View file

@ -55,10 +55,6 @@ export interface TranscribeOptions {
vadFilter?: boolean
/** 음 중 실시간 미리보기 요청 — 상태/이벤트를 건드리지 않고 greedy 디코딩을 사용한다. */
partial?: boolean
/** 받아쓰기 모델 대신 쓸 모델 (ensureAuxModel 로 올려 둔 것) */
modelId?: string
/** 내부용 — 409 후 모델을 다시 올리고 재시도한 요청인지 */
retriedAfterLoad?: boolean
}
/** sidecar /health 응답 */
@ -208,8 +204,6 @@ class LocalSTTService extends EventEmitter {
private _sidecarStarting: Promise<void> | null = null
private _port: number = SIDECAR_PORT
private _currentModelId: string | null = null
/** 보조 자리에 올린 모델 (실시간 자막 전용 모델 등). 사이드카가 죽으면 함께 사라진다 */
private _auxModelId: string | null = null
private _restartCount: number = 0
private _disposed: boolean = false
private _gpuAccelerated: boolean = false
@ -553,7 +547,6 @@ class LocalSTTService extends EventEmitter {
this._audioBuffer = []
this._modelReady = false
this._auxModelId = null
await this._shutdownSidecar()
this._setState(STTState.Uninitialized)
@ -738,7 +731,6 @@ class LocalSTTService extends EventEmitter {
this._sidecarProcess = null
}
this._modelReady = false
this._auxModelId = null
if (!this._disposed) {
this._handleSidecarCrash()
@ -866,25 +858,14 @@ class LocalSTTService extends EventEmitter {
)
}
/**
* 받아쓰기(기본) 모델과 다른 모델을 보조 자리에 올린다 — 실시간 자막처럼 따로 고른 모델용.
* 기본 모델과 같으면 아무것도 하지 않는다.
*/
async ensureAuxModel(modelId: string): Promise<void> {
await this._ensureSidecarRunning()
if (modelId === this._currentModelId || modelId === this._auxModelId) return
await this._loadModel(modelId, 'aux')
this._auxModelId = modelId
}
private async _loadModel(modelId: string, slot: 'primary' | 'aux' = 'primary'): Promise<void> {
logger.info(`모델 로딩 시작: ${modelId} (${slot})`)
private async _loadModel(modelId: string): Promise<void> {
logger.info(`모델 로딩 시작: ${modelId}`)
const startTime = Date.now()
const response = await fetch(`${this._baseUrl}/load`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model_id: modelId, slot }),
body: JSON.stringify({ model_id: modelId }),
signal: AbortSignal.timeout(SIDECAR_REQUEST_TIMEOUT_MS),
})
@ -900,7 +881,7 @@ class LocalSTTService extends EventEmitter {
const loadTimeMs = Date.now() - startTime
const model = MODEL_CATALOG.find((m) => m.id === modelId)
if (model && slot === 'primary') {
if (model) {
this.emit('model-loaded', {
model: { ...model, downloaded: true },
loadTimeMs,
@ -956,10 +937,6 @@ class LocalSTTService extends EventEmitter {
if (initialPrompt) {
formData.append('initial_prompt', initialPrompt)
}
const modelId = options?.modelId
if (modelId && modelId !== this._currentModelId) {
formData.append('model_id', modelId)
}
const response = await fetch(`${this._baseUrl}/transcribe`, {
method: 'POST',
@ -969,13 +946,6 @@ class LocalSTTService extends EventEmitter {
),
})
// 사이드카가 재시작되며 보조 모델을 잃었으면 다시 올리고 한 번만 재시도한다.
if (response.status === 409 && modelId && !options?.retriedAfterLoad) {
this._auxModelId = null
await this.ensureAuxModel(modelId)
return this._sendToSidecar(audioBuffer, { ...options, retriedAfterLoad: true })
}
if (!response.ok) {
const errorText = await response.text()
throw new D3ROError(
@ -1072,7 +1042,6 @@ class LocalSTTService extends EventEmitter {
const modelToReload = this._currentModelId
this._currentModelId = null
this._modelReady = false
this._auxModelId = null
// setTimeout으로 이벤트 루프에 양보
setTimeout(() => {

View file

@ -74,11 +74,10 @@ const RUNTIME_VERSION_FILE = '.runtime-version'
/**
* 이 앱이 요구하는 런타임 최소 버전. 사이드카 API 가 바뀔 때만 올린다.
* 1.5.0 — UIA 브리지(`/uia/focus`). 1.7.0 — 보조 모델 자리(`/load` slot, `/transcribe` model_id).
* ffmpeg 는 CLI 가 안정적이라 확인하지 않는다.
* 1.5.0 — UIA 브리지(`/uia/focus`)가 처음 들어간 사이드카. ffmpeg 는 CLI 가 안정적이라 확인하지 않는다.
*/
const RUNTIME_MIN_VERSION: Record<RuntimeComponent, string | null> = {
sidecar: '1.7.0',
sidecar: '1.5.0',
ffmpeg: null
}
const DOWNLOAD_TIMEOUT_MS = 120_000

View file

@ -41,7 +41,6 @@ import { buildSuggestionPrompt } from './llm-prompts'
import { getInputTelemetryService, type TypingContext } from './InputTelemetryService'
import { getPersonalGraphService } from './PersonalGraphService'
import { getTextInsertService } from './TextInsertService'
import { waitForModifiersReleased } from './modifier-state'
const logger = getLogger('SuggestionService')
@ -1001,7 +1000,6 @@ class SuggestionService extends EventEmitter {
if (token !== this._generationToken || this._isDuplicateCandidate(candidateText)) return false
this._candidates.push({ text: candidateText, rank: this._candidates.length })
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
this._armVisibleTtl()
this.emit('updated', this.getState())
this._record({
@ -1075,8 +1073,6 @@ class SuggestionService extends EventEmitter {
context.isPassword,
context.isComposing,
context.anchor ? 'A' : '-',
context.editedSinceFocus,
context.typedRecently,
getLocalLLMService().isAvailable(),
this.isEnabled()
].join('|')
@ -1085,8 +1081,7 @@ class SuggestionService extends EventEmitter {
this._lastDecisionSignature = signature
logger.info(
`제안 판단 입력: avail=${context.available} edit=${context.isEditable} pw=${context.isPassword} ` +
`comp=${context.isComposing} edited=${context.editedSinceFocus} typed=${context.typedRecently} ` +
`prefixLen=${context.prefix.length} idle=${context.idleMs}ms ` +
`comp=${context.isComposing} prefixLen=${context.prefix.length} idle=${context.idleMs}ms ` +
`app=${context.appName ?? '-'} enabled=${this.isEnabled()} ` +
`model=${getLocalLLMService().isAvailable()} anchor=${context.anchor ? 'yes' : 'no'}`
)
@ -1181,17 +1176,26 @@ class SuggestionService extends EventEmitter {
return this.getState()
}
/**
* 다음 후보로 — 페이지는 활성 후보를 따라 넘어간다.
*
* 마지막 후보에서 아직 더 만드는 중이면 그 자리에 머문다: 처음으로 돌아가 버리면
* 곧 도착할 후보를 보려던 사용자가 길을 잃는다. 다 만들었으면 처음으로 돌아간다.
*/
next(): SuggestionState {
const last = this._candidates.length - 1
if (last < 1) return this.getState()
if (this._activeIndex < last) this._moveActive(this._activeIndex + 1)
else if (!this._filling) this._moveActive(0)
if (this._candidates.length > 1) {
this._moveActive((this._activeIndex + 1) % this._candidates.length)
}
return this.getState()
}
/** 다음 페이지의 첫 항목으로 — 그 페이지에 후보가 없으면 그대로 둔다. */
pageNext(): SuggestionState {
const pageSize = SUGGESTION_DEFAULTS.pageSize
const totalPages = Math.ceil(this._candidates.length / pageSize)
const currentPage = Math.floor(this._activeIndex / pageSize)
if (currentPage < totalPages - 1) this._moveActive((currentPage + 1) * pageSize)
return this.getState()
}
/** 이전 페이지의 첫 항목으로 — 이미 첫 페이지면 그대로 둔다. */
pagePrev(): SuggestionState {
const currentPage = Math.floor(this._activeIndex / SUGGESTION_DEFAULTS.pageSize)
if (currentPage > 0) this._moveActive((currentPage - 1) * SUGGESTION_DEFAULTS.pageSize)
return this.getState()
}
@ -1248,24 +1252,11 @@ class SuggestionService extends EventEmitter {
}
const candidate = this._candidates[this._activeIndex]
if (!candidate) return { ok: false, reason: 'already-visible' }
const text = candidate.text
const appName = this._appName
const windowTitle = this._windowTitle
// 먼저 창을 닫고 생성을 멈춘다 — 수락은 즉시 반응해야 한다.
this.dismiss('accepted')
this.emit('state-changed', this.getState())
// 단축키로 수락했다면 사용자가 아직 Ctrl+Alt 를 쥐고 있다. 그대로 Ctrl+V 를 보내면
// 대상 앱에 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다(실측) — 뗄 때까지 기다린다.
if (!(await waitForModifiersReleased())) {
logger.warn('수정자 키가 떼어지지 않은 채 제안을 삽입한다 (1.5초 초과)')
}
const method = configGet('insertMethod')
try {
const result = await getTextInsertService().insertText(
text,
candidate.text,
method === 'keyboard' ? 'keyboard' : 'clipboard'
)
if (!result.success) {
@ -1277,9 +1268,16 @@ class SuggestionService extends EventEmitter {
return { ok: false, reason: 'generation-failed' }
}
this._markAccepted(text)
this._markAccepted(candidate.text)
// 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨).
getInputTelemetryService().recordExternalText(text, { appName, windowTitle, source: 'suggestion' })
getInputTelemetryService().recordExternalText(candidate.text, {
appName: this._appName,
windowTitle: this._windowTitle,
source: 'suggestion'
})
this.dismiss('accepted')
this.emit('state-changed', this.getState())
return { ok: true }
}

View file

@ -1,160 +0,0 @@
// src/main/services/caption/StreamingCaptionTrack.ts
//
// 오디오 한 줄기(마이크 또는 시스템 소리)의 실시간 자막 트랙.
// 판단은 core `decideCaptionTick` 이 하고, 이 클래스는 오디오 버퍼와 인식 호출만 맡는다.
import {
CAPTION_STREAMING_DEFAULTS,
agreedCaptionPrefix,
decideCaptionTick,
planForcedCommit,
splitCaptionWords,
type CaptionTimedSegment
} from '@d3ro/core/caption-streaming'
/** 16kHz · 16bit · mono PCM → 1ms = 32 bytes */
const BYTES_PER_MS = 32
export interface CaptionTranscription {
text: string
segments: CaptionTimedSegment[]
}
export interface StreamingCaptionTrackDeps {
transcribe: (audio: Buffer, opts: { initialPrompt: string; partial: boolean }) => Promise<CaptionTranscription>
/** 이 조각에 소리가 있는가 (RMS 등) */
isVoiced: (chunk: Buffer) => boolean
/** 확정되지 않은 현재 문장 — stable 은 두 번 연속 같게 나온 앞부분 */
onPartial: (text: string, stable: string) => void
onFinal: (text: string) => void
onError: (error: unknown) => void
now?: () => number
}
export class StreamingCaptionTrack {
private _buffer: Buffer = Buffer.alloc(0)
private _busy = false
private _lastVoiceAt = 0
private _lastPartialAt = 0
private _previousWords: string[] = []
private _context = ''
/** 버퍼를 자를 때마다 바뀐다 — 자르기 전에 시작한 인식 결과는 버린다 */
private _epoch = 0
private readonly _now: () => number
constructor(private readonly _deps: StreamingCaptionTrackDeps, initialContext = '') {
this._now = _deps.now ?? Date.now
this._context = initialContext
}
get bufferMs(): number {
return this._buffer.length / BYTES_PER_MS
}
push(chunk: Buffer): void {
this._buffer = this._buffer.length === 0 ? chunk : Buffer.concat([this._buffer, chunk])
if (this._deps.isVoiced(chunk)) this._lastVoiceAt = this._now()
}
/** 주기적으로 부른다. 한 번에 인식 한 건만 돈다. */
async tick(): Promise<void> {
const now = this._now()
const action = decideCaptionTick({
bufferMs: this.bufferMs,
hasVoice: this._lastVoiceAt > 0,
sinceVoiceMs: this._lastVoiceAt > 0 ? now - this._lastVoiceAt : Number.MAX_SAFE_INTEGER,
sincePartialMs: now - this._lastPartialAt,
busy: this._busy
})
if (action === 'trim-idle') {
this._keepTail(CAPTION_STREAMING_DEFAULTS.idleKeepMs)
return
}
if (action === 'partial') return this._run(() => this._partial())
if (action === 'finalize') return this._run(() => this._finalize())
if (action === 'force-commit') {
// 말이 끊기지 않고 너무 길어지면(배경 음악 등으로 무음이 없는 경우 포함) 앞쪽만 확정한다.
// 확정할 구간 경계가 끝내 안 나오면 두 배 길이에서 통째로 확정한다.
const hardLimit = this.bufferMs >= CAPTION_STREAMING_DEFAULTS.maxBufferMs * 2
return this._run(() => (hardLimit ? this._finalize() : this._forceCommit()))
}
}
/** 세션 종료 — 남은 말을 확정한다. */
async flush(): Promise<void> {
if (this._lastVoiceAt === 0 || this.bufferMs < CAPTION_STREAMING_DEFAULTS.minAudioMs) return
while (this._busy) await new Promise((resolve) => setTimeout(resolve, 20))
await this._run(() => this._finalize())
}
private async _run(job: () => Promise<void>): Promise<void> {
this._busy = true
try {
await job()
} catch (error) {
this._deps.onError(error)
} finally {
this._busy = false
}
}
private async _partial(): Promise<void> {
this._lastPartialAt = this._now()
const epoch = this._epoch
const result = await this._deps.transcribe(this._buffer, { initialPrompt: this._context, partial: true })
if (epoch !== this._epoch) return
const words = splitCaptionWords(result.text)
if (words.length === 0) return
const stable = agreedCaptionPrefix(this._previousWords, words)
this._previousWords = words
this._deps.onPartial(words.join(' '), stable.join(' '))
}
private async _finalize(): Promise<void> {
const snapshotBytes = this._buffer.length
const takenAt = this._now()
const result = await this._deps.transcribe(this._buffer.subarray(0, snapshotBytes), {
initialPrompt: this._context,
partial: false
})
this._cut(snapshotBytes)
// 인식하는 동안 들어온 오디오에 소리가 있었으면 그 소리는 다음 문장이다.
if (this._lastVoiceAt <= takenAt) this._lastVoiceAt = 0
this._emitFinal(result.text)
}
private async _forceCommit(): Promise<void> {
const snapshotBytes = this._buffer.length
const result = await this._deps.transcribe(this._buffer.subarray(0, snapshotBytes), {
initialPrompt: this._context,
partial: false
})
const plan = planForcedCommit(
result.segments,
snapshotBytes / BYTES_PER_MS / 1000,
CAPTION_STREAMING_DEFAULTS.keepTailMs / 1000
)
if (!plan) return
this._cut(Math.min(snapshotBytes, Math.round(plan.cutAtSec * 1000) * BYTES_PER_MS))
this._emitFinal(plan.text)
}
private _emitFinal(raw: string): void {
const text = raw.trim()
this._previousWords = []
if (!text) return
this._context = `${this._context} ${text}`.trim().slice(-CAPTION_STREAMING_DEFAULTS.contextChars)
this._deps.onFinal(text)
}
private _cut(bytes: number): void {
this._buffer = this._buffer.subarray(bytes - (bytes % 2))
this._epoch += 1
}
private _keepTail(ms: number): void {
const keep = ms * BYTES_PER_MS
if (this._buffer.length > keep) this._buffer = this._buffer.subarray(this._buffer.length - keep)
}
}

View file

@ -253,32 +253,3 @@ export function buildSuggestionPrompt(input: SuggestionPromptInput): {
}
export { SUGGESTION_SYSTEM_PROMPT }
/**
* 실시간 자막 문맥 다듬기 — 확정된 자막 한 줄을 앞 문맥에 맞게 고친다.
*
* 받아 적기의 오류(띄어쓰기·문장부호·잘못 들은 단어)만 고친다. 요약·의역·추가는
* 금지이며, 호출자는 `acceptCaptionRefinement` 로 변화량을 다시 검사한다.
*/
const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적은 자막 한 줄을 다듬습니다.
규칙:
- 띄어쓰기, 문장부호, 앞 문맥으로 볼 때 명백하게 잘못 들은 단어만 고치세요.
- 뜻을 바꾸거나, 요약하거나, 말을 더하거나 빼지 마세요.
- 원문과 같은 언어, 같은 말투(존댓말/반말, 구어체)를 유지하세요.
- 고친 문장 한 줄만 출력하세요. 설명, 따옴표, 번호를 붙이지 마세요.
- 고칠 것이 없으면 원문을 그대로 출력하세요.`
export function buildCaptionRefinePrompt(input: {
text: string
previous: readonly string[]
}): { systemPrompt: string; text: string } {
const sections: string[] = []
const previous = input.previous.filter((line) => line.trim().length > 0).slice(-2)
if (previous.length > 0) sections.push('[앞 문맥]', ...previous, '')
sections.push('[다듬을 자막]', input.text.trim())
return {
systemPrompt: `${SUGGESTION_NO_THINK_PREFIX}\n${CAPTION_REFINE_SYSTEM_PROMPT}`,
text: sections.join('\n')
}
}

View file

@ -1,50 +0,0 @@
// src/main/services/modifier-state.ts
//
// 사용자가 물리적으로 누르고 있는 수정자 키(Ctrl/Alt/Shift/Win)를 추적한다.
//
// 단축키로 무언가를 삽입할 때(예: Ctrl+Alt+Enter 로 제안 수락) 동작은 키를 누르는
// 순간 실행되는데, 그때 사용자는 아직 Ctrl+Alt 를 쥐고 있다. 그 상태로 Ctrl+V 를
// 보내면 대상 앱에는 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다(실측). 삽입 전에
// 손을 뗄 때까지 잠깐 기다린다.
import { uIOhook, type UiohookKeyboardEvent } from 'uiohook-napi'
import { acquireGlobalInputHook } from './global-input-hook'
/** uiohook 키 코드 (UiohookKey.Ctrl/CtrlRight/Alt/AltRight/Shift/ShiftRight/Meta/MetaRight) */
const MODIFIER_KEYCODES: ReadonlySet<number> = new Set([29, 3613, 56, 3640, 42, 54, 3675, 3676])
const held = new Set<number>()
let attached = false
function attach(): void {
if (attached) return
attached = true
acquireGlobalInputHook()
uIOhook.on('keydown', (event: UiohookKeyboardEvent) => {
if (MODIFIER_KEYCODES.has(event.keycode)) held.add(event.keycode)
})
uIOhook.on('keyup', (event: UiohookKeyboardEvent) => {
held.delete(event.keycode)
})
}
/** 추적을 시작한다 — 단축키가 눌리기 전에 붙어 있어야 누른 상태를 안다. */
export function trackModifierKeys(): void {
attach()
}
/**
* 수정자 키가 모두 떼어질 때까지 기다린다.
*
* 시간 안에 떼지 않으면(떼는 이벤트를 놓친 경우 포함) 추적 상태를 비우고 false 를
* 돌려준다 — 호출자는 그래도 진행한다(영원히 막히면 안 된다).
*/
export async function waitForModifiersReleased(timeoutMs = 1500): Promise<boolean> {
const deadline = Date.now() + timeoutMs
while (held.size > 0 && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 15))
}
if (held.size === 0) return true
held.clear()
return false
}

View file

@ -84,6 +84,7 @@ function getPopupI18nStrings(): Record<string, string> {
suggestionAppPhrases: t('popup.suggestion.appPhrases'),
// 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다)
suggestionHintMoveLabel: t('popup.suggestion.hintMove'),
suggestionHintPageLabel: t('popup.suggestion.hintPage'),
suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'),
suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'),
suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'),
@ -112,9 +113,10 @@ function sameModifiers(a: readonly string[], b: readonly string[]): boolean {
}
export interface SuggestionKeyHints {
/** 이동·수락이 모두 같은 수정자를 쓰면 그 수정자(예: "Ctrl+Alt") — 한 번만 보여준다 */
/** 이동·페이지·수락이 모두 같은 수정자를 쓰면 그 수정자(예: "Ctrl+Alt") — 한 번만 보여준다 */
shared: string | null
move: string | null
page: string | null
accept: string | null
close: string
}
@ -137,9 +139,11 @@ function buildSuggestionKeyHints(): SuggestionKeyHints {
const prev = splitOf('suggestion-prev')
const next = splitOf('suggestion-next')
const pagePrev = splitOf('suggestion-page-prev')
const pageNext = splitOf('suggestion-page-next')
const accept = splitOf('suggestion-accept')
const present = [prev, next, accept].filter((b): b is SplitBinding => b !== null)
const present = [prev, next, pagePrev, pageNext, accept].filter((b): b is SplitBinding => b !== null)
const common = present[0]?.modifiers ?? []
const shareAll =
present.length > 0 && common.length > 0 && present.every((b) => sameModifiers(b.modifiers, common))
@ -155,6 +159,7 @@ function buildSuggestionKeyHints(): SuggestionKeyHints {
return {
shared: shareAll ? joinBindingSegments(common, platform) : null,
move: pair(prev, next),
page: pair(pagePrev, pageNext),
accept: accept ? label(accept) : null,
close: 'Esc'
}

View file

@ -520,9 +520,7 @@ const electronAPI = {
getConfig: () => invoke<CaptionConfig>(IPC_CHANNELS.CAPTION.GET_CONFIG),
onSegment: (cb: (data: CaptionSegment) => void): Unsubscribe =>
on(IPC_CHANNELS.CAPTION.SEGMENT, cb),
onSegmentUpdated: (cb: (data: { id: string; text: string }) => void): Unsubscribe =>
on(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, cb),
onDelta: (cb: (data: { text: string; stable: string; isFinal: boolean }) => void): Unsubscribe =>
onDelta: (cb: (data: { text: string }) => void): Unsubscribe =>
on(IPC_CHANNELS.CAPTION.DELTA, cb),
onStateChanged: (cb: (data: { state: CaptionState }) => void): Unsubscribe =>
on(IPC_CHANNELS.CAPTION.STATE_CHANGED, cb),
@ -875,6 +873,16 @@ const electronAPI = {
checkRefund: () =>
invoke<import('@d3ro/core/types').RefundEligibilityResult>(IPC_CHANNELS.SUPPORT.CHECK_REFUND),
},
// ── Multi-PG Payment & Billing ─────────────────────────
payment: {
createCheckoutSession: (params: import('@d3ro/core/types').CheckoutSessionParams) =>
invoke<import('@d3ro/core/types').CheckoutSessionResult>(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, params),
verifyPayment: () =>
invoke<import('@d3ro/core/types').VerifyPaymentResult>(IPC_CHANNELS.PAYMENT.VERIFY_PAYMENT),
getSubscriptionStatus: () =>
invoke<import('@d3ro/core/types').SubscriptionStatusResult>(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS),
},
// ── Input telemetry (입력 수집 동의 · 리포트) ───────────
inputTelemetry: {
getState: () =>

View file

@ -29,6 +29,7 @@ import { OnboardingModal } from './OnboardingModal'
import { AdBanner } from './ads/AdBanner'
import { RewardedQuotaModal } from './ads/RewardedQuotaModal'
import { SupportModal } from './support/SupportModal'
import { CheckoutModal } from './payment/CheckoutModal'
import { StatusBar } from './StatusBar'
import { TitleBar } from './TitleBar'
import { d3roPalette, d3roFontSans, d3roFontMono, d3roTypo, d3roRadius, d3roShadow } from '@d3ro/ui/theme'
@ -78,6 +79,7 @@ export function AppLayout(): React.ReactElement {
const [onboardingOpen, setOnboardingOpen] = useState(false)
const [licenseModalOpen, setLicenseModalOpen] = useState(false)
const [supportModalOpen, setSupportModalOpen] = useState(false)
const [checkoutModalOpen, setCheckoutModalOpen] = useState(false)
const [rewardedModalOpen, setRewardedModalOpen] = useState(false)
const [currentTier, setCurrentTier] = useState<LicenseTier>('free')
const [fallbackMsg, setFallbackMsg] = useState<string | null>(null)
@ -380,7 +382,7 @@ export function AppLayout(): React.ReactElement {
<Box sx={{ px: 2, pb: 1, pt: 0.5, flexShrink: 0 }}>
<AdBanner
tier={currentTier}
onUpgrade={() => void window.electronAPI.license.openBilling({ tier: 'pro' })}
onOpenUpgradeModal={() => setCheckoutModalOpen(true)}
/>
</Box>
)}
@ -392,6 +394,13 @@ export function AppLayout(): React.ReactElement {
<LicenseModal open={licenseModalOpen} onClose={() => setLicenseModalOpen(false)} />
<OnboardingModal open={onboardingOpen} onClose={() => setOnboardingOpen(false)} />
<SupportModal open={supportModalOpen} onClose={() => setSupportModalOpen(false)} />
<CheckoutModal
open={checkoutModalOpen}
onClose={() => setCheckoutModalOpen(false)}
onSuccess={(newTier) => {
setCurrentTier(newTier)
}}
/>
<RewardedQuotaModal
open={rewardedModalOpen}
onClose={() => setRewardedModalOpen(false)}

View file

@ -1,41 +0,0 @@
// 실시간 자막 전용 로컬 Whisper 모델 선택 — STT 탭과 일반 탭 자막 섹션이 함께 쓴다.
import { FormControl, InputLabel, MenuItem, Select, Typography } from '@mui/material'
import { d3roPalette, d3roTypo } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import type { STTModel } from '@d3ro/core/types'
/** "받아쓰기와 같게" — 설정에는 null 로 저장한다 */
const SAME_AS_DICTATION = '__same__'
interface CaptionModelSelectProps {
value: string | null | undefined
/** 선택지로 보일 모델 — 받아 둔 모델만 넘긴다 */
models: readonly STTModel[]
onChange: (modelId: string | null) => void
fullWidth?: boolean
}
export function CaptionModelSelect({ value, models, onChange, fullWidth }: CaptionModelSelectProps): React.ReactElement {
const { t } = useI18n()
return (
<FormControl size="small" fullWidth={fullWidth}>
<InputLabel>{t('settings.captionModel')}</InputLabel>
<Select
label={t('settings.captionModel')}
value={value ?? SAME_AS_DICTATION}
onChange={(e) => onChange(e.target.value === SAME_AS_DICTATION ? null : e.target.value)}
>
<MenuItem value={SAME_AS_DICTATION}>{t('settings.captionModel.same')}</MenuItem>
{models.map((m) => (
<MenuItem key={m.id} value={m.id}>
{m.name}
</MenuItem>
))}
</Select>
<Typography sx={{ mt: 0.5, fontSize: d3roTypo.meta.size, color: d3roPalette.text.secondary }}>
{t('settings.captionModel.desc')}
</Typography>
</FormControl>
)
}

View file

@ -50,7 +50,6 @@ import type {
STTModel,
} from '@d3ro/core/types'
import { CodexOAuthGuideModal } from './CodexOAuthGuideModal'
import { CaptionModelSelect } from './CaptionModelSelect'
interface STTTabProps {
config: Partial<AppConfig>
@ -363,14 +362,6 @@ export function STTTab({ config, updateConfig }: STTTabProps): React.ReactElemen
</Select>
</FormControl>
{/* 실시간 자막 전용 모델 — 1초마다 다시 인식하므로 받아쓰기와 다른 모델이 나을 수 있다 */}
<CaptionModelSelect
fullWidth
value={config.captionSttModelId}
models={localModels.filter((m) => m.downloaded)}
onChange={(modelId) => updateConfig('captionSttModelId', modelId)}
/>
{/* 모델 다운로드 진행 바 또는 다운로드 버튼 */}
{(() => {
const selected = localModels.find((m) => m.id === (config.sttModelId ?? 'large-v3-turbo'))

View file

@ -28,7 +28,6 @@ import { Led } from '@d3ro/ui/components/ds'
import { LicenseTab } from './LicenseTab'
import { CloudSyncSection } from './CloudSyncSection'
import { STTTab } from './STTTab'
import { CaptionModelSelect } from './CaptionModelSelect'
import { InputConsentPanel } from './input-insights/InputConsentPanel'
import { KeyBindingField } from './keybinding/KeyBindingField'
import { asTranslationKey } from './keybinding/translation-key'
@ -36,7 +35,7 @@ import { useI18n, LOCALE_META } from '@d3ro/i18n'
import type { Locale } from '@d3ro/i18n'
import type { KeyBindingActionGroup } from '@d3ro/core/keybinding'
import { auditKeyBindingMap, KEYBINDING_ACTIONS } from '@d3ro/core/keybinding'
import type { ThemeMode, AppConfig, AudioDevice, LLMModel, LLMStatus, STTModel } from '@d3ro/core/types'
import type { ThemeMode, AppConfig, AudioDevice, LLMModel, LLMStatus } from '@d3ro/core/types'
import { useKeyBindingMap } from '../hooks/useKeyBindingMap'
interface SettingsModalProps {
@ -109,15 +108,6 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
const [micTesting, setMicTesting] = useState(false)
const [micLevel, setMicLevel] = useState(0)
// 실시간 자막 모델 선택지 — 받아 둔 로컬 Whisper 모델만
const [downloadedSttModels, setDownloadedSttModels] = useState<STTModel[]>([])
useEffect(() => {
if (!open) return
window.electronAPI.stt.getModels().then((res) => {
if (res.success && res.data) setDownloadedSttModels(res.data.filter((m) => m.downloaded))
})
}, [open])
// Ollama 상태
const [ollamaStatus, setOllamaStatus] = useState<LLMStatus | null>(null)
const [ollamaModels, setOllamaModels] = useState<LLMModel[]>([])
@ -491,33 +481,6 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
</Select>
</FormControl>
<CaptionModelSelect
value={config.captionSttModelId}
models={downloadedSttModels}
onChange={(modelId) => updateConfig('captionSttModelId', modelId)}
/>
<FormControlLabel
sx={{ mr: 0, alignItems: 'flex-start' }}
control={
<Switch
size="small"
checked={config.captionRefineEnabled !== false}
onChange={(e) => updateConfig('captionRefineEnabled', e.target.checked)}
/>
}
label={
<Box sx={{ pt: '2px' }}>
<Typography sx={{ fontSize: d3roTypo.body.size, color: d3roPalette.text.primary }}>
{t('settings.captionRefine')}
</Typography>
<Typography sx={{ fontSize: d3roTypo.meta.size, color: d3roPalette.text.secondary }}>
{t('settings.captionRefine.desc')}
</Typography>
</Box>
}
/>
<Divider sx={{ borderColor: d3roPalette.border.subtle }} />
<Typography variant="overline" sx={{ color: d3roPalette.text.label, letterSpacing: '1.5px' }}>

View file

@ -9,11 +9,10 @@ import type { LicenseTier, AdCreativePayload } from '@d3ro/core/types'
interface AdBannerProps {
tier: LicenseTier
/** 웹 결제 페이지(billingUrl)로 보낸다. 등급 변경은 license:tierChanged 로 돌아온다. */
onUpgrade: () => void
onOpenUpgradeModal: () => void
}
export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement | null {
export function AdBanner({ tier, onOpenUpgradeModal }: AdBannerProps): React.ReactElement | null {
const [creative, setCreative] = useState<AdCreativePayload | null>(null)
// Fetch highest bidding ad creative via mediation auction
@ -246,7 +245,7 @@ export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement
</Button>
<Typography
onClick={onUpgrade}
onClick={onOpenUpgradeModal}
sx={{
fontFamily: d3roFontSans,
fontSize: '10px',

View file

@ -0,0 +1,309 @@
// src/renderer/components/payment/CheckoutModal.tsx
// Server-authoritative Stripe checkout and subscription confirmation modal.
import React, { useEffect, useRef, useState } from 'react'
import { Alert, Box, Button, CircularProgress, IconButton, Modal, Typography } from '@mui/material'
import { CheckCircle2, CreditCard, ExternalLink, Lock, RefreshCw, Shield, X } from 'lucide-react'
import { d3roPalette, d3roFontSans, d3roFontMono, d3roRadius, d3roShadow } from '@d3ro/ui/theme'
import type { CheckoutTier, LicenseTier } from '@d3ro/core/types'
import {
CheckoutFlowController,
INITIAL_CHECKOUT_FLOW_STATE,
checkoutErrorMessage
} from './checkout-flow'
interface CheckoutModalProps {
open: boolean
initialTier?: LicenseTier
onClose: () => void
onSuccess: (tier: CheckoutTier) => void
}
function normalizeInitialTier(tier: LicenseTier): CheckoutTier {
return tier === 'pro' ? 'pro' : 'pro_plus'
}
export function CheckoutModal({
open,
initialTier = 'pro_plus',
onClose,
onSuccess
}: CheckoutModalProps): React.ReactElement {
const [tier, setTier] = useState<CheckoutTier>(() => normalizeInitialTier(initialTier))
const [flowState, setFlowState] = useState(INITIAL_CHECKOUT_FLOW_STATE)
const controllerRef = useRef<CheckoutFlowController | null>(null)
if (controllerRef.current === null) {
controllerRef.current = new CheckoutFlowController({
createCheckoutSession: (params) => window.electronAPI.payment.createCheckoutSession(params),
openExternal: (params) => window.electronAPI.system.openExternal(params),
getSubscriptionStatus: () => window.electronAPI.payment.getSubscriptionStatus()
})
}
const controller = controllerRef.current
useEffect(() => controller.subscribe(setFlowState), [controller])
useEffect(() => {
if (open) {
setTier(normalizeInitialTier(initialTier))
controller.reset()
} else {
controller.cancel()
}
}, [controller, initialTier, open])
const handleClose = (): void => {
controller.cancel()
onClose()
}
const handleCheckout = (): void => {
void controller.start(tier)
}
const handleVerification = async (): Promise<void> => {
const verifiedTier = await controller.verify()
if (verifiedTier) onSuccess(verifiedTier)
}
const busy = flowState.phase === 'creating' || flowState.phase === 'verifying'
const awaitingConfirmation = flowState.phase === 'awaiting' || flowState.phase === 'verifying'
return (
<Modal open={open} onClose={handleClose} aria-labelledby="checkout-modal-title">
<Box
role="dialog"
aria-modal="true"
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: { xs: '90%', sm: 520 },
bgcolor: d3roPalette.bg.card,
backdropFilter: 'blur(28px)',
border: `1px solid ${d3roPalette.glass.hairline}`,
borderRadius: d3roRadius.outer,
boxShadow: d3roShadow.dialog,
p: 3,
outline: 'none',
display: 'flex',
flexDirection: 'column',
gap: 2
}}
>
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
borderBottom: `1px solid ${d3roPalette.glass.hairline}`,
pb: 1.5
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.25 }}>
<CreditCard size={18} color={d3roPalette.accent.light} />
<Typography
id="checkout-modal-title"
sx={{
fontFamily: d3roFontSans,
fontSize: '16px',
fontWeight: 600,
color: d3roPalette.text.primary
}}
>
D3RO Voice Secure Checkout
</Typography>
</Box>
<IconButton
onClick={handleClose}
aria-label="결제 창 닫기"
sx={{
color: d3roPalette.text.dimLabel,
'&:hover': { color: d3roPalette.text.primary }
}}
>
<X size={18} />
</IconButton>
</Box>
{flowState.phase === 'complete' && flowState.verifiedTier ? (
<Box
sx={{
textAlign: 'center',
py: 4,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 1.5
}}
>
<CheckCircle2 size={48} color={d3roPalette.tag.green} />
<Typography
sx={{ fontFamily: d3roFontSans, fontSize: '18px', fontWeight: 600, color: 'var(--d3-text-inverse)' }}
>
서버에서 구독 활성화를 확인했습니다.
</Typography>
<Typography
sx={{ fontFamily: d3roFontMono, fontSize: '12px', color: d3roPalette.accent.light }}
>
Plan: {flowState.verifiedTier.toUpperCase()}
</Typography>
<Button
onClick={handleClose}
sx={{
mt: 2,
bgcolor: d3roPalette.accent.main,
color: 'var(--d3-text-inverse)',
px: 3,
borderRadius: '8px'
}}
>
완료
</Button>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<Typography
sx={{ fontFamily: d3roFontSans, fontSize: '12px', color: d3roPalette.text.secondary }}
>
결제 세션과 최종 금액은 로그인된 계정의 Stripe 서버에서 생성됩니다.
</Typography>
<Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1 }}>
{(['pro', 'pro_plus'] as const).map((candidate) => (
<Button
key={candidate}
onClick={() => setTier(candidate)}
disabled={flowState.phase !== 'idle' || busy}
aria-pressed={tier === candidate}
sx={{
p: 1.5,
borderRadius: d3roRadius.inner,
border: `1px solid ${tier === candidate ? d3roPalette.accent.main : d3roPalette.glass.hairline}`,
bgcolor:
tier === candidate ? 'var(--d3-accent-glow)' : 'var(--d3-overlay-strong)',
color: 'var(--d3-text-inverse)',
fontFamily: d3roFontSans,
fontWeight: 500,
textTransform: 'none'
}}
>
{candidate === 'pro' ? 'Pro' : 'Pro+'}
</Button>
))}
</Box>
<Box
sx={{
p: 2,
borderRadius: d3roRadius.inner,
bgcolor: 'var(--d3-bg-card-soft)',
border: `1px solid ${d3roPalette.accent.dim}`,
display: 'flex',
gap: 1.25,
alignItems: 'flex-start'
}}
>
<Shield size={19} color={d3roPalette.accent.light} />
<Box>
<Typography
sx={{
fontFamily: d3roFontSans,
fontSize: '13px',
fontWeight: 500,
color: 'var(--d3-text-inverse)'
}}
>
Stripe 보안 결제
</Typography>
<Typography
sx={{
mt: 0.5,
fontFamily: d3roFontSans,
fontSize: '11px',
color: d3roPalette.text.secondary
}}
>
실제 금액, 통화, 세금과 결제 수단은 Stripe 결제 페이지에서 확인해 주세요.
</Typography>
</Box>
</Box>
{awaitingConfirmation && (
<Alert severity="info" icon={<ExternalLink size={18} />}>
브라우저에서 결제를 완료하거나 취소한 뒤, 아래에서 서버 구독 상태를 확인해 주세요.
</Alert>
)}
{flowState.error && (
<Alert severity="error" role="alert">
{checkoutErrorMessage(flowState.error)}
</Alert>
)}
<Box aria-live="polite">
{flowState.phase === 'idle' || flowState.phase === 'creating' ? (
<Button
fullWidth
disabled={busy}
onClick={handleCheckout}
sx={{
py: 1.25,
bgcolor: d3roPalette.accent.main,
color: 'var(--d3-text-inverse)',
fontWeight: 500,
fontSize: '13px',
borderRadius: '10px',
boxShadow: d3roShadow.glowAccent,
'&:hover': { bgcolor: d3roPalette.accent.light }
}}
>
{flowState.phase === 'creating' ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<CircularProgress size={14} color="inherit" /> 결제 세션 생성 중...
</Box>
) : (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Lock size={14} /> Stripe에서 결제 계속하기
</Box>
)}
</Button>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
<Button
fullWidth
disabled={busy}
onClick={() => void handleVerification()}
sx={{
py: 1.25,
bgcolor: d3roPalette.accent.main,
color: 'var(--d3-text-inverse)',
fontWeight: 500,
fontSize: '13px',
borderRadius: '10px'
}}
>
{flowState.phase === 'verifying' ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<CircularProgress size={14} color="inherit" /> 서버 구독 확인 중...
</Box>
) : (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<RefreshCw size={14} /> 결제 상태 확인
</Box>
)}
</Button>
<Button onClick={handleClose} sx={{ color: d3roPalette.text.secondary }}>
닫기 — 구독 등급 변경 안 함
</Button>
</Box>
)}
</Box>
</Box>
)}
</Box>
</Modal>
)
}

View file

@ -0,0 +1,203 @@
import type { IPCResult } from '@d3ro/core/errors'
import type {
CheckoutSessionParams,
CheckoutSessionResult,
CheckoutTier,
SubscriptionStatusResult
} from '@d3ro/core/types'
const STRIPE_CHECKOUT_ORIGIN = 'https://checkout.stripe.com'
const STRIPE_CHECKOUT_PATH_PREFIX = '/c/pay/'
export type CheckoutPhase = 'idle' | 'creating' | 'awaiting' | 'verifying' | 'complete'
export type CheckoutErrorCode =
| 'checkout-failed'
| 'unsafe-checkout-response'
| 'open-failed'
| 'network-failed'
| 'verification-failed'
| 'not-confirmed'
| 'invalid-entitlement'
export interface CheckoutFlowState {
phase: CheckoutPhase
error: CheckoutErrorCode | null
verifiedTier: CheckoutTier | null
}
export interface CheckoutFlowPorts {
createCheckoutSession: (
params: CheckoutSessionParams
) => Promise<IPCResult<CheckoutSessionResult>>
openExternal: (params: { url: string }) => Promise<IPCResult<void>>
getSubscriptionStatus: () => Promise<IPCResult<SubscriptionStatusResult>>
}
export const INITIAL_CHECKOUT_FLOW_STATE: CheckoutFlowState = {
phase: 'idle',
error: null,
verifiedTier: null
}
const ERROR_MESSAGES: Record<CheckoutErrorCode, string> = {
'checkout-failed': '결제 세션을 만들지 못했습니다. 잠시 후 다시 시도해 주세요.',
'unsafe-checkout-response': '안전한 Stripe 결제 페이지를 확인하지 못했습니다.',
'open-failed': '결제 페이지를 열지 못했습니다. 잠시 후 다시 시도해 주세요.',
'network-failed': '결제 서비스에 연결하지 못했습니다. 네트워크 상태를 확인해 주세요.',
'verification-failed': '서버 구독 상태를 확인하지 못했습니다. 잠시 후 다시 시도해 주세요.',
'not-confirmed': '서버에서 결제 완료를 아직 확인하지 못했습니다. 결제 후 다시 확인해 주세요.',
'invalid-entitlement': '서버가 유효한 구독 등급을 반환하지 않았습니다.'
}
export function checkoutErrorMessage(error: CheckoutErrorCode): string {
return ERROR_MESSAGES[error]
}
export function isTrustedStripeCheckoutUrl(value: unknown): value is string {
if (typeof value !== 'string') return false
try {
const url = new URL(value)
return (
url.protocol === 'https:' &&
url.origin === STRIPE_CHECKOUT_ORIGIN &&
url.username === '' &&
url.password === '' &&
url.pathname.startsWith(STRIPE_CHECKOUT_PATH_PREFIX) &&
url.pathname.length > STRIPE_CHECKOUT_PATH_PREFIX.length
)
} catch {
return false
}
}
function isPaidTier(value: unknown): value is CheckoutTier {
return value === 'pro' || value === 'pro_plus'
}
export class CheckoutFlowController {
private state: CheckoutFlowState = INITIAL_CHECKOUT_FLOW_STATE
private listener: ((state: CheckoutFlowState) => void) | null = null
private inFlight = false
private generation = 0
constructor(private readonly ports: CheckoutFlowPorts) {}
subscribe(listener: (state: CheckoutFlowState) => void): () => void {
this.listener = listener
listener(this.state)
return () => {
if (this.listener === listener) this.listener = null
}
}
getState(): CheckoutFlowState {
return this.state
}
reset(): void {
this.generation += 1
this.inFlight = false
this.update(INITIAL_CHECKOUT_FLOW_STATE)
}
cancel(): void {
this.reset()
}
async start(tier: CheckoutTier): Promise<boolean> {
if (this.inFlight || this.state.phase === 'awaiting' || this.state.phase === 'complete') {
return false
}
this.inFlight = true
const generation = ++this.generation
let stage: 'checkout' | 'open' = 'checkout'
this.update({ phase: 'creating', error: null, verifiedTier: null })
try {
const session = await this.ports.createCheckoutSession({ tier, provider: 'stripe' })
if (!this.isCurrent(generation)) return false
if (!session.success) {
this.fail('idle', 'checkout-failed')
return false
}
if (
session.data.provider !== 'stripe' ||
session.data.status !== 'pending' ||
!isTrustedStripeCheckoutUrl(session.data.checkoutUrl)
) {
this.fail('idle', 'unsafe-checkout-response')
return false
}
stage = 'open'
const opened = await this.ports.openExternal({ url: session.data.checkoutUrl })
if (!this.isCurrent(generation)) return false
if (!opened.success) {
this.fail('idle', 'open-failed')
return false
}
this.update({ phase: 'awaiting', error: null, verifiedTier: null })
return true
} catch {
if (this.isCurrent(generation)) {
this.fail('idle', stage === 'open' ? 'open-failed' : 'network-failed')
}
return false
} finally {
if (this.isCurrent(generation)) this.inFlight = false
}
}
async verify(): Promise<CheckoutTier | null> {
if (this.inFlight || this.state.phase !== 'awaiting') return null
this.inFlight = true
const generation = ++this.generation
this.update({ phase: 'verifying', error: null, verifiedTier: null })
try {
const subscription = await this.ports.getSubscriptionStatus()
if (!this.isCurrent(generation)) return null
if (!subscription.success) {
this.fail('awaiting', 'verification-failed')
return null
}
if (!subscription.data.valid) {
this.fail('awaiting', 'not-confirmed')
return null
}
if (!isPaidTier(subscription.data.tier)) {
this.fail('awaiting', 'invalid-entitlement')
return null
}
this.update({
phase: 'complete',
error: null,
verifiedTier: subscription.data.tier
})
return subscription.data.tier
} catch {
if (this.isCurrent(generation)) this.fail('awaiting', 'network-failed')
return null
} finally {
if (this.isCurrent(generation)) this.inFlight = false
}
}
private isCurrent(generation: number): boolean {
return generation === this.generation
}
private fail(phase: 'idle' | 'awaiting', error: CheckoutErrorCode): void {
this.update({ phase, error, verifiedTier: null })
}
private update(state: CheckoutFlowState): void {
this.state = state
this.listener?.(state)
}
}

View file

@ -397,7 +397,7 @@ export function SupportModal({ open, onClose }: SupportModalProps): React.ReactE
• 클라우드 사용량: 0% (자격 충족)
</Typography>
<Button
onClick={() => alert('Payple 결제 취소가 접수되었습니다. 영업일 기준 2~3일 내 카드사 취소 처리됩니다.')}
onClick={() => alert('토스페이먼츠 / Stripe 결제 취소가 접수되었습니다. 영업일 기준 2~3일 내 카드사 취소 처리됩니다.')}
sx={{ mt: 1, bgcolor: d3roPalette.tag.green, color: 'var(--d3-scrim)', fontWeight: 500, fontSize: '12px', borderRadius: '8px' }}
>
즉시 전액 환불 승인

View file

@ -75,9 +75,6 @@
return
}
// 첫 중간 결과가 오면 준비 안내를 걷는다 — 이제 실제로 듣고 있다.
removeStatusLine()
if (!deltaLine) {
deltaLine = document.createElement('div')
deltaLine.className = 'caption-line delta'
@ -85,35 +82,7 @@
linesContainer.appendChild(deltaLine)
}
// 두 번 연속 같게 들린 앞부분은 또렷하게, 아직 바뀔 수 있는 뒷부분은 흐리게.
var text = data.text || ''
var stable = data.stable || ''
if (stable && text.indexOf(stable) !== 0) stable = ''
deltaLine.textContent = ''
if (stable) deltaLine.appendChild(document.createTextNode(stable))
var rest = text.slice(stable.length)
if (rest) {
var tentative = document.createElement('span')
tentative.className = 'tentative'
tentative.textContent = rest
deltaLine.appendChild(tentative)
}
}
/**
* 문맥 다듬기로 고쳐진 줄을 제자리에서 바꾼다.
* @param {{id: string, text: string}} update
*/
function updateSegment(update) {
for (var i = 0; i < lines.length; i++) {
if (lines[i].id !== update.id) continue
lines[i].el.textContent = update.text
lines[i].el.classList.remove('refined')
// 다시 그려야 애니메이션이 재시작된다
void lines[i].el.offsetWidth
lines[i].el.classList.add('refined')
return
}
deltaLine.textContent = data.text
}
/**
@ -194,11 +163,6 @@
updateDelta(data)
})
// 문맥 다듬기 결과
window.popupAPI.on('caption:segmentUpdated', function (update) {
updateSegment(update)
})
// 설정 업데이트
window.popupAPI.on('caption:config', function (newConfig) {
applyConfig(newConfig)

View file

@ -144,21 +144,6 @@ html, body {
50% { opacity: 0; }
}
/* 아직 바뀔 수 있는 뒷부분 (중간 결과) */
.caption-line .tentative {
opacity: 0.6;
}
/* 문맥 다듬기로 고쳐진 줄 — 잠깐 강조 */
.caption-line.refined {
animation: refined-flash 0.9s ease-out;
}
@keyframes refined-flash {
0% { border-color: var(--d3-accent-main); box-shadow: 0 0 0 2px var(--d3-accent-glow-dim); }
100% { box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5); }
}
/* 로딩 중 표시 — 점멸 애니메이션 */
.caption-line.loading {
opacity: 0.6;

View file

@ -83,9 +83,7 @@
)
item.type = 'button'
item.setAttribute('data-index', String(i))
// click 이 아니라 누르는 순간 수락한다 — 후보가 1초마다 추가되며 목록을 다시 그려,
// 누르고 떼는 사이에 버튼이 바뀌면 click 이 성립하지 않았다(실측: 클릭 수락 무반응).
item.addEventListener('pointerdown', onItemPress)
item.addEventListener('click', onItemClick)
candidatesContainer.appendChild(item)
}
@ -145,7 +143,7 @@
keyHintsContainer.textContent = ''
if (!keyHints) return
// 이동·수락이 같은 수정자를 쓰면 앞에 한 번만 보여준다 ("Ctrl+Alt +").
// 이동·페이지·수락이 같은 수정자를 쓰면 앞에 한 번만 보여준다 ("Ctrl+Alt +").
if (keyHints.shared) {
var shared = document.createElement('span')
shared.className = 'key-hint shared'
@ -156,6 +154,7 @@
var entries = [
[keyHints.move, i18nStrings.suggestionHintMoveLabel, ''],
[keyHints.page, i18nStrings.suggestionHintPageLabel, ''],
[keyHints.accept, i18nStrings.suggestionHintAcceptLabel, ''],
[keyHints.close, i18nStrings.suggestionHintCloseLabel, ' close-hint']
]
@ -181,9 +180,7 @@
provenanceContainer.textContent = sourceLabel || ''
}
function onItemPress(event) {
if (event.button !== 0) return
event.preventDefault()
function onItemClick(event) {
var target = event.currentTarget
var index = Number(target.getAttribute('data-index'))
if (!window.popupAPI) return

View file

@ -120,11 +120,22 @@ test.describe('Launch Readiness E2E & Visual Verification', () => {
await window.waitForTimeout(500);
});
test('03. Should expose the web billing upgrade link without an in-app checkout modal', async () => {
// "Remove ads with Pro" opens billingUrl({ tier }) in the external browser (LICENSE.OPEN_BILLING).
test('03. Should open the server-authoritative Stripe CheckoutModal', async () => {
// Trigger checkout via "Remove ads with Pro" link in AdBanner
const removeAdsLink = window.locator('text=/Remove ads with Pro/').first();
if (await removeAdsLink.isVisible()) {
await expect(window.locator('text=/D3RO Voice Secure Checkout/')).toHaveCount(0);
await removeAdsLink.click();
await window.waitForTimeout(600);
// Verify Checkout Modal is visible
await expect(window.locator('text=/D3RO Voice Secure Checkout/').first()).toBeVisible();
// Capture screenshot of CheckoutModal
await window.screenshot({ path: path.join(SCREENSHOT_DIR, '04_checkout_modal_stripe.png') });
// Close modal
await window.keyboard.press('Escape');
await window.waitForTimeout(400);
}
});
});

View file

@ -114,6 +114,13 @@ describe('ConfigService suggestion tuning migration', () => {
// 옮기지 않는 액션은 그대로 남는다.
expect(bindings['suggestion-next']).toEqual(OLD_NEXT)
expect(bindings['suggestion-prev']).toEqual(OLD_PREV)
// accept/dismiss 가 비켜난 자리를 새 페이지 이동 액션이 충돌 없이 채운다.
expect(bindings['suggestion-page-next']).toEqual([
{ device: 'keyboard', code: 0x27, ctrl: true, alt: true, shift: false, meta: false }
])
expect(bindings['suggestion-page-prev']).toEqual([
{ device: 'keyboard', code: 0x25, ctrl: true, alt: true, shift: false, meta: false }
])
expect(configGet('suggestionTuningRevision')).toBe(5)
resetInMemoryConfig()
@ -144,4 +151,31 @@ describe('ConfigService suggestion tuning migration', () => {
resetInMemoryConfig()
})
it('revision 5: 새 페이지 이동 기본값이 다른 액션과 충돌하면 바인딩 없이 둔다', async () => {
// suggestion-next 를 페이지-다음의 새 기본값(Ctrl+Alt+→)과 똑같이 커스터마이즈해 충돌을 만든다.
const CONFLICTING_NEXT = [{ device: 'keyboard' as const, code: 0x27, ctrl: true, alt: true, shift: false, meta: false }]
vi.doMock('electron-store', () => ({
default: makeTestStore({
suggestionTuningRevision: 4,
keyBindings: {
'suggestion-next': CONFLICTING_NEXT
}
})
}))
const { configGet, initConfigService, resetInMemoryConfig } = await import(
'../../../src/main/services/ConfigService'
)
await initConfigService()
const bindings = configGet('keyBindings')
expect(bindings['suggestion-page-next']).toEqual([])
// 충돌이 없는 page-prev 는 정상적으로 기본값을 받는다.
expect(bindings['suggestion-page-prev']).toEqual([
{ device: 'keyboard', code: 0x25, ctrl: true, alt: true, shift: false, meta: false }
])
expect(bindings['suggestion-next']).toEqual(CONFLICTING_NEXT)
resetInMemoryConfig()
})
})

View file

@ -346,25 +346,21 @@ describe('SuggestionService warm-up', () => {
expect(internal._lastSkipReason).not.toBe('rate-limited')
})
it('마지막 후보에서 아직 더 만드는 중이면 next 는 제자리, 다 만들었으면 처음으로 돌아간다', async () => {
it('pageNext는 다음 페이지 첫 항목으로, 후보가 없는 페이지면 그대로 둔다', async () => {
const { getSuggestionService } = await import('../../../src/main/services/SuggestionService')
const service = getSuggestionService()
const internal = service as unknown as {
_candidates: Array<{ text: string; rank: number }>
_filling: boolean
}
internal._candidates = Array.from({ length: 4 }, (_v, i) => ({ text: `후보${i}`, rank: i }))
const internal = service as unknown as { _candidates: Array<{ text: string; rank: number }> }
internal._candidates = Array.from({ length: 5 }, (_v, i) => ({ text: `후보${i}`, rank: i }))
for (let i = 0; i < 3; i += 1) service.next()
// 3번째(0-based 3)에서 ↓ — 4번째 칸이 곧 페이지 2 로 넘어간 상태다.
expect(service.getState().activeIndex).toBe(0)
service.pageNext()
expect(service.getState().activeIndex).toBe(3)
internal._filling = true
service.next()
service.pageNext()
// 5개뿐이라 다음 페이지가 없다 — 그대로 둔다.
expect(service.getState().activeIndex).toBe(3)
internal._filling = false
service.next()
service.pagePrev()
expect(service.getState().activeIndex).toBe(0)
service.pagePrev()
expect(service.getState().activeIndex).toBe(0)
})

View file

@ -1,184 +0,0 @@
// tests/main/services/caption-streaming.test.ts
// 실시간 자막 스트리밍: 판단 로직(core) + 트랙(오디오 버퍼·인식 호출) 흐름.
import { describe, it, expect } from 'vitest'
import {
CAPTION_STREAMING_DEFAULTS,
acceptCaptionRefinement,
agreedCaptionPrefix,
captionChangeRatio,
decideCaptionTick,
planForcedCommit
} from '@d3ro/core/caption-streaming'
import {
StreamingCaptionTrack,
type CaptionTranscription
} from '../../../src/main/services/caption/StreamingCaptionTrack'
const BYTES_PER_MS = 32
function chunk(ms: number, voiced: boolean): Buffer {
const buffer = Buffer.alloc(ms * BYTES_PER_MS)
buffer[0] = voiced ? 1 : 0
return buffer
}
describe('decideCaptionTick', () => {
const base = { bufferMs: 2000, hasVoice: true, sinceVoiceMs: 100, sincePartialMs: 1500, busy: false }
it('말하는 중이면 1초마다 중간 결과를 만든다', () => {
expect(decideCaptionTick(base)).toBe('partial')
expect(decideCaptionTick({ ...base, sincePartialMs: 400 })).toBe('wait')
})
it('말이 멈추면 문장을 확정한다', () => {
expect(decideCaptionTick({ ...base, sinceVoiceMs: CAPTION_STREAMING_DEFAULTS.silenceCommitMs })).toBe('finalize')
})
it('멈추지 않고 길어지면 앞쪽을 강제로 확정한다', () => {
expect(decideCaptionTick({ ...base, bufferMs: CAPTION_STREAMING_DEFAULTS.maxBufferMs })).toBe('force-commit')
})
it('소리가 없는 오디오는 들고 있지 않는다', () => {
expect(decideCaptionTick({ ...base, hasVoice: false, bufferMs: 5000 })).toBe('trim-idle')
expect(decideCaptionTick({ ...base, hasVoice: false, bufferMs: 500 })).toBe('wait')
})
it('인식 중이거나 오디오가 짧으면 기다린다', () => {
expect(decideCaptionTick({ ...base, busy: true })).toBe('wait')
expect(decideCaptionTick({ ...base, bufferMs: 300 })).toBe('wait')
})
})
describe('LocalAgreement / 강제 확정 / 다듬기 검사', () => {
it('두 가설이 앞에서부터 같은 단어만 합의한다', () => {
expect(agreedCaptionPrefix(['오늘', '회의는', '세시에'], ['오늘', '회의는', '네시에', '해요'])).toEqual(['오늘', '회의는'])
expect(agreedCaptionPrefix([], ['오늘'])).toEqual([])
})
it('끝부분(keepTail) 안쪽 구간은 남기고 앞쪽만 확정한다', () => {
const plan = planForcedCommit(
[
{ text: '첫 문장', start: 0, end: 4 },
{ text: '둘째 문장', start: 4, end: 9 },
{ text: '진행 중', start: 9, end: 12 }
],
12,
1.5
)
expect(plan).toEqual({ text: '첫 문장 둘째 문장', cutAtSec: 9 })
expect(planForcedCommit([{ text: '긴 한 문장', start: 0, end: 12 }], 12, 1.5)).toBeNull()
})
it('띄어쓰기·문장부호 수준의 수정은 받고, 뜻을 바꾼 문장은 버린다', () => {
expect(acceptCaptionRefinement('오늘회의는 세시에 시작합니다', '오늘 회의는 세 시에 시작합니다.')).toBe(
'오늘 회의는 세 시에 시작합니다.'
)
expect(acceptCaptionRefinement('오늘 회의는 세 시에 시작합니다', '회의 일정이 변경되었다는 공지입니다')).toBeNull()
expect(acceptCaptionRefinement('그대로', '"그대로"')).toBeNull()
expect(captionChangeRatio('abc', 'abc')).toBe(0)
})
})
describe('StreamingCaptionTrack', () => {
function setup(results: CaptionTranscription[]) {
let now = 1_000
const partials: Array<{ text: string; stable: string }> = []
const finals: string[] = []
const calls: Array<{ bytes: number; partial: boolean; prompt: string }> = []
const track = new StreamingCaptionTrack(
{
transcribe: async (audio, opts) => {
calls.push({ bytes: audio.length, partial: opts.partial, prompt: opts.initialPrompt })
return results.shift() ?? { text: '', segments: [] }
},
isVoiced: (c) => c[0] === 1,
onPartial: (text, stable) => partials.push({ text, stable }),
onFinal: (text) => finals.push(text),
onError: (error) => {
throw error
},
now: () => now
},
'앞 문맥'
)
return {
track,
partials,
finals,
calls,
advance: (ms: number) => {
now += ms
}
}
}
it('말하는 동안 단어가 갱신되고, 멈추면 한 문장으로 확정된다', async () => {
const t = setup([
{ text: '오늘 회의는', segments: [] },
{ text: '오늘 회의는 세시에', segments: [] },
{ text: '오늘 회의는 세 시에 시작합니다', segments: [] }
])
t.track.push(chunk(1000, true))
await t.track.tick()
t.advance(1000)
t.track.push(chunk(1000, true))
await t.track.tick()
expect(t.partials.map((p) => p.text)).toEqual(['오늘 회의는', '오늘 회의는 세시에'])
expect(t.partials[1].stable).toBe('오늘 회의는')
expect(t.calls.every((c) => c.partial)).toBe(true)
t.advance(800)
t.track.push(chunk(800, false))
await t.track.tick()
expect(t.finals).toEqual(['오늘 회의는 세 시에 시작합니다'])
expect(t.calls[2].partial).toBe(false)
expect(t.calls[2].prompt).toBe('앞 문맥')
expect(t.track.bufferMs).toBe(0)
})
it('확정된 문장은 다음 인식의 앞 문맥이 된다', async () => {
const t = setup([{ text: '첫 문장', segments: [] }, { text: '둘째', segments: [] }])
t.track.push(chunk(1000, true))
t.advance(800)
await t.track.tick()
t.track.push(chunk(1000, true))
await t.track.tick()
expect(t.calls[1].prompt).toBe('앞 문맥 첫 문장')
})
it('끊기지 않는 긴 소리는 앞쪽만 확정하고 그만큼 오디오를 잘라낸다', async () => {
const t = setup([
{
text: '첫 문장 둘째 문장 진행 중',
segments: [
{ text: '첫 문장', start: 0, end: 5 },
{ text: '둘째 문장', start: 5, end: 9 },
{ text: '진행 중', start: 9, end: 12 }
]
}
])
t.track.push(chunk(CAPTION_STREAMING_DEFAULTS.maxBufferMs, true))
await t.track.tick()
expect(t.finals).toEqual(['첫 문장 둘째 문장'])
expect(t.track.bufferMs).toBe(CAPTION_STREAMING_DEFAULTS.maxBufferMs - 9000)
})
it('소리가 없으면 오디오를 짧게만 남기고 인식하지 않는다', async () => {
const t = setup([])
t.track.push(chunk(5000, false))
await t.track.tick()
expect(t.calls).toHaveLength(0)
expect(t.track.bufferMs).toBe(CAPTION_STREAMING_DEFAULTS.idleKeepMs)
})
it('종료할 때 말하던 문장을 확정한다', async () => {
const t = setup([{ text: '마지막 말', segments: [] }])
t.track.push(chunk(1200, true))
await t.track.flush()
expect(t.finals).toEqual(['마지막 말'])
})
})

View file

@ -26,7 +26,6 @@ import {
SUGGESTION_NO_THINK_PREFIX,
SUGGESTION_SYSTEM_PROMPT,
} from '../../../src/main/services/llm-prompts'
import { buildCaptionRefinePrompt } from '../../../src/main/services/llm-prompts'
beforeEach(() => {
vi.clearAllMocks()
@ -249,21 +248,3 @@ describe('buildSuggestionPrompt', () => {
expect(text).not.toContain('이미 제안한 문장')
})
})
describe('buildCaptionRefinePrompt', () => {
it('지시문은 시스템 프롬프트에만 두고, 본문에는 앞 문맥 2줄과 다듬을 자막만 넣는다', () => {
const { systemPrompt, text } = buildCaptionRefinePrompt({
text: '오늘회의는 세시에',
previous: ['첫 줄', '둘째 줄', '셋째 줄']
})
expect(systemPrompt).toContain('뜻을 바꾸거나')
expect(text).not.toContain('규칙')
expect(text).toContain(['둘째 줄', '셋째 줄'].join('\n'))
expect(text).not.toContain('첫 줄')
expect(text.endsWith('오늘회의는 세시에')).toBe(true)
})
it('앞 문맥이 없으면 다듬을 자막만 넣는다', () => {
expect(buildCaptionRefinePrompt({ text: '안녕', previous: [] }).text).toBe(['[다듬을 자막]', '안녕'].join('\n'))
})
})

View file

@ -101,7 +101,7 @@ describe('E2E RED — 계열 F: 정산·수익 원장', () => {
const stats = engine.getRevenueStats()
for (const s of stats.settlements) {
expect(['pending', 'processing', 'settled', 'paid']).toContain(s.payoutStatus)
expect(['bank_wire_krw', 'paypal']).toContain(s.paymentMethod)
expect(['bank_wire_krw', 'paypal', 'stripe_connect']).toContain(s.paymentMethod)
}
})
it(`[${network}] 순지급 = 총수익 × (1-원천세) 환율 적립`, () => {

View file

@ -0,0 +1,252 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { IPCResult } from '@d3ro/core/errors'
import type { CheckoutSessionResult, SubscriptionStatusResult } from '@d3ro/core/types'
import {
CheckoutFlowController,
type CheckoutFlowPorts,
isTrustedStripeCheckoutUrl
} from '../../src/renderer/components/payment/checkout-flow'
type CreateResult = IPCResult<CheckoutSessionResult>
type StatusResult = IPCResult<SubscriptionStatusResult>
const trustedUrl = 'https://checkout.stripe.com/c/pay/cs_test_renderer_safe#fragment'
const checkoutSuccess: CreateResult = {
success: true,
data: { checkoutUrl: trustedUrl, provider: 'stripe', status: 'pending' }
}
const openSuccess: IPCResult<void> = { success: true, data: undefined }
const activeSubscription: StatusResult = {
success: true,
data: { tier: 'pro_plus', valid: true, expiresAt: Date.parse('2099-01-01T00:00:00.000Z') }
}
const ipcFailure = {
success: false as const,
error: { code: 999, message: 'private provider details' }
}
function deferred<T>(): {
promise: Promise<T>
resolve: (value: T) => void
} {
let resolve!: (value: T) => void
const promise = new Promise<T>((done) => {
resolve = done
})
return { promise, resolve }
}
describe('renderer checkout flow', () => {
let createCheckoutSession: ReturnType<typeof vi.fn>
let openExternal: ReturnType<typeof vi.fn>
let getSubscriptionStatus: ReturnType<typeof vi.fn>
let controller: CheckoutFlowController
beforeEach(() => {
createCheckoutSession = vi.fn().mockResolvedValue(checkoutSuccess)
openExternal = vi.fn().mockResolvedValue(openSuccess)
getSubscriptionStatus = vi.fn().mockResolvedValue(activeSubscription)
const ports: CheckoutFlowPorts = {
createCheckoutSession,
openExternal,
getSubscriptionStatus
}
controller = new CheckoutFlowController(ports)
})
it('opens only the authenticated IPC checkout result and waits for server confirmation', async () => {
const opened = await controller.start('pro')
expect(opened).toBe(true)
expect(createCheckoutSession).toHaveBeenCalledWith({ tier: 'pro', provider: 'stripe' })
expect(openExternal).toHaveBeenCalledWith({ url: trustedUrl })
expect(getSubscriptionStatus).not.toHaveBeenCalled()
expect(controller.getState()).toEqual({
phase: 'awaiting',
error: null,
verifiedTier: null
})
})
it('fails closed when checkout IPC returns a provider error', async () => {
createCheckoutSession.mockResolvedValue(ipcFailure)
await controller.start('pro')
expect(controller.getState()).toMatchObject({ phase: 'idle', error: 'checkout-failed' })
expect(openExternal).not.toHaveBeenCalled()
})
it('fails closed when checkout IPC throws a network error', async () => {
createCheckoutSession.mockRejectedValue(new Error('private network details'))
await controller.start('pro')
expect(controller.getState()).toMatchObject({ phase: 'idle', error: 'network-failed' })
expect(openExternal).not.toHaveBeenCalled()
})
it.each([
{
checkoutUrl: 'http://checkout.stripe.com/c/pay/cs_test_bad',
provider: 'stripe',
status: 'pending'
},
{ checkoutUrl: 'https://evil.test/c/pay/cs_test_bad', provider: 'stripe', status: 'pending' },
{ checkoutUrl: trustedUrl, provider: 'toss', status: 'pending' },
{ checkoutUrl: trustedUrl, provider: 'stripe', status: 'completed' }
])('rejects an unsafe or forged checkout response %#', async (data) => {
createCheckoutSession.mockResolvedValue({ success: true, data })
await controller.start('pro')
expect(controller.getState()).toMatchObject({
phase: 'idle',
error: 'unsafe-checkout-response'
})
expect(openExternal).not.toHaveBeenCalled()
})
it('fails closed when the OS cannot open the checkout page', async () => {
openExternal.mockResolvedValue(ipcFailure)
await controller.start('pro')
expect(controller.getState()).toMatchObject({ phase: 'idle', error: 'open-failed' })
})
it('fails closed when opening the checkout page throws', async () => {
openExternal.mockRejectedValue(new Error('private shell details'))
await controller.start('pro')
expect(controller.getState()).toMatchObject({ phase: 'idle', error: 'open-failed' })
})
it('coalesces duplicate checkout clicks into one IPC request', async () => {
const pending = deferred<CreateResult>()
createCheckoutSession.mockReturnValue(pending.promise)
const first = controller.start('pro')
const duplicate = controller.start('pro_plus')
expect(await duplicate).toBe(false)
expect(createCheckoutSession).toHaveBeenCalledTimes(1)
pending.resolve(checkoutSuccess)
expect(await first).toBe(true)
expect(openExternal).toHaveBeenCalledTimes(1)
})
it('invalidates a pending checkout when the user closes the modal', async () => {
const pending = deferred<CreateResult>()
createCheckoutSession.mockReturnValue(pending.promise)
const start = controller.start('pro')
controller.cancel()
pending.resolve(checkoutSuccess)
expect(await start).toBe(false)
expect(openExternal).not.toHaveBeenCalled()
expect(controller.getState()).toEqual({ phase: 'idle', error: null, verifiedTier: null })
})
it('does not treat an opened or cancelled provider page as payment success', async () => {
await controller.start('pro')
getSubscriptionStatus.mockResolvedValue({
success: true,
data: { tier: 'free', valid: false, expiresAt: null }
})
const tier = await controller.verify()
expect(tier).toBeNull()
expect(controller.getState()).toMatchObject({ phase: 'awaiting', error: 'not-confirmed' })
})
it('fails closed when subscription readback returns an IPC error', async () => {
await controller.start('pro')
getSubscriptionStatus.mockResolvedValue(ipcFailure)
const tier = await controller.verify()
expect(tier).toBeNull()
expect(controller.getState()).toMatchObject({
phase: 'awaiting',
error: 'verification-failed'
})
})
it('fails closed when subscription readback throws a network error', async () => {
await controller.start('pro')
getSubscriptionStatus.mockRejectedValue(new Error('private subscription details'))
const tier = await controller.verify()
expect(tier).toBeNull()
expect(controller.getState()).toMatchObject({ phase: 'awaiting', error: 'network-failed' })
})
it('rejects an arbitrary paid tier even when a forged response claims it is valid', async () => {
await controller.start('pro')
getSubscriptionStatus.mockResolvedValue({
success: true,
data: { tier: 'enterprise', valid: true, expiresAt: null }
})
const tier = await controller.verify()
expect(tier).toBeNull()
expect(controller.getState()).toMatchObject({
phase: 'awaiting',
error: 'invalid-entitlement'
})
})
it('returns and displays only the server-read subscription tier', async () => {
await controller.start('pro')
const tier = await controller.verify()
expect(tier).toBe('pro_plus')
expect(controller.getState()).toEqual({
phase: 'complete',
error: null,
verifiedTier: 'pro_plus'
})
})
it('coalesces duplicate subscription verification clicks', async () => {
await controller.start('pro')
const pending = deferred<StatusResult>()
getSubscriptionStatus.mockReturnValue(pending.promise)
const first = controller.verify()
const duplicate = controller.verify()
expect(await duplicate).toBeNull()
expect(getSubscriptionStatus).toHaveBeenCalledTimes(1)
pending.resolve(activeSubscription)
expect(await first).toBe('pro_plus')
})
it('ignores a successful subscription response after cancellation', async () => {
await controller.start('pro')
const pending = deferred<StatusResult>()
getSubscriptionStatus.mockReturnValue(pending.promise)
const verification = controller.verify()
controller.cancel()
pending.resolve(activeSubscription)
expect(await verification).toBeNull()
expect(controller.getState()).toEqual({ phase: 'idle', error: null, verifiedTier: null })
})
it('accepts only the trusted Stripe HTTPS checkout origin and path', () => {
expect(isTrustedStripeCheckoutUrl(trustedUrl)).toBe(true)
expect(isTrustedStripeCheckoutUrl('https://checkout.stripe.com/portal/cs_test_bad')).toBe(false)
expect(
isTrustedStripeCheckoutUrl('https://user:pass@checkout.stripe.com/c/pay/cs_test_bad')
).toBe(false)
})
})

View file

@ -1,50 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { app, ipcMain, shell } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
vi.mock('../../src/main/services/LicenseService', () => ({
getLicenseService: () => ({ on: vi.fn() })
}))
import { registerLicenseHandlers } from '../../src/main/ipc/license-handlers'
type CapturedHandler = (...args: unknown[]) => unknown
const handlers = new Map<string, CapturedHandler>()
async function openBilling(tier: 'pro' | 'pro_plus'): Promise<unknown> {
const handler = handlers.get(IPC_CHANNELS.LICENSE.OPEN_BILLING)
if (!handler) throw new Error('Missing OPEN_BILLING handler')
return handler({}, { tier })
}
function setPackaged(value: boolean): void {
Object.defineProperty(app, 'isPackaged', { value, configurable: true, writable: true })
}
beforeEach(() => {
vi.clearAllMocks()
handlers.clear()
vi.mocked(ipcMain.handle).mockImplementation((channel: string, handler: CapturedHandler) => {
handlers.set(channel, handler)
})
registerLicenseHandlers()
})
describe('LICENSE.OPEN_BILLING', () => {
it('opens the single web billing entry with the chosen tier in packaged builds', async () => {
setPackaged(true)
try {
await expect(openBilling('pro_plus')).resolves.toEqual({ success: true, data: undefined })
expect(shell.openExternal).toHaveBeenCalledWith('https://d3ro.chanpaca.net/app/billing?tier=pro_plus')
} finally {
setPackaged(false)
}
})
it('opens the local web app under the same base path in development', async () => {
setPackaged(false)
await openBilling('pro')
expect(shell.openExternal).toHaveBeenCalledWith('http://localhost:3000/app/billing?tier=pro')
})
})

View file

@ -0,0 +1,332 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import type { IPCResult } from '@d3ro/core/errors'
import type { CheckoutSessionParams, CheckoutSessionResult } from '@d3ro/core/types'
const mocks = vi.hoisted(() => {
const invokeFunction = vi.fn()
const activate = vi.fn()
const getLicenseService = vi.fn(() => ({ activate }))
const cloud = {
isAuthenticated: vi.fn(() => true),
getUser: vi.fn(() => ({ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' })),
invokeFunction
}
return { activate, cloud, getLicenseService, invokeFunction }
})
vi.mock('../../src/main/services/CloudSyncService', () => ({
getCloudSyncService: () => mocks.cloud
}))
vi.mock('../../src/main/services/LicenseService', () => ({
getLicenseService: mocks.getLicenseService
}))
import {
PAYMENT_REQUEST_TIMEOUT_MS,
registerPaymentHandlers
} from '../../src/main/ipc/payment-handlers'
type CapturedHandler = (...args: unknown[]) => unknown
const handlers = new Map<string, CapturedHandler>()
const validParams: CheckoutSessionParams = {
tier: 'pro',
provider: 'stripe'
}
async function invokeIpc<T>(channel: string, ...args: unknown[]): Promise<IPCResult<T>> {
const handler = handlers.get(channel)
if (!handler) throw new Error(`Missing IPC handler: ${channel}`)
return (await handler({}, ...args)) as IPCResult<T>
}
function checkoutResponse(url = 'https://checkout.stripe.com/c/pay/cs_test_safe#fragment') {
return { data: { url }, error: null }
}
beforeEach(() => {
vi.useRealTimers()
vi.clearAllMocks()
handlers.clear()
mocks.cloud.isAuthenticated.mockReturnValue(true)
mocks.cloud.getUser.mockReturnValue({ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' })
vi.mocked(ipcMain.handle).mockImplementation((channel: string, handler: CapturedHandler) => {
handlers.set(channel, handler)
})
registerPaymentHandlers()
})
afterEach(() => {
vi.useRealTimers()
})
describe('desktop payment IPC security boundary', () => {
it('uses the authenticated Stripe Edge checkout contract and returns only its trusted URL', async () => {
mocks.invokeFunction.mockResolvedValue(checkoutResponse())
const result = await invokeIpc<CheckoutSessionResult>(
IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION,
validParams
)
expect(result).toEqual({
success: true,
data: {
checkoutUrl: 'https://checkout.stripe.com/c/pay/cs_test_safe#fragment',
provider: 'stripe',
status: 'pending'
}
})
expect(mocks.invokeFunction).toHaveBeenCalledTimes(1)
const [name, body, options] = mocks.invokeFunction.mock.calls[0]
expect(name).toBe('stripe-checkout')
expect(body).toEqual({
tier: 'pro',
success_url: 'https://d3ro.chanpaca.net/billing?desktop_checkout=success',
cancel_url: 'https://d3ro.chanpaca.net/billing?desktop_checkout=cancelled',
idempotency_key: expect.stringMatching(/^desktop:stripe-checkout:[0-9a-f-]{36}$/)
})
expect(options).toMatchObject({ timeoutMs: PAYMENT_REQUEST_TIMEOUT_MS })
expect(options.signal).toBeInstanceOf(AbortSignal)
})
it.each(['toss', 'portone', 'arbitrary-provider'])(
'rejects unsupported provider %s before network I/O',
async (provider) => {
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, {
...validParams,
provider
})
expect(result.success).toBe(false)
expect(mocks.invokeFunction).not.toHaveBeenCalled()
}
)
it.each(['free', 'team', 'enterprise', 'arbitrary-tier'])(
'rejects renderer-selected tier %s before network I/O',
async (tier) => {
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, {
...validParams,
tier
})
expect(result.success).toBe(false)
expect(mocks.invokeFunction).not.toHaveBeenCalled()
}
)
it.each([
'http://checkout.stripe.com/c/pay/cs_test_unsafe',
'https://checkout.stripe.com.evil.test/c/pay/cs_test_unsafe',
'https://checkout.stripe.com@evil.test/c/pay/cs_test_unsafe',
'https://user:pass@checkout.stripe.com/c/pay/cs_test_unsafe',
'https://checkout.stripe.com/portal/cs_test_unsafe'
])('rejects an untrusted checkout URL: %s', async (url) => {
mocks.invokeFunction.mockResolvedValue(checkoutResponse(url))
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
expect(result.success).toBe(false)
})
it('fails closed on provider errors without exposing provider details', async () => {
mocks.invokeFunction.mockResolvedValue({
data: null,
error: { message: 'sensitive Stripe provider details' }
})
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
expect(result).toMatchObject({
success: false,
error: { message: 'Checkout service rejected the request' }
})
expect(JSON.stringify(result)).not.toContain('sensitive Stripe provider details')
})
it('fails closed on network errors without converting them into checkout success', async () => {
mocks.invokeFunction.mockRejectedValue(new Error('sensitive network details'))
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
expect(result).toMatchObject({
success: false,
error: { message: 'Checkout service is unavailable' }
})
expect(JSON.stringify(result)).not.toContain('sensitive network details')
})
it('coalesces concurrent and sequential duplicate checkout requests', async () => {
let resolveProvider: ((value: ReturnType<typeof checkoutResponse>) => void) | undefined
mocks.invokeFunction.mockReturnValue(
new Promise((resolve) => {
resolveProvider = resolve
})
)
const first = invokeIpc<CheckoutSessionResult>(
IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION,
validParams
)
const concurrent = invokeIpc<CheckoutSessionResult>(
IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION,
validParams
)
expect(mocks.invokeFunction).toHaveBeenCalledTimes(1)
resolveProvider?.(checkoutResponse())
const [firstResult, concurrentResult] = await Promise.all([first, concurrent])
const sequentialResult = await invokeIpc<CheckoutSessionResult>(
IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION,
validParams
)
expect(firstResult).toEqual(concurrentResult)
expect(sequentialResult).toEqual(firstResult)
expect(mocks.invokeFunction).toHaveBeenCalledTimes(1)
})
it('reuses the server idempotency key when a failed checkout is retried', async () => {
mocks.invokeFunction.mockResolvedValue({
data: null,
error: { message: 'provider unavailable' }
})
const first = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
const retry = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
expect(first.success).toBe(false)
expect(retry.success).toBe(false)
expect(mocks.invokeFunction).toHaveBeenCalledTimes(2)
expect(mocks.invokeFunction.mock.calls[0][1].idempotency_key).toBe(
mocks.invokeFunction.mock.calls[1][1].idempotency_key
)
})
it('aborts and fails closed when checkout exceeds the deadline', async () => {
vi.useFakeTimers()
mocks.invokeFunction.mockReturnValue(new Promise(() => undefined))
const pending = invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
await vi.advanceTimersByTimeAsync(PAYMENT_REQUEST_TIMEOUT_MS)
const result = await pending
expect(result).toMatchObject({
success: false,
error: { message: 'Payment server request timed out' }
})
const options = mocks.invokeFunction.mock.calls[0][2]
expect(options.signal.aborted).toBe(true)
})
it('uses server subscription readback and never mutates the local license', async () => {
mocks.invokeFunction.mockResolvedValue({
data: {
tier: 'pro_plus',
status: 'active',
current_period_end: '2099-01-01T00:00:00.000Z'
},
error: null
})
const result = await invokeIpc<{ success: boolean; activeTier: string }>(
IPC_CHANNELS.PAYMENT.VERIFY_PAYMENT,
{ tier: 'enterprise' }
)
expect(result).toEqual({
success: true,
data: { success: true, activeTier: 'pro_plus' }
})
expect(mocks.invokeFunction).toHaveBeenCalledWith(
'payple-manage',
{ action: 'info' },
expect.objectContaining({ timeoutMs: PAYMENT_REQUEST_TIMEOUT_MS })
)
expect(mocks.getLicenseService).not.toHaveBeenCalled()
expect(mocks.activate).not.toHaveBeenCalled()
})
it('does not grant an arbitrary renderer tier when the server says free', async () => {
mocks.invokeFunction.mockResolvedValue({
data: { tier: 'free', status: 'active', current_period_end: null },
error: null
})
const result = await invokeIpc<{ success: boolean; activeTier: string }>(
IPC_CHANNELS.PAYMENT.VERIFY_PAYMENT,
{ tier: 'enterprise' }
)
expect(result).toEqual({
success: true,
data: { success: false, activeTier: 'free' }
})
expect(mocks.activate).not.toHaveBeenCalled()
})
it('preserves prepaid cancellation until expiry and fails closed after expiry', async () => {
mocks.invokeFunction
.mockResolvedValueOnce({
data: {
tier: 'pro',
status: 'canceled',
current_period_end: '2099-01-01T00:00:00.000Z'
},
error: null
})
.mockResolvedValueOnce({
data: {
tier: 'pro',
status: 'canceled',
current_period_end: '2000-01-01T00:00:00.000Z'
},
error: null
})
const current = await invokeIpc<{
tier: string
valid: boolean
expiresAt: number | null
}>(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS)
const expired = await invokeIpc<{
tier: string
valid: boolean
expiresAt: number | null
}>(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS)
expect(current).toMatchObject({ success: true, data: { tier: 'pro', valid: true } })
expect(expired).toMatchObject({ success: true, data: { tier: 'free', valid: false } })
})
it('rejects malformed or arbitrary server entitlement data', async () => {
mocks.invokeFunction.mockResolvedValue({
data: {
tier: 'enterprise',
status: 'active',
current_period_end: '2099-01-01T00:00:00.000Z'
},
error: null
})
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS)
expect(result).toMatchObject({
success: false,
error: { message: 'Subscription status is unavailable' }
})
})
it('requires an authenticated user before invoking payment functions', async () => {
mocks.cloud.isAuthenticated.mockReturnValue(false)
const result = await invokeIpc(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, validParams)
expect(result.success).toBe(false)
expect(mocks.invokeFunction).not.toHaveBeenCalled()
})
})

View file

@ -1,6 +1,5 @@
import type { RealtimeChannel } from '@supabase/supabase-js'
import type { Meeting, Team, TeamRole } from '@d3ro/api-client'
import { PUBLIC_SITE_ORIGIN, SITE_URLS } from '@d3ro/core/web-urls'
import { supabase } from '../../lib/supabase'
export interface TeamSummary extends Team {
@ -100,9 +99,7 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const INVITE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{32}$/
const TEAM_NAME_MAX_LENGTH = 80
const EMAIL_MAX_LENGTH = 254
const TRUSTED_INVITE_ORIGIN = PUBLIC_SITE_ORIGIN
// '/accept-invite' — 사이트 정본 URL에서 경로만 떼어 끝 슬래시 유무를 모두 허용한다.
const INVITE_PATH = SITE_URLS.acceptInvite.slice(PUBLIC_SITE_ORIGIN.length).replace(/\/$/, '')
const TRUSTED_INVITE_ORIGIN = 'https://d3ro.chanpaca.net'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
@ -184,7 +181,7 @@ export function normalizeInviteUrl(value: string): string {
}
if (
parsed.origin !== TRUSTED_INVITE_ORIGIN
|| (parsed.pathname !== INVITE_PATH && parsed.pathname !== `${INVITE_PATH}/`)
|| (parsed.pathname !== '/accept-invite' && parsed.pathname !== '/accept-invite/')
|| parsed.username !== ''
|| parsed.password !== ''
|| parsed.hash !== ''

View file

@ -9,7 +9,6 @@ import {
type ReactNode,
} from 'react'
import { Linking, Platform } from 'react-native'
import { billingUrl } from '@d3ro/core/web-urls'
import {
ErrorCode,
deepLinkToSubscriptions,
@ -542,7 +541,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
})
return
}
await Linking.openURL(billingUrl())
await Linking.openURL('https://d3ro.chanpaca.net/billing')
}, [entitlement.snapshot.provider, entitlement.snapshot.storeProductId])
const clearOperation = useCallback(() => {

View file

@ -24,7 +24,6 @@ import {
} from '../lib/mobile-ads-context'
import { useMobilePreferences } from '../lib/preferences-context'
import { ThemeButton, ThemeCard, ThemeText } from '../theme/themed-components'
import { SITE_URLS } from '@d3ro/core/web-urls'
type Navigation = NativeStackNavigationProp<RootStackParamList, 'ProPaywall'>
type TranslationKey = Parameters<ReturnType<typeof useI18n>['t']>[0]
@ -306,7 +305,7 @@ export default function ProPaywallScreen(): React.ReactElement {
<Pressable
accessibilityRole="link"
accessibilityLabel={t('mobile.paywall.terms')}
onPress={() => void Linking.openURL(SITE_URLS.terms)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/terms')}
style={styles.legalLink}
>
<ThemeText variant="small" color="accent">{t('mobile.paywall.terms')}</ThemeText>
@ -315,7 +314,7 @@ export default function ProPaywallScreen(): React.ReactElement {
<Pressable
accessibilityRole="link"
accessibilityLabel={t('mobile.paywall.privacy')}
onPress={() => void Linking.openURL(SITE_URLS.privacy)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/privacy/')}
style={styles.legalLink}
>
<ThemeText variant="small" color="accent">{t('mobile.paywall.privacy')}</ThemeText>

View file

@ -11,7 +11,6 @@ import {
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useNavigation } from '@react-navigation/native'
import { useI18n, type TranslationKey } from '@d3ro/i18n'
import { SITE_URLS } from '@d3ro/core/web-urls'
import { useAuth } from '../lib/auth-context'
import { useEntitlement } from '../lib/entitlement-context'
import {
@ -476,21 +475,21 @@ export default function SettingsScreen(): React.ReactElement {
label={t('mobile.set.privacyPolicy')}
hint={t('mobile.set.privacyPolicyHint')}
testID="settings-privacy-policy"
onPress={() => void Linking.openURL(SITE_URLS.privacy)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/privacy/')}
/>
<LegalLinkRow
label={t('mobile.set.termsOfService')}
hint={t('mobile.set.termsOfServiceHint')}
testID="settings-terms-of-service"
bordered
onPress={() => void Linking.openURL(SITE_URLS.terms)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/terms/')}
/>
<LegalLinkRow
label={t('mobile.set.accountDeletion')}
hint={t('mobile.set.accountDeletionHint')}
testID="settings-account-deletion-web"
bordered
onPress={() => void Linking.openURL(SITE_URLS.deleteAccount)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/delete-account/')}
/>
</ThemeCard>

View file

@ -21,7 +21,6 @@ import {
d3roNativeFonts,
} from '@d3ro/ui-native'
import { useI18n } from '@d3ro/i18n'
import { SITE_URLS } from '@d3ro/core/web-urls'
import { isSupabaseConfigured, supabase } from '../lib/supabase'
import { AUTH_REDIRECT_URL } from '../lib/auth-redirect'
import { getAuthCapabilities, type AuthCapabilities } from '../lib/auth-capabilities'
@ -347,7 +346,7 @@ export default function SignUpScreen(): React.ReactElement {
accessibilityRole="link"
accessibilityLabel={t('mobile.set.termsOfService')}
testID="sign-up-terms-link"
onPress={() => void Linking.openURL(SITE_URLS.terms)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/terms/')}
style={styles.legalLink}
disabled={interfaceBusy}
>
@ -362,7 +361,7 @@ export default function SignUpScreen(): React.ReactElement {
accessibilityRole="link"
accessibilityLabel={t('mobile.set.privacyPolicy')}
testID="sign-up-privacy-link"
onPress={() => void Linking.openURL(SITE_URLS.privacy)}
onPress={() => void Linking.openURL('https://d3ro.chanpaca.net/privacy/')}
style={styles.legalLink}
disabled={interfaceBusy}
>

View file

@ -1,45 +0,0 @@
# apps/web/Dockerfile
# 웹앱(@d3ro/web) standalone 이미지. 빌드 컨텍스트는 저장소 루트다.
# docker build -t d3ro-voice-web:latest -f apps/web/Dockerfile \
# --build-arg NEXT_PUBLIC_SUPABASE_URL=... \
# --build-arg NEXT_PUBLIC_SUPABASE_ANON_KEY=... \
# --build-arg NEXT_PUBLIC_PAYPLE_CLIENT_KEY=... .
# 공개 경로는 https://d3ro.chanpaca.net/app (Next basePath '/app', 정본 packages/core/src/web-urls.ts).
FROM node:24.19.0-alpine AS base
FROM base AS builder
WORKDIR /app
# NEXT_PUBLIC_* 는 next build 때 클라이언트·서버 번들에 박힌다. 런타임 환경변수로는 바뀌지 않는다.
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ARG NEXT_PUBLIC_PAYPLE_CLIENT_KEY=""
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \
NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY \
NEXT_PUBLIC_PAYPLE_CLIENT_KEY=$NEXT_PUBLIC_PAYPLE_CLIENT_KEY \
NEXT_TELEMETRY_DISABLED=1
RUN test -n "$NEXT_PUBLIC_SUPABASE_URL" && test -n "$NEXT_PUBLIC_SUPABASE_ANON_KEY" \
|| (echo "NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY build args are required" >&2 && exit 1)
COPY package*.json tsconfig*.json ./
COPY packages ./packages
COPY apps/web ./apps/web
# 개발자 로컬 .env* 가 컨텍스트에 섞여 들어와도 빌드 값은 위 build arg 만 쓴다.
RUN rm -f apps/web/.env apps/web/.env.*
RUN npm ci
RUN npm run build --workspace=@d3ro/web
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3002
ENV HOSTNAME="0.0.0.0"
ENV NEXT_TELEMETRY_DISABLED=1
# node 사용자로 실행하므로 .next/cache 쓰기가 가능하도록 소유권을 넘긴다.
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
USER node
EXPOSE 3002
CMD ["node", "apps/web/server.js"]

View file

@ -12,6 +12,7 @@ const catalogPayload = {
tier: 'pro',
prices: [
{ provider: 'payple', unit_amount: 9900, currency: 'KRW', interval: 'month', interval_count: 1 },
{ provider: 'stripe', unit_amount: 999, currency: 'USD', interval: 'month', interval_count: 1 },
],
},
{
@ -28,8 +29,9 @@ test.describe('billing catalog strict client contract', () => {
const catalog = parseBillingCatalog(catalogPayload)
expect(catalog).not.toBeNull()
expect(formatBillingPrice(catalog!.plans.pro[0])).toContain('9,900')
expect(formatPlanCatalogPrice('pro', catalog)).toContain('9,900')
expect(formatPlanCatalogPrice('pro_plus', catalog)).toContain('29,900')
expect(formatBillingPrice(catalog!.plans.pro[1])).toContain('9.99')
expect(formatPlanCatalogPrice('pro', catalog)).toContain('Payple')
expect(formatPlanCatalogPrice('pro', catalog)).toContain('Stripe')
expect(formatPlanCatalogPrice('free', catalog)).toBe('무료')
})
@ -54,10 +56,6 @@ test.describe('billing catalog strict client contract', () => {
...catalogPayload,
plans: [{ tier: 'pro', prices: [{ ...catalogPayload.plans[0].prices[0], currency: 'KRW<script>' }] }, catalogPayload.plans[1]],
},
{
...catalogPayload,
plans: [{ tier: 'pro', prices: [{ ...catalogPayload.plans[0].prices[0], provider: 'google_play' }] }, catalogPayload.plans[1]],
},
]
for (const value of invalid) expect(parseBillingCatalog(value)).toBeNull()
})

View file

@ -124,12 +124,12 @@ test.describe('Billing provider and Payple DOM flow', () => {
})
})
await page.goto('/app/login')
await page.goto('/login')
await page.getByPlaceholder('user@studio.com').fill(email)
await page.getByPlaceholder('••••••••').fill(password)
await page.getByRole('button', { name: '로그인', exact: true }).click()
await page.waitForURL(/\/dashboard/, { timeout: 15_000 })
await page.goto('/app/billing')
await page.goto('/billing')
await expect(page.getByTestId('billing-current-tier')).toHaveText('FREE')
await expect(page.getByTestId('billing-current-provider')).toContainText('없음')
@ -138,9 +138,10 @@ test.describe('Billing provider and Payple DOM flow', () => {
await expect(proPlan.getByTestId('payple-upgrade-pro')).toBeEnabled()
await expect(page.getByTestId('billing-plan-pro_plus')).toBeVisible()
await expect(proPlan.getByRole('button', { name: /Stripe/ })).toHaveCount(0)
await proPlan.getByLabel('Stripe 해외 카드').click()
await expect(proPlan.getByTestId('stripe-upgrade-pro')).toBeVisible()
await proPlan.getByLabel('Payple 국내 카드').click()
// 결제 경로가 없어도 과거 provider='stripe' 구독 행은 계속 읽혀야 한다.
const stripePeriodEnd = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
const { error: stripeFixtureError } = await admin.from('subscriptions').update({
tier: 'pro',
@ -155,7 +156,7 @@ test.describe('Billing provider and Payple DOM flow', () => {
if (stripeFixtureError) throw stripeFixtureError
await page.reload()
await expect(page.getByTestId('billing-current-provider')).toContainText('Stripe')
await expect(page.getByTestId('stripe-portal-open')).toHaveCount(0)
await expect(page.getByTestId('stripe-portal-open')).toBeVisible()
await expect(page.getByTestId('billing-checkout-pro')).toHaveCount(0)
const { error: freeFixtureError } = await admin.from('subscriptions').update({

View file

@ -35,7 +35,7 @@ test.describe('Dashboard, dictionary and command Supabase parity', () => {
let otherId = ''
async function login(page: import('@playwright/test').Page): Promise<void> {
await page.goto('/app/login')
await page.goto('/login')
await page.getByPlaceholder('user@studio.com').fill(ownerEmail)
await page.getByPlaceholder('••••••••').fill(password)
await page.getByRole('button', { name: '로그인', exact: true }).click()
@ -146,7 +146,7 @@ test.describe('Dashboard, dictionary and command Supabase parity', () => {
test('dictionary uses RLS CRUD, filters, pagination, duplicate protection and optimistic rollback', async ({ page }) => {
await login(page)
await page.goto('/app/dictionary')
await page.goto('/dictionary')
await expect(page.getByText('CUSTOM DICTIONARY')).toBeVisible()
await expect(page.getByText(foreignDictionaryWord)).toHaveCount(0)
await expect(page.getByText(oldestWord)).toHaveCount(0)
@ -237,7 +237,7 @@ test.describe('Dashboard, dictionary and command Supabase parity', () => {
expect(bootstrapA.data).toHaveLength(4)
expect(bootstrapB.data).toHaveLength(4)
await bootstrapClient.auth.signOut({ scope: 'local' })
await page.goto('/app/commands')
await page.goto('/commands')
await expect(page.getByText('SYNCED COMMANDS (4)')).toBeVisible()
await expect(page.getByText('Translate to English', { exact: true }).first()).toBeVisible()
await expect(page.getByText('BUILT-IN · READ ONLY').first()).toBeVisible()

View file

@ -90,13 +90,13 @@ test.describe('History Supabase SSOT', () => {
})
test('session, RLS, search, favorite, pagination, detail and mutation rollback work end-to-end', async ({ page }) => {
await page.goto('/app/login')
await page.goto('/login')
await page.getByPlaceholder('user@studio.com').fill(ownerEmail)
await page.getByPlaceholder('••••••••').fill(password)
await page.getByRole('button', { name: '로그인', exact: true }).click()
await page.waitForURL(/\/dashboard/, { timeout: 15_000 })
await page.goto('/app/history')
await page.goto('/history')
await expect(page.getByText('TRANSCRIPTION HISTORY')).toBeVisible()
await expect(page.getByText(foreignTitle)).toHaveCount(0)
await expect(page.getByTestId(`history-card-${oldestId}`)).toHaveCount(0)

View file

@ -95,7 +95,7 @@ test.describe('Payple payer number and fail-closed checkout', () => {
test('rejects missing or tampered catalog price before opening Payple', async () => {
for (const catalogPrice of [
{ provider: 'google_play', unitAmount: 9900, currency: 'KRW', interval: 'month', intervalCount: 1 },
{ provider: 'stripe', unitAmount: 9900, currency: 'KRW', interval: 'month', intervalCount: 1 },
{ provider: 'payple', unitAmount: 1, currency: 'USD', interval: 'month', intervalCount: 1 },
{ provider: 'payple', unitAmount: 9900, currency: 'KRW', interval: 'year', intervalCount: 1 },
{ provider: 'payple', unitAmount: 0, currency: 'KRW', interval: 'month', intervalCount: 1 }

View file

@ -1,7 +1,6 @@
import { test, expect } from '@playwright/test';
import path from 'path';
import fs from 'fs';
import { SITE_URLS } from '@d3ro/core/web-urls';
const SCREENSHOT_DIR = path.resolve('C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots');
@ -22,9 +21,9 @@ test.describe.serial('Extreme Red Team - Cycle 4: Web Console & Public Surfaces'
});
});
test('RT-14: Web Public Hub - /login and the /download redirect to the landing site', async ({ page }) => {
test('RT-14: Web Public Hub - /login, /download, /releases & /accept-invite', async ({ page }) => {
// 1. Test /login
await page.goto('/app/login');
await page.goto('/login');
await page.waitForLoadState('domcontentloaded');
await expect(page.getByText(/D3RO[- ]VOICE/i)).toBeVisible({ timeout: 10000 });
@ -36,10 +35,49 @@ test.describe.serial('Extreme Red Team - Cycle 4: Web Console & Public Surfaces'
path: path.join(SCREENSHOT_DIR, 'rt14_01_web_login.png'),
});
// 2. /download lives only on the landing site; the web app just redirects there.
const downloadRes = await page.request.get('/app/download', { maxRedirects: 0 });
expect([307, 308]).toContain(downloadRes.status());
expect(downloadRes.headers()['location']).toBe(SITE_URLS.download);
// 2. Test /download
await page.goto('/download');
await page.waitForLoadState('domcontentloaded');
await expect(page.getByText(/OFFICIAL STABLE RELEASE|D3RO Voice Desktop 1.1.0/i).first()).toBeVisible({ timeout: 10000 });
await expect(page.getByText(/Windows|macOS/i).first()).toBeVisible();
const primaryDownloadBtn = page.getByRole('link', { name: /Download for Windows/i });
await expect(primaryDownloadBtn).toBeVisible();
await expect(primaryDownloadBtn).toHaveAttribute('href', '/releases/1.1.0/D3RO-Voice-Setup-1.1.0-x64.exe');
await expect(primaryDownloadBtn).toHaveAttribute('download', 'D3RO-Voice-Setup-1.1.0-x64.exe');
const cardDownloadBtn = page.getByRole('link', { name: /Download Setup \(\.exe\)/i });
await expect(cardDownloadBtn).toBeVisible();
await expect(cardDownloadBtn).toHaveAttribute('href', '/releases/1.1.0/D3RO-Voice-Setup-1.1.0-x64.exe');
// Verify static release asset HTTP availability
const releaseHead = await page.request.head('/releases/1.1.0/D3RO-Voice-Setup-1.1.0-x64.exe');
expect(releaseHead.status()).toBe(200);
expect(Number(releaseHead.headers()['content-length'])).toBeGreaterThan(100000000);
// Screenshot download
await page.screenshot({
path: path.join(SCREENSHOT_DIR, 'rt14_02_web_download.png'),
});
// 3. Test /releases
await page.goto('/releases');
await page.waitForLoadState('domcontentloaded');
await expect(page.getByText(/OFFICIAL STABLE RELEASE|D3RO Voice Desktop 1.1.0/i).first()).toBeVisible({ timeout: 10000 });
await expect(page.getByRole('link', { name: /Download for Windows/i })).toBeVisible();
// Screenshot releases
await page.screenshot({
path: path.join(SCREENSHOT_DIR, 'rt14_03_web_releases.png'),
});
// 4. Test /accept-invite
await page.goto('/accept-invite?token=red-team-bogus-token');
await page.waitForLoadState('domcontentloaded');
await expect(page.getByText(/TEAM INVITE|초대/i).first()).toBeVisible({ timeout: 10000 });
expect(uncaughtExceptions).toEqual([]);
});
@ -60,7 +98,7 @@ test.describe.serial('Extreme Red Team - Cycle 4: Web Console & Public Surfaces'
];
for (const route of protectedRoutes) {
await page.goto(`/app${route}`);
await page.goto(route);
await page.waitForURL(/\/login/, { timeout: 10000 });
expect(page.url()).toContain('/login');
}

View file

@ -10,31 +10,36 @@ import { test, expect } from '@playwright/test'
test.describe('Smoke: unauthenticated access', () => {
test('루트(/)는 /login으로 리다이렉트된다 (Supabase 미설정 시)', async ({ page }) => {
await page.goto('/app')
await page.goto('/')
await page.waitForURL(/\/login/, { timeout: 10000 })
expect(page.url()).toContain('/login')
})
test('/login 페이지가 로드되고 D3RO VOICE 로고가 표시된다', async ({ page }) => {
await page.goto('/app/login')
await page.goto('/login')
await expect(page.getByText(/D3RO[- ]VOICE/i)).toBeVisible({ timeout: 10000 })
})
test('/login에 Google/GitHub OAuth 버튼이 보인다', async ({ page }) => {
await page.goto('/app/login')
await page.goto('/login')
await expect(page.getByRole('button', { name: /Google/i })).toBeVisible()
await expect(page.getByRole('button', { name: /GitHub/i })).toBeVisible()
})
test('/dashboard는 미로그인 시 /login으로 리다이렉트', async ({ page }) => {
await page.goto('/app/dashboard')
await page.goto('/dashboard')
await page.waitForURL(/\/login/, { timeout: 10000 })
expect(page.url()).toContain('/login')
})
test('/meetings도 미로그인 시 /login으로 리다이렉트', async ({ page }) => {
await page.goto('/app/meetings')
await page.goto('/meetings')
await page.waitForURL(/\/login/, { timeout: 10000 })
expect(page.url()).toContain('/login')
})
test('/accept-invite?token=bogus는 페이지 로드 (에러 메시지 표시)', async ({ page }) => {
await page.goto('/accept-invite?token=bogus')
await expect(page.getByText(/TEAM INVITE/i)).toBeVisible({ timeout: 10000 })
})
})

View file

@ -7,8 +7,8 @@
NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
# 공개 주소는 @d3ro/core/web-urls 가 정본이다. 로컬 개발 주소는 http://localhost:3000/app (basePath).
# NEXT_PUBLIC_* 값은 빌드 시점에 번들에 들어간다. Docker 이미지는 --build-arg 로 넘긴다.
# OAuth callback base URL
NEXT_PUBLIC_SITE_URL=http://localhost:3000
# Payple browser SDK client key (test keys start with test_)
# Missing values fail closed and disable the Payple checkout button.

12
apps/web/next.config.mjs Normal file
View file

@ -0,0 +1,12 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
// monorepo workspace 패키지는 소스 TypeScript 그대로 번들 대상
transpilePackages: ['@d3ro/core', '@d3ro/ui', '@d3ro/i18n', '@d3ro/api-client'],
experimental: {
// MUI + Emotion 최적화
optimizePackageImports: ['@mui/material', '@mui/icons-material', '@d3ro/ui']
}
}
export default nextConfig

View file

@ -1,26 +0,0 @@
import type { NextConfig } from 'next'
import { SITE_URLS, WEB_APP_BASE_PATH } from '@d3ro/core/web-urls'
const nextConfig: NextConfig = {
reactStrictMode: true,
// 웹앱은 d3ro.chanpaca.net/app 아래에서 서빙된다. 사이트 브리지 워커가 /app/* 를 이 서버로 보낸다.
basePath: WEB_APP_BASE_PATH,
// NAS Docker 이미지(apps/web/Dockerfile)는 standalone 산출물만 복사한다.
output: 'standalone',
// monorepo workspace 패키지는 소스 TypeScript 그대로 번들 대상
transpilePackages: ['@d3ro/core', '@d3ro/ui', '@d3ro/i18n', '@d3ro/api-client'],
experimental: {
// MUI + Emotion 최적화
optimizePackageImports: ['@mui/material', '@mui/icons-material', '@d3ro/ui']
},
async redirects() {
// 다운로드·릴리스 안내는 랜딩 사이트 한 벌만 둔다. source 는 basePath 가 붙어 /app/download, /app/releases(/…) 가 된다.
return ['/download', '/releases/:path*'].map((source) => ({
source,
destination: SITE_URLS.download,
permanent: true
}))
}
}
export default nextConfig

View file

@ -0,0 +1,12 @@
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.d3ro.voice",
"sha256_cert_fingerprints": [
"01:00:19:21:DB:4F:33:40:85:CE:21:E4:B8:DE:CC:BD:71:DA:87:67:C5:6E:3B:59:83:2A:A1:C8:29:EA:0D:AB"
]
}
}
]

View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="refresh" content="0; url=/download" />
<link rel="canonical" href="https://d3ro.chanpaca.net/download" />
<title>D3RO Voice 릴리스 준비</title>
</head>
<body>
<main>
<h1>D3RO Voice 릴리스 준비</h1>
<p>설치 파일은 서명과 업데이트 경로 검증이 끝난 뒤 공식 페이지에서 제공합니다.</p>
<p><a href="/download">공식 릴리스 준비 페이지로 이동</a></p>
</main>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show more