feat(release): prepare 1.1.0 candidate
This commit is contained in:
parent
5a34f66981
commit
5205dcdfa9
736 changed files with 115667 additions and 12203 deletions
|
|
@ -6,11 +6,8 @@ import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
|||
import { getAudioCaptureService, calculateRMS } from '../services/AudioCaptureService'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import { configGet, configSet } from '../services/ConfigService'
|
||||
import { getLogger } from '../services/LoggerService'
|
||||
import type { SetDeviceParams } from '@d3ro/core/types'
|
||||
|
||||
const logger = getLogger('audio-handlers')
|
||||
|
||||
let testTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let testAudioHandler: ((payload: { buffer: Buffer; timestamp: number }) => void) | null = null
|
||||
let testLevelInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
|
|
|||
|
|
@ -1,48 +1,246 @@
|
|||
// apps/desktop/src/main/ipc/payment-handlers.ts
|
||||
// IPC handlers for Multi-PG Payment & Billing
|
||||
// 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 { ok } from '@d3ro/core/errors'
|
||||
import { ErrorCode, ipcError, ok, type IPCResult } from '@d3ro/core/errors'
|
||||
import type { CheckoutSessionParams, CheckoutSessionResult } from '@d3ro/core/types'
|
||||
import { getLicenseService } from '../services/LicenseService'
|
||||
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 {
|
||||
// 1. Create Checkout Session
|
||||
ipcMain.handle(IPC_CHANNELS.PAYMENT.CREATE_CHECKOUT_SESSION, async (_event, params: CheckoutSessionParams) => {
|
||||
const isKrw = params.currency === 'KRW'
|
||||
const session: CheckoutSessionResult = {
|
||||
sessionId: `cs_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
|
||||
checkoutUrl: isKrw
|
||||
? `https://pay.tosspayments.com/v1/billing/${params.planId}`
|
||||
: `https://checkout.stripe.com/c/pay/${params.planId}`,
|
||||
provider: params.provider || (isKrw ? 'toss_payments' : 'stripe'),
|
||||
orderId: `ORD-${Date.now()}`,
|
||||
amount: params.amount,
|
||||
currency: params.currency,
|
||||
}
|
||||
return ok(session)
|
||||
})
|
||||
const attempts = new Map<string, CheckoutAttempt>()
|
||||
|
||||
// 2. Verify Payment & Activate Tier
|
||||
ipcMain.handle(IPC_CHANNELS.PAYMENT.VERIFY_PAYMENT, async (_event, { tier }: { tier: string }) => {
|
||||
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 license = getLicenseService()
|
||||
await license.activate(`D3RO-${tier.toUpperCase()}-${Date.now().toString(36).toUpperCase()}`)
|
||||
} catch {
|
||||
// ignore
|
||||
const status = await readServerSubscription(authenticated.cloud)
|
||||
return ok({ success: status.valid, activeTier: status.tier })
|
||||
} catch (error) {
|
||||
return paymentFailure(error, 'Subscription status is unavailable')
|
||||
}
|
||||
return ok({ success: true, activeTier: tier })
|
||||
})
|
||||
|
||||
// 3. Get Subscription Status
|
||||
ipcMain.handle(IPC_CHANNELS.PAYMENT.GET_SUBSCRIPTION_STATUS, async () => {
|
||||
const license = getLicenseService()
|
||||
const info = license.getLicenseInfo()
|
||||
return ok({
|
||||
tier: info.tier,
|
||||
valid: info.valid,
|
||||
expiresAt: info.expiresAt,
|
||||
})
|
||||
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')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export function registerSTTHandlers(): void {
|
|||
safeSendToRenderer(IPC_CHANNELS.STT.DOWNLOAD_PROGRESS, payload)
|
||||
})
|
||||
|
||||
getSTTManager().on('provider-changed', (payload) => {
|
||||
getSTTManager().on('provider-changed', (_payload) => {
|
||||
safeSendToRenderer(IPC_CHANNELS.STT.STATUS_CHANGED, { status: getSTTManager().getStatus() })
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// apps/desktop/src/main/ipc/support-handlers.ts
|
||||
// IPC handlers for Customer Assistance, AI Helpdesk & Diagnostics
|
||||
|
||||
import { ipcMain } from 'electron'
|
||||
import { app, ipcMain } from 'electron'
|
||||
import os from 'os'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ok } from '@d3ro/core/errors'
|
||||
|
|
@ -30,7 +30,7 @@ export function registerSupportHandlers(): void {
|
|||
|
||||
const payload: SystemDiagnosticsPayload = {
|
||||
machineId: `d3ro-${os.hostname().toLowerCase().slice(0, 12)}`,
|
||||
appVersion: '1.0.0-release',
|
||||
appVersion: app.getVersion(),
|
||||
platform: `${os.platform()} (${os.arch()})`,
|
||||
osRelease: `${os.type()} ${os.release()}`,
|
||||
activeAudioDevice: (configGet('audio.selectedDevice') as string) || 'Default System Microphone',
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ export function registerVoiceHandlers(): void {
|
|||
return ipcSuccess(getVoiceModeService().getState())
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.VOICE.SET_MODE, async (_event, params: SetVoiceModeParams) => {
|
||||
ipcMain.handle(IPC_CHANNELS.VOICE.SET_MODE, async (_event, _params: SetVoiceModeParams) => {
|
||||
// Phase 2: 모드만 설정에 저장 (실제 모드 전환은 핫키에서 처리)
|
||||
return ipcSuccess(undefined)
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue