204 lines
11 KiB
TypeScript
204 lines
11 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
import type { WorksBillingSummary, WorksPointHistory, WorksRechargeOrder, WorksRechargeProduct, WorksTokenPointBalance } from '../../../shared/works-billing';
|
|
import { getValidWorksSquareAccessToken, getWorksSquareAccountBinding, isCurrentWorksSquareAccountBinding } from '../../services/works-square-session';
|
|
import { proxyAwareFetch } from '../../utils/proxy-fetch';
|
|
import { parseJsonBody, sendJson } from '../route-utils';
|
|
import { hasRendererCapability } from '../renderer-capability';
|
|
import { WORKS_SQUARE_CONFIG } from '../works-config';
|
|
|
|
const pointsPattern = /^(?:0|[1-9]\d*)\.\d{2}$/u;
|
|
function record(value: unknown): Record<string, unknown> {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid billing response');
|
|
return value as Record<string, unknown>;
|
|
}
|
|
function text(value: unknown): string {
|
|
if (typeof value !== 'string' || !value.trim()) throw new Error('Invalid billing text');
|
|
return value;
|
|
}
|
|
function bool(value: unknown): boolean {
|
|
if (typeof value !== 'boolean') throw new Error('Invalid billing flag');
|
|
return value;
|
|
}
|
|
function point(value: unknown, signed = false): string {
|
|
const result = text(value);
|
|
if (!pointsPattern.test(signed ? result.replace(/^-/, '') : result)) throw new Error('Invalid points');
|
|
return result;
|
|
}
|
|
function date(value: unknown): string {
|
|
const result = text(value);
|
|
if (!Number.isFinite(Date.parse(result))) throw new Error('Invalid billing date');
|
|
return result;
|
|
}
|
|
function items(value: unknown): unknown[] {
|
|
if (!Array.isArray(value)) throw new Error('Invalid billing page');
|
|
return value;
|
|
}
|
|
function amount(value: unknown): number {
|
|
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) throw new Error('Invalid amount');
|
|
return value;
|
|
}
|
|
function currency(value: unknown): 'CNY' {
|
|
if (value !== 'CNY') throw new Error('Invalid currency');
|
|
return value;
|
|
}
|
|
|
|
export function projectBillingBalance(input: unknown): WorksTokenPointBalance {
|
|
const value = record(input);
|
|
const source = value.entitlement_source;
|
|
if (source !== 'self' && source !== 'family_owner' && source !== 'shared_group') throw new Error('Invalid funding source');
|
|
const shared = bool(value.family_shared);
|
|
// A family payer can use their own shared wallet. The API exposes coarse
|
|
// availability only when the selected wallet belongs to someone else.
|
|
const coarse = value.shared_available !== null;
|
|
if (coarse) bool(value.shared_available);
|
|
if (value.expires_at !== null) throw new Error('Invalid permanent wallet');
|
|
return {
|
|
total: coarse ? null : point(value.total),
|
|
used: coarse ? null : point(value.used),
|
|
reserved: coarse ? null : point(value.reserved),
|
|
total_remaining: coarse ? null : point(value.total_remaining),
|
|
entitlement_source: source,
|
|
family_shared: shared,
|
|
can_recharge: coarse ? false : bool(value.can_recharge),
|
|
shared_available: coarse ? bool(value.shared_available) : null,
|
|
expires_at: null,
|
|
};
|
|
}
|
|
|
|
function projectProduct(input: unknown): WorksRechargeProduct {
|
|
const value = record(input);
|
|
const cents = amount(value.amount_cents);
|
|
const points = point(value.point_amount);
|
|
if (BigInt(points.replace('.', '')) !== BigInt(cents) * 50n) throw new Error('Invalid recharge ratio');
|
|
return { id: text(value.id), name: text(value.name), amount_cents: cents, point_amount: points, currency: currency(value.currency) };
|
|
}
|
|
|
|
export function projectBillingSummary(input: unknown): WorksBillingSummary {
|
|
const value = record(input);
|
|
const own = projectBillingBalance(value.own_points);
|
|
if (own.family_shared || value.points_per_yuan !== 50 || value.signup_bonus !== '100.00') throw new Error('Invalid wallet contract');
|
|
const canRecharge = bool(value.can_recharge);
|
|
if (own.can_recharge !== canRecharge) throw new Error('Invalid recharge permission');
|
|
return {
|
|
own_points: own,
|
|
points: value.points === null ? null : projectBillingBalance(value.points),
|
|
// Do not pass arbitrary upstream exception messages to Renderer.
|
|
funding_error: value.funding_error ? 'AI 编程付款来源不可用,请在网页账户页选择或检查付款来源。' : null,
|
|
recharge_products: items(value.recharge_products).map(projectProduct),
|
|
points_per_yuan: 50, signup_bonus: '100.00',
|
|
can_recharge: canRecharge, payment_configured: bool(value.payment_configured),
|
|
};
|
|
}
|
|
|
|
function paymentQr(input: unknown): string | null {
|
|
if (!input || typeof input !== 'object') return null;
|
|
const payload = record(input);
|
|
for (const key of ['codeUrl', 'code_url', 'qrCode', 'qr_code', 'qrCodeUrl', 'qr_code_url', 'paymentQrCodeUrl', 'payment_qr_code_url', 'nativeUrl', 'native_url', 'payUrl', 'pay_url', 'mwebUrl', 'mweb_url', 'checkout_url']) {
|
|
const value = payload[key];
|
|
if (typeof value !== 'string') continue;
|
|
try {
|
|
const url = new URL(value);
|
|
if ((url.protocol === 'weixin:' || url.protocol === 'https:') && !url.username && !url.password) return value;
|
|
} catch { /* Not a supported desktop payment URL. */ }
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function projectRechargeOrder(input: unknown, payment?: unknown): WorksRechargeOrder {
|
|
const value = record(input);
|
|
const status = value.status;
|
|
if (status !== 'pending' && status !== 'succeeded' && status !== 'failed' && status !== 'canceled' && status !== 'manual_review') throw new Error('Invalid order state');
|
|
const review = bool(value.manual_review_required);
|
|
return {
|
|
id: text(value.id), product_id: text(value.product_id), product_name: text(value.product_name),
|
|
status: review ? 'manual_review' : status,
|
|
amount_cents: amount(value.amount_cents), point_amount: point(value.point_amount), currency: currency(value.currency),
|
|
created_at: date(value.created_at), paid_at: value.paid_at === null ? null : date(value.paid_at),
|
|
manual_review_required: review,
|
|
qr_payload: status === 'pending' && !review ? paymentQr(payment ?? value.provider_payload) : null,
|
|
};
|
|
}
|
|
|
|
export function projectPointHistory(input: unknown): WorksPointHistory {
|
|
const value = record(input);
|
|
return { has_more: bool(value.has_more), items: items(value.items).map((item) => {
|
|
const row = record(item);
|
|
if (row.kind !== 'credit' && row.kind !== 'usage') throw new Error('Invalid transaction kind');
|
|
return { id: text(row.id), kind: row.kind, description: text(row.description), status: text(row.status), points: point(row.points, true), reserved_points: point(row.reserved_points), created_at: date(row.created_at) };
|
|
}) };
|
|
}
|
|
|
|
export async function handleWorksBillingRoutes(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
|
const prefix = '/api/works/billing';
|
|
if (!url.pathname.startsWith(`${prefix}/`)) return false;
|
|
const path = url.pathname.slice(prefix.length);
|
|
const creating = path === '/recharge/orders' && req.method === 'POST';
|
|
const orderMatch = /^\/recharge\/orders\/([^/]+)$/.exec(path);
|
|
const reading = req.method === 'GET' && (['/me', '/points', '/points/transactions', '/recharge/orders'].includes(path) || orderMatch);
|
|
if (!creating && !reading) {
|
|
sendJson(res, 410, { success: false, code: 'membership_retired', error: '旧账户接口已停用,请使用词元点数充值。' });
|
|
return true;
|
|
}
|
|
if (creating && !hasRendererCapability(req)) {
|
|
sendJson(res, 403, { success: false, error: '请从应用内发起充值。', commandOutcome: 'definitive_failure' });
|
|
return true;
|
|
}
|
|
const binding = getWorksSquareAccountBinding();
|
|
let dispatched = false;
|
|
try {
|
|
const accessToken = await getValidWorksSquareAccessToken();
|
|
if (!binding || !accessToken || !isCurrentWorksSquareAccountBinding(binding)) {
|
|
sendJson(res, 401, { success: false, error: '请重新登录后查看账户。', commandOutcome: 'definitive_failure' });
|
|
return true;
|
|
}
|
|
const target = new URL(`/api/billing${path}`, WORKS_SQUARE_CONFIG.apiBaseUrl);
|
|
const headers: Record<string, string> = { Authorization: `Bearer ${accessToken}` };
|
|
let body: string | undefined;
|
|
if (creating) {
|
|
const input = record(await parseJsonBody(req));
|
|
const productId = text(input.productId);
|
|
const requestId = text(input.requestId);
|
|
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(requestId) || !isCurrentWorksSquareAccountBinding(binding)) throw new Error('Invalid recharge request');
|
|
headers['Content-Type'] = 'application/json';
|
|
headers['Idempotency-Key'] = `makelore:${requestId}`;
|
|
body = JSON.stringify({ product_id: productId });
|
|
} else if (path === '/points/transactions' || path === '/recharge/orders') {
|
|
const offset = Number(url.searchParams.get('offset') ?? 0);
|
|
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('Invalid page');
|
|
target.searchParams.set('limit', '20');
|
|
target.searchParams.set('offset', String(offset));
|
|
}
|
|
dispatched = true;
|
|
const response = await proxyAwareFetch(target.toString(), { method: creating ? 'POST' : 'GET', headers, body });
|
|
const payload: unknown = await response.json();
|
|
if (!isCurrentWorksSquareAccountBinding(binding)) {
|
|
sendJson(res, 409, { success: false, error: '账户已切换,请重新打开词元点数。', commandOutcome: 'unknown' });
|
|
return true;
|
|
}
|
|
if (!response.ok) {
|
|
const detail = record(payload).detail;
|
|
const rejection = detail && typeof detail === 'object' && record(detail).outcome === 'definitive_rejection';
|
|
const messages: Record<number, string> = { 401: '登录已失效,请重新登录。', 403: '当前账户不能充值,请联系家长。', 404: '充值档位或订单已不可用,请刷新。', 409: '请先完成或核查已有充值订单;计费服务也可能正在切换。', 410: '账户服务版本不匹配,请更新客户端和服务端。' };
|
|
sendJson(res, response.status >= 400 && response.status < 500 ? response.status : 502, {
|
|
success: false, error: rejection ? '支付服务拒绝了本次请求,请稍后重试。' : messages[response.status] ?? '支付结果尚未确认,请刷新订单或联系运营核查,勿重复付款。',
|
|
commandOutcome: rejection || [401, 403, 404, 422].includes(response.status) ? 'definitive_failure' : 'unknown',
|
|
});
|
|
return true;
|
|
}
|
|
let data: unknown;
|
|
if (path === '/me') data = projectBillingSummary(payload);
|
|
else if (path === '/points') data = projectBillingBalance(payload);
|
|
else if (path === '/points/transactions') data = projectPointHistory(payload);
|
|
else if (creating) data = projectRechargeOrder(record(payload).order, record(payload).provider_payload);
|
|
else if (orderMatch) data = projectRechargeOrder(payload);
|
|
else data = { items: items(record(payload).items).map((item) => projectRechargeOrder(item)) };
|
|
sendJson(res, 200, { success: true, data });
|
|
} catch {
|
|
sendJson(res, creating && !dispatched ? 400 : 502, {
|
|
success: false, error: creating && dispatched ? '充值结果尚未确认,请刷新订单,重试时沿用本次请求。' : '词元点数服务暂时不可用,请刷新后重试。',
|
|
commandOutcome: dispatched ? 'unknown' : 'definitive_failure',
|
|
});
|
|
}
|
|
return true;
|
|
}
|