Skip to content

Prompt as Code | GPT Image 2 / 2.5 提示词与案例库,530+ 个案例、20+ 套工业级模板与可复用 Skills,新增 2.5 同提示词对比专区,附完整提示词与生成记录,持续更新。

Add paid community Alipay checkout

苍何225e13aa3698
diff --git a/.env.example b/.env.example
index 63a96f6..fdfe44e 100644
--- a/.env.example
+++ b/.env.example
@@ -10,6 +10,23 @@ APP_URL=https://gpt-image2.canghe.ai
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
+# Alipay production settings. Local sandbox development reads
+# .alipay-sandbox.json directly and does not copy its keys into this file.
+ALIPAY_APP_ID=
+ALIPAY_PRIVATE_KEY=
+ALIPAY_PUBLIC_KEY=
+ALIPAY_SELLER_ID=
+ALIPAY_GATEWAY=https://openapi.alipay.com/gateway.do
+ALIPAY_NOTIFY_URL=
+# Dedicated callback for paid-community orders. Keep this separate from credit-pack fulfillment.
+COMMUNITY_ALIPAY_NOTIFY_URL=https://gpt-image2.canghe.ai/api/community/alipay/notify
+# Set to false only for local production-parameter acceptance without a public HTTPS callback.
+ALIPAY_NOTIFY_ENABLED=true
+
+# Paid community: production deployments must start with new payments disabled.
+COMMUNITY_PAYMENT_ENABLED=false
+COMMUNITY_SUPPORT_TEXT=微信搜索苍何
+
VITE_GA_MEASUREMENT_ID=
GA4_PROPERTY_ID=
GOOGLE_ANALYTICS_CLIENT_ID=
diff --git a/.gitignore b/.gitignore
index 40f93f4..ea99cf1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ dist/
.env*.local
npm-debug.log*
.vercel
+/.alipay-sandbox.json
diff --git a/README.md b/README.md
index c582730..96d4f64 100644
--- a/README.md
+++ b/README.md
@@ -27,17 +27,13 @@ Use the live site at [gpt-image2.canghe.ai](https://gpt-image2.canghe.ai/) to br
</a>
</p>
-## WeChat Official Account
+## Paid Community
-Search **苍何** on WeChat or scan the QR card below. To join the GPT-Image2 community group, follow the account and reply with **gpt-image-2交流群**.
-
-<p align="center">
- <img src="data/images/wechat-community.jpg" alt="Canghe WeChat community QR card" width="760">
-</p>
+The GPT-Image2 discussion group is now a paid community. Sign in on the [community page](https://gpt-image2.canghe.ai/community), make a one-time **¥9.90** Alipay payment, and the protected group QR will appear only after the server confirms payment. For refunds or manual support, search **苍何** on WeChat.
## ❤️ Sponsors
-> [Want to appear here?](data/images/sponsors/wechat-personal.jpg) Support the project through GitHub Sponsors, or follow the WeChat official account above and send your product name plus a short sponsorship note.
+> [Want to appear here?](data/images/sponsors/wechat-personal.jpg) Support the project through GitHub Sponsors, or search 苍何 on WeChat and send your product name plus a short sponsorship note.
| Sponsor | Description |
| ------- | ----------- |
@@ -330,6 +326,8 @@ Setup checklist:
- Apply [`supabase/migrations/202605090001_user_credits.sql`](supabase/migrations/202605090001_user_credits.sql) to the Supabase project.
- Apply [`supabase/migrations/20260509090000_membership_billing.sql`](supabase/migrations/20260509090000_membership_billing.sql) to add membership plans, credit packs, Stripe order records, and credit adjustment RPCs.
+- Apply [`supabase/migrations/20260721090000_alipay_webpay.sql`](supabase/migrations/20260721090000_alipay_webpay.sql) before enabling Alipay website payments, then configure each credit pack's reviewed CNY price. See [Alipay website payment setup](docs/alipay-web-payment.md).
+- Apply [`supabase/migrations/20260722090000_paid_community.sql`](supabase/migrations/20260722090000_paid_community.sql) before enabling the paid community. Keep `COMMUNITY_PAYMENT_ENABLED=false` until the protected QR, Alipay onboarding, and production payment/refund checks are complete. See the [paid community runbook](docs/paid-community.md).
- Apply [`supabase/migrations/20260512090000_google_account_center.sql`](supabase/migrations/20260512090000_google_account_center.sql) to add account usage summaries and forced credit charging for super admins.
- Apply [`supabase/migrations/20260512143000_pricing_admin_metrics.sql`](supabase/migrations/20260512143000_pricing_admin_metrics.sql) to update the `$5 / 300 credits` catalog and add admin dashboard metrics.
- Apply [`supabase/migrations/20260515090000_case_favorites.sql`](supabase/migrations/20260515090000_case_favorites.sql) to add per-user case favorites.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9f378f8..a720f12 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -27,17 +27,13 @@
</a>
</p>
-## 公众号与交流群
+## 付费交流群
-微信搜 **苍何** 或扫描下方二维码关注苍何公众号。加入 GPT-Image2 交流群,请关注后回复:**gpt-image-2交流群**。
-
-<p align="center">
- <img src="data/images/wechat-community.jpg" alt="苍何微信交流群二维码" width="760">
-</p>
+GPT-Image2 交流群现已改为付费加入。请登录[付费群页面](https://gpt-image2.canghe.ai/community),通过支付宝一次性支付 **¥9.90**;只有服务端确认付款后,当前账号才能查看受保护的群二维码。退款或人工支持请在微信搜索 **苍何**。
## ❤️ 赞助方
-> [想出现在这里?](data/images/sponsors/wechat-personal.jpg) 可以通过 GitHub Sponsors 支持项目,也可以关注上方公众号并发送产品名与简短赞助说明。
+> [想出现在这里?](data/images/sponsors/wechat-personal.jpg) 可以通过 GitHub Sponsors 支持项目,也可以在微信搜索苍何并发送产品名与简短赞助说明。
| 赞助方 | 说明 |
| ------ | ---- |
@@ -328,6 +324,8 @@ GOOGLE_ANALYTICS_REFRESH_TOKEN=
- 将 [`supabase/migrations/202605090001_user_credits.sql`](supabase/migrations/202605090001_user_credits.sql) 应用到 Supabase 项目。
- 将 [`supabase/migrations/20260509090000_membership_billing.sql`](supabase/migrations/20260509090000_membership_billing.sql) 应用到 Supabase 项目,添加会员套餐、积分包、Stripe 订单记录和积分调整 RPC。
+- 启用支付宝网站支付前,应用 [`supabase/migrations/20260721090000_alipay_webpay.sql`](supabase/migrations/20260721090000_alipay_webpay.sql),并为需要销售的积分包配置经业务确认的人民币价格。详见[支付宝网站支付接入说明](docs/alipay-web-payment.md)。
+- 启用付费交流群前,应用 [`supabase/migrations/20260722090000_paid_community.sql`](supabase/migrations/20260722090000_paid_community.sql)。在新群码、支付宝签约和生产付款退款验收完成前,保持 `COMMUNITY_PAYMENT_ENABLED=false`。详见[付费交流群上线手册](docs/paid-community.md)。
- 将 [`supabase/migrations/20260512090000_google_account_center.sql`](supabase/migrations/20260512090000_google_account_center.sql) 应用到 Supabase 项目,添加账户用量统计和超级管理员强制扣积分逻辑。
- 将 [`supabase/migrations/20260512143000_pricing_admin_metrics.sql`](supabase/migrations/20260512143000_pricing_admin_metrics.sql) 应用到 Supabase 项目,更新 `$5 / 300 credits` 价格体系,并添加管理员数据看板指标。
- 将 [`supabase/migrations/20260515090000_case_favorites.sql`](supabase/migrations/20260515090000_case_favorites.sql) 应用到 Supabase 项目,添加用户案例收藏表。
diff --git a/api/_lib/alipay.js b/api/_lib/alipay.js
new file mode 100644
index 0000000..66690ec
--- /dev/null
+++ b/api/_lib/alipay.js
@@ -0,0 +1,246 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { AlipaySdk } from 'alipay-sdk';
+
+const SANDBOX_CONFIG_FILE = '.alipay-sandbox.json';
+const SANDBOX_GATEWAY = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do';
+const PRODUCTION_GATEWAY = 'https://openapi.alipay.com/gateway.do';
+
+function requiredText(value, field) {
+ const text = String(value || '').trim();
+ if (!text) throw new Error(`ALIPAY_CONFIG_MISSING_${field}`);
+ return text;
+}
+
+function requiredPrivateKey(value) {
+ const text = String(value || '');
+ if (!text || text !== text.trim() || /-----BEGIN|-----END|\s/.test(text)) {
+ throw new Error('ALIPAY_CONFIG_INVALID_PRIVATE_KEY');
+ }
+ return text;
+}
+
+function loadProductionConfig() {
+ const configuredFields = [
+ process.env.ALIPAY_APP_ID,
+ process.env.ALIPAY_PRIVATE_KEY,
+ process.env.ALIPAY_PUBLIC_KEY,
+ process.env.ALIPAY_SELLER_ID
+ ];
+ if (!configuredFields.some(Boolean)) return null;
+
+ const gateway = requiredText(process.env.ALIPAY_GATEWAY || PRODUCTION_GATEWAY, 'GATEWAY');
+ if (gateway !== PRODUCTION_GATEWAY) throw new Error('ALIPAY_CONFIG_INVALID_PRODUCTION_GATEWAY');
+
+ return {
+ mode: 'production',
+ configPath: 'server environment',
+ appId: requiredText(process.env.ALIPAY_APP_ID, 'APP_ID'),
+ privateKey: requiredPrivateKey(process.env.ALIPAY_PRIVATE_KEY),
+ alipayPublicKey: requiredText(process.env.ALIPAY_PUBLIC_KEY, 'PUBLIC_KEY'),
+ sellerId: requiredText(process.env.ALIPAY_SELLER_ID, 'SELLER_ID'),
+ gateway
+ };
+}
+
+function loadSandboxConfig() {
+ const configPath = path.resolve(process.cwd(), SANDBOX_CONFIG_FILE);
+ const raw = fs.readFileSync(configPath, 'utf8');
+ const payload = JSON.parse(raw);
+ const app = Array.isArray(payload?.appIds) ? payload.appIds[0] : null;
+
+ return {
+ mode: 'sandbox',
+ configPath,
+ appId: requiredText(app?.appId, 'APP_ID'),
+ privateKey: requiredPrivateKey(app?.appPrivatePkcsKey),
+ alipayPublicKey: requiredText(app?.alipayPublicKey, 'PUBLIC_KEY'),
+ sellerId: requiredText(app?.pid || payload?.sandboxAccounts?.partner?.userId, 'SELLER_ID'),
+ gateway: SANDBOX_GATEWAY
+ };
+}
+
+export function getAlipayRuntimeConfig() {
+ return loadProductionConfig() || loadSandboxConfig();
+}
+
+export function isAlipayConfigured() {
+ try {
+ getAlipayRuntimeConfig();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function getAlipayClient() {
+ const runtime = getAlipayRuntimeConfig();
+ const sdk = new AlipaySdk({
+ appId: runtime.appId,
+ privateKey: runtime.privateKey,
+ alipayPublicKey: runtime.alipayPublicKey,
+ gateway: runtime.gateway,
+ signType: 'RSA2',
+ keyType: 'PKCS1',
+ charset: 'utf-8',
+ version: '1.0',
+ camelcase: false
+ });
+
+ return {
+ sdk,
+ mode: runtime.mode,
+ configPath: runtime.configPath,
+ appId: runtime.appId,
+ sellerId: runtime.sellerId,
+ gateway: runtime.gateway
+ };
+}
+
+export function getAlipayNotifyUrl(appUrl) {
+ if (process.env.ALIPAY_NOTIFY_ENABLED === 'false') return '';
+ if (process.env.ALIPAY_NOTIFY_URL) {
+ const notifyUrl = new URL(requiredText(process.env.ALIPAY_NOTIFY_URL, 'NOTIFY_URL'));
+ if (notifyUrl.protocol !== 'https:' || notifyUrl.username || notifyUrl.password || notifyUrl.hash) {
+ throw new Error('ALIPAY_CONFIG_INVALID_NOTIFY_URL');
+ }
+ return notifyUrl.toString();
+ }
+
+ try {
+ const url = new URL(appUrl);
+ const isLocal = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);
+ if (url.protocol !== 'https:' || isLocal) return '';
+ return `${url.origin}/api/billing/alipay/notify`;
+ } catch {
+ return '';
+ }
+}
+
+export function getCommunityAlipayNotifyUrl(appUrl) {
+ if (process.env.ALIPAY_NOTIFY_ENABLED === 'false') return '';
+ if (process.env.COMMUNITY_ALIPAY_NOTIFY_URL) {
+ const notifyUrl = new URL(requiredText(
+ process.env.COMMUNITY_ALIPAY_NOTIFY_URL,
+ 'COMMUNITY_NOTIFY_URL'
+ ));
+ if (notifyUrl.protocol !== 'https:' || notifyUrl.username || notifyUrl.password || notifyUrl.hash) {
+ throw new Error('ALIPAY_CONFIG_INVALID_COMMUNITY_NOTIFY_URL');
+ }
+ return notifyUrl.toString();
+ }
+
+ try {
+ const url = new URL(appUrl);
+ const isLocal = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);
+ if (url.protocol !== 'https:' || isLocal) return '';
+ return `${url.origin}/api/community/alipay/notify`;
+ } catch {
+ return '';
+ }
+}
+
+export function formatAlipayAmount(amountCents) {
+ const cents = Number(amountCents);
+ if (!Number.isSafeInteger(cents) || cents <= 0) {
+ throw new Error('ALIPAY_INVALID_AMOUNT');
+ }
+ return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`;
+}
+
+export function parseAlipayAmount(amount) {
+ const text = String(amount || '').trim();
+ if (!/^\d{1,9}(?:\.\d{1,2})?$/.test(text)) return null;
+ const [yuan, fraction = ''] = text.split('.');
+ const cents = Number(yuan) * 100 + Number(fraction.padEnd(2, '0'));
+ return Number.isSafeInteger(cents) ? cents : null;
+}
+
+export function normalizeAlipaySubject(value) {
+ const subject = String(value || '')
+ .replace(/[\/=,&]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 256);
+ if (!subject) throw new Error('ALIPAY_INVALID_SUBJECT');
+ return subject;
+}
+
+export function parseAlipayFormBody(rawBody) {
+ const params = new URLSearchParams(Buffer.from(rawBody || '').toString('utf8'));
+ return Object.fromEntries(params.entries());
+}
+
+export function isAlipayTradePaid(status) {
+ return status === 'TRADE_SUCCESS' || status === 'TRADE_FINISHED';
+}
+
+export function isAlipayPaidNotification(params = {}) {
+ return isAlipayTradePaid(params.trade_status)
+ && !params.out_biz_no
+ && !params.gmt_refund
+ && !params.refund_fee;
+}
+
+export function sanitizeAlipayNotifyParams(params = {}) {
+ const safe = {};
+ for (const key of [
+ 'notify_type',
+ 'notify_id',
+ 'sign_type',
+ 'trade_no',
+ 'app_id',
+ 'out_trade_no',
+ 'trade_status',
+ 'total_amount',
+ 'currency',
+ 'seller_id',
+ 'seller_email',
+ 'out_biz_no',
+ 'gmt_refund',
+ 'refund_fee'
+ ]) {
+ if (params[key] != null && params[key] !== '') safe[key] = params[key];
+ }
+ return safe;
+}
+
+export function validateAlipayOrderResult(order, result) {
+ const outTradeNo = String(result?.out_trade_no || '');
+ const totalAmountCents = parseAlipayAmount(result?.total_amount);
+ const orderCurrency = String(order?.currency || '').toUpperCase();
+ const resultCurrency = String(result?.currency || '').toUpperCase();
+ return Boolean(
+ outTradeNo === order.id
+ && totalAmountCents !== null
+ && totalAmountCents === Number(order.amount_cents)
+ && orderCurrency === 'CNY'
+ && (!resultCurrency || resultCurrency === 'CNY')
+ );
+}
+
+export async function completeAlipayCreditPackOrder(client, order, result, options = {}) {
+ const tradeNo = requiredText(result?.trade_no, 'TRADE_NO');
+ const paidAmountCents = parseAlipayAmount(result?.total_amount);
+ if (paidAmountCents === null) throw new Error('ALIPAY_INVALID_PAID_AMOUNT');
+
+ const { data, error } = await client.rpc('complete_alipay_credit_pack_order', {
+ p_order_id: order.id,
+ p_trade_no: tradeNo,
+ p_paid_amount_cents: paidAmountCents,
+ p_notify_id: options.notifyId || null,
+ p_notify_payload: options.notifyPayload || {}
+ });
+ if (error) throw error;
+ return Array.isArray(data) ? data[0] : data;
+}
+
+export async function finalizeAlipayRefund(client, orderId, result) {
+ const { data, error } = await client.rpc('finalize_alipay_credit_pack_refund', {
+ p_order_id: orderId,
+ p_trade_no: requiredText(result?.trade_no, 'TRADE_NO'),
+ p_refund_amount_cents: parseAlipayAmount(result?.refund_fee || result?.refund_amount)
+ });
+ if (error) throw error;
+ return Array.isArray(data) ? data[0] : data;
+}
diff --git a/api/_lib/alipay.test.js b/api/_lib/alipay.test.js
new file mode 100644
index 0000000..1e31d04
--- /dev/null
+++ b/api/_lib/alipay.test.js
@@ -0,0 +1,159 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import {
+ formatAlipayAmount,
+ getCommunityAlipayNotifyUrl,
+ getAlipayNotifyUrl,
+ isAlipayPaidNotification,
+ isAlipayTradePaid,
+ normalizeAlipaySubject,
+ parseAlipayAmount,
+ parseAlipayFormBody,
+ sanitizeAlipayNotifyParams,
+ validateAlipayOrderResult
+} from './alipay.js';
+
+const webpayMigration = readFileSync(
+ new URL('../../supabase/migrations/20260721090000_alipay_webpay.sql', import.meta.url),
+ 'utf8'
+);
+const notifyHandlerSource = readFileSync(
+ new URL('../billing/alipay/notify.js', import.meta.url),
+ 'utf8'
+);
+
+test('formats integer cents as a two-decimal yuan amount', () => {
+ assert.equal(formatAlipayAmount(1), '0.01');
+ assert.equal(formatAlipayAmount(12345), '123.45');
+ assert.throws(() => formatAlipayAmount(0), /ALIPAY_INVALID_AMOUNT/);
+});
+
+test('parses Alipay decimal amounts without floating-point rounding', () => {
+ assert.equal(parseAlipayAmount('0.01'), 1);
+ assert.equal(parseAlipayAmount('123.4'), 12340);
+ assert.equal(parseAlipayAmount('123.456'), null);
+ assert.equal(parseAlipayAmount('-1.00'), null);
+});
+
+test('normalizes forbidden subject characters', () => {
+ assert.equal(normalizeAlipaySubject('GPT/Image = pack, 300 & more'), 'GPT Image pack 300 more');
+});
+
+test('parses form encoded notification bodies', () => {
+ const params = parseAlipayFormBody(Buffer.from('trade_status=TRADE_SUCCESS&sign=a%2Bb%3D'));
+ assert.deepEqual(params, { trade_status: 'TRADE_SUCCESS', sign: 'a+b=' });
+});
+
+test('validates order identity and amount before fulfillment', () => {
+ const order = { id: 'order-1', amount_cents: 500, currency: 'cny' };
+ assert.equal(validateAlipayOrderResult(order, {
+ out_trade_no: 'order-1',
+ total_amount: '5.00'
+ }), true);
+ assert.equal(validateAlipayOrderResult(order, {
+ out_trade_no: 'order-2',
+ total_amount: '5.00'
+ }), false);
+ assert.equal(validateAlipayOrderResult(order, {
+ out_trade_no: 'order-1',
+ total_amount: '5.01'
+ }), false);
+ assert.equal(validateAlipayOrderResult({ ...order, currency: 'usd' }, {
+ out_trade_no: 'order-1',
+ total_amount: '5.00'
+ }), false);
+ assert.equal(validateAlipayOrderResult(order, {
+ out_trade_no: 'order-1',
+ total_amount: '5.00',
+ currency: 'USD'
+ }), false);
+});
+
+test('accepts only paid Alipay trade states', () => {
+ assert.equal(isAlipayTradePaid('TRADE_SUCCESS'), true);
+ assert.equal(isAlipayTradePaid('TRADE_FINISHED'), true);
+ assert.equal(isAlipayTradePaid('WAIT_BUYER_PAY'), false);
+});
+
+test('accepts only genuine payment notifications for fulfillment', () => {
+ const paid = { trade_status: 'TRADE_SUCCESS' };
+ assert.equal(isAlipayPaidNotification(paid), true);
+ assert.equal(isAlipayPaidNotification({ ...paid, out_biz_no: 'refund-1' }), false);
+ assert.equal(isAlipayPaidNotification({ ...paid, refund_fee: '5.00' }), false);
+ assert.equal(isAlipayPaidNotification({ trade_status: 'TRADE_CLOSED' }), false);
+});
+
+test('sanitizes notifications before persistence or logging', () => {
+ assert.deepEqual(sanitizeAlipayNotifyParams({
+ notify_id: 'notify-1',
+ out_trade_no: 'order-1',
+ sign: 'secret-signature',
+ buyer_id: 'private-buyer'
+ }), {
+ notify_id: 'notify-1',
+ out_trade_no: 'order-1'
+ });
+});
+
+test('persists notification idempotency with protected database access', () => {
+ assert.match(webpayMigration, /create table if not exists public\.alipay_notify_events/i);
+ assert.match(webpayMigration, /alter table public\.alipay_notify_events enable row level security/i);
+ assert.match(
+ webpayMigration,
+ /revoke all on table public\.alipay_notify_events from public, anon, authenticated/i
+ );
+ assert.match(webpayMigration, /grant all on table public\.alipay_notify_events to service_role/i);
+ assert.match(
+ webpayMigration,
+ /complete_alipay_credit_pack_order\(uuid, text, integer, text, jsonb\)[\s\S]*from public, anon, authenticated/i
+ );
+});
+
+test('webpay notification uses raw-safe SDK verification and excludes non-payment events', () => {
+ assert.match(notifyHandlerSource, /checkNotifySignV2\(params\)/);
+ assert.match(notifyHandlerSource, /isAlipayPaidNotification\(params\)/);
+ assert.doesNotMatch(notifyHandlerSource, /checkNotifySign\(params\)/);
+});
+
+test('omits local notify URLs and requires HTTPS for explicit callbacks', () => {
+ const previousUrl = process.env.ALIPAY_NOTIFY_URL;
+ const previousEnabled = process.env.ALIPAY_NOTIFY_ENABLED;
+ delete process.env.ALIPAY_NOTIFY_URL;
+ delete process.env.ALIPAY_NOTIFY_ENABLED;
+
+ try {
+ assert.equal(getAlipayNotifyUrl('http://127.0.0.1:3000'), '');
+ assert.equal(
+ getAlipayNotifyUrl('https://gpt-image2.canghe.ai'),
+ 'https://gpt-image2.canghe.ai/api/billing/alipay/notify'
+ );
+ process.env.ALIPAY_NOTIFY_URL = 'http://127.0.0.1:3000/notify';
+ assert.throws(() => getAlipayNotifyUrl('https://gpt-image2.canghe.ai'), /INVALID_NOTIFY_URL/);
+ } finally {
+ if (previousUrl === undefined) delete process.env.ALIPAY_NOTIFY_URL;
+ else process.env.ALIPAY_NOTIFY_URL = previousUrl;
+ if (previousEnabled === undefined) delete process.env.ALIPAY_NOTIFY_ENABLED;
+ else process.env.ALIPAY_NOTIFY_ENABLED = previousEnabled;
+ }
+});
+
+test('uses a separate HTTPS callback for paid-community orders', () => {
+ const previous = process.env.COMMUNITY_ALIPAY_NOTIFY_URL;
+ delete process.env.COMMUNITY_ALIPAY_NOTIFY_URL;
+ try {
+ assert.equal(getCommunityAlipayNotifyUrl('http://localhost:5173'), '');
+ assert.equal(
+ getCommunityAlipayNotifyUrl('https://gpt-image2.canghe.ai'),
+ 'https://gpt-image2.canghe.ai/api/community/alipay/notify'
+ );
+ process.env.COMMUNITY_ALIPAY_NOTIFY_URL = 'http://localhost:5173/notify';
+ assert.throws(
+ () => getCommunityAlipayNotifyUrl('https://gpt-image2.canghe.ai'),
+ /INVALID_COMMUNITY_NOTIFY_URL/
+ );
+ } finally {
+ if (previous === undefined) delete process.env.COMMUNITY_ALIPAY_NOTIFY_URL;
+ else process.env.COMMUNITY_ALIPAY_NOTIFY_URL = previous;
+ }
+});
diff --git a/api/_lib/api-imports.test.js b/api/_lib/api-imports.test.js
new file mode 100644
index 0000000..c018241
--- /dev/null
+++ b/api/_lib/api-imports.test.js
@@ -0,0 +1,32 @@
+import assert from 'node:assert/strict';
+import { readdir } from 'node:fs/promises';
+import { dirname, extname, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import test from 'node:test';
+
+const apiRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+async function listApiModules(directory) {
+ const entries = await readdir(directory, { withFileTypes: true });
+ const modules = [];
+
+ for (const entry of entries) {
+ const entryPath = resolve(directory, entry.name);
+ if (entry.isDirectory()) {
+ modules.push(...await listApiModules(entryPath));
+ } else if (extname(entry.name) === '.js' && !entry.name.endsWith('.test.js')) {
+ modules.push(entryPath);
+ }
+ }
+
+ return modules;
+}
+
+test('all Vercel API modules load without broken imports', async () => {
+ const modules = await listApiModules(apiRoot);
+ assert.ok(modules.length > 0);
+
+ for (const modulePath of modules) {
+ await import(pathToFileURL(modulePath).href);
+ }
+});
diff --git a/api/_lib/billing.js b/api/_lib/billing.js
index 9cc173d..8c87760 100644
--- a/api/_lib/billing.js
+++ b/api/_lib/billing.js
@@ -83,6 +83,7 @@ export function formatPlan(row) {
}
export function formatPack(row) {
+ const alipayAmountCents = Number(row.alipay_amount_cents || 0);
return {
id: row.id,
type: 'credit_pack',
@@ -98,6 +99,9 @@ export function formatPack(row) {
amountCents: Number(row.amount_cents || 0),
currency: normalizeCurrency(row.currency),
priceLabel: moneyLabel(row.amount_cents, row.currency),
+ alipayAmountCents,
+ alipayPriceLabel: alipayAmountCents > 0 ? moneyLabel(alipayAmountCents, 'cny') : '',
+ alipayAvailable: alipayAmountCents > 0,
active: Boolean(row.active)
};
}
@@ -185,7 +189,13 @@ export function checkoutLineItem(product) {
};
}
-export async function createPaymentOrder(client, { userId, product, customerId }) {
+export async function createPaymentOrder(client, {
+ userId,
+ product,
+ customerId = null,
+ paymentProvider = 'stripe',
+ metadata = {}
+}) {
const credits = product.type === 'membership' ? product.monthlyCredits : product.credits;
const { data, error } = await client
.from('payment_orders')
@@ -194,10 +204,15 @@ export async function createPaymentOrder(client, { userId, product, customerId }
product_type: product.type,
product_id: product.id,
status: 'created',
+ payment_provider: paymentProvider,
stripe_customer_id: customerId,
amount_cents: product.amountCents,
currency: product.currency,
- credits
+ credits,
+ metadata: {
+ ...metadata,
+ paymentProvider
+ }
})
.select('*')
.single();
@@ -215,6 +230,7 @@ export async function markOrderCheckoutCreated(client, orderId, session) {
stripe_customer_id: typeof session.customer === 'string' ? session.customer : null,
stripe_subscription_id: typeof session.subscription === 'string' ? session.subscription : null,
metadata: {
+ paymentProvider: 'stripe',
checkoutUrl: session.url || ''
}
})
diff --git a/api/_lib/community-alipay.js b/api/_lib/community-alipay.js
new file mode 100644
index 0000000..f5154a8
--- /dev/null
+++ b/api/_lib/community-alipay.js
@@ -0,0 +1,60 @@
+import {
+ closeCommunityOrderLocally,
+ isPaidTradeStatus,
+ markCommunityOrderPaid,
+ validateCommunityTradeResult
+} from './community.js';
+
+export function isAlipayTradeNotFound(result) {
+ const code = String(result?.sub_code || result?.code || '').toUpperCase();
+ return code === 'ACQ.TRADE_NOT_EXIST' || code.includes('TRADE_NOT_EXIST');
+}
+
+export async function queryCommunityOrderAtAlipay(client, sdk, order) {
+ const result = await sdk.exec('alipay.trade.query', {
+ bizContent: { out_trade_no: order.id }
+ }, { validateSign: true });
+
+ if (String(result?.code || '') !== '10000') {
+ if (isAlipayTradeNotFound(result)) return { state: 'NOT_FOUND', result };
+ const error = new Error('ALIPAY_COMMUNITY_QUERY_FAILED');
+ error.alipayCode = String(result?.sub_code || result?.code || 'UNKNOWN');
+ throw error;
+ }
+
+ const validation = validateCommunityTradeResult(order, result);
+ if (!validation.ok) throw new Error(`ALIPAY_COMMUNITY_${validation.error}`);
+
+ if (isPaidTradeStatus(result.trade_status)) {
+ await markCommunityOrderPaid(client, order, result);
+ return { state: 'PAID', result };
+ }
+
+ if (result.trade_status === 'TRADE_CLOSED') {
+ await closeCommunityOrderLocally(client, order.id);
+ return { state: 'CLOSED', result };
+ }
+
+ if (result.trade_status !== 'WAIT_BUYER_PAY') {
+ throw new Error('ALIPAY_COMMUNITY_UNKNOWN_TRADE_STATE');
+ }
+ return { state: 'PENDING', result };
+}
+
+export async function closeCommunityOrderAtAlipay(client, sdk, order) {
+ const query = await queryCommunityOrderAtAlipay(client, sdk, order);
+ if (query.state === 'PAID' || query.state === 'CLOSED') return query;
+
+ const result = await sdk.exec('alipay.trade.close', {
+ bizContent: { out_trade_no: order.id }
+ }, { validateSign: true });
+ const closed = String(result?.code || '') === '10000' || isAlipayTradeNotFound(result);
+ if (!closed) {
+ const error = new Error('ALIPAY_COMMUNITY_CLOSE_FAILED');
+ error.alipayCode = String(result?.sub_code || result?.code || 'UNKNOWN');
+ throw error;
+ }
+
+ await closeCommunityOrderLocally(client, order.id);
+ return { state: 'CLOSED', result };
+}
diff --git a/api/_lib/community.js b/api/_lib/community.js
new file mode 100644
index 0000000..4c2ac86
--- /dev/null
+++ b/api/_lib/community.js
@@ -0,0 +1,317 @@
+import { parseAlipayAmount } from './alipay.js';
+
+export const COMMUNITY_PRICE_CENTS = 990;
+export const COMMUNITY_CURRENCY = 'CNY';
+export const COMMUNITY_SUBJECT = 'GPT-Image2 付费交流群长期资格';
+export const COMMUNITY_TERMS_VERSION = '2026-07-22';
+export const COMMUNITY_PENDING_MINUTES = 30;
+export const COMMUNITY_QR_MAX_BYTES = 2 * 1024 * 1024;
+export const COMMUNITY_ORDER_STATUSES = Object.freeze([
+ 'PENDING',
+ 'PAID',
+ 'CLOSED',
+ 'REFUNDED',
+ 'REVOKED'
+]);
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const communityRateBuckets = new Map();
+
+export function isUuid(value) {
+ return UUID_PATTERN.test(String(value || '').trim());
+}
+
+export function isCommunityPaymentEnabled(env = process.env) {
+ return String(env.COMMUNITY_PAYMENT_ENABLED || '').trim().toLowerCase() === 'true';
+}
+
+export function communityPublicConfig(env = process.env) {
+ return {
+ priceCents: COMMUNITY_PRICE_CENTS,
+ priceLabel: '¥9.90',
+ currency: COMMUNITY_CURRENCY,
+ paymentEnabled: isCommunityPaymentEnabled(env),
+ support: String(env.COMMUNITY_SUPPORT_TEXT || '微信搜索苍何').trim(),
+ refundPolicy: '人工审核后原路退款',
+ termsVersion: COMMUNITY_TERMS_VERSION
+ };
+}
+
+export function communityOrderPayload(userId, termsVersion = COMMUNITY_TERMS_VERSION) {
+ return {
+ userId,
+ amountCents: COMMUNITY_PRICE_CENTS,
+ currency: COMMUNITY_CURRENCY,
+ subject: COMMUNITY_SUBJECT,
+ termsVersion
+ };
+}
+
+export function serializeCommunityOrder(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ status: row.status,
+ amountCents: Number(row.amount_cents || 0),
+ currency: String(row.currency || '').toUpperCase(),
+ refundStatus: row.refund_status || 'NONE',
+ createdAt: row.created_at || '',
+ paidAt: row.paid_at || '',
+ refundedAt: row.refunded_at || '',
+ revokedAt: row.revoked_at || ''
+ };
+}
+
+export function canAccessCommunityQr(status) {
+ return status === 'PAID';
+}
+
+export function isOrderOwnedBy(order, userId) {
+ return Boolean(order?.user_id && userId && order.user_id === userId);
+}
+
+export function isCommunityAdmin(auth) {
+ return Boolean(auth?.profile?.isSuperAdmin || auth?.profile?.role === 'super_admin');
+}
+
+export function takeCommunityRateLimit(key, { limit = 30, windowMs = 60_000, now = Date.now() } = {}) {
+ const bucketKey = String(key || 'anonymous');
+ const current = communityRateBuckets.get(bucketKey);
+ if (!current || now >= current.resetAt) {
+ communityRateBuckets.set(bucketKey, { count: 1, resetAt: now + windowMs });
+ return { allowed: true, remaining: limit - 1, retryAfterSeconds: 0 };
+ }
+ current.count += 1;
+ if (current.count > limit) {
+ return {
+ allowed: false,
+ remaining: 0,
+ retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000))
+ };
+ }
+ return { allowed: true, remaining: Math.max(0, limit - current.count), retryAfterSeconds: 0 };
+}
+
+export function communityRequestRateKey(req, scope, userId = '') {
+ const forwarded = String(req?.headers?.['x-forwarded-for'] || '').split(',')[0].trim();
+ const remote = forwarded || String(req?.socket?.remoteAddress || 'unknown');
+ return `${scope}:${userId || remote}`;
+}
+
+export function applyCommunityRateLimit(res, result) {
+ if (result.allowed) return true;
+ res.setHeader('Retry-After', String(result.retryAfterSeconds));
+ res.status(429).json({ ok: false, error: 'RATE_LIMITED' });
+ return false;
+}
+
+export function shouldExpireCommunityOrder(order, now = Date.now()) {
+ if (order?.status !== 'PENDING') return false;
+ const createdAt = Date.parse(order.created_at || '');
+ if (!Number.isFinite(createdAt)) return true;
+ return now - createdAt >= COMMUNITY_PENDING_MINUTES * 60 * 1000;
+}
+
+export function communityRefundRequestNo(orderId) {
+ if (!isUuid(orderId)) throw new Error('INVALID_COMMUNITY_ORDER');
+ return `cg_${String(orderId).replace(/-/g, '')}`;
+}
+
+export function isPaidTradeStatus(status) {
+ return status === 'TRADE_SUCCESS' || status === 'TRADE_FINISHED';
+}
+
+export function validateCommunityTradeResult(order, result) {
+ if (!order || !result) return { ok: false, error: 'ORDER_RESULT_REQUIRED' };
+ if (String(result.out_trade_no || '') !== order.id) {
+ return { ok: false, error: 'OUT_TRADE_NO_MISMATCH' };
+ }
+ const amountCents = parseAlipayAmount(result.total_amount);
+ if (amountCents !== Number(order.amount_cents) || amountCents !== COMMUNITY_PRICE_CENTS) {
+ return { ok: false, error: 'AMOUNT_MISMATCH' };
+ }
+ if (String(order.currency || '').toUpperCase() !== COMMUNITY_CURRENCY) {
+ return { ok: false, error: 'CURRENCY_MISMATCH' };
+ }
+ if (result.currency && String(result.currency).toUpperCase() !== COMMUNITY_CURRENCY) {
+ return { ok: false, error: 'CURRENCY_MISMATCH' };
+ }
+ if (!String(result.trade_no || '').trim()) {
+ return { ok: false, error: 'TRADE_NO_REQUIRED' };
+ }
+ return { ok: true, amountCents };
+}
+
+export function validateCommunityPaidNotification(order, params, runtime) {
+ if (params?.notify_type !== 'trade_status_sync') {
+ return { ok: false, error: 'NOTIFY_TYPE_MISMATCH' };
+ }
+ if (params.app_id !== runtime?.appId) {
+ return { ok: false, error: 'APP_ID_MISMATCH' };
+ }
+ if (params.seller_id !== runtime?.sellerId) {
+ return { ok: false, error: 'SELLER_ID_MISMATCH' };
+ }
+ const result = validateCommunityTradeResult(order, params);
+ if (!result.ok) return result;
+ if (!isPaidTradeStatus(params.trade_status)) {
+ return { ok: false, error: 'TRADE_NOT_PAID' };
+ }
+ if (params.out_biz_no || params.gmt_refund || params.refund_fee) {
+ return { ok: false, error: 'NON_PAYMENT_EVENT' };
+ }
+ return result;
+}
+
+export function sanitizeAlipayNotifyParams(params = {}) {
+ const safe = {};
+ for (const key of [
+ 'notify_type',
+ 'notify_id',
+ 'sign_type',
+ 'trade_no',
+ 'app_id',
+ 'out_trade_no',
+ 'trade_status',
+ 'total_amount',
+ 'currency',
+ 'seller_id',
+ 'seller_email',
+ 'out_biz_no',
+ 'gmt_refund',
+ 'refund_fee'
+ ]) {
+ if (params[key] != null && params[key] !== '') safe[key] = params[key];
+ }
+ return safe;
+}
+
+export function validateSameOrigin(req) {
+ const originText = String(req?.headers?.origin || '').trim();
+ if (!originText) return false;
+
+ try {
+ const origin = new URL(originText).origin;
+ const host = req?.headers?.['x-forwarded-host'] || req?.headers?.host;
+ const protocol = req?.headers?.['x-forwarded-proto'] || 'https';
+ const requestUrl = host ? new URL(`${protocol}://${host}`).origin : '';
+ const configuredUrl = process.env.APP_URL ? new URL(process.env.APP_URL).origin : '';
+ return Boolean(
+ (requestUrl && origin === requestUrl)
+ || (configuredUrl && origin === configuredUrl)
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function detectCommunityQrMediaType(buffer) {
+ if (!Buffer.isBuffer(buffer) || !buffer.length) return '';
+ if (
+ buffer.length >= 8
+ && buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
+ ) return 'image/png';
+ if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
+ return 'image/jpeg';
+ }
+ if (
+ buffer.length >= 12
+ && buffer.subarray(0, 4).toString('ascii') === 'RIFF'
+ && buffer.subarray(8, 12).toString('ascii') === 'WEBP'
+ ) return 'image/webp';
+ return '';
+}
+
+export function validateCommunityQrUpload(buffer, declaredType = '') {
+ if (!Buffer.isBuffer(buffer) || !buffer.length) {
+ return { ok: false, error: 'COMMUNITY_QR_REQUIRED' };
+ }
+ if (buffer.length > COMMUNITY_QR_MAX_BYTES) {
+ return { ok: false, error: 'COMMUNITY_QR_TOO_LARGE' };
+ }
+ const mediaType = detectCommunityQrMediaType(buffer);
+ if (!mediaType) return { ok: false, error: 'COMMUNITY_QR_INVALID_TYPE' };
+ const normalizedDeclaredType = String(declaredType || '').split(';')[0].trim().toLowerCase();
+ if (normalizedDeclaredType && normalizedDeclaredType !== mediaType) {
+ return { ok: false, error: 'COMMUNITY_QR_SIGNATURE_MISMATCH' };
+ }
+ return { ok: true, mediaType, sizeBytes: buffer.length };
+}
+
+export function encodePostgresBytea(buffer) {
+ return `\\x${buffer.toString('hex')}`;
+}
+
+export function decodePostgresBytea(value) {
+ if (Buffer.isBuffer(value)) return value;
+ const text = String(value || '');
+ if (/^\\x[0-9a-f]+$/i.test(text)) return Buffer.from(text.slice(2), 'hex');
+ return Buffer.from(text, 'base64');
+}
+
+export function noStore(res) {
+ res.setHeader('Cache-Control', 'private, no-store, max-age=0');
+ res.setHeader('Pragma', 'no-cache');
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+}
+
+export async function getLatestCommunityOrder(client, userId) {
+ const { data, error } = await client
+ .from('community_orders')
+ .select('*')
+ .eq('user_id', userId)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) throw error;
+ return data || null;
+}
+
+export async function getActiveCommunityOrder(client, userId) {
+ const { data, error } = await client
+ .from('community_orders')
+ .select('*')
+ .eq('user_id', userId)
+ .in('status', ['PENDING', 'PAID'])
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) throw error;
+ return data || null;
+}
+
+export async function getCurrentCommunityQr(client, { includeBytes = false } = {}) {
+ const columns = includeBytes
+ ? 'id,media_type,size_bytes,qr_bytes,created_at'
+ : 'id,media_type,size_bytes,created_at';
+ const { data, error } = await client
+ .from('community_group_qr_assets')
+ .select(columns)
+ .eq('is_current', true)
+ .maybeSingle();
+ if (error) throw error;
+ return data || null;
+}
+
+export async function markCommunityOrderPaid(client, order, result, options = {}) {
+ const validation = validateCommunityTradeResult(order, result);
+ if (!validation.ok || !isPaidTradeStatus(result.trade_status)) {
+ throw new Error(validation.error || 'TRADE_NOT_PAID');
+ }
+ const { data, error } = await client.rpc('mark_community_order_paid', {
+ p_order_id: order.id,
+ p_trade_no: String(result.trade_no),
+ p_paid_amount_cents: validation.amountCents,
+ p_paid_currency: COMMUNITY_CURRENCY,
+ p_notify_id: options.notifyId || null,
+ p_notify_payload: options.notifyPayload || {}
+ });
+ if (error) throw error;
+ return Array.isArray(data) ? data[0] : data;
+}
+
+export async function closeCommunityOrderLocally(client, orderId) {
+ const { data, error } = await client.rpc('close_community_order', { p_order_id: orderId });
+ if (error) throw error;
+ return Array.isArray(data) ? data[0] : data;
+}
diff --git a/api/_lib/community.test.js b/api/_lib/community.test.js
new file mode 100644
index 0000000..6bfdb5c
--- /dev/null
+++ b/api/_lib/community.test.js
@@ -0,0 +1,164 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+import {
+ COMMUNITY_CURRENCY,
+ COMMUNITY_PRICE_CENTS,
+ canAccessCommunityQr,
+ communityOrderPayload,
+ communityRefundRequestNo,
+ detectCommunityQrMediaType,
+ isCommunityAdmin,
+ isCommunityPaymentEnabled,
+ isOrderOwnedBy,
+ shouldExpireCommunityOrder,
+ takeCommunityRateLimit,
+ validateCommunityPaidNotification,
+ validateCommunityQrUpload,
+ validateSameOrigin
+} from './community.js';
+
+const migrationPath = fileURLToPath(new URL(
+ '../../supabase/migrations/20260722090000_paid_community.sql',
+ import.meta.url
+));
+const migration = readFileSync(migrationPath, 'utf8');
+
+function paidNotification(overrides = {}) {
+ return {
+ notify_type: 'trade_status_sync',
+ notify_id: 'notify-1',
+ app_id: 'app-1',
+ seller_id: 'seller-1',
+ out_trade_no: '11111111-1111-4111-8111-111111111111',
+ trade_no: 'trade-1',
+ trade_status: 'TRADE_SUCCESS',
+ total_amount: '9.90',
+ currency: 'CNY',
+ ...overrides
+ };
+}
+
+const order = {
+ id: '11111111-1111-4111-8111-111111111111',
+ user_id: 'user-1',
+ status: 'PENDING',
+ amount_cents: COMMUNITY_PRICE_CENTS,
+ currency: COMMUNITY_CURRENCY
+};
+
+test('community checkout payload keeps the server-owned ¥9.90 CNY price', () => {
+ const payload = communityOrderPayload('user-1', 'terms-v1');
+ assert.equal(payload.amountCents, 990);
+ assert.equal(payload.currency, 'CNY');
+ assert.equal(Object.hasOwn(payload, 'clientAmount'), false);
+});
+
+test('migration enforces one active PENDING or PAID order per user', () => {
+ assert.match(migration, /create unique index if not exists community_orders_one_active_per_user_idx/i);
+ assert.match(migration, /where status in \('PENDING', 'PAID'\)/i);
+ assert.match(migration, /pg_advisory_xact_lock\(hashtext\(p_user_id::text\)\)/i);
+});
+
+test('expired pending orders are identified before replacement', () => {
+ const oldOrder = { status: 'PENDING', created_at: '2026-07-22T00:00:00.000Z' };
+ assert.equal(shouldExpireCommunityOrder(oldOrder, Date.parse('2026-07-22T00:30:00.000Z')), true);
+ assert.equal(shouldExpireCommunityOrder(oldOrder, Date.parse('2026-07-22T00:29:59.000Z')), false);
+ assert.equal(shouldExpireCommunityOrder({ ...oldOrder, status: 'PAID' }, Date.now()), false);
+});
+
+test('community order ownership is bound to the authenticated user', () => {
+ assert.equal(isOrderOwnedBy(order, 'user-1'), true);
+ assert.equal(isOrderOwnedBy(order, 'user-2'), false);
+});
+
+test('paid notification rejects mismatched business fields', () => {
+ const runtime = { appId: 'app-1', sellerId: 'seller-1' };
+ assert.equal(validateCommunityPaidNotification(order, paidNotification(), runtime).ok, true);
+ for (const params of [
+ paidNotification({ app_id: 'wrong' }),
+ paidNotification({ seller_id: 'wrong' }),
+ paidNotification({ out_trade_no: 'wrong' }),
+ paidNotification({ total_amount: '9.91' }),
+ paidNotification({ currency: 'USD' }),
+ paidNotification({ trade_status: 'WAIT_BUYER_PAY' }),
+ paidNotification({ refund_fee: '9.90' })
+ ]) {
+ assert.equal(validateCommunityPaidNotification(order, params, runtime).ok, false);
+ }
+});
+
+test('notification and paid transition are persistently idempotent', () => {
+ assert.match(migration, /notify_id text not null unique/i);
+ assert.match(migration, /on conflict \(notify_id\) do nothing/i);
+ assert.match(migration, /if v_order\.status in \('PAID', 'REFUNDED', 'REVOKED'\)/i);
+});
+
+test('only PAID status can read the protected QR', () => {
+ assert.equal(canAccessCommunityQr('PAID'), true);
+ for (const status of ['PENDING', 'CLOSED', 'REFUNDED', 'REVOKED', null]) {
+ assert.equal(canAccessCommunityQr(status), false);
+ }
+});
+
+test('refund keeps PAID access until final success then revokes it', () => {
+ assert.match(migration, /refund_status\s*=\s*'PROCESSING'/i);
+ assert.match(migration, /set status = 'REFUNDED',[\s\S]*refund_status = 'SUCCEEDED'/i);
+ assert.match(migration, /if v_order\.status <> 'PAID' or v_order\.refund_status <> 'PROCESSING'/i);
+ assert.equal(communityRefundRequestNo(order.id), 'cg_11111111111141118111111111111111');
+});
+
+test('QR replacement uses a transaction lock and one-current-row index', () => {
+ assert.match(migration, /community_group_qr_one_current_idx/i);
+ assert.match(migration, /pg_advisory_xact_lock\(hashtext\('community_group_qr_current'\)\)/i);
+ assert.match(migration, /set is_current = false,[\s\S]*insert into public\.community_group_qr_assets/i);
+});
+
+test('QR uploads validate signatures and size', () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]);
+ const jpg = Buffer.from([0xff, 0xd8, 0xff, 0x00]);
+ const webp = Buffer.from('RIFF0000WEBP', 'ascii');
+ assert.equal(detectCommunityQrMediaType(png), 'image/png');
+ assert.equal(detectCommunityQrMediaType(jpg), 'image/jpeg');
+ assert.equal(detectCommunityQrMediaType(webp), 'image/webp');
+ assert.equal(validateCommunityQrUpload(png, 'image/png').ok, true);
+ assert.equal(validateCommunityQrUpload(png, 'image/jpeg').ok, false);
+ assert.equal(validateCommunityQrUpload(Buffer.alloc(2 * 1024 * 1024 + 1), '').error, 'COMMUNITY_QR_TOO_LARGE');
+});
+
+test('admin operations require super_admin and same-origin writes', () => {
+ assert.equal(isCommunityAdmin({ profile: { role: 'super_admin' } }), true);
+ assert.equal(isCommunityAdmin({ profile: { role: 'user' } }), false);
+ const previousAppUrl = process.env.APP_URL;
+ process.env.APP_URL = 'https://gpt-image2.canghe.ai';
+ try {
+ assert.equal(validateSameOrigin({ headers: { origin: 'https://gpt-image2.canghe.ai', host: 'gpt-image2.canghe.ai' } }), true);
+ assert.equal(validateSameOrigin({ headers: { origin: 'https://evil.example', host: 'gpt-image2.canghe.ai' } }), false);
+ } finally {
+ if (previousAppUrl === undefined) delete process.env.APP_URL;
+ else process.env.APP_URL = previousAppUrl;
+ }
+});
+
+test('payment kill switch defaults closed and changes only on explicit true', () => {
+ assert.equal(isCommunityPaymentEnabled({}), false);
+ assert.equal(isCommunityPaymentEnabled({ COMMUNITY_PAYMENT_ENABLED: 'false' }), false);
+ assert.equal(isCommunityPaymentEnabled({ COMMUNITY_PAYMENT_ENABLED: 'true' }), true);
+});
+
+test('community actions use bounded per-user rate limits', () => {
+ const key = `test-rate-${Date.now()}`;
+ assert.equal(takeCommunityRateLimit(key, { limit: 2, windowMs: 1000, now: 100 }).allowed, true);
+ assert.equal(takeCommunityRateLimit(key, { limit: 2, windowMs: 1000, now: 101 }).allowed, true);
+ const blocked = takeCommunityRateLimit(key, { limit: 2, windowMs: 1000, now: 102 });
+ assert.equal(blocked.allowed, false);
+ assert.equal(blocked.retryAfterSeconds, 1);
+ assert.equal(takeCommunityRateLimit(key, { limit: 2, windowMs: 1000, now: 1100 }).allowed, true);
+});
+
+test('browser roles have no direct table grants for orders or QR bytes', () => {
+ assert.match(migration, /revoke all on table public\.community_orders from public, anon, authenticated/i);
+ assert.match(migration, /revoke all on table public\.community_group_qr_assets from public, anon, authenticated/i);
+ assert.match(migration, /grant execute on function public\.replace_community_group_qr_asset[\s\S]*to service_role/i);
+});
diff --git a/api/admin/community/orders.js b/api/admin/community/orders.js
new file mode 100644
index 0000000..e1077cf
--- /dev/null
+++ b/api/admin/community/orders.js
@@ -0,0 +1,69 @@
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ isCommunityAdmin,
+ noStore,
+ serializeCommunityOrder,
+ takeCommunityRateLimit
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!isCommunityAdmin(auth)) return res.status(403).json({ ok: false, error: 'FORBIDDEN' });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-admin-orders', auth.user.id)
+ ))) return;
+
+ const status = String(req.query?.status || '').trim().toUpperCase();
+ const limit = Math.min(100, Math.max(1, Number(req.query?.limit || 50)));
+ try {
+ let query = auth.client
+ .from('community_orders')
+ .select('id,user_id,status,amount_cents,currency,alipay_trade_no,refund_request_no,refund_status,refund_failure_code,created_at,paid_at,refund_requested_at,refund_checked_at,refunded_at,revoked_at')
+ .order('created_at', { ascending: false })
+ .limit(limit);
+ if (status) query = query.eq('status', status);
+ const { data: rows, error } = await query;
+ if (error) throw error;
+
+ const userIds = [...new Set((rows || []).map((row) => row.user_id))];
+ let profiles = [];
+ if (userIds.length) {
+ const result = await auth.client
+ .from('profiles')
+ .select('id,email,full_name')
+ .in('id', userIds);
+ if (result.error) throw result.error;
+ profiles = result.data || [];
+ }
+ const profilesById = new Map(profiles.map((profile) => [profile.id, profile]));
+
+ return res.status(200).json({
+ ok: true,
+ orders: (rows || []).map((row) => ({
+ ...serializeCommunityOrder(row),
+ userId: row.user_id,
+ email: profilesById.get(row.user_id)?.email || '',
+ fullName: profilesById.get(row.user_id)?.full_name || '',
+ alipayTradeNo: row.alipay_trade_no || '',
+ refundRequestNo: row.refund_request_no || '',
+ refundFailureCode: row.refund_failure_code || '',
+ refundRequestedAt: row.refund_requested_at || '',
+ refundCheckedAt: row.refund_checked_at || ''
+ }))
+ });
+ } catch (error) {
+ console.warn('Failed to load paid community admin orders', {
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_ADMIN_ORDERS_FAILED' });
+ }
+}
diff --git a/api/admin/community/qr.js b/api/admin/community/qr.js
new file mode 100644
index 0000000..ee61404
--- /dev/null
+++ b/api/admin/community/qr.js
@@ -0,0 +1,106 @@
+import { readRawBody } from '../../_lib/billing.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ decodePostgresBytea,
+ encodePostgresBytea,
+ getCurrentCommunityQr,
+ isCommunityAdmin,
+ noStore,
+ takeCommunityRateLimit,
+ validateCommunityQrUpload,
+ validateSameOrigin
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export const config = {
+ api: { bodyParser: false }
+};
+
+export default async function handler(req, res) {
+ if (!['GET', 'POST'].includes(req.method)) {
+ res.setHeader('Allow', 'GET, POST');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!isCommunityAdmin(auth)) return res.status(403).json({ ok: false, error: 'FORBIDDEN' });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-admin-qr', auth.user.id),
+ { limit: req.method === 'POST' ? 10 : 60 }
+ ))) return;
+
+ if (req.method === 'GET') {
+ try {
+ const asset = await getCurrentCommunityQr(auth.client, {
+ includeBytes: req.query?.metadata !== '1'
+ });
+ if (!asset) return res.status(404).json({ ok: false, error: 'COMMUNITY_QR_NOT_READY' });
+ if (req.query?.metadata === '1') {
+ return res.status(200).json({
+ ok: true,
+ asset: {
+ id: asset.id,
+ mediaType: asset.media_type,
+ sizeBytes: Number(asset.size_bytes),
+ createdAt: asset.created_at
+ }
+ });
+ }
+
+ const bytes = decodePostgresBytea(asset.qr_bytes);
+ res.setHeader('Content-Type', asset.media_type);
+ res.setHeader('Content-Length', String(bytes.length));
+ return res.status(200).send(bytes);
+ } catch (error) {
+ console.warn('Failed to load paid community QR for admin', {
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_QR_FAILED' });
+ }
+ }
+
+ if (!validateSameOrigin(req)) {
+ return res.status(403).json({ ok: false, error: 'ORIGIN_NOT_ALLOWED' });
+ }
+ const contentLength = Number(req.headers['content-length'] || 0);
+ if (contentLength > 2 * 1024 * 1024) {
+ return res.status(413).json({ ok: false, error: 'COMMUNITY_QR_TOO_LARGE' });
+ }
+
+ try {
+ const bytes = await readRawBody(req);
+ const validation = validateCommunityQrUpload(bytes, req.headers['content-type']);
+ if (!validation.ok) {
+ return res.status(validation.error === 'COMMUNITY_QR_TOO_LARGE' ? 413 : 400).json({
+ ok: false,
+ error: validation.error
+ });
+ }
+
+ const { data, error } = await auth.client.rpc('replace_community_group_qr_asset', {
+ p_media_type: validation.mediaType,
+ p_qr_bytes: encodePostgresBytea(bytes),
+ p_uploaded_by: auth.user.id
+ });
+ if (error) throw error;
+ const asset = Array.isArray(data) ? data[0] : data;
+ return res.status(200).json({
+ ok: true,
+ asset: {
+ id: asset.id,
+ mediaType: asset.media_type,
+ sizeBytes: Number(asset.size_bytes),
+ createdAt: asset.created_at
+ }
+ });
+ } catch (error) {
+ console.warn('Failed to replace paid community QR', {
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_QR_UPLOAD_FAILED' });
+ }
+}
diff --git a/api/admin/community/refund-query.js b/api/admin/community/refund-query.js
new file mode 100644
index 0000000..6479873
--- /dev/null
+++ b/api/admin/community/refund-query.js
@@ -0,0 +1,118 @@
+import { getAlipayClient, parseAlipayAmount } from '../../_lib/alipay.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ isCommunityAdmin,
+ isUuid,
+ noStore,
+ takeCommunityRateLimit
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!isCommunityAdmin(auth)) return res.status(403).json({ ok: false, error: 'FORBIDDEN' });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-admin-refund-query', auth.user.id),
+ { limit: 30 }
+ ))) return;
+
+ const orderId = String(req.query?.orderId || '').trim();
+ if (!isUuid(orderId)) return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+
+ try {
+ const { data: order, error } = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', orderId)
+ .maybeSingle();
+ if (error) throw error;
+ if (!order) return res.status(404).json({ ok: false, error: 'COMMUNITY_ORDER_NOT_FOUND' });
+ if (order.status === 'REFUNDED') {
+ return res.status(200).json({ ok: true, refunded: true, refundStatus: 'SUCCEEDED' });
+ }
+ if (!order.refund_request_no || order.refund_status === 'NONE') {
+ return res.status(409).json({ ok: false, error: 'COMMUNITY_REFUND_NOT_PREPARED' });
+ }
+
+ const requestedAt = Date.parse(order.refund_requested_at || '');
+ const ageMs = Date.now() - requestedAt;
+ if (!Number.isFinite(requestedAt) || ageMs < 10_000) {
+ return res.status(409).json({
+ ok: false,
+ error: 'COMMUNITY_REFUND_QUERY_TOO_EARLY',
+ retryAfterSeconds: Math.max(1, Math.ceil((10_000 - Math.max(0, ageMs)) / 1000))
+ });
+ }
+
+ const { sdk } = getAlipayClient();
+ const queryResult = await sdk.exec('alipay.trade.fastpay.refund.query', {
+ bizContent: {
+ out_trade_no: order.id,
+ out_request_no: order.refund_request_no
+ }
+ }, { validateSign: true });
+
+ if (String(queryResult?.code || '') !== '10000') {
+ const { error: stateError } = await auth.client.rpc('set_community_refund_state', {
+ p_order_id: order.id,
+ p_refund_status: 'PROCESSING',
+ p_failure_code: String(queryResult?.sub_code || queryResult?.code || 'UNKNOWN')
+ });
+ if (stateError) throw stateError;
+ return res.status(200).json({
+ ok: true,
+ refunded: false,
+ refundStatus: 'PROCESSING',
+ queryCode: String(queryResult?.sub_code || queryResult?.code || 'UNKNOWN')
+ });
+ }
+
+ const refundAmountCents = parseAlipayAmount(queryResult.refund_amount);
+ const tradeNo = String(queryResult.trade_no || order.alipay_trade_no || '');
+ const matches = queryResult.out_trade_no === order.id
+ && queryResult.out_request_no === order.refund_request_no
+ && tradeNo === order.alipay_trade_no
+ && refundAmountCents === Number(order.amount_cents);
+ if (!matches) {
+ return res.status(409).json({ ok: false, error: 'COMMUNITY_REFUND_RESULT_MISMATCH' });
+ }
+
+ const refunded = queryResult.refund_status === 'REFUND_SUCCESS';
+ if (refunded) {
+ const finalization = await auth.client.rpc('finalize_community_refund', {
+ p_order_id: order.id,
+ p_trade_no: tradeNo,
+ p_refund_request_no: order.refund_request_no,
+ p_refund_amount_cents: refundAmountCents
+ });
+ if (finalization.error) throw finalization.error;
+ } else {
+ const state = await auth.client.rpc('set_community_refund_state', {
+ p_order_id: order.id,
+ p_refund_status: 'PROCESSING',
+ p_failure_code: null
+ });
+ if (state.error) throw state.error;
+ }
+
+ return res.status(200).json({
+ ok: true,
+ refunded,
+ refundStatus: refunded ? 'SUCCEEDED' : 'PROCESSING'
+ });
+ } catch (error) {
+ console.warn('Failed to query paid community refund', {
+ orderId,
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_REFUND_QUERY_FAILED' });
+ }
+}
diff --git a/api/admin/community/refund.js b/api/admin/community/refund.js
new file mode 100644
index 0000000..83fdd35
--- /dev/null
+++ b/api/admin/community/refund.js
@@ -0,0 +1,143 @@
+import {
+ formatAlipayAmount,
+ getAlipayClient,
+ parseAlipayAmount
+} from '../../_lib/alipay.js';
+import { readJsonBody } from '../../_lib/billing.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ communityRefundRequestNo,
+ isCommunityAdmin,
+ isUuid,
+ noStore,
+ takeCommunityRateLimit,
+ validateSameOrigin
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+async function setRefundState(client, orderId, status, failureCode = null) {
+ const { error } = await client.rpc('set_community_refund_state', {
+ p_order_id: orderId,
+ p_refund_status: status,
+ p_failure_code: failureCode
+ });
+ if (error) throw error;
+}
+
+async function finalizeRefund(client, order, requestNo, result) {
+ const refundAmount = parseAlipayAmount(result.refund_fee || result.refund_amount);
+ const tradeNo = String(result.trade_no || order.alipay_trade_no || '');
+ if ((result.out_trade_no && result.out_trade_no !== order.id)
+ || tradeNo !== order.alipay_trade_no
+ || refundAmount !== Number(order.amount_cents)) {
+ throw new Error('COMMUNITY_REFUND_RESULT_MISMATCH');
+ }
+ const { error } = await client.rpc('finalize_community_refund', {
+ p_order_id: order.id,
+ p_trade_no: tradeNo,
+ p_refund_request_no: requestNo,
+ p_refund_amount_cents: refundAmount
+ });
+ if (error) throw error;
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ if (!validateSameOrigin(req)) {
+ return res.status(403).json({ ok: false, error: 'ORIGIN_NOT_ALLOWED' });
+ }
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!isCommunityAdmin(auth)) return res.status(403).json({ ok: false, error: 'FORBIDDEN' });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-admin-refund', auth.user.id),
+ { limit: 10 }
+ ))) return;
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+ }
+ const orderId = String(body.orderId || '').trim();
+ if (!isUuid(orderId)) return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+
+ let order;
+ let requestNo;
+ try {
+ const result = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', orderId)
+ .maybeSingle();
+ if (result.error) throw result.error;
+ order = result.data;
+ if (!order) return res.status(404).json({ ok: false, error: 'COMMUNITY_ORDER_NOT_FOUND' });
+ if (order.status === 'REFUNDED') {
+ return res.status(200).json({ ok: true, refunded: true, refundStatus: 'SUCCEEDED' });
+ }
+
+ requestNo = order.refund_request_no || communityRefundRequestNo(order.id);
+ const preparation = await auth.client.rpc('prepare_community_refund', {
+ p_order_id: order.id,
+ p_refund_request_no: requestNo
+ });
+ if (preparation.error) throw preparation.error;
+
+ const { sdk } = getAlipayClient();
+ const refundResult = await sdk.exec('alipay.trade.refund', {
+ bizContent: {
+ out_trade_no: order.id,
+ refund_amount: formatAlipayAmount(order.amount_cents),
+ refund_reason: '付费交流群人工审核退款',
+ out_request_no: requestNo
+ }
+ }, { validateSign: true });
+
+ const accepted = String(refundResult?.code || '') === '10000';
+ if (!accepted) {
+ await setRefundState(
+ auth.client,
+ order.id,
+ 'FAILED',
+ String(refundResult?.sub_code || refundResult?.code || 'UNKNOWN')
+ );
+ return res.status(502).json({
+ ok: false,
+ error: 'COMMUNITY_REFUND_REQUEST_FAILED',
+ refundStatus: 'FAILED'
+ });
+ }
+
+ if (refundResult.fund_change === 'Y') {
+ await finalizeRefund(auth.client, order, requestNo, refundResult);
+ return res.status(200).json({ ok: true, refunded: true, refundStatus: 'SUCCEEDED' });
+ }
+
+ await setRefundState(auth.client, order.id, 'PROCESSING');
+ return res.status(200).json({
+ ok: true,
+ refunded: false,
+ refundStatus: 'PROCESSING',
+ queryRequired: true
+ });
+ } catch (error) {
+ console.warn('Failed to request paid community refund', {
+ orderId,
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({
+ ok: false,
+ error: 'COMMUNITY_REFUND_FAILED',
+ refundStatus: requestNo ? 'PROCESSING' : 'NONE',
+ queryRequired: Boolean(requestNo)
+ });
+ }
+}
diff --git a/api/admin/community/revoke.js b/api/admin/community/revoke.js
new file mode 100644
index 0000000..a4c5fb3
--- /dev/null
+++ b/api/admin/community/revoke.js
@@ -0,0 +1,63 @@
+import { readJsonBody } from '../../_lib/billing.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ isCommunityAdmin,
+ isUuid,
+ noStore,
+ takeCommunityRateLimit,
+ validateSameOrigin
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ if (!validateSameOrigin(req)) {
+ return res.status(403).json({ ok: false, error: 'ORIGIN_NOT_ALLOWED' });
+ }
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!isCommunityAdmin(auth)) return res.status(403).json({ ok: false, error: 'FORBIDDEN' });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-admin-revoke', auth.user.id),
+ { limit: 10 }
+ ))) return;
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+ }
+ const orderId = String(body.orderId || '').trim();
+ if (!isUuid(orderId)) return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+
+ try {
+ const { data, error } = await auth.client.rpc('revoke_community_access', {
+ p_order_id: orderId
+ });
+ if (error) {
+ if (String(error.message || '').includes('COMMUNITY_ORDER_NOT_REVOKABLE')) {
+ return res.status(409).json({ ok: false, error: 'COMMUNITY_ORDER_NOT_REVOKABLE' });
+ }
+ throw error;
+ }
+ const result = Array.isArray(data) ? data[0] : data;
+ return res.status(200).json({
+ ok: true,
+ status: result?.current_status || 'REVOKED',
+ transitioned: Boolean(result?.transitioned)
+ });
+ } catch (error) {
+ console.warn('Failed to revoke paid community access', {
+ orderId,
+ adminUserId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_REVOKE_FAILED' });
+ }
+}
diff --git a/api/billing/alipay/checkout.js b/api/billing/alipay/checkout.js
new file mode 100644
index 0000000..08b4f22
--- /dev/null
+++ b/api/billing/alipay/checkout.js
@@ -0,0 +1,129 @@
+import { getAuthContext, getProfileById, isSupabaseServerConfigured } from '../../_lib/supabase.js';
+import {
+ createPaymentOrder,
+ getAppUrl,
+ getBillingProduct,
+ readJsonBody
+} from '../../_lib/billing.js';
+import {
+ formatAlipayAmount,
+ getAlipayClient,
+ getAlipayNotifyUrl,
+ isAlipayConfigured,
+ normalizeAlipaySubject
+} from '../../_lib/alipay.js';
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ if (!isSupabaseServerConfigured()) {
+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ if (!isAlipayConfigured()) {
+ return json(res, 500, { ok: false, error: 'ALIPAY_NOT_CONFIGURED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return json(res, auth.status || 401, {
+ ok: false,
+ error: auth.error,
+ loginRequired: auth.error === 'AUTH_REQUIRED'
+ });
+ }
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_BILLING_PRODUCT' });
+ }
+
+ const productType = body.productType === 'creditPack' ? 'credit_pack' : body.productType;
+ const productId = String(body.productId || '').trim();
+ if (productType !== 'credit_pack' || !productId) {
+ return json(res, 400, { ok: false, error: 'ALIPAY_CREDIT_PACKS_ONLY' });
+ }
+
+ try {
+ const product = await getBillingProduct(auth.client, productType, productId);
+ if (!product) {
+ return json(res, 404, { ok: false, error: 'BILLING_PRODUCT_NOT_FOUND' });
+ }
+ if (!product.alipayAvailable || product.alipayAmountCents <= 0) {
+ return json(res, 400, { ok: false, error: 'ALIPAY_PRICE_NOT_CONFIGURED' });
+ }
+
+ const alipayProduct = {
+ ...product,
+ amountCents: product.alipayAmountCents,
+ currency: 'cny'
+ };
+ const order = await createPaymentOrder(auth.client, {
+ userId: auth.user.id,
+ product: alipayProduct,
+ paymentProvider: 'alipay'
+ });
+
+ const appUrl = getAppUrl(req);
+ const returnUrl = `${appUrl}/?billing=alipay_return&order_id=${encodeURIComponent(order.id)}`;
+ const notifyUrl = getAlipayNotifyUrl(appUrl);
+ const { sdk } = getAlipayClient();
+ const request = {
+ returnUrl,
+ bizContent: {
+ out_trade_no: order.id,
+ total_amount: formatAlipayAmount(order.amount_cents),
+ subject: normalizeAlipaySubject(product.name.zh || product.name.en),
+ product_code: 'FAST_INSTANT_TRADE_PAY',
+ timeout_express: '30m'
+ }
+ };
+ if (notifyUrl) request.notifyUrl = notifyUrl;
+
+ const paymentHtml = sdk.pageExec('alipay.trade.page.pay', 'POST', request);
+ if (typeof paymentHtml !== 'string' || !paymentHtml.includes('<form')) {
+ throw new Error('ALIPAY_PAYMENT_FORM_INVALID');
+ }
+
+ const { data: updatedOrder, error: updateError } = await auth.client
+ .from('payment_orders')
+ .update({
+ status: 'checkout_created',
+ metadata: {
+ ...(order.metadata || {}),
+ paymentProvider: 'alipay',
+ notifyEnabled: Boolean(notifyUrl),
+ returnUrl
+ }
+ })
+ .eq('id', order.id)
+ .eq('user_id', auth.user.id)
+ .select('*')
+ .single();
+
+ if (updateError) throw updateError;
+
+ return json(res, 200, {
+ ok: true,
+ paymentHtml,
+ orderId: updatedOrder.id,
+ returnUrl,
+ user: await getProfileById(auth.user.id)
+ });
+ } catch (error) {
+ console.warn('Failed to create Alipay checkout', {
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'ALIPAY_CHECKOUT_FAILED' });
+ }
+}
diff --git a/api/billing/alipay/close.js b/api/billing/alipay/close.js
new file mode 100644
index 0000000..3074d61
--- /dev/null
+++ b/api/billing/alipay/close.js
@@ -0,0 +1,79 @@
+import { getAuthContext } from '../../_lib/supabase.js';
+import { readJsonBody } from '../../_lib/billing.js';
+import { getAlipayClient } from '../../_lib/alipay.js';
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) return json(res, auth.status || 401, { ok: false, error: auth.error });
+ if (!auth.profile?.isSuperAdmin) {
+ return json(res, 403, { ok: false, error: 'FORBIDDEN' });
+ }
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ const orderId = String(body.orderId || body.order_id || '').trim();
+ if (!UUID_PATTERN.test(orderId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ try {
+ const { data: order, error: orderError } = await auth.client
+ .from('payment_orders')
+ .select('*')
+ .eq('id', orderId)
+ .eq('payment_provider', 'alipay')
+ .maybeSingle();
+ if (orderError) throw orderError;
+ if (!order) return json(res, 404, { ok: false, error: 'PAYMENT_ORDER_NOT_FOUND' });
+ if (order.status === 'canceled') {
+ return json(res, 200, { ok: true, closed: true, orderId });
+ }
+ if (!['created', 'checkout_created'].includes(order.status)) {
+ return json(res, 409, { ok: false, error: 'ALIPAY_ORDER_NOT_CLOSABLE' });
+ }
+
+ const { sdk } = getAlipayClient();
+ const result = await sdk.exec('alipay.trade.close', {
+ bizContent: { out_trade_no: order.id }
+ }, { validateSign: true });
+
+ if (String(result?.code || '') !== '10000') {
+ return json(res, 502, {
+ ok: false,
+ closed: false,
+ error: 'ALIPAY_CLOSE_FAILED',
+ queryCode: String(result?.sub_code || result?.code || '')
+ });
+ }
+
+ const { error: updateError } = await auth.client
+ .from('payment_orders')
+ .update({ status: 'canceled' })
+ .eq('id', order.id)
+ .in('status', ['created', 'checkout_created']);
+ if (updateError) throw updateError;
+
+ return json(res, 200, { ok: true, closed: true, orderId });
+ } catch (error) {
+ console.warn('Failed to close Alipay order', {
+ orderId,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'ALIPAY_CLOSE_FAILED' });
+ }
+}
diff --git a/api/billing/alipay/notify.js b/api/billing/alipay/notify.js
new file mode 100644
index 0000000..4ebff03
--- /dev/null
+++ b/api/billing/alipay/notify.js
@@ -0,0 +1,109 @@
+import { getSupabaseAdminClient, isSupabaseServerConfigured } from '../../_lib/supabase.js';
+import { readRawBody } from '../../_lib/billing.js';
+import {
+ completeAlipayCreditPackOrder,
+ getAlipayClient,
+ isAlipayPaidNotification,
+ parseAlipayFormBody,
+ sanitizeAlipayNotifyParams,
+ validateAlipayOrderResult
+} from '../../_lib/alipay.js';
+
+export const config = {
+ api: {
+ bodyParser: false
+ }
+};
+
+function text(res, status, value) {
+ res.status(status).setHeader('Content-Type', 'text/plain; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-store');
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.send(value);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return text(res, 405, 'fail');
+ }
+
+ if (!isSupabaseServerConfigured()) {
+ return text(res, 500, 'fail');
+ }
+
+ let safeParams = {};
+ try {
+ const contentLength = Number(req.headers['content-length'] || 0);
+ if (contentLength > 128 * 1024) return text(res, 413, 'fail');
+
+ const rawBody = await readRawBody(req);
+ if (!rawBody.length || rawBody.length > 128 * 1024) return text(res, 400, 'fail');
+
+ const params = parseAlipayFormBody(rawBody);
+ safeParams = sanitizeAlipayNotifyParams(params);
+ const { sdk, appId, sellerId } = getAlipayClient();
+ if (!sdk.checkNotifySignV2(params)) return text(res, 400, 'fail');
+ if (params.sign_type !== 'RSA2') return text(res, 400, 'fail');
+ if (params.notify_type !== 'trade_status_sync') return text(res, 400, 'fail');
+ if (params.app_id !== appId || params.seller_id !== sellerId) return text(res, 400, 'fail');
+ if (!String(params.notify_id || '').trim() || !String(params.trade_no || '').trim()) {
+ return text(res, 400, 'fail');
+ }
+
+ const client = getSupabaseAdminClient();
+ const { data: order, error: orderError } = await client
+ .from('payment_orders')
+ .select('*')
+ .eq('id', params.out_trade_no)
+ .eq('payment_provider', 'alipay')
+ .maybeSingle();
+
+ if (orderError || !order) return text(res, 400, 'fail');
+ if (!validateAlipayOrderResult(order, params)) return text(res, 400, 'fail');
+
+ if (isAlipayPaidNotification(params)) {
+ await completeAlipayCreditPackOrder(client, order, params, {
+ notifyId: params.notify_id,
+ notifyPayload: safeParams
+ });
+ } else if (params.trade_status === 'TRADE_CLOSED' && order.status !== 'completed') {
+ const { error: eventError } = await client
+ .from('alipay_notify_events')
+ .upsert({
+ order_id: order.id,
+ notify_id: params.notify_id,
+ trade_no: params.trade_no,
+ trade_status: params.trade_status,
+ payload: safeParams
+ }, { onConflict: 'notify_id', ignoreDuplicates: true });
+ if (eventError) throw eventError;
+
+ const { error: updateError } = await client
+ .from('payment_orders')
+ .update({ status: 'canceled' })
+ .eq('id', order.id)
+ .neq('status', 'completed');
+ if (updateError) throw updateError;
+ } else {
+ const { error: eventError } = await client
+ .from('alipay_notify_events')
+ .upsert({
+ order_id: order.id,
+ notify_id: params.notify_id,
+ trade_no: params.trade_no,
+ trade_status: params.trade_status || 'UNKNOWN',
+ payload: safeParams
+ }, { onConflict: 'notify_id', ignoreDuplicates: true });
+ if (eventError) throw eventError;
+ }
+
+ return text(res, 200, 'success');
+ } catch (error) {
+ console.warn('Failed to process Alipay notification', {
+ orderId: String(safeParams.out_trade_no || '').slice(0, 64),
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return text(res, 500, 'fail');
+ }
+}
diff --git a/api/billing/alipay/query.js b/api/billing/alipay/query.js
new file mode 100644
index 0000000..13dcfd0
--- /dev/null
+++ b/api/billing/alipay/query.js
@@ -0,0 +1,98 @@
+import { getAuthContext, getProfileById } from '../../_lib/supabase.js';
+import {
+ completeAlipayCreditPackOrder,
+ getAlipayClient,
+ isAlipayTradePaid,
+ validateAlipayOrderResult
+} from '../../_lib/alipay.js';
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return json(res, auth.status || 401, {
+ ok: false,
+ error: auth.error,
+ loginRequired: auth.error === 'AUTH_REQUIRED'
+ });
+ }
+
+ const orderId = String(req.query?.orderId || req.query?.order_id || '').trim();
+ if (!UUID_PATTERN.test(orderId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ try {
+ const { data: order, error: orderError } = await auth.client
+ .from('payment_orders')
+ .select('*')
+ .eq('id', orderId)
+ .eq('user_id', auth.user.id)
+ .eq('payment_provider', 'alipay')
+ .maybeSingle();
+
+ if (orderError) throw orderError;
+ if (!order) {
+ return json(res, 404, { ok: false, error: 'PAYMENT_ORDER_NOT_FOUND' });
+ }
+
+ const { sdk } = getAlipayClient();
+ const result = await sdk.exec('alipay.trade.query', {
+ bizContent: { out_trade_no: order.id }
+ }, { validateSign: true });
+
+ if (String(result?.code || '') !== '10000') {
+ return json(res, 200, {
+ ok: true,
+ paid: false,
+ orderId: order.id,
+ orderStatus: order.status,
+ tradeStatus: '',
+ queryCode: String(result?.sub_code || result?.code || '')
+ });
+ }
+
+ if (!validateAlipayOrderResult(order, result)) {
+ return json(res, 409, { ok: false, error: 'ALIPAY_PAYMENT_RESULT_MISMATCH' });
+ }
+
+ const paid = isAlipayTradePaid(result.trade_status);
+ if (paid) {
+ await completeAlipayCreditPackOrder(auth.client, order, result);
+ } else if (result.trade_status === 'TRADE_CLOSED' && order.status !== 'completed') {
+ const { error: updateError } = await auth.client
+ .from('payment_orders')
+ .update({ status: 'canceled' })
+ .eq('id', order.id)
+ .neq('status', 'completed');
+ if (updateError) throw updateError;
+ }
+
+ return json(res, 200, {
+ ok: true,
+ paid,
+ orderId: order.id,
+ orderStatus: paid ? 'completed' : order.status,
+ tradeStatus: String(result.trade_status || ''),
+ totalAmount: String(result.total_amount || ''),
+ user: paid ? await getProfileById(auth.user.id) : auth.profile
+ });
+ } catch (error) {
+ console.warn('Failed to query Alipay order', {
+ orderId,
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'ALIPAY_QUERY_FAILED' });
+ }
+}
diff --git a/api/billing/alipay/refund-query.js b/api/billing/alipay/refund-query.js
new file mode 100644
index 0000000..bbac686
--- /dev/null
+++ b/api/billing/alipay/refund-query.js
@@ -0,0 +1,89 @@
+import { getAuthContext } from '../../_lib/supabase.js';
+import {
+ finalizeAlipayRefund,
+ getAlipayClient,
+ parseAlipayAmount
+} from '../../_lib/alipay.js';
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) return json(res, auth.status || 401, { ok: false, error: auth.error });
+ if (!auth.profile?.isSuperAdmin) {
+ return json(res, 403, { ok: false, error: 'FORBIDDEN' });
+ }
+
+ const orderId = String(req.query?.orderId || req.query?.order_id || '').trim();
+ if (!UUID_PATTERN.test(orderId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ try {
+ const { data: order, error: orderError } = await auth.client
+ .from('payment_orders')
+ .select('*')
+ .eq('id', orderId)
+ .eq('payment_provider', 'alipay')
+ .maybeSingle();
+ if (orderError) throw orderError;
+ if (!order) return json(res, 404, { ok: false, error: 'PAYMENT_ORDER_NOT_FOUND' });
+ if (!order.provider_refund_request_no) {
+ return json(res, 409, { ok: false, error: 'ALIPAY_REFUND_NOT_PREPARED' });
+ }
+
+ const { sdk } = getAlipayClient();
+ const result = await sdk.exec('alipay.trade.fastpay.refund.query', {
+ bizContent: {
+ out_trade_no: order.id,
+ out_request_no: order.provider_refund_request_no
+ }
+ }, { validateSign: true });
+
+ if (String(result?.code || '') !== '10000') {
+ return json(res, 200, {
+ ok: true,
+ refunded: order.status === 'refunded',
+ refundStatus: order.status,
+ queryCode: String(result?.sub_code || result?.code || '')
+ });
+ }
+
+ const identifiersMatch = result.out_trade_no === order.id
+ && result.out_request_no === order.provider_refund_request_no;
+ const refundAmountCents = parseAlipayAmount(result.refund_amount);
+ if (!identifiersMatch || (refundAmountCents !== null && refundAmountCents !== Number(order.amount_cents))) {
+ return json(res, 409, { ok: false, error: 'ALIPAY_REFUND_RESULT_MISMATCH' });
+ }
+
+ const refunded = result.refund_status === 'REFUND_SUCCESS';
+ if (refunded) {
+ await finalizeAlipayRefund(auth.client, order.id, {
+ ...result,
+ trade_no: result.trade_no || order.provider_trade_no,
+ refund_amount: result.refund_amount
+ });
+ }
+
+ return json(res, 200, {
+ ok: true,
+ refunded,
+ refundStatus: refunded ? 'refunded' : 'refund_pending',
+ orderId: order.id
+ });
+ } catch (error) {
+ console.warn('Failed to query Alipay refund', {
+ orderId,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'ALIPAY_REFUND_QUERY_FAILED' });
+ }
+}
diff --git a/api/billing/alipay/refund.js b/api/billing/alipay/refund.js
new file mode 100644
index 0000000..f55fae0
--- /dev/null
+++ b/api/billing/alipay/refund.js
@@ -0,0 +1,97 @@
+import { getAuthContext } from '../../_lib/supabase.js';
+import { readJsonBody } from '../../_lib/billing.js';
+import {
+ finalizeAlipayRefund,
+ formatAlipayAmount,
+ getAlipayClient
+} from '../../_lib/alipay.js';
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+function refundRequestNo(orderId) {
+ return `refund_${orderId.replace(/-/g, '')}`;
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) return json(res, auth.status || 401, { ok: false, error: auth.error });
+ if (!auth.profile?.isSuperAdmin) {
+ return json(res, 403, { ok: false, error: 'FORBIDDEN' });
+ }
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ const orderId = String(body.orderId || body.order_id || '').trim();
+ if (!UUID_PATTERN.test(orderId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_PAYMENT_ORDER' });
+ }
+
+ try {
+ const requestNo = refundRequestNo(orderId);
+ const { data: prepared, error: prepareError } = await auth.client.rpc(
+ 'prepare_alipay_credit_pack_refund',
+ {
+ p_order_id: orderId,
+ p_refund_request_no: requestNo
+ }
+ );
+ if (prepareError) {
+ const message = String(prepareError.message || '');
+ if (message.includes('PURCHASED_CREDITS_ALREADY_USED')) {
+ return json(res, 409, { ok: false, error: 'PURCHASED_CREDITS_ALREADY_USED' });
+ }
+ throw prepareError;
+ }
+
+ const preparation = Array.isArray(prepared) ? prepared[0] : prepared;
+ const refundAmountCents = Number(preparation?.refund_amount_cents || 0);
+ const { sdk } = getAlipayClient();
+ const result = await sdk.exec('alipay.trade.refund', {
+ bizContent: {
+ out_trade_no: orderId,
+ refund_amount: formatAlipayAmount(refundAmountCents),
+ refund_reason: '管理员全额退款',
+ out_request_no: requestNo
+ }
+ }, { validateSign: true });
+
+ const requestAccepted = String(result?.code || '') === '10000';
+ const refunded = requestAccepted && result?.fund_change === 'Y';
+ if (refunded) {
+ await finalizeAlipayRefund(auth.client, orderId, result);
+ }
+
+ return json(res, requestAccepted ? 200 : 502, {
+ ok: requestAccepted,
+ orderId,
+ refundRequestNo: requestNo,
+ refundStatus: refunded ? 'refunded' : 'refund_pending',
+ queryRequired: !refunded,
+ error: requestAccepted ? undefined : 'ALIPAY_REFUND_REQUEST_FAILED'
+ });
+ } catch (error) {
+ console.warn('Failed to request Alipay refund', {
+ orderId,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, {
+ ok: false,
+ error: 'ALIPAY_REFUND_FAILED',
+ refundStatus: 'refund_pending',
+ queryRequired: true
+ });
+ }
+}
diff --git a/api/billing/plans.js b/api/billing/plans.js
index cf8ff18..e6de01d 100644
--- a/api/billing/plans.js
+++ b/api/billing/plans.js
@@ -1,5 +1,6 @@
import { getAuthContext, getProfileById, isSupabaseServerConfigured } from '../_lib/supabase.js';
import { getBillingCatalog, isStripeConfigured } from '../_lib/billing.js';
+import { isAlipayConfigured } from '../_lib/alipay.js';
function json(res, status, payload) {
res.status(status).json(payload);
@@ -23,9 +24,16 @@ export default async function handler(req, res) {
try {
const catalog = await getBillingCatalog(auth.client);
const user = auth.user ? await getProfileById(auth.user.id) : null;
+ const alipayCheckoutAvailable = isAlipayConfigured()
+ && catalog.packs.some((pack) => pack.alipayAvailable);
+ const checkoutProviders = {
+ stripe: isStripeConfigured(),
+ alipay: alipayCheckoutAvailable
+ };
return json(res, 200, {
ok: true,
- checkoutAvailable: isStripeConfigured(),
+ checkoutAvailable: checkoutProviders.stripe || checkoutProviders.alipay,
+ checkoutProviders,
...catalog,
user
});
diff --git a/api/community/alipay/checkout.js b/api/community/alipay/checkout.js
new file mode 100644
index 0000000..337b756
--- /dev/null
+++ b/api/community/alipay/checkout.js
@@ -0,0 +1,170 @@
+import {
+ formatAlipayAmount,
+ getAlipayClient,
+ getCommunityAlipayNotifyUrl,
+ isAlipayConfigured,
+ normalizeAlipaySubject
+} from '../../_lib/alipay.js';
+import { getAppUrl, readJsonBody } from '../../_lib/billing.js';
+import { closeCommunityOrderAtAlipay } from '../../_lib/community-alipay.js';
+import {
+ COMMUNITY_CURRENCY,
+ COMMUNITY_PRICE_CENTS,
+ COMMUNITY_SUBJECT,
+ COMMUNITY_TERMS_VERSION,
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ communityPublicConfig,
+ getActiveCommunityOrder,
+ isCommunityPaymentEnabled,
+ noStore,
+ serializeCommunityOrder,
+ shouldExpireCommunityOrder,
+ takeCommunityRateLimit,
+ validateSameOrigin
+} from '../../_lib/community.js';
+import { getAuthContext, isSupabaseServerConfigured } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+
+ if (!validateSameOrigin(req)) {
+ return res.status(403).json({ ok: false, error: 'ORIGIN_NOT_ALLOWED' });
+ }
+ if (!isSupabaseServerConfigured()) {
+ return res.status(500).json({ ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return res.status(auth.status || 401).json({
+ ok: false,
+ error: auth.error,
+ loginRequired: auth.error === 'AUTH_REQUIRED'
+ });
+ }
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-checkout', auth.user.id),
+ { limit: 10 }
+ ))) return;
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return res.status(400).json({ ok: false, error: 'INVALID_REQUEST' });
+ }
+ if (body.acceptedTerms !== true || body.termsVersion !== COMMUNITY_TERMS_VERSION) {
+ return res.status(400).json({ ok: false, error: 'COMMUNITY_TERMS_REQUIRED' });
+ }
+
+ try {
+ let order = await getActiveCommunityOrder(auth.client, auth.user.id);
+ if (order?.status === 'PAID') {
+ return res.status(200).json({
+ ok: true,
+ paid: true,
+ paymentEnabled: isCommunityPaymentEnabled(),
+ order: serializeCommunityOrder(order)
+ });
+ }
+
+ if (!isCommunityPaymentEnabled()) {
+ return res.status(503).json({
+ ok: false,
+ error: 'COMMUNITY_PAYMENT_PAUSED',
+ ...communityPublicConfig()
+ });
+ }
+ if (!isAlipayConfigured()) {
+ return res.status(500).json({ ok: false, error: 'ALIPAY_NOT_CONFIGURED' });
+ }
+
+ const { sdk, appId, sellerId } = getAlipayClient();
+ if (order && shouldExpireCommunityOrder(order)) {
+ const reconciliation = await closeCommunityOrderAtAlipay(auth.client, sdk, order);
+ if (reconciliation.state === 'PAID') {
+ const paidOrder = await getActiveCommunityOrder(auth.client, auth.user.id);
+ return res.status(200).json({
+ ok: true,
+ paid: true,
+ paymentEnabled: true,
+ order: serializeCommunityOrder(paidOrder)
+ });
+ }
+ order = null;
+ }
+
+ if (!order) {
+ const { data, error } = await auth.client.rpc('create_or_reuse_community_order', {
+ p_user_id: auth.user.id,
+ p_terms_version: COMMUNITY_TERMS_VERSION
+ });
+ if (error) throw error;
+ order = Array.isArray(data) ? data[0] : data;
+ }
+ if (!order || order.status !== 'PENDING') {
+ throw new Error('COMMUNITY_ORDER_NOT_PENDING');
+ }
+ if (Number(order.amount_cents) !== COMMUNITY_PRICE_CENTS
+ || String(order.currency).toUpperCase() !== COMMUNITY_CURRENCY) {
+ throw new Error('COMMUNITY_ORDER_PRICE_INVALID');
+ }
+
+ const appUrl = getAppUrl(req);
+ const returnUrl = `${appUrl}/community/result?order_id=${encodeURIComponent(order.id)}`;
+ const notifyUrl = getCommunityAlipayNotifyUrl(appUrl);
+ const request = {
+ returnUrl,
+ bizContent: {
+ out_trade_no: order.id,
+ total_amount: formatAlipayAmount(COMMUNITY_PRICE_CENTS),
+ subject: normalizeAlipaySubject(COMMUNITY_SUBJECT),
+ product_code: 'FAST_INSTANT_TRADE_PAY',
+ timeout_express: '30m'
+ }
+ };
+ if (notifyUrl) request.notifyUrl = notifyUrl;
+
+ const paymentHtml = sdk.pageExec('alipay.trade.page.pay', 'POST', request);
+ if (typeof paymentHtml !== 'string' || !paymentHtml.includes('<form')) {
+ throw new Error('ALIPAY_PAYMENT_FORM_INVALID');
+ }
+
+ const { data: updatedOrder, error: updateError } = await auth.client
+ .from('community_orders')
+ .update({
+ alipay_app_id: appId,
+ alipay_seller_id: sellerId,
+ metadata: {
+ ...(order.metadata || {}),
+ notifyEnabled: Boolean(notifyUrl),
+ returnUrl,
+ termsAcceptedAt: new Date().toISOString()
+ }
+ })
+ .eq('id', order.id)
+ .eq('user_id', auth.user.id)
+ .eq('status', 'PENDING')
+ .select('*')
+ .single();
+ if (updateError) throw updateError;
+
+ return res.status(200).json({
+ ok: true,
+ paid: false,
+ order: serializeCommunityOrder(updatedOrder),
+ paymentHtml
+ });
+ } catch (error) {
+ console.warn('Failed to create paid community checkout', {
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_CHECKOUT_FAILED' });
+ }
+}
diff --git a/api/community/alipay/close.js b/api/community/alipay/close.js
new file mode 100644
index 0000000..d5566f4
--- /dev/null
+++ b/api/community/alipay/close.js
@@ -0,0 +1,85 @@
+import { getAlipayClient, isAlipayConfigured } from '../../_lib/alipay.js';
+import { readJsonBody } from '../../_lib/billing.js';
+import { closeCommunityOrderAtAlipay } from '../../_lib/community-alipay.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ isUuid,
+ noStore,
+ serializeCommunityOrder,
+ takeCommunityRateLimit,
+ validateSameOrigin
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+ if (!validateSameOrigin(req)) {
+ return res.status(403).json({ ok: false, error: 'ORIGIN_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-close', auth.user.id),
+ { limit: 10 }
+ ))) return;
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+ }
+ const orderId = String(body.orderId || '').trim();
+ if (!isUuid(orderId)) {
+ return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+ }
+
+ try {
+ const { data: order, error } = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', orderId)
+ .eq('user_id', auth.user.id)
+ .maybeSingle();
+ if (error) throw error;
+ if (!order) return res.status(404).json({ ok: false, error: 'COMMUNITY_ORDER_NOT_FOUND' });
+ if (order.status !== 'PENDING') {
+ return res.status(409).json({
+ ok: false,
+ error: order.status === 'PAID' ? 'COMMUNITY_ALREADY_PAID' : 'COMMUNITY_ORDER_NOT_PENDING',
+ order: serializeCommunityOrder(order)
+ });
+ }
+ if (!isAlipayConfigured()) {
+ return res.status(500).json({ ok: false, error: 'ALIPAY_NOT_CONFIGURED' });
+ }
+
+ const { sdk } = getAlipayClient();
+ const result = await closeCommunityOrderAtAlipay(auth.client, sdk, order);
+ const { data: refreshed, error: refreshError } = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', order.id)
+ .single();
+ if (refreshError) throw refreshError;
+ return res.status(result.state === 'PAID' ? 409 : 200).json({
+ ok: result.state !== 'PAID',
+ paid: result.state === 'PAID',
+ closed: result.state === 'CLOSED',
+ order: serializeCommunityOrder(refreshed)
+ });
+ } catch (error) {
+ console.warn('Failed to close paid community order', {
+ orderId,
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(502).json({ ok: false, error: 'COMMUNITY_CLOSE_FAILED' });
+ }
+}
diff --git a/api/community/alipay/notify.js b/api/community/alipay/notify.js
new file mode 100644
index 0000000..edbda0e
--- /dev/null
+++ b/api/community/alipay/notify.js
@@ -0,0 +1,98 @@
+import {
+ getAlipayClient,
+ parseAlipayFormBody
+} from '../../_lib/alipay.js';
+import { readRawBody } from '../../_lib/billing.js';
+import {
+ closeCommunityOrderLocally,
+ isPaidTradeStatus,
+ markCommunityOrderPaid,
+ sanitizeAlipayNotifyParams,
+ validateCommunityPaidNotification,
+ validateCommunityTradeResult
+} from '../../_lib/community.js';
+import { getSupabaseAdminClient, isSupabaseServerConfigured } from '../../_lib/supabase.js';
+
+export const config = {
+ api: { bodyParser: false }
+};
+
+function text(res, status, value) {
+ res.status(status);
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-store');
+ return res.send(value);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return text(res, 405, 'fail');
+ }
+ if (!isSupabaseServerConfigured()) return text(res, 500, 'fail');
+
+ let safeParams = {};
+ try {
+ const contentLength = Number(req.headers['content-length'] || 0);
+ if (contentLength > 128 * 1024) return text(res, 413, 'fail');
+ const rawBody = await readRawBody(req);
+ if (!rawBody.length || rawBody.length > 128 * 1024) return text(res, 400, 'fail');
+
+ const params = parseAlipayFormBody(rawBody);
+ safeParams = sanitizeAlipayNotifyParams(params);
+ const { sdk, appId, sellerId } = getAlipayClient();
+ if (!sdk.checkNotifySignV2(params)) return text(res, 400, 'fail');
+ if (params.sign_type !== 'RSA2') return text(res, 400, 'fail');
+ if (params.app_id !== appId || params.seller_id !== sellerId) return text(res, 400, 'fail');
+ if (!String(params.notify_id || '').trim()) return text(res, 400, 'fail');
+
+ const client = getSupabaseAdminClient();
+ const { data: order, error } = await client
+ .from('community_orders')
+ .select('*')
+ .eq('id', params.out_trade_no)
+ .maybeSingle();
+ if (error || !order) return text(res, 400, 'fail');
+ if ((order.alipay_app_id && order.alipay_app_id !== appId)
+ || (order.alipay_seller_id && order.alipay_seller_id !== sellerId)) {
+ return text(res, 400, 'fail');
+ }
+
+ if (isPaidTradeStatus(params.trade_status)) {
+ const validation = validateCommunityPaidNotification(order, params, { appId, sellerId });
+ if (!validation.ok) return text(res, 400, 'fail');
+ await markCommunityOrderPaid(client, order, params, {
+ notifyId: params.notify_id,
+ notifyPayload: safeParams
+ });
+ return text(res, 200, 'success');
+ }
+
+ const validation = validateCommunityTradeResult(order, params);
+ if (!validation.ok || params.notify_type !== 'trade_status_sync') {
+ return text(res, 400, 'fail');
+ }
+
+ const { error: eventError } = await client
+ .from('community_alipay_notify_events')
+ .upsert({
+ order_id: order.id,
+ notify_id: params.notify_id,
+ trade_no: params.trade_no,
+ trade_status: params.trade_status || 'UNKNOWN',
+ payload: safeParams
+ }, { onConflict: 'notify_id', ignoreDuplicates: true });
+ if (eventError) throw eventError;
+
+ if (params.trade_status === 'TRADE_CLOSED' && order.status === 'PENDING') {
+ await closeCommunityOrderLocally(client, order.id);
+ }
+ return text(res, 200, 'success');
+ } catch (error) {
+ console.warn('Failed to process paid community Alipay notification', {
+ orderId: String(safeParams.out_trade_no || '').slice(0, 64),
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return text(res, 500, 'fail');
+ }
+}
diff --git a/api/community/alipay/query.js b/api/community/alipay/query.js
new file mode 100644
index 0000000..06d8c7f
--- /dev/null
+++ b/api/community/alipay/query.js
@@ -0,0 +1,82 @@
+import { getAlipayClient, isAlipayConfigured } from '../../_lib/alipay.js';
+import { queryCommunityOrderAtAlipay } from '../../_lib/community-alipay.js';
+import {
+ applyCommunityRateLimit,
+ communityRequestRateKey,
+ isUuid,
+ noStore,
+ serializeCommunityOrder,
+ takeCommunityRateLimit
+} from '../../_lib/community.js';
+import { getAuthContext } from '../../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return res.status(auth.status || 401).json({
+ ok: false,
+ error: auth.error,
+ loginRequired: auth.error === 'AUTH_REQUIRED'
+ });
+ }
+ if (!applyCommunityRateLimit(res, takeCommunityRateLimit(
+ communityRequestRateKey(req, 'community-query', auth.user.id),
+ { limit: 30 }
+ ))) return;
+
+ const orderId = String(req.query?.orderId || req.query?.order_id || '').trim();
+ if (!isUuid(orderId)) {
+ return res.status(400).json({ ok: false, error: 'INVALID_COMMUNITY_ORDER' });
+ }
+
+ try {
+ const { data: order, error } = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', orderId)
+ .eq('user_id', auth.user.id)
+ .maybeSingle();
+ if (error) throw error;
+ if (!order) return res.status(404).json({ ok: false, error: 'COMMUNITY_ORDER_NOT_FOUND' });
+ if (order.status !== 'PENDING') {
+ return res.status(200).json({
+ ok: true,
+ paid: order.status === 'PAID',
+ order: serializeCommunityOrder(order)
+ });
+ }
+ if (!isAlipayConfigured()) {
+ return res.status(500).json({ ok: false, error: 'ALIPAY_NOT_CONFIGURED' });
+ }
+
+ const { sdk } = getAlipayClient();
+ const reconciliation = await queryCommunityOrderAtAlipay(auth.client, sdk, order);
+ const { data: refreshed, error: refreshError } = await auth.client
+ .from('community_orders')
+ .select('*')
+ .eq('id', order.id)
+ .eq('user_id', auth.user.id)
+ .single();
+ if (refreshError) throw refreshError;
+
+ return res.status(200).json({
+ ok: true,
+ paid: reconciliation.state === 'PAID',
+ pending: ['PENDING', 'NOT_FOUND'].includes(reconciliation.state),
+ order: serializeCommunityOrder(refreshed)
+ });
+ } catch (error) {
+ console.warn('Failed to query paid community order', {
+ orderId,
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(502).json({ ok: false, error: 'COMMUNITY_QUERY_FAILED' });
+ }
+}
diff --git a/api/community/config.js b/api/community/config.js
new file mode 100644
index 0000000..0e7787c
--- /dev/null
+++ b/api/community/config.js
@@ -0,0 +1,20 @@
+import { isAlipayConfigured } from '../_lib/alipay.js';
+import { communityPublicConfig, noStore } from '../_lib/community.js';
+import { isSupabaseServerConfigured } from '../_lib/supabase.js';
+
+export default function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ noStore(res);
+ const config = communityPublicConfig();
+ return res.status(200).json({
+ ok: true,
+ ...config,
+ paymentEnabled: config.paymentEnabled
+ && isSupabaseServerConfigured()
+ && isAlipayConfigured()
+ });
+}
diff --git a/api/community/qr.js b/api/community/qr.js
new file mode 100644
index 0000000..925e470
--- /dev/null
+++ b/api/community/qr.js
@@ -0,0 +1,51 @@
+import {
+ canAccessCommunityQr,
+ decodePostgresBytea,
+ getActiveCommunityOrder,
+ getCurrentCommunityQr,
+ noStore
+} from '../_lib/community.js';
+import { getAuthContext } from '../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return res.status(auth.status || 401).json({
+ ok: false,
+ error: auth.error,
+ loginRequired: auth.error === 'AUTH_REQUIRED'
+ });
+ }
+
+ try {
+ const order = await getActiveCommunityOrder(auth.client, auth.user.id);
+ if (!canAccessCommunityQr(order?.status)) {
+ return res.status(403).json({ ok: false, error: 'COMMUNITY_PAYMENT_REQUIRED' });
+ }
+
+ const asset = await getCurrentCommunityQr(auth.client, { includeBytes: true });
+ if (!asset) {
+ return res.status(409).json({ ok: false, error: 'COMMUNITY_QR_NOT_READY' });
+ }
+ const bytes = decodePostgresBytea(asset.qr_bytes);
+ if (!bytes.length || bytes.length !== Number(asset.size_bytes)) {
+ throw new Error('COMMUNITY_QR_CORRUPT');
+ }
+
+ res.setHeader('Content-Type', asset.media_type);
+ res.setHeader('Content-Length', String(bytes.length));
+ return res.status(200).send(bytes);
+ } catch (error) {
+ console.warn('Failed to serve paid community QR', {
+ userId: auth.user?.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_QR_FAILED' });
+ }
+}
diff --git a/api/community/status.js b/api/community/status.js
new file mode 100644
index 0000000..b8d7909
--- /dev/null
+++ b/api/community/status.js
@@ -0,0 +1,61 @@
+import { isAlipayConfigured } from '../_lib/alipay.js';
+import {
+ canAccessCommunityQr,
+ communityPublicConfig,
+ getCurrentCommunityQr,
+ getLatestCommunityOrder,
+ noStore,
+ serializeCommunityOrder
+} from '../_lib/community.js';
+import { getAuthContext, isSupabaseServerConfigured } from '../_lib/supabase.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ noStore(res);
+
+ if (!isSupabaseServerConfigured()) {
+ return res.status(500).json({ ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ const auth = await getAuthContext(req, { allowAnonymous: true });
+ if (auth.error) {
+ return res.status(auth.status || 401).json({ ok: false, error: auth.error });
+ }
+
+ const publicConfig = communityPublicConfig();
+ const paymentEnabled = publicConfig.paymentEnabled && isAlipayConfigured();
+ if (!auth.user) {
+ return res.status(200).json({
+ ok: true,
+ authenticated: false,
+ eligible: false,
+ qrReady: false,
+ paymentEnabled,
+ order: null
+ });
+ }
+
+ try {
+ const [order, qr] = await Promise.all([
+ getLatestCommunityOrder(auth.client, auth.user.id),
+ getCurrentCommunityQr(auth.client)
+ ]);
+ return res.status(200).json({
+ ok: true,
+ authenticated: true,
+ eligible: canAccessCommunityQr(order?.status),
+ qrReady: Boolean(qr),
+ paymentEnabled,
+ order: serializeCommunityOrder(order)
+ });
+ } catch (error) {
+ console.warn('Failed to load paid community status', {
+ userId: auth.user.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return res.status(500).json({ ok: false, error: 'COMMUNITY_STATUS_FAILED' });
+ }
+}
diff --git a/docs/alipay-web-payment.md b/docs/alipay-web-payment.md
new file mode 100644
index 0000000..9964c56
--- /dev/null
+++ b/docs/alipay-web-payment.md
@@ -0,0 +1,47 @@
+# 支付宝网站支付
+
+项目同时保留 Stripe,并为一次性积分包增加支付宝网站支付。会员订阅仍由 Stripe 处理,避免把支付宝单次支付误当成自动续费。
+
+## 接口
+
+| 路径 | 用途 | 权限 |
+| --- | --- | --- |
+| `POST /api/billing/alipay/checkout` | 创建订单并返回支付宝 POST 表单 | 登录用户 |
+| `GET /api/billing/alipay/query` | 主动查询交易并幂等发放积分 | 订单所属用户 |
+| `POST /api/billing/alipay/notify` | 验签、校验订单并处理异步通知 | 支付宝服务器 |
+| `POST /api/billing/alipay/refund` | 发起全额退款并预扣对应积分 | 超级管理员 |
+| `GET /api/billing/alipay/refund-query` | 查询退款结果 | 超级管理员 |
+| `POST /api/billing/alipay/close` | 关闭未支付订单 | 超级管理员 |
+
+支付结果只接受验签通过的异步通知或 `alipay.trade.query` 主动查询。浏览器同步回跳只用于打开结果页,不直接判定付款成功。
+
+## 数据库与人民币定价
+
+先应用迁移 `supabase/migrations/20260721090000_alipay_webpay.sql`。迁移会增加支付通道、支付宝交易号、退款状态和原子积分入账/退款函数。
+
+每个需要开放支付宝购买的积分包,都必须在 `credit_packs.alipay_amount_cents` 中填写经过业务确认的人民币分值。没有独立人民币价格的积分包不会展示可用的支付宝按钮;代码不会把现有美元价格按 1:1 当作人民币价格。
+
+## 本地沙箱
+
+本地代码直接读取项目根目录下、由支付宝 AI 付 Skill 创建并验证的 `.alipay-sandbox.json`:
+
+- Node.js 使用 `appIds[0].appPrivatePkcsKey`(PKCS#1)。
+- 网关固定为 `https://openapi-sandbox.dl.alipaydev.com/gateway.do`。
+- 配置文件必须保持 Git 忽略和仅当前用户可读写。
+- 本地没有公网 HTTPS 地址时不发送 `notify_url`,付款结果由交易查询确认;通知处理代码仍会保留。
+
+## 生产配置
+
+生产环境通过服务端环境变量设置:
+
+- `ALIPAY_APP_ID`
+- `ALIPAY_PRIVATE_KEY`
+- `ALIPAY_PUBLIC_KEY`
+- `ALIPAY_SELLER_ID`
+- `ALIPAY_GATEWAY`
+- `ALIPAY_NOTIFY_URL`
+- `ALIPAY_NOTIFY_ENABLED`
+
+`ALIPAY_APP_ID`、应用公钥和应用私钥必须属于同一套生产应用密钥。Node.js 使用 PKCS#1 原始私钥字符串,不添加 PEM 头尾,不在日志、前端或仓库中保存密钥。
+
+真实上线必须使用公网 HTTPS `notify_url`,完成通知验签、幂等处理、`app_id`、`seller_id`、订单号和金额校验,并保留主动查询作为补偿链路。
diff --git a/docs/paid-community.md b/docs/paid-community.md
new file mode 100644
index 0000000..faf8c9b
--- /dev/null
+++ b/docs/paid-community.md
@@ -0,0 +1,80 @@
+# GPT-Image2 付费交流群上线手册
+
+当前实现将付费群与积分包、会员支付完全分离:支付宝一次性支付 `¥9.90` 后,资格绑定 Supabase 用户账号;只有服务端确认订单为 `PAID` 时才能读取受保护群二维码。
+
+## 本地能力
+
+- 页面:`/community`
+- 支付回跳:`/community/result`
+- 支付方式:支付宝网站支付 `alipay.trade.page.pay`
+- 固定金额:`990` 分,`CNY`
+- 订单状态:`PENDING`、`PAID`、`CLOSED`、`REFUNDED`、`REVOKED`
+- 退款处理状态:`NONE`、`PROCESSING`、`SUCCEEDED`、`FAILED`
+- 资格规则:仅 `PAID` 有效;退款处理中保持 `PAID`;支付宝确认退款成功后改为 `REFUNDED`
+- 群码:数据库 `bytea` 资源,限 PNG/JPEG/WebP、最大 2 MB,管理员通过事务 RPC 原子替换
+
+## API
+
+公开与当前用户:
+
+- `GET /api/community/config`
+- `GET /api/community/status`
+- `GET /api/community/qr`
+
+支付宝:
+
+- `POST /api/community/alipay/checkout`
+- `GET /api/community/alipay/query`
+- `POST /api/community/alipay/close`
+- `POST /api/community/alipay/notify`
+
+超级管理员:
+
+- `GET /api/admin/community/orders`
+- `GET|POST /api/admin/community/qr`
+- `POST /api/admin/community/refund`
+- `GET /api/admin/community/refund-query`
+- `POST /api/admin/community/revoke`
+
+## 环境变量
+
+生产部署必须先保持:
+
+```dotenv
+COMMUNITY_PAYMENT_ENABLED=false
+COMMUNITY_ALIPAY_NOTIFY_URL=https://gpt-image2.canghe.ai/api/community/alipay/notify
+COMMUNITY_SUPPORT_TEXT=微信搜索苍何
+```
+
+支付宝生产变量沿用现有 `ALIPAY_APP_ID`、`ALIPAY_PRIVATE_KEY`、`ALIPAY_PUBLIC_KEY`、`ALIPAY_SELLER_ID` 和生产网关配置。生产私钥只在 Vercel Sensitive Environment Variables 中配置,不写入仓库、文档或对话。
+
+## 首次部署顺序
+
+1. 保持 `COMMUNITY_PAYMENT_ENABLED=false`。
+2. 在目标 Supabase 项目应用 `supabase/migrations/20260722090000_paid_community.sql`。
+3. 部署同一版本代码,确认 `/community`、`/community/result` 和只读状态接口正常。
+4. 由 `super_admin` 在管理面板上传一张从未公开过的新群二维码。
+5. 在支付宝开放平台完成网站支付签约、应用配置与发布,并确认公网 HTTPS 通知地址无重定向。
+6. 配置属于同一生产应用的 App ID、应用公钥、应用私钥和支付宝公钥;Node.js 使用 PKCS#1 私钥原文。
+7. 开启 `COMMUNITY_PAYMENT_ENABLED=true`。
+8. 用同一生产版本完成一笔真实 `¥9.90` 付款和原路退款验收。
+
+## 生产验收
+
+真实付款必须逐项确认:
+
+- 前端不能提交或覆盖金额。
+- 创建的是独立 `community_orders`,不会触发积分包履约。
+- 支付宝主动查单和异步通知都能幂等写入 `PAID`。
+- 同步回跳只触发服务端查单,不信任 URL 参数。
+- 付款账号可以读取群码,未付款账号得到拒绝响应。
+- 管理员退款使用稳定退款请求号;处理中资格仍有效。
+- 退款查询得到 `REFUND_SUCCESS` 后写入 `REFUNDED`,随后群码访问失效。
+- 任何关键项失败时立即将 `COMMUNITY_PAYMENT_ENABLED` 改回 `false`。
+
+## 群码轮换与日常运维
+
+- 群二维码过期时,在管理面板上传新图片;RPC 会在同一事务中停用旧图并启用新图。
+- 不要把受保护群码上传到 GitHub、README、公开对象存储或前端静态目录。
+- 退款由“微信搜索苍何”人工审核;管理员操作前核对账号、订单号和退款状态。
+- 人工撤销资格不会自动退款;需要退款时使用退款流程,不用撤销代替退款。
diff --git a/package-lock.json b/package-lock.json
index 635e4be..3ca076a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,7 @@
"@google-analytics/data": "^5.2.2",
"@supabase/supabase-js": "^2.105.4",
"@vitejs/plugin-react": "^5.1.1",
+ "alipay-sdk": "^4.14.0",
"google-auth-library": "^10.6.2",
"lucide-react": "^0.561.0",
"react": "^19.2.1",
@@ -20,12 +21,12 @@
}
},
"node_modules/@babel/code-frame": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
- "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
"license": "MIT",
"dependencies": {
- "@babel/helper-validator-identifier": "^7.28.5",
+ "@babel/helper-validator-identifier": "^7.29.7",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
@@ -34,29 +35,29 @@
}
},
"node_modules/@babel/compat-data": {
- "version": "7.29.3",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.3.tgz",
- "integrity": "sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/core": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
- "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
- "license": "MIT",
- "dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-compilation-targets": "^7.28.6",
- "@babel/helper-module-transforms": "^7.28.6",
- "@babel/helpers": "^7.28.6",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/traverse": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/remapping": "^2.3.5",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
@@ -73,13 +74,13 @@
}
},
"node_modules/@babel/generator": {
- "version": "7.29.1",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
- "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz",
+ "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==",
"license": "MIT",
"dependencies": {
- "@babel/parser": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/gen-mapping": "^0.3.12",
"@jridgewell/trace-mapping": "^0.3.28",
"jsesc": "^3.0.2"
@@ -89,13 +90,13 @@
}
},
"node_modules/@babel/helper-compilation-targets": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
- "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"license": "MIT",
"dependencies": {
- "@babel/compat-data": "^7.28.6",
- "@babel/helper-validator-option": "^7.27.1",
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
@@ -105,36 +106,36 @@
}
},
"node_modules/@babel/helper-globals": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
- "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-imports": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",
- "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
"license": "MIT",
"dependencies": {
- "@babel/traverse": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-transforms": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",
- "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
"license": "MIT",
"dependencies": {
- "@babel/helper-module-imports": "^7.28.6",
- "@babel/helper-validator-identifier": "^7.28.5",
- "@babel/traverse": "^7.28.6"
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -153,52 +154,52 @@
}
},
"node_modules/@babel/helper-string-parser": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
- "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
- "version": "7.28.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
- "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-option": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
- "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helpers": {
- "version": "7.29.2",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",
- "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"license": "MIT",
"dependencies": {
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0"
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
- "version": "7.29.3",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz",
- "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
+ "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.0"
+ "@babel/types": "^7.29.7"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -238,31 +239,31 @@
}
},
"node_modules/@babel/template": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
- "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.28.6",
- "@babel/parser": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",
- "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz",
+ "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-globals": "^7.28.0",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0",
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7",
"debug": "^4.3.1"
},
"engines": {
@@ -270,22 +271,22 @@
}
},
"node_modules/@babel/types": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
- "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
+ "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
"license": "MIT",
"dependencies": {
- "@babel/helper-string-parser": "^7.27.1",
- "@babel/helper-validator-identifier": "^7.28.5"
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
- "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
@@ -299,9 +300,9 @@
}
},
"node_modules/@esbuild/android-arm": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",
- "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
@@ -315,9 +316,9 @@
}
},
"node_modules/@esbuild/android-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",
- "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
@@ -331,9 +332,9 @@
}
},
"node_modules/@esbuild/android-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",
- "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
@@ -347,9 +348,9 @@
}
},
"node_modules/@esbuild/darwin-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",
- "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
@@ -363,9 +364,9 @@
}
},
"node_modules/@esbuild/darwin-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",
- "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
@@ -379,9 +380,9 @@
}
},
"node_modules/@esbuild/freebsd-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",
- "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
@@ -395,9 +396,9 @@
}
},
"node_modules/@esbuild/freebsd-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",
- "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
@@ -411,9 +412,9 @@
}
},
"node_modules/@esbuild/linux-arm": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",
- "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
@@ -427,9 +428,9 @@
}
},
"node_modules/@esbuild/linux-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",
- "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
@@ -443,9 +444,9 @@
}
},
"node_modules/@esbuild/linux-ia32": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",
- "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
@@ -459,9 +460,9 @@
}
},
"node_modules/@esbuild/linux-loong64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",
- "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
@@ -475,9 +476,9 @@
}
},
"node_modules/@esbuild/linux-mips64el": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",
- "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
@@ -491,9 +492,9 @@
}
},
"node_modules/@esbuild/linux-ppc64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",
- "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
@@ -507,9 +508,9 @@
}
},
"node_modules/@esbuild/linux-riscv64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",
- "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
@@ -523,9 +524,9 @@
}
},
"node_modules/@esbuild/linux-s390x": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",
- "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
@@ -539,9 +540,9 @@
}
},
"node_modules/@esbuild/linux-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",
- "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
@@ -555,9 +556,9 @@
}
},
"node_modules/@esbuild/netbsd-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",
- "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
@@ -571,9 +572,9 @@
}
},
"node_modules/@esbuild/netbsd-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",
- "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
@@ -587,9 +588,9 @@
}
},
"node_modules/@esbuild/openbsd-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",
- "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
@@ -603,9 +604,9 @@
}
},
"node_modules/@esbuild/openbsd-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",
- "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
@@ -619,9 +620,9 @@
}
},
"node_modules/@esbuild/openharmony-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",
- "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
@@ -635,9 +636,9 @@
}
},
"node_modules/@esbuild/sunos-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",
- "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
@@ -651,9 +652,9 @@
}
},
"node_modules/@esbuild/win32-arm64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",
- "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
@@ -667,9 +668,9 @@
}
},
"node_modules/@esbuild/win32-ia32": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",
- "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
@@ -683,9 +684,9 @@
}
},
"node_modules/@esbuild/win32-x64": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",
- "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
@@ -698,6 +699,28 @@
"node": ">=18"
}
},
+ "node_modules/@fidm/asn1": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
+ "integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@fidm/x509": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",
+ "integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",
+ "license": "MIT",
+ "dependencies": {
+ "@fidm/asn1": "^1.0.4",
+ "tweetnacl": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/@google-analytics/data": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@google-analytics/data/-/data-5.2.2.tgz",
@@ -711,9 +734,9 @@
}
},
"node_modules/@grpc/grpc-js": {
- "version": "1.14.3",
- "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.3.tgz",
- "integrity": "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==",
+ "version": "1.14.4",
+ "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz",
+ "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==",
"license": "Apache-2.0",
"dependencies": {
"@grpc/proto-loader": "^0.8.0",
@@ -842,19 +865,18 @@
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/eventemitter": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz",
- "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
+ "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/fetch": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz",
- "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
+ "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
"license": "BSD-3-Clause",
"dependencies": {
- "@protobufjs/aspromise": "^1.1.1",
- "@protobufjs/inquire": "^1.1.0"
+ "@protobufjs/aspromise": "^1.1.1"
}
},
"node_modules/@protobufjs/float": {
@@ -863,12 +885,6 @@
"integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
"license": "BSD-3-Clause"
},
- "node_modules/@protobufjs/inquire": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.1.tgz",
- "integrity": "sha512-mnzgDV26ueAvk7rsbt9L7bE0SuAoqyuys/sMMrmVcN5x9VsxpcG3rqAUSgDyLp0UZlmNfIbQ4fHfCtreVBk8Ew==",
- "license": "BSD-3-Clause"
- },
"node_modules/@protobufjs/path": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
@@ -978,9 +994,6 @@
"cpu": [
"arm"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -994,9 +1007,6 @@
"cpu": [
"arm"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1010,9 +1020,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1026,9 +1033,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1042,9 +1046,6 @@
"cpu": [
"loong64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1058,9 +1059,6 @@
"cpu": [
"loong64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1074,9 +1072,6 @@
"cpu": [
"ppc64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1090,9 +1085,6 @@
"cpu": [
"ppc64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1106,9 +1098,6 @@
"cpu": [
"riscv64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1122,9 +1111,6 @@
"cpu": [
"riscv64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1138,9 +1124,6 @@
"cpu": [
"s390x"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1154,9 +1137,6 @@
"cpu": [
"x64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1170,9 +1150,6 @@
"cpu": [
"x64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1426,6 +1403,26 @@
"node": ">= 14"
}
},
+ "node_modules/alipay-sdk": {
+ "version": "4.14.0",
+ "resolved": "https://registry.npmjs.org/alipay-sdk/-/alipay-sdk-4.14.0.tgz",
+ "integrity": "sha512-oiD/VP5Ei0RRacHHmE+N0uqgOj2xzce7c0fHrtyyh1P04O+o9I1r65LdGPzU8960J56xOxS/d3c+R/9lsPUH7g==",
+ "license": "MIT",
+ "dependencies": {
+ "@fidm/x509": "^1.2.1",
+ "bignumber.js": "^9.1.2",
+ "camelcase-keys": "^7.0.2",
+ "crypto-js": "^4.2.0",
+ "formstream": "^1.5.0",
+ "snakecase-keys": "^8.0.0",
+ "sse-decoder": "^1.0.0",
+ "urllib": "^4",
+ "utility": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
@@ -1450,6 +1447,12 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -1477,9 +1480,9 @@
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
- "version": "2.10.27",
- "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.27.tgz",
- "integrity": "sha512-zEs/ufmZoUd7WftKpKyXaT6RFxpQ5Qm9xytKRHvJfxFV9DFJkZph9RvJ1LcOUi0Z1ZVijMte65JbILeV+8QQEA==",
+ "version": "2.10.44",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.44.tgz",
+ "integrity": "sha512-T3ghW+sl/ZJ8w1v/yQx3qvJ9040DWoLBz8JT/CILbAKcFyG9b2MRe75v6W5uXjv6uH1lumK2Kv46y2zSkcej0Q==",
"license": "Apache-2.0",
"bin": {
"baseline-browser-mapping": "dist/cli.cjs"
@@ -1498,18 +1501,18 @@
}
},
"node_modules/brace-expansion": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
- "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
+ "integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/browserslist": {
- "version": "4.28.2",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",
- "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==",
+ "version": "4.28.6",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.6.tgz",
+ "integrity": "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw==",
"funding": [
{
"type": "opencollective",
@@ -1526,10 +1529,10 @@
],
"license": "MIT",
"dependencies": {
- "baseline-browser-mapping": "^2.10.12",
- "caniuse-lite": "^1.0.30001782",
- "electron-to-chromium": "^1.5.328",
- "node-releases": "^2.0.36",
+ "baseline-browser-mapping": "^2.10.42",
+ "caniuse-lite": "^1.0.30001803",
+ "electron-to-chromium": "^1.5.389",
+ "node-releases": "^2.0.51",
"update-browserslist-db": "^1.2.3"
},
"bin": {
@@ -1545,10 +1548,69 @@
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause"
},
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/camelcase": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/camelcase-keys": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-7.0.2.tgz",
+ "integrity": "sha512-Rjs1H+A9R+Ig+4E/9oyB66UC5Mj9Xq3N//vcLf2WzgdTi/3gUu3Z9KoqmlrEG4VuuLK8wJHofxzdQXz/knhiYg==",
+ "license": "MIT",
+ "dependencies": {
+ "camelcase": "^6.3.0",
+ "map-obj": "^4.1.0",
+ "quick-lru": "^5.1.1",
+ "type-fest": "^1.2.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/caniuse-lite": {
- "version": "1.0.30001791",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001791.tgz",
- "integrity": "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==",
+ "version": "1.0.30001806",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz",
+ "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==",
"funding": [
{
"type": "opencollective",
@@ -1670,6 +1732,18 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -1690,6 +1764,12 @@
"node": ">= 8"
}
},
+ "node_modules/crypto-js": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
+ "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
+ "license": "MIT"
+ },
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
@@ -1716,6 +1796,49 @@
}
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8",
+ "npm": "1.2.8000 || >= 1.4.16"
+ }
+ },
+ "node_modules/dot-case": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz",
+ "integrity": "sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==",
+ "license": "MIT",
+ "dependencies": {
+ "no-case": "^3.0.4",
+ "tslib": "^2.0.3"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/duplexify": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz",
@@ -1744,9 +1867,9 @@
}
},
"node_modules/electron-to-chromium": {
- "version": "1.5.349",
- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.349.tgz",
- "integrity": "sha512-QsWVGyRuY07Aqb234QytTfwd5d9AJlfNIQ5wIOl1L+PZDzI9d9+Fn0FRale/QYlFxt/bUnB0/nLd1jFPGxGK1A==",
+ "version": "1.5.394",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.394.tgz",
+ "integrity": "sha512-Wmt2Gm0o8JWBuGgmc4XZ0u9s1RaCRqhxP47phplmfg04+qypTUurpeJGP45A7Fhv7jdrrVH44PLlR9qXo37cVQ==",
"license": "ISC"
},
"node_modules/emoji-regex": {
@@ -1764,10 +1887,55 @@
"once": "^1.4.0"
}
},
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/esbuild": {
- "version": "0.27.7",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",
- "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
@@ -1777,32 +1945,32 @@
"node": ">=18"
},
"optionalDependencies": {
- "@esbuild/aix-ppc64": "0.27.7",
- "@esbuild/android-arm": "0.27.7",
- "@esbuild/android-arm64": "0.27.7",
- "@esbuild/android-x64": "0.27.7",
- "@esbuild/darwin-arm64": "0.27.7",
- "@esbuild/darwin-x64": "0.27.7",
- "@esbuild/freebsd-arm64": "0.27.7",
- "@esbuild/freebsd-x64": "0.27.7",
- "@esbuild/linux-arm": "0.27.7",
- "@esbuild/linux-arm64": "0.27.7",
- "@esbuild/linux-ia32": "0.27.7",
- "@esbuild/linux-loong64": "0.27.7",
- "@esbuild/linux-mips64el": "0.27.7",
- "@esbuild/linux-ppc64": "0.27.7",
- "@esbuild/linux-riscv64": "0.27.7",
- "@esbuild/linux-s390x": "0.27.7",
- "@esbuild/linux-x64": "0.27.7",
- "@esbuild/netbsd-arm64": "0.27.7",
- "@esbuild/netbsd-x64": "0.27.7",
- "@esbuild/openbsd-arm64": "0.27.7",
- "@esbuild/openbsd-x64": "0.27.7",
- "@esbuild/openharmony-arm64": "0.27.7",
- "@esbuild/sunos-x64": "0.27.7",
- "@esbuild/win32-arm64": "0.27.7",
- "@esbuild/win32-ia32": "0.27.7",
- "@esbuild/win32-x64": "0.27.7"
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/escalade": {
@@ -1814,12 +1982,30 @@
"node": ">=6"
}
},
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
+ "node_modules/extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==",
+ "license": "MIT",
+ "dependencies": {
+ "is-extendable": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -1876,6 +2062,22 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/form-data": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.4",
+ "mime-types": "^2.1.35"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@@ -1888,6 +2090,18 @@
"node": ">=12.20.0"
}
},
+ "node_modules/formstream": {
+ "version": "1.5.2",
+ "resolved": "https://registry.npmjs.org/formstream/-/formstream-1.5.2.tgz",
+ "integrity": "sha512-NASf0lgxC1AyKNXQIrXTEYkiX99LhCEXTkiGObXAkpBui86a4u8FjH1o2bGb3PpqI3kafC+yw4zWeK6l6VHTgg==",
+ "license": "MIT",
+ "dependencies": {
+ "destroy": "^1.0.4",
+ "mime": "^2.5.2",
+ "node-hex": "^1.0.1",
+ "pause-stream": "~0.0.11"
+ }
+ },
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1902,6 +2116,15 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/gaxios": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.4.tgz",
@@ -1948,6 +2171,43 @@
"node": "6.* || 8.* || >= 10.*"
}
},
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/glob": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
@@ -2017,6 +2277,57 @@
"node": ">=14"
}
},
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
@@ -2058,6 +2369,15 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
+ "node_modules/is-extendable": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",
+ "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
@@ -2160,6 +2480,15 @@
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
+ "node_modules/lower-case": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz",
+ "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.3"
+ }
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -2178,6 +2507,60 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
+ "node_modules/map-obj": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz",
+ "integrity": "sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/mime": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
+ "license": "MIT",
+ "bin": {
+ "mime": "cli.js"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/minimatch": {
"version": "9.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
@@ -2226,6 +2609,16 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/no-case": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz",
+ "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==",
+ "license": "MIT",
+ "dependencies": {
+ "lower-case": "^2.0.2",
+ "tslib": "^2.0.3"
+ }
+ },
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
@@ -2264,11 +2657,23 @@
"url": "https://opencollective.com/node-fetch"
}
},
+ "node_modules/node-hex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/node-hex/-/node-hex-1.0.1.tgz",
+ "integrity": "sha512-iwpZdvW6Umz12ICmu9IYPRxg0tOLGmU3Tq2tKetejCj3oZd7b2nUXwP3a7QA5M9glWy8wlPS1G3RwM/CdsUbdQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/node-releases": {
- "version": "2.0.38",
- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",
- "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==",
- "license": "MIT"
+ "version": "2.0.51",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz",
+ "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
},
"node_modules/object-hash": {
"version": "3.0.0",
@@ -2279,6 +2684,18 @@
"node": ">= 6"
}
},
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -2325,6 +2742,18 @@
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"license": "ISC"
},
+ "node_modules/pause-stream": {
+ "version": "0.0.11",
+ "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz",
+ "integrity": "sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==",
+ "license": [
+ "MIT",
+ "Apache2"
+ ],
+ "dependencies": {
+ "through": "~2.3"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -2384,29 +2813,56 @@
}
},
"node_modules/protobufjs": {
- "version": "7.5.7",
- "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.7.tgz",
- "integrity": "sha512-NGnrxS/nLKUo5nkbVQxlC71sB4hdfImdYIbFeSCidxtwATx0AHRPcANSLd0q5Bb2BkoSWo2iisQhGg5/r+ihbA==",
+ "version": "7.6.5",
+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz",
+ "integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==",
"hasInstallScript": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.2",
"@protobufjs/base64": "^1.1.2",
"@protobufjs/codegen": "^2.0.5",
- "@protobufjs/eventemitter": "^1.1.0",
- "@protobufjs/fetch": "^1.1.0",
+ "@protobufjs/eventemitter": "^1.1.1",
+ "@protobufjs/fetch": "^1.1.1",
"@protobufjs/float": "^1.0.2",
- "@protobufjs/inquire": "^1.1.1",
"@protobufjs/path": "^1.1.2",
"@protobufjs/pool": "^1.1.0",
"@protobufjs/utf8": "^1.1.1",
"@types/node": ">=13.7.0",
- "long": "^5.0.0"
+ "long": "^5.3.2"
},
"engines": {
"node": ">=12.0.0"
}
},
+ "node_modules/qs": {
+ "version": "6.15.3",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
+ "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "es-define-property": "^1.0.1",
+ "side-channel": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/quick-lru": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/react": {
"version": "19.2.5",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz",
@@ -2588,6 +3044,78 @@
"node": ">=8"
}
},
+ "node_modules/side-channel": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4",
+ "side-channel-list": "^1.0.1",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
@@ -2600,6 +3128,42 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/snake-case": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-3.0.4.tgz",
+ "integrity": "sha512-LAOh4z89bGQvl9pFfNF8V146i7o7/CqFPbqzYgP+yYzDIDeS9HaNFtXABamRW+AQzEVODcvE79ljJ+8a9YSdMg==",
+ "license": "MIT",
+ "dependencies": {
+ "dot-case": "^3.0.4",
+ "tslib": "^2.0.3"
+ }
+ },
+ "node_modules/snakecase-keys": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/snakecase-keys/-/snakecase-keys-8.1.0.tgz",
+ "integrity": "sha512-9/Eug2btrCiOi+9+vIXJnxUcKVfcbLy5Uwff4BrO6PQf3Oq/2iYQ/1zkmnrpIIjfel/DAasAlux7OvAmCa+Xnw==",
+ "license": "MIT",
+ "dependencies": {
+ "map-obj": "^4.2.0",
+ "snake-case": "^3.0.4",
+ "type-fest": "^4.15.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/snakecase-keys/node_modules/type-fest": {
+ "version": "4.41.0",
+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz",
+ "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==",
+ "license": "(MIT OR CC0-1.0)",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2609,6 +3173,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/sse-decoder": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/sse-decoder/-/sse-decoder-1.0.0.tgz",
+ "integrity": "sha512-JPopy3jfNmPcUz5Ru6skKhHNRJbsvcEW6Z4SirKkucLS8Jya1Bmf4FVX8giOkLm8xQJ7kK68P6GXoVSTkbedUA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.19.3"
+ }
+ },
"node_modules/stream-events": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz",
@@ -2767,6 +3340,12 @@
"node": ">=18"
}
},
+ "node_modules/through": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",
+ "license": "MIT"
+ },
"node_modules/tinyglobby": {
"version": "0.2.16",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",
@@ -2789,12 +3368,51 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
+ "node_modules/tweetnacl": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
+ "license": "Unlicense"
+ },
+ "node_modules/type-fest": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz",
+ "integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==",
+ "license": "(MIT OR CC0-1.0)",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/undici": {
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz",
+ "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
"node_modules/undici-types": {
"version": "7.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.21.0.tgz",
"integrity": "sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==",
"license": "MIT"
},
+ "node_modules/unescape": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/unescape/-/unescape-1.0.1.tgz",
+ "integrity": "sha512-O0+af1Gs50lyH1nUu3ZyYS1cRh01Q/kUKatTOkSs7jukXE6/NebucDVxyiDsA9AQ4JC1V1jUH9EO8JX2nMDgGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "extend-shallow": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -2825,19 +3443,63 @@
"browserslist": ">= 4.21.0"
}
},
+ "node_modules/urllib": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/urllib/-/urllib-4.9.0.tgz",
+ "integrity": "sha512-Rp3DBvVqy9arSTMH6oN5N7OAN01U3dQ2xc19AadP86MzC4j67MDeqOup5shpWnjkDVGWfLfWPOd8CyqOtd6u3w==",
+ "license": "MIT",
+ "dependencies": {
+ "form-data": "^4.0.1",
+ "formstream": "^1.5.1",
+ "mime-types": "^2.1.35",
+ "qs": "^6.12.1",
+ "type-fest": "^4.20.1",
+ "undici": "^7.1.1",
+ "ylru": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 18.19.0"
+ }
+ },
+ "node_modules/urllib/node_modules/type-fest": {
+ "version": "4.41.0",
+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz",
+ "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==",
+ "license": "(MIT OR CC0-1.0)",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
+ "node_modules/utility": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/utility/-/utility-2.5.0.tgz",
+ "integrity": "sha512-lDbOVde5UAKgtxrSyZNhqrTA7f7anba6DTqbsDWgUFk6PZlmr7djqPYw0FnL5a6TbJvRt38VmYqt07zVLzXG2A==",
+ "license": "MIT",
+ "dependencies": {
+ "escape-html": "^1.0.3",
+ "unescape": "^1.0.1",
+ "ylru": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 16.0.0"
+ }
+ },
"node_modules/vite": {
- "version": "7.3.2",
- "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
- "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
+ "version": "7.3.6",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",
+ "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",
"license": "MIT",
"dependencies": {
- "esbuild": "^0.27.0",
+ "esbuild": "^0.27.0 || ^0.28.0",
"fdir": "^6.5.0",
"picomatch": "^4.0.3",
"postcss": "^8.5.6",
@@ -3108,6 +3770,15 @@
"engines": {
"node": ">=8"
}
+ },
+ "node_modules/ylru": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ylru/-/ylru-2.0.0.tgz",
+ "integrity": "sha512-T6hTrKcr9lKeUG0MQ/tO72D3UGptWVohgzpHG8ljU1jeBt2RCjcWxvsTPD8ZzUq1t1FvwROAw1kxg2euvg/THg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 18.19.0"
+ }
}
}
}
diff --git a/package.json b/package.json
index d24f098..71ffc5b 100644
--- a/package.json
+++ b/package.json
@@ -12,14 +12,17 @@
"publish:skill:npm": "npm publish ./agents/skills/gpt-image-2-style-library --access public",
"predev": "npm run generate:site-data && npm run generate:style-skill",
"dev": "vite",
+ "dev:alipay-sandbox": "node scripts/alipay-webpay-sandbox-server.mjs",
"prebuild": "npm run generate:site-data && npm run generate:style-skill",
"build": "vite build",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "node --test api/_lib/*.test.js"
},
"dependencies": {
"@google-analytics/data": "^5.2.2",
"@supabase/supabase-js": "^2.105.4",
"@vitejs/plugin-react": "^5.1.1",
+ "alipay-sdk": "^4.14.0",
"google-auth-library": "^10.6.2",
"lucide-react": "^0.561.0",
"react": "^19.2.1",
diff --git a/scripts/alipay-webpay-sandbox-server.mjs b/scripts/alipay-webpay-sandbox-server.mjs
new file mode 100644
index 0000000..c06436a
--- /dev/null
+++ b/scripts/alipay-webpay-sandbox-server.mjs
@@ -0,0 +1,234 @@
+import { createServer } from 'node:http';
+import { randomUUID } from 'node:crypto';
+import {
+ formatAlipayAmount,
+ getAlipayClient,
+ isAlipayTradePaid,
+ validateAlipayOrderResult
+} from '../api/_lib/alipay.js';
+
+const host = '127.0.0.1';
+const port = Number(process.env.ALIPAY_SANDBOX_PORT || 4174);
+const origin = `http://${host}:${port}`;
+const amountCents = 990;
+const orders = new Map();
+const checkoutToken = randomUUID();
+
+function escapeHtml(value) {
+ return String(value || '')
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+}
+
+function send(res, status, body, contentType = 'text/html; charset=utf-8') {
+ res.writeHead(status, {
+ 'Content-Type': contentType,
+ 'Cache-Control': 'no-store, max-age=0',
+ 'X-Content-Type-Options': 'nosniff',
+ 'Referrer-Policy': 'no-referrer'
+ });
+ res.end(body);
+}
+
+function layout(title, content, script = '') {
+ return `<!doctype html>
+<html lang="zh-CN">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>${escapeHtml(title)}</title>
+ <style>
+ :root { color-scheme: light; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; color: #18211d; background: radial-gradient(circle at top, #e8fff3, #f7f5ee 55%); }
+ main { width: min(92vw, 680px); padding: 38px; border: 1px solid #d9ded9; border-radius: 28px; background: rgba(255,255,255,.94); box-shadow: 0 24px 70px rgba(28,50,38,.12); }
+ .eyebrow { color: #087443; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
+ h1 { margin: 10px 0 12px; font-size: clamp(32px, 6vw, 54px); line-height: 1.03; }
+ p { line-height: 1.75; color: #526059; }
+ .price { margin: 30px 0; font-size: 46px; font-weight: 850; }
+ .price small { font-size: 15px; font-weight: 650; color: #66736c; }
+ button, a.button { display: inline-flex; align-items: center; justify-content: center; width: 100%; min-height: 52px; border: 0; border-radius: 14px; color: white; background: #0b7b49; font: inherit; font-weight: 760; cursor: pointer; text-decoration: none; }
+ .notice { margin-top: 22px; padding: 16px; border-radius: 14px; background: #fff7dc; color: #6b5413; font-size: 14px; }
+ .status { margin: 24px 0; padding: 18px; border-radius: 14px; background: #eef7f1; font-weight: 720; }
+ code { overflow-wrap: anywhere; }
+ </style>
+</head>
+<body><main>${content}</main>${script}</body>
+</html>`;
+}
+
+function paymentPage() {
+ return layout('支付宝网站支付沙箱体验', `
+ <div class="eyebrow">Local sandbox only</div>
+ <h1>支付宝网站支付</h1>
+ <p>这是项目本地沙箱体验入口。点击后会生成支付宝沙箱收银台表单,不会产生真实资金扣款,也不会写入线上 Supabase。</p>
+ <div class="price">¥9.90 <small>一次性沙箱订单</small></div>
+ <form method="post" action="/checkout">
+ <input type="hidden" name="checkout_token" value="${escapeHtml(checkoutToken)}">
+ <button type="submit">进入支付宝沙箱收银台</button>
+ </form>
+ <div class="notice">仅用于网站支付联调。生产环境仍使用项目现有的登录、订单、异步通知和资格交付链路。</div>
+ `);
+}
+
+async function readForm(req) {
+ let body = '';
+ for await (const chunk of req) {
+ body += chunk;
+ if (Buffer.byteLength(body) > 8 * 1024) {
+ throw new Error('REQUEST_BODY_TOO_LARGE');
+ }
+ }
+ return new URLSearchParams(body);
+}
+
+function resultPage(orderId) {
+ const safeId = escapeHtml(orderId);
+ return layout('正在确认支付结果', `
+ <div class="eyebrow">Server-side query</div>
+ <h1>正在确认支付结果</h1>
+ <p>页面不会根据回跳参数直接判定成功,而是使用本地保存的订单并由服务端向支付宝查询。</p>
+ <div id="status" class="status">正在查询支付宝订单状态…</div>
+ <p><code>${safeId}</code></p>
+ <a class="button" href="/">返回沙箱付款页</a>
+ `, `<script>
+ const statusNode = document.getElementById('status');
+ const orderId = ${JSON.stringify(orderId)};
+ async function refresh() {
+ try {
+ const response = await fetch('/api/status?order_id=' + encodeURIComponent(orderId), { cache: 'no-store' });
+ const payload = await response.json();
+ if (!response.ok) throw new Error(payload.error || 'QUERY_FAILED');
+ statusNode.textContent = payload.message;
+ if (payload.state === 'PENDING') setTimeout(refresh, 2500);
+ } catch {
+ statusNode.textContent = '暂时无法确认,请稍后刷新页面重试。';
+ }
+ }
+ refresh();
+ </script>`);
+}
+
+async function queryOrder(order) {
+ if (order.status === 'PAID') {
+ return { state: 'PAID', message: '支付宝已确认付款成功(沙箱)。' };
+ }
+
+ const { sdk } = getAlipayClient();
+ const result = await sdk.exec('alipay.trade.query', {
+ bizContent: { out_trade_no: order.id }
+ }, { validateSign: true });
+
+ if (String(result?.code || '') !== '10000') {
+ const code = String(result?.sub_code || result?.code || '');
+ if (code.includes('TRADE_NOT_EXIST')) {
+ return { state: 'PENDING', message: '订单尚未创建或支付宝仍在处理,请稍候…' };
+ }
+ throw new Error('ALIPAY_SANDBOX_QUERY_FAILED');
+ }
+ if (!validateAlipayOrderResult(order, result)) {
+ throw new Error('ALIPAY_SANDBOX_RESULT_MISMATCH');
+ }
+ if (isAlipayTradePaid(result.trade_status)) {
+ order.status = 'PAID';
+ return { state: 'PAID', message: '支付宝已确认付款成功(沙箱)。' };
+ }
+ if (result.trade_status === 'TRADE_CLOSED') {
+ order.status = 'CLOSED';
+ return { state: 'CLOSED', message: '订单已关闭。' };
+ }
+ return { state: 'PENDING', message: '订单待支付,请在沙箱收银台完成付款…' };
+}
+
+const server = createServer(async (req, res) => {
+ const url = new URL(req.url || '/', origin);
+ try {
+ if (req.method === 'GET' && url.pathname === '/') {
+ return send(res, 200, paymentPage());
+ }
+
+ if (req.method === 'GET' && url.pathname === '/checkout') {
+ res.writeHead(303, {
+ Location: '/',
+ 'Cache-Control': 'no-store, max-age=0',
+ 'X-Content-Type-Options': 'nosniff'
+ });
+ return res.end();
+ }
+
+ if (req.method === 'POST' && url.pathname === '/checkout') {
+ const form = await readForm(req);
+ if (form.get('checkout_token') !== checkoutToken) {
+ return send(res, 403, 'forbidden', 'text/plain; charset=utf-8');
+ }
+ const id = randomUUID();
+ const order = {
+ id,
+ amount_cents: amountCents,
+ currency: 'CNY',
+ status: 'PENDING',
+ created_at: new Date().toISOString()
+ };
+ orders.set(id, order);
+
+ const { sdk } = getAlipayClient();
+ const paymentHtml = sdk.pageExec('alipay.trade.page.pay', 'POST', {
+ returnUrl: `${origin}/result?order_id=${encodeURIComponent(id)}`,
+ bizContent: {
+ out_trade_no: id,
+ total_amount: formatAlipayAmount(amountCents),
+ subject: 'GPT-Image2 付费交流群沙箱体验',
+ product_code: 'FAST_INSTANT_TRADE_PAY',
+ timeout_express: '30m'
+ }
+ });
+ if (typeof paymentHtml !== 'string' || !paymentHtml.includes('<form')) {
+ throw new Error('ALIPAY_PAYMENT_FORM_INVALID');
+ }
+ return send(res, 200, paymentHtml);
+ }
+
+ if (req.method === 'GET' && url.pathname === '/result') {
+ const orderId = String(url.searchParams.get('order_id') || '');
+ if (!orders.has(orderId)) {
+ return send(res, 200, layout('未找到本地订单', `
+ <div class="eyebrow">Safe fallback</div>
+ <h1>未找到本地订单</h1>
+ <p>该页面不会仅凭回跳参数展示付款成功。请返回付款页重新创建沙箱订单。</p>
+ <a class="button" href="/">返回沙箱付款页</a>
+ `));
+ }
+ return send(res, 200, resultPage(orderId));
+ }
+
+ if (req.method === 'GET' && url.pathname === '/api/status') {
+ const orderId = String(url.searchParams.get('order_id') || '');
+ const order = orders.get(orderId);
+ if (!order) {
+ return send(res, 404, JSON.stringify({ ok: false, error: 'ORDER_NOT_FOUND' }), 'application/json; charset=utf-8');
+ }
+ const status = await queryOrder(order);
+ return send(res, 200, JSON.stringify({ ok: true, ...status }), 'application/json; charset=utf-8');
+ }
+
+ return send(res, 404, 'not found', 'text/plain; charset=utf-8');
+ } catch (error) {
+ console.warn('Alipay sandbox experience request failed', {
+ path: url.pathname,
+ message: String(error?.message || 'unknown').slice(0, 160)
+ });
+ return send(res, 500, layout('沙箱请求失败', `
+ <div class="eyebrow">Request failed</div>
+ <h1>沙箱请求失败</h1>
+ <p>请回到付款页重试;终端日志只记录脱敏错误类别。</p>
+ <a class="button" href="/">返回沙箱付款页</a>
+ `));
+ }
+});
+
+server.listen(port, host, () => {
+ console.log(`Alipay web payment sandbox: ${origin}/`);
+});
diff --git a/scripts/vite-local-api.mjs b/scripts/vite-local-api.mjs
new file mode 100644
index 0000000..eeaab2c
--- /dev/null
+++ b/scripts/vite-local-api.mjs
@@ -0,0 +1,100 @@
+const routeLoaders = new Map([
+ ['/api/community/config', () => import('../api/community/config.js')],
+ ['/api/community/status', () => import('../api/community/status.js')],
+ ['/api/community/qr', () => import('../api/community/qr.js')],
+ ['/api/community/alipay/checkout', () => import('../api/community/alipay/checkout.js')],
+ ['/api/community/alipay/close', () => import('../api/community/alipay/close.js')],
+ ['/api/community/alipay/query', () => import('../api/community/alipay/query.js')],
+ ['/api/community/alipay/notify', () => import('../api/community/alipay/notify.js')],
+ ['/api/admin/community/orders', () => import('../api/admin/community/orders.js')],
+ ['/api/admin/community/qr', () => import('../api/admin/community/qr.js')],
+ ['/api/admin/community/refund', () => import('../api/admin/community/refund.js')],
+ ['/api/admin/community/refund-query', () => import('../api/admin/community/refund-query.js')],
+ ['/api/admin/community/revoke', () => import('../api/admin/community/revoke.js')]
+]);
+
+function sendJson(res, status, payload) {
+ res.statusCode = status;
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.setHeader('Cache-Control', 'private, no-store, max-age=0');
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.end(JSON.stringify(payload));
+}
+
+function isSupabaseServerConfigured() {
+ return Boolean(
+ (process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL)
+ && process.env.SUPABASE_SERVICE_ROLE_KEY
+ );
+}
+
+function attachVercelResponseHelpers(res) {
+ res.status = (status) => {
+ res.statusCode = status;
+ return res;
+ };
+ res.json = (payload) => {
+ if (!res.headersSent) res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(payload));
+ return res;
+ };
+ res.send = (payload) => {
+ res.end(payload);
+ return res;
+ };
+ res.redirect = (statusOrLocation, maybeLocation) => {
+ const status = typeof statusOrLocation === 'number' ? statusOrLocation : 307;
+ const location = typeof statusOrLocation === 'number' ? maybeLocation : statusOrLocation;
+ res.statusCode = status;
+ res.setHeader('Location', location);
+ res.end();
+ return res;
+ };
+}
+
+export function localVercelApi() {
+ return {
+ name: 'local-vercel-community-api',
+ apply: 'serve',
+ configureServer(server) {
+ server.middlewares.use(async (req, res, next) => {
+ const requestUrl = new URL(req.url || '/', 'http://127.0.0.1');
+ const routeLoader = routeLoaders.get(requestUrl.pathname);
+ const isCommunityApi = requestUrl.pathname.startsWith('/api/community/')
+ || requestUrl.pathname.startsWith('/api/admin/community/');
+
+ if (!routeLoader) {
+ if (isCommunityApi) return sendJson(res, 404, { ok: false, error: 'NOT_FOUND' });
+ return next();
+ }
+
+ if (requestUrl.pathname === '/api/community/status' && !isSupabaseServerConfigured()) {
+ return sendJson(res, 200, {
+ ok: true,
+ authenticated: false,
+ eligible: false,
+ qrReady: false,
+ paymentEnabled: false,
+ order: null,
+ localPreview: true
+ });
+ }
+
+ req.query = Object.fromEntries(requestUrl.searchParams.entries());
+ req.headers['x-forwarded-proto'] ||= 'http';
+ attachVercelResponseHelpers(res);
+
+ try {
+ const module = await routeLoader();
+ await module.default(req, res);
+ } catch (error) {
+ server.config.logger.error(`Local API request failed: ${requestUrl.pathname}`);
+ if (!res.headersSent) {
+ return sendJson(res, 500, { ok: false, error: 'LOCAL_API_FAILED' });
+ }
+ if (!res.writableEnded) res.end();
+ }
+ });
+ }
+ };
+}
diff --git a/src/community.css b/src/community.css
new file mode 100644
index 0000000..4492b34
--- /dev/null
+++ b/src/community.css
@@ -0,0 +1,461 @@
+.communityPage {
+ min-height: 100vh;
+ color: #f6f7fb;
+ background:
+ radial-gradient(circle at 12% 8%, rgba(77, 224, 255, 0.16), transparent 34rem),
+ radial-gradient(circle at 90% 24%, rgba(202, 255, 102, 0.12), transparent 30rem),
+ #080a0d;
+}
+
+.communityTopbar {
+ position: sticky;
+ z-index: 20;
+ top: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 24px;
+ min-height: 68px;
+ padding: 0 5vw;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(8, 10, 13, 0.82);
+ backdrop-filter: blur(20px);
+}
+
+.communityBrand,
+.communityTopbar nav,
+.communityTopbar nav a,
+.communityTopbar nav button {
+ display: flex;
+ align-items: center;
+}
+
+.communityBrand {
+ gap: 10px;
+ color: #fff;
+ font-weight: 800;
+ text-decoration: none;
+}
+
+.communityTopbar nav {
+ gap: 10px;
+}
+
+.communityTopbar nav a,
+.communityTopbar nav button {
+ gap: 7px;
+ min-height: 38px;
+ padding: 0 13px;
+ color: #d8dce4;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.04);
+ font: inherit;
+ text-decoration: none;
+ cursor: pointer;
+}
+
+.communityLanguage {
+ display: flex;
+ padding: 3px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 999px;
+}
+
+.communityTopbar nav .communityLanguage button {
+ min-height: 30px;
+ padding: 0 9px;
+ border: 0;
+ background: transparent;
+}
+
+.communityTopbar nav .communityLanguage button.active {
+ color: #0a0d10;
+ background: #caff66;
+}
+
+.communityMain {
+ width: min(1180px, 90vw);
+ margin: 0 auto;
+ padding: 80px 0 64px;
+}
+
+.communityHero {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: end;
+ gap: 48px;
+ padding-bottom: 52px;
+}
+
+.communityEyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 18px;
+ color: #caff66;
+ font-size: 13px;
+ font-weight: 800;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+}
+
+.communityHero h1 {
+ max-width: 820px;
+ margin: 0;
+ font-size: clamp(40px, 6.5vw, 78px);
+ line-height: 0.98;
+ letter-spacing: -0.055em;
+}
+
+.communityHero p {
+ max-width: 720px;
+ margin: 24px 0 0;
+ color: #aab1bd;
+ font-size: 18px;
+ line-height: 1.75;
+}
+
+.communityPrice {
+ display: grid;
+ grid-template-columns: auto auto;
+ align-items: start;
+ min-width: 180px;
+ padding: 26px;
+ color: #080a0d;
+ border-radius: 28px;
+ background: #caff66;
+ box-shadow: 0 24px 80px rgba(143, 255, 91, 0.18);
+}
+
+.communityPrice span {
+ padding-top: 9px;
+ font-size: 22px;
+ font-weight: 800;
+}
+
+.communityPrice strong {
+ font-size: 56px;
+ line-height: 1;
+ letter-spacing: -0.06em;
+}
+
+.communityPrice em {
+ grid-column: 1 / -1;
+ margin-top: 8px;
+ font-size: 13px;
+ font-style: normal;
+ font-weight: 800;
+ text-align: right;
+ text-transform: uppercase;
+}
+
+.communityContentGrid {
+ display: grid;
+ grid-template-columns: minmax(0, 1.4fr) minmax(300px, 0.72fr);
+ gap: 22px;
+ align-items: start;
+}
+
+.communityPrimary,
+.communitySidebar {
+ display: grid;
+ gap: 18px;
+}
+
+.communityStateCard,
+.communitySidebar section,
+.communitySupport {
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(20, 23, 28, 0.78);
+ box-shadow: 0 18px 70px rgba(0, 0, 0, 0.22);
+}
+
+.communityStateCard {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: 18px;
+ min-height: 250px;
+ padding: 34px;
+ border-radius: 30px;
+}
+
+.communityStateCard.success { border-color: rgba(202, 255, 102, 0.45); }
+.communityStateCard.pending { border-color: rgba(77, 224, 255, 0.4); }
+.communityStateCard.paused,
+.communityStateCard.muted { border-color: rgba(255, 203, 102, 0.28); }
+.communityStateCard.error { border-color: rgba(255, 112, 112, 0.45); }
+
+.communityStateIcon {
+ display: grid;
+ width: 52px;
+ height: 52px;
+ place-items: center;
+ color: #0a0d10;
+ border-radius: 17px;
+ background: #caff66;
+}
+
+.communityStateCard h2,
+.communitySidebar h2,
+.communitySupport h2 {
+ margin: 0;
+ color: #fff;
+}
+
+.communityStateCard h2 { font-size: clamp(25px, 3vw, 38px); }
+
+.communityStateCard p {
+ max-width: 660px;
+ margin: 14px 0 0;
+ color: #b4bbc6;
+ font-size: 16px;
+ line-height: 1.72;
+}
+
+.communityStateActions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ margin-top: 24px;
+}
+
+.communityStateActions button,
+.communityPayButton {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 46px;
+ padding: 0 18px;
+ color: #080a0d;
+ border: 0;
+ border-radius: 13px;
+ background: #caff66;
+ font: inherit;
+ font-weight: 800;
+ cursor: pointer;
+}
+
+.communityStateActions button.secondary {
+ color: #e8ebf1;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+.communityTerms {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 12px;
+ margin: 24px 0 16px;
+ padding: 16px;
+ color: #c5cad3;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 15px;
+ background: rgba(255, 255, 255, 0.03);
+ font-size: 14px;
+ line-height: 1.65;
+}
+
+.communityTerms input {
+ width: 18px;
+ height: 18px;
+ margin-top: 3px;
+ accent-color: #caff66;
+}
+
+.communityPayButton:disabled {
+ cursor: not-allowed;
+ opacity: 0.38;
+}
+
+.communityProtectedQr {
+ display: block;
+ width: min(360px, 100%);
+ margin-top: 24px;
+ padding: 12px;
+ border-radius: 20px;
+ background: #fff;
+}
+
+.communityOrderBadge {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ min-width: 0;
+ padding: 12px 16px;
+ color: #9da5b0;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 14px;
+ background: rgba(255, 255, 255, 0.03);
+ font-size: 12px;
+}
+
+.communityOrderBadge code {
+ overflow: hidden;
+ margin-left: auto;
+ color: #737c89;
+ text-overflow: ellipsis;
+}
+
+.communityInlineNotice {
+ margin: 0;
+ color: #ffcb66;
+}
+
+.communitySidebar section {
+ padding: 25px;
+ border-radius: 22px;
+}
+
+.communitySidebar section.boundary {
+ background: rgba(255, 203, 102, 0.06);
+}
+
+.communitySidebar h2 { font-size: 18px; }
+
+.communitySidebar ul {
+ display: grid;
+ gap: 14px;
+ margin: 20px 0 0;
+ padding: 0;
+ list-style: none;
+}
+
+.communitySidebar li {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 10px;
+ color: #b7bec9;
+ font-size: 14px;
+ line-height: 1.55;
+}
+
+.communitySidebar li svg { margin-top: 3px; color: #caff66; }
+
+.communitySupport {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 16px;
+ margin-top: 22px;
+ padding: 26px;
+ border-radius: 22px;
+}
+
+.communitySupport > svg { color: #4de0ff; }
+.communitySupport h2 { font-size: 18px; }
+.communitySupport p,
+.communitySupport small { display: block; margin: 8px 0 0; color: #aeb5c0; line-height: 1.6; }
+.communitySupport small { color: #727c89; }
+
+.communityPaymentHandoff {
+ position: fixed;
+ z-index: 99999;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ background: #fff;
+}
+
+.communityAdminBlock {
+ margin: 28px 0;
+ padding: 24px;
+ border: 1px solid rgba(202, 255, 102, 0.22);
+ border-radius: 22px;
+ background: rgba(202, 255, 102, 0.035);
+}
+
+.communityAdminHeader,
+.communityAdminHeader > div > span,
+.communityAdminHeader button,
+.communityAdminQr,
+.communityAdminQr label,
+.communityAdminActions {
+ display: flex;
+ align-items: center;
+}
+
+.communityAdminHeader {
+ justify-content: space-between;
+ gap: 18px;
+}
+
+.communityAdminHeader > div > span { gap: 7px; color: #caff66; font-size: 12px; font-weight: 800; text-transform: uppercase; }
+.communityAdminHeader h3 { margin: 6px 0 0; font-size: 22px; }
+.communityAdminHeader button,
+.communityAdminActions button {
+ gap: 7px;
+ min-height: 36px;
+ padding: 0 12px;
+ color: #e9edf4;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.06);
+ font: inherit;
+ cursor: pointer;
+}
+
+.communityAdminQr {
+ gap: 18px;
+ margin-top: 20px;
+ padding: 16px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 16px;
+}
+
+.communityAdminQr img,
+.communityAdminQr > div {
+ width: 96px;
+ height: 96px;
+ border-radius: 12px;
+ object-fit: contain;
+ background: #fff;
+}
+
+.communityAdminQr > div { display: grid; place-items: center; color: #59616d; font-size: 10px; text-align: center; }
+.communityAdminQr label { gap: 8px; padding: 10px 13px; color: #0a0d10; border-radius: 10px; background: #caff66; font-weight: 800; cursor: pointer; }
+.communityAdminQr input { display: none; }
+.communityAdminQr small { color: #8e97a4; }
+.communityAdminMessage { color: #ffcb66; }
+
+.communityAdminTableWrap { overflow-x: auto; margin-top: 18px; }
+.communityAdminTableWrap table { width: 100%; border-collapse: collapse; font-size: 13px; }
+.communityAdminTableWrap th,
+.communityAdminTableWrap td { padding: 12px 10px; border-bottom: 1px solid rgba(255, 255, 255, 0.08); text-align: left; vertical-align: top; }
+.communityAdminTableWrap td strong,
+.communityAdminTableWrap td small { display: block; }
+.communityAdminTableWrap td small { max-width: 220px; overflow: hidden; margin-top: 5px; color: #737d8a; text-overflow: ellipsis; }
+.communityAdminActions { gap: 7px; }
+.communityAdminActions button.danger { color: #ff9d9d; }
+
+.communityOrderStatus { display: inline-flex; padding: 4px 8px; border-radius: 999px; background: rgba(255, 255, 255, 0.08); font-size: 11px; font-weight: 800; }
+.communityOrderStatus.paid { color: #caff66; }
+.communityOrderStatus.pending { color: #4de0ff; }
+.communityOrderStatus.refunded,
+.communityOrderStatus.revoked { color: #ffcb66; }
+
+@media (max-width: 900px) {
+ .communityTopbar { position: static; align-items: flex-start; padding-top: 16px; padding-bottom: 16px; }
+ .communityTopbar nav { flex-wrap: wrap; justify-content: flex-end; }
+ .communityTopbar nav > a:first-child { display: none; }
+ .communityMain { padding-top: 48px; }
+ .communityHero,
+ .communityContentGrid { grid-template-columns: 1fr; }
+ .communityHero { align-items: start; }
+ .communityPrice { justify-self: start; }
+}
+
+@media (max-width: 620px) {
+ .communityTopbar { gap: 12px; padding-inline: 18px; }
+ .communityBrand { max-width: 140px; font-size: 14px; }
+ .communityTopbar nav { gap: 6px; }
+ .communityTopbar nav > button { padding-inline: 10px; }
+ .communityTopbar nav > button svg { display: none; }
+ .communityMain { width: min(92vw, 1180px); }
+ .communityHero { gap: 28px; padding-bottom: 36px; }
+ .communityHero h1 { font-size: 42px; }
+ .communityHero p { font-size: 16px; }
+ .communityStateCard { grid-template-columns: 1fr; padding: 24px; border-radius: 22px; }
+ .communityStateActions { flex-direction: column; align-items: stretch; }
+ .communityAdminQr { align-items: flex-start; flex-direction: column; }
+}
diff --git a/src/community.jsx b/src/community.jsx
new file mode 100644
index 0000000..dac7a35
--- /dev/null
+++ b/src/community.jsx
@@ -0,0 +1,677 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ ArrowLeft,
+ Check,
+ CheckCircle2,
+ CircleAlert,
+ Clock3,
+ CreditCard,
+ ImageUp,
+ LoaderCircle,
+ LockKeyhole,
+ LogIn,
+ LogOut,
+ MessageCircle,
+ RefreshCw,
+ RotateCcw,
+ ShieldCheck,
+ Sparkles,
+ Users,
+ Wrench
+} from 'lucide-react';
+import './community.css';
+
+const TERMS_VERSION = '2026-07-22';
+
+const communityCopy = {
+ zh: {
+ brand: 'GPT-Image2 付费交流群',
+ back: '返回案例库',
+ admin: '管理后台',
+ signIn: '登录',
+ signOut: '退出登录',
+ eyebrow: '一次付费 · 长期资格',
+ title: '和真正做图的人,一起拆 Prompt、案例与工作流。',
+ subtitle: '支付宝一次性支付 ¥9.90。付款资格绑定当前账号,换设备登录后仍可重新查看入群二维码。',
+ priceSuffix: '一次性',
+ benefitsTitle: '群里主要交流什么',
+ benefits: ['GPT-Image2 Prompt 与案例拆解', '生图工具、模型表现与实用工作流', '创作者之间的实战问题与经验交流'],
+ audienceTitle: '更适合这些人',
+ audience: ['正在用 AI 做图或内容生产', '希望把零散 Prompt 变成稳定流程', '愿意分享真实尝试,也尊重他人交流'],
+ boundaryTitle: '服务边界',
+ boundaries: ['不承诺一对一服务或固定答疑次数', '不承诺独家资料、收益结果或永久群活跃度', '违法违规、广告骚扰或破坏交流秩序的账号可被撤销资格'],
+ checking: '正在核对账号与付款资格…',
+ loginTitle: '登录后才能购买和恢复资格',
+ loginText: '资格绑定现有 Supabase 账号,避免二维码公开传播,也方便跨设备恢复。',
+ availableTitle: '准备好后即可支付',
+ availableText: '金额由服务端固定为 ¥9.90,浏览器无法修改。支付完成后由服务器向支付宝查单确认。',
+ terms: '我已阅读并同意:本群以实战交流为主,不包含一对一服务、固定答疑、独家资料或收益承诺;退款需联系管理员人工审核。',
+ pay: '支付宝支付 ¥9.90',
+ redirecting: '正在打开支付宝收银台…',
+ pendingTitle: '订单待支付或待确认',
+ pendingText: '请勿重复付款。若已完成支付,可重新查询同一订单;支付宝通知和主动查单任一确认后都会恢复资格。',
+ query: '重新查询支付结果',
+ closeOrder: '关闭待支付订单',
+ paidTitle: '付款资格已确认',
+ paidText: '请使用微信扫描下方二维码入群。二维码仅对当前已付款账号显示。',
+ qrUpdatingTitle: '付款已确认,群码正在更新',
+ qrUpdatingText: '管理员尚未上传当前群二维码,或刚完成换码。请稍后刷新;你的付款资格不会丢失。',
+ pausedTitle: '当前暂停新订单',
+ pausedText: '已付款用户仍可查看群码,退款和管理员操作也不受影响。',
+ refundedTitle: '该订单已退款',
+ refundedText: '支付宝已确认退款成功,因此该订单的群码访问资格已失效。',
+ revokedTitle: '该资格已被撤销',
+ revokedText: '如有疑问,请通过页面底部的人工支持渠道联系管理员。',
+ failedTitle: '暂时无法完成操作',
+ retry: '重试',
+ support: '退款与人工支持',
+ supportText: '微信搜索苍何。退款经人工审核后原路退回;退款处理中仍保留资格,平台确认成功后才撤销。',
+ resultEyebrow: '支付宝支付结果',
+ resultTitle: '正在由服务器确认这笔订单。',
+ resultText: '本页不会信任网址参数判定付款成功,只展示服务端查单或验签通知确认后的状态。',
+ qrAlt: 'GPT-Image2 付费交流群二维码',
+ noOrder: '当前账号没有可查询的付费群订单。',
+ statusLabels: {
+ PENDING: '待支付', PAID: '已付款', CLOSED: '已关闭', REFUNDED: '已退款', REVOKED: '已撤销'
+ }
+ },
+ en: {
+ brand: 'GPT-Image2 Paid Community',
+ back: 'Back to gallery',
+ admin: 'Admin',
+ signIn: 'Sign in',
+ signOut: 'Sign out',
+ eyebrow: 'One payment · Long-term access',
+ title: 'Discuss prompts, real cases, tools, and practical image workflows.',
+ subtitle: 'A one-time Alipay payment of ¥9.90. Access is tied to your account and can be restored on another device.',
+ priceSuffix: 'one time',
+ benefitsTitle: 'What the group covers',
+ benefits: ['GPT-Image2 prompt and case breakdowns', 'Image tools, model behavior, and practical workflows', 'Peer discussion grounded in real attempts'],
+ audienceTitle: 'A good fit for',
+ audience: ['People using AI for images or content production', 'People turning scattered prompts into stable workflows', 'People willing to share and respect the community'],
+ boundaryTitle: 'Service boundaries',
+ boundaries: ['No promise of one-to-one service or fixed answer frequency', 'No promise of exclusive materials, income, or permanent activity', 'Spam, unlawful behavior, or disruption may lead to access revocation'],
+ checking: 'Checking your account and payment access…',
+ loginTitle: 'Sign in to buy or restore access',
+ loginText: 'Access is tied to your existing account so the group QR stays protected and works across devices.',
+ availableTitle: 'Ready when you are',
+ availableText: 'The server fixes the price at ¥9.90. Payment is confirmed only by a server-side Alipay query or verified notification.',
+ terms: 'I agree that this is a peer discussion group, not one-to-one support, fixed Q&A, exclusive materials, or an income guarantee. Refunds require manual review.',
+ pay: 'Pay ¥9.90 with Alipay',
+ redirecting: 'Opening Alipay checkout…',
+ pendingTitle: 'Payment pending or being confirmed',
+ pendingText: 'Do not pay twice. Query the same order after payment; access is restored after a verified notification or server-side query.',
+ query: 'Query payment again',
+ closeOrder: 'Close pending order',
+ paidTitle: 'Payment access confirmed',
+ paidText: 'Scan the protected QR below with WeChat. It is available only to the signed-in paid account.',
+ qrUpdatingTitle: 'Paid — group QR is being updated',
+ qrUpdatingText: 'The administrator has not uploaded the current QR yet, or is replacing it. Your paid access remains valid.',
+ pausedTitle: 'New payments are paused',
+ pausedText: 'Paid users still retain QR access, while refunds and administrator operations continue.',
+ refundedTitle: 'This order was refunded',
+ refundedText: 'Alipay confirmed the refund, so QR access from this order is no longer active.',
+ revokedTitle: 'This access was revoked',
+ revokedText: 'Contact the administrator through the support channel below if you need help.',
+ failedTitle: 'The operation could not be completed',
+ retry: 'Retry',
+ support: 'Refunds and support',
+ supportText: 'Search 苍何 on WeChat. Approved refunds return through Alipay; access remains active until Alipay confirms success.',
+ resultEyebrow: 'Alipay result',
+ resultTitle: 'The server is confirming this order.',
+ resultText: 'URL parameters are never treated as proof of payment. This page only shows server-verified status.',
+ qrAlt: 'GPT-Image2 paid community QR code',
+ noOrder: 'This account has no paid-community order to query.',
+ statusLabels: {
+ PENDING: 'Pending', PAID: 'Paid', CLOSED: 'Closed', REFUNDED: 'Refunded', REVOKED: 'Revoked'
+ }
+ }
+};
+
+function authHeaders(session) {
+ return session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {};
+}
+
+function submitPaymentForm(paymentHtml) {
+ const container = document.createElement('div');
+ container.className = 'communityPaymentHandoff';
+ container.innerHTML = paymentHtml;
+ document.body.appendChild(container);
+ const form = container.querySelector('form');
+ if (!form) {
+ container.remove();
+ throw new Error('PAYMENT_FORM_INVALID');
+ }
+ form.submit();
+}
+
+function CommunityStateCard({ icon, title, children, tone = '', actions = null }) {
+ return (
+ <section className={`communityStateCard ${tone}`.trim()}>
+ <span className="communityStateIcon">{icon}</span>
+ <div>
+ <h2>{title}</h2>
+ {children}
+ {actions ? <div className="communityStateActions">{actions}</div> : null}
+ </div>
+ </section>
+ );
+}
+
+export function CommunityPage({
+ language,
+ setLanguage,
+ authReady,
+ session,
+ profile,
+ onSignIn,
+ onSignOut,
+ onOpenAdmin
+}) {
+ const t = communityCopy[language] || communityCopy.en;
+ const [config, setConfig] = useState(null);
+ const [communityStatus, setCommunityStatus] = useState(null);
+ const [phase, setPhase] = useState('checking');
+ const [message, setMessage] = useState('');
+ const [acceptedTerms, setAcceptedTerms] = useState(false);
+ const [qrUrl, setQrUrl] = useState('');
+ const [qrState, setQrState] = useState('idle');
+ const resultQueryRef = useRef('');
+ const isResultPage = window.location.pathname.replace(/\/+$/, '') === '/community/result';
+ const resultOrderId = useMemo(
+ () => new URLSearchParams(window.location.search).get('order_id') || '',
+ []
+ );
+
+ useEffect(() => {
+ const previousTitle = document.title;
+ document.title = language === 'zh'
+ ? 'GPT-Image2 付费交流群'
+ : 'GPT-Image2 Paid Community';
+ return () => { document.title = previousTitle; };
+ }, [language]);
+
+ const loadQr = useCallback(async () => {
+ if (!session?.access_token) return;
+ setQrState('loading');
+ try {
+ const response = await fetch('/api/community/qr', {
+ headers: authHeaders(session),
+ cache: 'no-store'
+ });
+ if (!response.ok) {
+ const payload = await response.json().catch(() => ({}));
+ if (payload.error === 'COMMUNITY_QR_NOT_READY') {
+ setQrState('missing');
+ return;
+ }
+ throw new Error(payload.error || 'COMMUNITY_QR_FAILED');
+ }
+ const blob = await response.blob();
+ const nextUrl = URL.createObjectURL(blob);
+ setQrUrl((current) => {
+ if (current) URL.revokeObjectURL(current);
+ return nextUrl;
+ });
+ setQrState('ready');
+ } catch (error) {
+ setQrState('error');
+ setMessage(String(error?.message || 'COMMUNITY_QR_FAILED'));
+ throw error;
+ }
+ }, [session?.access_token]);
+
+ const loadStatus = useCallback(async () => {
+ const response = await fetch('/api/community/status', {
+ headers: authHeaders(session),
+ cache: 'no-store'
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_STATUS_FAILED');
+ setCommunityStatus(payload);
+ if (payload.eligible && payload.qrReady) await loadQr();
+ else {
+ setQrState(payload.eligible ? 'missing' : 'idle');
+ setQrUrl((current) => {
+ if (current) URL.revokeObjectURL(current);
+ return '';
+ });
+ }
+ return payload;
+ }, [loadQr, session?.access_token]);
+
+ useEffect(() => {
+ if (!authReady) return undefined;
+ let cancelled = false;
+ setPhase('checking');
+ setMessage('');
+ Promise.all([
+ fetch('/api/community/config', { cache: 'no-store' }).then((response) => response.json()),
+ loadStatus()
+ ])
+ .then(([configPayload]) => {
+ if (cancelled) return;
+ if (!configPayload?.ok) throw new Error(configPayload?.error || 'COMMUNITY_CONFIG_FAILED');
+ setConfig(configPayload);
+ setPhase('ready');
+ })
+ .catch((error) => {
+ if (!cancelled) {
+ setMessage(String(error?.message || 'COMMUNITY_STATUS_FAILED'));
+ setPhase('failed');
+ }
+ });
+ return () => { cancelled = true; };
+ }, [authReady, loadStatus, session?.access_token]);
+
+ useEffect(() => () => {
+ if (qrUrl) URL.revokeObjectURL(qrUrl);
+ }, [qrUrl]);
+
+ useEffect(() => {
+ if (!authReady || !session?.access_token || !isResultPage || !resultOrderId) return undefined;
+ const key = `${session.user?.id || ''}:${resultOrderId}`;
+ if (resultQueryRef.current === key) return undefined;
+ resultQueryRef.current = key;
+ let cancelled = false;
+ let timeoutId;
+
+ async function confirmAndPoll() {
+ setPhase('checking');
+ try {
+ const response = await fetch(`/api/community/alipay/query?orderId=${encodeURIComponent(resultOrderId)}`, {
+ headers: authHeaders(session),
+ cache: 'no-store'
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok && payload.error !== 'COMMUNITY_QUERY_FAILED') {
+ throw new Error(payload.error || 'COMMUNITY_QUERY_FAILED');
+ }
+
+ let latest = await loadStatus();
+ setPhase('ready');
+ for (let attempt = 0; attempt < 6 && !cancelled && latest.order?.status === 'PENDING'; attempt += 1) {
+ await new Promise((resolve) => {
+ timeoutId = window.setTimeout(resolve, 2500);
+ });
+ if (cancelled) return;
+ latest = await loadStatus();
+ }
+ } catch (error) {
+ if (!cancelled) {
+ setMessage(String(error?.message || 'COMMUNITY_QUERY_FAILED'));
+ setPhase('failed');
+ }
+ }
+ }
+ confirmAndPoll();
+ return () => {
+ cancelled = true;
+ if (timeoutId) window.clearTimeout(timeoutId);
+ };
+ }, [authReady, isResultPage, loadStatus, resultOrderId, session?.access_token, session?.user?.id]);
+
+ async function handleCheckout() {
+ if (!acceptedTerms || !session?.access_token) return;
+ setPhase('redirecting');
+ setMessage('');
+ try {
+ const response = await fetch('/api/community/alipay/checkout', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...authHeaders(session)
+ },
+ body: JSON.stringify({ acceptedTerms: true, termsVersion: TERMS_VERSION })
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_CHECKOUT_FAILED');
+ if (payload.paid) {
+ await loadStatus();
+ setPhase('ready');
+ return;
+ }
+ submitPaymentForm(payload.paymentHtml);
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_CHECKOUT_FAILED'));
+ setPhase('failed');
+ }
+ }
+
+ async function handleRefreshStatus() {
+ setPhase('checking');
+ setMessage('');
+ try {
+ await loadStatus();
+ setPhase('ready');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_STATUS_FAILED'));
+ setPhase('failed');
+ }
+ }
+
+ async function handleQuery() {
+ const orderId = communityStatus?.order?.id;
+ if (!orderId) return;
+ setPhase('checking');
+ setMessage('');
+ try {
+ const response = await fetch(`/api/community/alipay/query?orderId=${encodeURIComponent(orderId)}`, {
+ headers: authHeaders(session),
+ cache: 'no-store'
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_QUERY_FAILED');
+ await loadStatus();
+ setPhase('ready');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_QUERY_FAILED'));
+ setPhase('failed');
+ }
+ }
+
+ async function handleClose() {
+ const orderId = communityStatus?.order?.id;
+ if (!orderId) return;
+ setPhase('checking');
+ setMessage('');
+ try {
+ const response = await fetch('/api/community/alipay/close', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...authHeaders(session)
+ },
+ body: JSON.stringify({ orderId })
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_CLOSE_FAILED');
+ await loadStatus();
+ setPhase('ready');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_CLOSE_FAILED'));
+ setPhase('failed');
+ }
+ }
+
+ const orderStatus = communityStatus?.order?.status || '';
+ const paymentEnabled = Boolean(communityStatus?.paymentEnabled ?? config?.paymentEnabled);
+ let view = 'available';
+ if (!authReady || phase === 'checking') view = 'checking';
+ else if (phase === 'redirecting') view = 'redirecting';
+ else if (phase === 'failed') view = 'failed';
+ else if (!session?.access_token) view = 'login';
+ else if (orderStatus === 'REFUNDED') view = 'refunded';
+ else if (orderStatus === 'REVOKED') view = 'revoked';
+ else if (communityStatus?.eligible && (qrState === 'missing' || !communityStatus.qrReady)) view = 'qrUpdating';
+ else if (communityStatus?.eligible) view = 'paid';
+ else if (orderStatus === 'PENDING') view = 'pending';
+ else if (!paymentEnabled) view = 'paused';
+
+ return (
+ <div className="communityPage">
+ <header className="communityTopbar">
+ <a className="communityBrand" href="/community"><Users size={20} />{t.brand}</a>
+ <nav>
+ <a href="/"><ArrowLeft size={16} />{t.back}</a>
+ <div className="communityLanguage" aria-label="Language">
+ <button className={language === 'en' ? 'active' : ''} type="button" onClick={() => setLanguage('en')}>EN</button>
+ <button className={language === 'zh' ? 'active' : ''} type="button" onClick={() => setLanguage('zh')}>中文</button>
+ </div>
+ {profile?.isSuperAdmin ? <button type="button" onClick={onOpenAdmin}><Wrench size={16} />{t.admin}</button> : null}
+ {session?.access_token
+ ? <button type="button" onClick={onSignOut}><LogOut size={16} />{t.signOut}</button>
+ : <button type="button" onClick={onSignIn}><LogIn size={16} />{t.signIn}</button>}
+ </nav>
+ </header>
+
+ <main className="communityMain">
+ <section className="communityHero">
+ <div>
+ <span className="communityEyebrow"><Sparkles size={15} />{isResultPage ? t.resultEyebrow : t.eyebrow}</span>
+ <h1>{isResultPage ? t.resultTitle : t.title}</h1>
+ <p>{isResultPage ? t.resultText : t.subtitle}</p>
+ </div>
+ <div className="communityPrice">
+ <span>¥</span><strong>9.90</strong><em>{t.priceSuffix}</em>
+ </div>
+ </section>
+
+ <section className="communityContentGrid">
+ <div className="communityPrimary">
+ {view === 'checking' ? (
+ <CommunityStateCard icon={<LoaderCircle className="spinIcon" size={24} />} title={t.checking} />
+ ) : null}
+ {view === 'redirecting' ? (
+ <CommunityStateCard icon={<LoaderCircle className="spinIcon" size={24} />} title={t.redirecting} />
+ ) : null}
+ {view === 'login' ? (
+ <CommunityStateCard
+ icon={<LockKeyhole size={24} />}
+ title={t.loginTitle}
+ actions={<button type="button" onClick={onSignIn}><LogIn size={17} />{t.signIn}</button>}
+ ><p>{t.loginText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'available' ? (
+ <CommunityStateCard icon={<CreditCard size={24} />} title={t.availableTitle}>
+ <p>{t.availableText}</p>
+ <label className="communityTerms">
+ <input type="checkbox" checked={acceptedTerms} onChange={(event) => setAcceptedTerms(event.target.checked)} />
+ <span>{t.terms}</span>
+ </label>
+ <button className="communityPayButton" type="button" disabled={!acceptedTerms} onClick={handleCheckout}>
+ <CreditCard size={18} />{t.pay}
+ </button>
+ </CommunityStateCard>
+ ) : null}
+ {view === 'pending' ? (
+ <CommunityStateCard
+ icon={<Clock3 size={24} />}
+ title={t.pendingTitle}
+ tone="pending"
+ actions={<><button type="button" onClick={handleQuery}><RefreshCw size={17} />{t.query}</button><button className="secondary" type="button" onClick={handleClose}>{t.closeOrder}</button></>}
+ ><p>{t.pendingText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'paid' ? (
+ <CommunityStateCard icon={<CheckCircle2 size={24} />} title={t.paidTitle} tone="success">
+ <p>{t.paidText}</p>
+ {qrUrl ? <img className="communityProtectedQr" src={qrUrl} alt={t.qrAlt} /> : null}
+ </CommunityStateCard>
+ ) : null}
+ {view === 'qrUpdating' ? (
+ <CommunityStateCard
+ icon={<ImageUp size={24} />}
+ title={t.qrUpdatingTitle}
+ tone="pending"
+ actions={<button type="button" onClick={handleRefreshStatus}><RefreshCw size={17} />{t.retry}</button>}
+ ><p>{t.qrUpdatingText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'paused' ? (
+ <CommunityStateCard icon={<CircleAlert size={24} />} title={t.pausedTitle} tone="paused"><p>{t.pausedText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'refunded' ? (
+ <CommunityStateCard icon={<RotateCcw size={24} />} title={t.refundedTitle} tone="muted"><p>{t.refundedText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'revoked' ? (
+ <CommunityStateCard icon={<LockKeyhole size={24} />} title={t.revokedTitle} tone="muted"><p>{t.revokedText}</p></CommunityStateCard>
+ ) : null}
+ {view === 'failed' ? (
+ <CommunityStateCard
+ icon={<CircleAlert size={24} />}
+ title={t.failedTitle}
+ tone="error"
+ actions={<button type="button" onClick={() => { setPhase('checking'); loadStatus().then(() => setPhase('ready')).catch((error) => { setMessage(String(error?.message || 'COMMUNITY_STATUS_FAILED')); setPhase('failed'); }); }}><RefreshCw size={17} />{t.retry}</button>}
+ ><p>{message}</p></CommunityStateCard>
+ ) : null}
+ {isResultPage && authReady && session?.access_token && !resultOrderId ? (
+ <p className="communityInlineNotice">{t.noOrder}</p>
+ ) : null}
+ {communityStatus?.order ? (
+ <div className="communityOrderBadge">
+ <ShieldCheck size={15} />
+ <span>{t.statusLabels[communityStatus.order.status] || communityStatus.order.status}</span>
+ <code>{communityStatus.order.id}</code>
+ </div>
+ ) : null}
+ </div>
+
+ <aside className="communitySidebar">
+ <section><h2>{t.benefitsTitle}</h2><ul>{t.benefits.map((item) => <li key={item}><Check size={16} />{item}</li>)}</ul></section>
+ <section><h2>{t.audienceTitle}</h2><ul>{t.audience.map((item) => <li key={item}><Check size={16} />{item}</li>)}</ul></section>
+ <section className="boundary"><h2>{t.boundaryTitle}</h2><ul>{t.boundaries.map((item) => <li key={item}><ShieldCheck size={16} />{item}</li>)}</ul></section>
+ </aside>
+ </section>
+
+ <section className="communitySupport">
+ <MessageCircle size={21} />
+ <div><h2>{t.support}</h2><p>{config?.support || t.supportText}</p><small>{t.supportText}</small></div>
+ </section>
+ </main>
+ </div>
+ );
+}
+
+export function CommunityAdminSection({ language, session }) {
+ const zh = language === 'zh';
+ const [orders, setOrders] = useState([]);
+ const [qrMeta, setQrMeta] = useState(null);
+ const [qrUrl, setQrUrl] = useState('');
+ const [status, setStatus] = useState('idle');
+ const [message, setMessage] = useState('');
+ const [busyId, setBusyId] = useState('');
+
+ const loadData = useCallback(async () => {
+ if (!session?.access_token) return;
+ setStatus('loading');
+ setMessage('');
+ try {
+ const headers = authHeaders(session);
+ const [ordersResponse, qrResponse] = await Promise.all([
+ fetch('/api/admin/community/orders', { headers, cache: 'no-store' }),
+ fetch('/api/admin/community/qr?metadata=1', { headers, cache: 'no-store' })
+ ]);
+ const ordersPayload = await ordersResponse.json().catch(() => ({}));
+ if (!ordersResponse.ok || !ordersPayload.ok) throw new Error(ordersPayload.error || 'COMMUNITY_ADMIN_ORDERS_FAILED');
+ setOrders(ordersPayload.orders || []);
+ if (qrResponse.ok) {
+ const qrPayload = await qrResponse.json().catch(() => ({}));
+ setQrMeta(qrPayload.asset || null);
+ const imageResponse = await fetch(`/api/admin/community/qr?v=${encodeURIComponent(qrPayload.asset?.id || '')}`, {
+ headers,
+ cache: 'no-store'
+ });
+ if (imageResponse.ok) {
+ const nextUrl = URL.createObjectURL(await imageResponse.blob());
+ setQrUrl((current) => {
+ if (current) URL.revokeObjectURL(current);
+ return nextUrl;
+ });
+ }
+ } else if (qrResponse.status === 404) {
+ setQrMeta(null);
+ setQrUrl((current) => {
+ if (current) URL.revokeObjectURL(current);
+ return '';
+ });
+ } else {
+ const qrPayload = await qrResponse.json().catch(() => ({}));
+ throw new Error(qrPayload.error || 'COMMUNITY_QR_FAILED');
+ }
+ setStatus('ready');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_ADMIN_FAILED'));
+ setStatus('error');
+ }
+ }, [session?.access_token]);
+
+ useEffect(() => { loadData(); }, [loadData]);
+ useEffect(() => () => { if (qrUrl) URL.revokeObjectURL(qrUrl); }, [qrUrl]);
+
+ async function uploadQr(event) {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (!file) return;
+ if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type) || file.size > 2 * 1024 * 1024) {
+ setMessage(zh ? '仅支持 2 MB 内的 PNG、JPEG 或 WebP。' : 'Use a PNG, JPEG, or WebP file under 2 MB.');
+ return;
+ }
+ setStatus('loading');
+ try {
+ const response = await fetch('/api/admin/community/qr', {
+ method: 'POST',
+ headers: { 'Content-Type': file.type, ...authHeaders(session) },
+ body: file
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_QR_UPLOAD_FAILED');
+ await loadData();
+ setMessage(zh ? '群二维码已原子替换。' : 'The group QR was replaced atomically.');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_QR_UPLOAD_FAILED'));
+ setStatus('error');
+ }
+ }
+
+ async function orderAction(order, action) {
+ const destructive = action === 'refund' || action === 'revoke';
+ if (destructive && !window.confirm(zh ? '确认对这笔订单执行该操作?' : 'Confirm this order action?')) return;
+ setBusyId(`${action}:${order.id}`);
+ setMessage('');
+ try {
+ const isQuery = action === 'refund-query';
+ const url = isQuery
+ ? `/api/admin/community/refund-query?orderId=${encodeURIComponent(order.id)}`
+ : `/api/admin/community/${action}`;
+ const response = await fetch(url, {
+ method: isQuery ? 'GET' : 'POST',
+ headers: isQuery ? authHeaders(session) : { 'Content-Type': 'application/json', ...authHeaders(session) },
+ body: isQuery ? undefined : JSON.stringify({ orderId: order.id })
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) throw new Error(payload.error || 'COMMUNITY_ADMIN_ACTION_FAILED');
+ await loadData();
+ setMessage(zh ? '订单状态已更新。' : 'Order status updated.');
+ } catch (error) {
+ setMessage(String(error?.message || 'COMMUNITY_ADMIN_ACTION_FAILED'));
+ } finally {
+ setBusyId('');
+ }
+ }
+
+ return (
+ <section className="communityAdminBlock">
+ <div className="communityAdminHeader">
+ <div><span><Users size={17} />{zh ? '付费交流群' : 'Paid community'}</span><h3>{zh ? '订单、群码与退款' : 'Orders, QR, and refunds'}</h3></div>
+ <button type="button" onClick={loadData} disabled={status === 'loading'}><RefreshCw size={16} />{zh ? '刷新' : 'Refresh'}</button>
+ </div>
+ <div className="communityAdminQr">
+ {qrUrl ? <img src={qrUrl} alt={zh ? '当前付费群二维码' : 'Current paid group QR'} /> : <div><ImageUp size={28} /><span>{zh ? '尚未上传受保护群码' : 'No protected QR uploaded'}</span></div>}
+ <label><ImageUp size={16} />{qrMeta ? (zh ? '替换群二维码' : 'Replace QR') : (zh ? '上传群二维码' : 'Upload QR')}<input type="file" accept="image/png,image/jpeg,image/webp" onChange={uploadQr} /></label>
+ {qrMeta ? <small>{qrMeta.mediaType} · {Math.ceil(qrMeta.sizeBytes / 1024)} KB</small> : null}
+ </div>
+ {message ? <p className="communityAdminMessage">{message}</p> : null}
+ <div className="communityAdminTableWrap">
+ <table>
+ <thead><tr><th>{zh ? '账号' : 'Account'}</th><th>{zh ? '状态' : 'Status'}</th><th>{zh ? '金额' : 'Amount'}</th><th>{zh ? '付款时间' : 'Paid at'}</th><th>{zh ? '退款状态' : 'Refund'}</th><th>{zh ? '操作' : 'Actions'}</th></tr></thead>
+ <tbody>
+ {orders.map((order) => (
+ <tr key={order.id}>
+ <td><strong>{order.email || order.userId}</strong><small>{order.id}</small></td>
+ <td><span className={`communityOrderStatus ${order.status.toLowerCase()}`}>{order.status}</span></td>
+ <td>¥{(order.amountCents / 100).toFixed(2)}</td>
+ <td>{order.paidAt ? new Date(order.paidAt).toLocaleString() : '—'}</td>
+ <td>{order.refundStatus}</td>
+ <td><div className="communityAdminActions">
+ {order.status === 'PAID' && order.refundStatus !== 'PROCESSING' ? <button type="button" disabled={Boolean(busyId)} onClick={() => orderAction(order, 'refund')}>{zh ? '退款' : 'Refund'}</button> : null}
+ {order.status === 'PAID' && order.refundStatus === 'PROCESSING' ? <button type="button" disabled={Boolean(busyId)} onClick={() => orderAction(order, 'refund-query')}>{zh ? '查询退款' : 'Query refund'}</button> : null}
+ {order.status === 'PAID' && order.refundStatus !== 'PROCESSING' ? <button className="danger" type="button" disabled={Boolean(busyId)} onClick={() => orderAction(order, 'revoke')}>{zh ? '撤销资格' : 'Revoke'}</button> : null}
+ </div></td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {!orders.length && status !== 'loading' ? <p>{zh ? '暂无付费群订单。' : 'No paid-community orders yet.'}</p> : null}
+ </div>
+ </section>
+ );
+}
diff --git a/src/main.jsx b/src/main.jsx
index b8f7998..b9787ec 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -34,7 +34,7 @@ import {
} from 'lucide-react';
import './styles.css';
import { isSupabaseConfigured, supabase } from './supabaseClient';
-import wechatCommunityImage from './assets/wechat-community.jpg';
+import { CommunityAdminSection, CommunityPage } from './community';
import skillExampleImage from '../agents/skills/gpt-image-2-style-library/assets/city-life-system-map.png';
const fallbackRepoUrl = 'https://github.com/freestylefly/awesome-gpt-image-2';
@@ -130,6 +130,10 @@ const copy = {
checkoutFailed: 'Checkout failed. Please try again later.',
billingSuccess: 'Payment is processing. Credits will appear after Stripe confirms it.',
billingCancelled: 'Checkout cancelled. You can choose another pack anytime.',
+ alipayReturnPending: 'Returned from Alipay. Confirming the order with Alipay now…',
+ alipayPaymentSuccess: 'Alipay payment confirmed. Your credits are available.',
+ alipayPaymentPending: 'The Alipay result is not confirmed yet. Do not pay again; refresh this return page to query the same order.',
+ alipayQueryFailed: 'The Alipay result could not be confirmed. Do not pay again; refresh this return page or contact support.',
authRequired: 'Sign in to generate a test image.',
signIn: 'Sign in',
signInTitle: 'Sign in to generate test images',
@@ -182,8 +186,11 @@ const copy = {
noTransactions: 'No credit history yet.',
loadBilling: 'Loading billing...',
openBilling: 'Open membership center',
- paymentReady: 'Secure checkout via Stripe.',
- billingNotReady: 'Stripe checkout is not configured yet.',
+ paymentReady: 'Secure checkout via Stripe or Alipay.',
+ billingNotReady: 'No payment provider is configured yet.',
+ payWithStripe: 'Stripe',
+ payWithAlipay: 'Alipay',
+ alipayPriceMissing: 'Alipay price pending',
adminAdjust: 'Adjust credits',
creditAmount: 'Amount',
reason: 'Reason',
@@ -343,6 +350,10 @@ const copy = {
checkoutFailed: '创建支付失败,请稍后再试。',
billingSuccess: '支付正在处理中,Stripe 确认后积分会自动到账。',
billingCancelled: '已取消支付,你可以随时换一个积分包或会员方案。',
+ alipayReturnPending: '已从支付宝返回,正在通过服务端查询订单结果…',
+ alipayPaymentSuccess: '支付宝付款已确认,积分已经到账。',
+ alipayPaymentPending: '支付宝结果暂未确认,请勿重复付款;刷新当前回跳页会继续查询同一订单。',
+ alipayQueryFailed: '暂时无法确认支付宝结果,请勿重复付款;请刷新当前回跳页或联系支持。',
authRequired: '登录后即可生成测试图。',
signIn: '登录',
signInTitle: '登录后生成测试图',
@@ -395,8 +406,11 @@ const copy = {
noTransactions: '暂无积分流水。',
loadBilling: '正在加载会员与积分...',
openBilling: '打开会员中心',
- paymentReady: '使用 Stripe 安全支付。',
- billingNotReady: 'Stripe 支付还没有完成配置。',
+ paymentReady: '支持 Stripe 或支付宝安全支付。',
+ billingNotReady: '支付通道还没有完成配置。',
+ payWithStripe: 'Stripe 支付',
+ payWithAlipay: '支付宝',
+ alipayPriceMissing: '待配置人民币价格',
adminAdjust: '调整积分',
creditAmount: '数量',
reason: '原因',
@@ -802,12 +816,56 @@ function generationErrorMessage(error, language) {
if (error === 'FORBIDDEN') return t.adminOnly;
if (error === 'UPSTREAM_BUSY') return t.generationBusy;
if (error === 'SERVER_NOT_CONFIGURED') return t.serverUnavailable;
- if (error === 'BILLING_NOT_CONFIGURED') return t.checkoutUnavailable;
- if (error === 'CHECKOUT_FAILED' || error === 'BILLING_PORTAL_FAILED') return t.checkoutFailed;
+ if (
+ error === 'BILLING_NOT_CONFIGURED'
+ || error === 'ALIPAY_NOT_CONFIGURED'
+ || error === 'ALIPAY_PRICE_NOT_CONFIGURED'
+ ) return t.checkoutUnavailable;
+ if (
+ error === 'CHECKOUT_FAILED'
+ || error === 'BILLING_PORTAL_FAILED'
+ || error === 'ALIPAY_CHECKOUT_FAILED'
+ ) return t.checkoutFailed;
+ if (
+ error === 'ALIPAY_QUERY_FAILED'
+ || error === 'ALIPAY_PAYMENT_RESULT_MISMATCH'
+ ) return t.alipayQueryFailed;
if (error === 'INVALID_PROMPT') return t.promptRequired;
return t.generationFailed;
}
+function submitAlipayPaymentForm(paymentHtml) {
+ const documentNode = new DOMParser().parseFromString(paymentHtml, 'text/html');
+ const sourceForm = documentNode.querySelector('form');
+ if (!sourceForm) throw new Error('ALIPAY_CHECKOUT_FAILED');
+
+ const action = new URL(sourceForm.getAttribute('action') || '');
+ const allowedHosts = new Set([
+ 'openapi.alipay.com',
+ 'openapi-sandbox.dl.alipaydev.com'
+ ]);
+ if (action.protocol !== 'https:' || !allowedHosts.has(action.hostname)) {
+ throw new Error('ALIPAY_CHECKOUT_FAILED');
+ }
+
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = action.toString();
+ form.acceptCharset = 'utf-8';
+ form.style.display = 'none';
+
+ sourceForm.querySelectorAll('input[name]').forEach((sourceInput) => {
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = sourceInput.getAttribute('name');
+ input.value = sourceInput.getAttribute('value') || '';
+ form.appendChild(input);
+ });
+
+ document.body.appendChild(form);
+ form.submit();
+}
+
function getAuthHeaders(session) {
return session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {};
}
@@ -1107,31 +1165,11 @@ function WeChatIcon({ size = 17 }) {
function CommunityNavItem({ language }) {
const t = copy[language];
- const [open, setOpen] = useState(false);
return (
- <span
- className={cx('communityNavItem', open && 'open')}
- onMouseEnter={() => setOpen(true)}
- onMouseLeave={() => setOpen(false)}
- onFocus={() => setOpen(true)}
- onBlur={(event) => {
- if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
- }}
- >
- <button
- type="button"
- aria-haspopup="dialog"
- aria-expanded={open}
- aria-label={t.navCommunity}
- onClick={() => setOpen((current) => !current)}
- >
- <WeChatIcon />
- {t.navCommunity}
- </button>
- <span className="communityPopover" role="dialog" aria-label={t.navCommunity}>
- <img src={wechatCommunityImage} alt={t.communityQrAlt} loading="lazy" />
- </span>
- </span>
+ <a className="communityNavLink" href="/community" aria-label={t.navCommunity}>
+ <WeChatIcon />
+ {t.navCommunity}
+ </a>
);
}
@@ -1980,6 +2018,8 @@ function AdminPanel({ open, language, session, casesById, onClose, onOpenCase })
</div>
</div>
+ <CommunityAdminSection language={language} session={session} />
+
{metrics ? (
<div className="adminDashboard">
<section className="adminBlock">
@@ -2201,6 +2241,7 @@ function BillingPanel({
const [packs, setPacks] = useState([]);
const [transactions, setTransactions] = useState([]);
const [checkoutAvailable, setCheckoutAvailable] = useState(false);
+ const [checkoutProviders, setCheckoutProviders] = useState({ stripe: false, alipay: false });
const [status, setStatus] = useState('idle');
const [message, setMessage] = useState('');
const [busyProduct, setBusyProduct] = useState('');
@@ -2226,6 +2267,10 @@ function BillingPanel({
setPlans(plansPayload.plans || []);
setPacks(plansPayload.packs || []);
setCheckoutAvailable(Boolean(plansPayload.checkoutAvailable));
+ setCheckoutProviders({
+ stripe: Boolean(plansPayload.checkoutProviders?.stripe),
+ alipay: Boolean(plansPayload.checkoutProviders?.alipay)
+ });
if (plansPayload.user) onProfileChange(plansPayload.user);
if (historyResponse) {
@@ -2248,21 +2293,27 @@ function BillingPanel({
if (open) loadBilling();
}, [open, session?.access_token]);
- async function handleCheckout(product) {
+ useEffect(() => {
+ if (open && notice) setMessage(notice);
+ }, [notice, open]);
+
+ async function handleCheckout(product, provider = 'stripe') {
if (!session?.access_token) {
onAuthRequired();
return;
}
- if (!checkoutAvailable) {
+ if (!checkoutProviders[provider] || (provider === 'alipay' && !product.alipayAvailable)) {
setMessage(t.checkoutUnavailable);
return;
}
- setBusyProduct(`${product.type}:${product.id}`);
+ setBusyProduct(`${provider}:${product.type}:${product.id}`);
setMessage('');
try {
- const response = await fetch('/api/billing/checkout', {
+ const response = await fetch(
+ provider === 'alipay' ? '/api/billing/alipay/checkout' : '/api/billing/checkout',
+ {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -2272,13 +2323,21 @@ function BillingPanel({
productType: product.type,
productId: product.id
})
- });
+ }
+ );
const payload = await response.json().catch(() => ({}));
- if (!response.ok || !payload.ok || !payload.url) {
+ if (!response.ok || !payload.ok) {
throw new Error(payload.error || 'CHECKOUT_FAILED');
}
if (payload.user) onProfileChange(payload.user);
- window.location.href = payload.url;
+
+ if (provider === 'alipay') {
+ if (!payload.paymentHtml) throw new Error('ALIPAY_CHECKOUT_FAILED');
+ submitAlipayPaymentForm(payload.paymentHtml);
+ } else {
+ if (!payload.url) throw new Error('CHECKOUT_FAILED');
+ window.location.href = payload.url;
+ }
} catch (error) {
setBusyProduct('');
setMessage(generationErrorMessage(error.message, language));
@@ -2384,14 +2443,18 @@ function BillingPanel({
<div className="billingCards">
{plans.map((plan) => {
const isCurrent = activePlanId === plan.id;
- const busy = busyProduct === `${plan.type}:${plan.id}`;
+ const busy = busyProduct === `stripe:${plan.type}:${plan.id}`;
return (
<article className={cx('billingCard', isCurrent && 'current')} key={plan.id}>
<span>{productText(plan.name, language)}</span>
<strong>{plan.priceLabel}<small>/{plan.interval}</small></strong>
<p>{productText(plan.description, language)}</p>
<div className="billingCredits">{t.monthlyCredits(plan.monthlyCredits)}</div>
- <button type="button" disabled={busy || isCurrent} onClick={() => handleCheckout(plan)}>
+ <button
+ type="button"
+ disabled={busy || isCurrent || !checkoutProviders.stripe}
+ onClick={() => handleCheckout(plan, 'stripe')}
+ >
{busy ? <LoaderCircle className="spinIcon" size={16} /> : <Crown size={16} />}
{isCurrent ? t.currentPlan : t.subscribe}
</button>
@@ -2414,17 +2477,36 @@ function BillingPanel({
</h3>
<div className="billingCards">
{packs.map((pack) => {
- const busy = busyProduct === `${pack.type}:${pack.id}`;
+ const stripeBusy = busyProduct === `stripe:${pack.type}:${pack.id}`;
+ const alipayBusy = busyProduct === `alipay:${pack.type}:${pack.id}`;
+ const busy = stripeBusy || alipayBusy;
return (
<article className="billingCard" key={pack.id}>
<span>{productText(pack.name, language)}</span>
<strong>{pack.priceLabel}</strong>
<p>{productText(pack.description, language)}</p>
<div className="billingCredits">{t.packCredits(pack.credits)}</div>
- <button type="button" disabled={busy} onClick={() => handleCheckout(pack)}>
- {busy ? <LoaderCircle className="spinIcon" size={16} /> : <Coins size={16} />}
- {t.buyCredits}
- </button>
+ <div className="billingPaymentActions">
+ <button
+ type="button"
+ disabled={busy || !checkoutProviders.stripe}
+ onClick={() => handleCheckout(pack, 'stripe')}
+ >
+ {stripeBusy ? <LoaderCircle className="spinIcon" size={16} /> : <CreditCard size={16} />}
+ {t.payWithStripe}
+ </button>
+ <button
+ className="alipayButton"
+ type="button"
+ disabled={busy || !checkoutProviders.alipay || !pack.alipayAvailable}
+ onClick={() => handleCheckout(pack, 'alipay')}
+ >
+ {alipayBusy ? <LoaderCircle className="spinIcon" size={16} /> : <Coins size={16} />}
+ {pack.alipayAvailable
+ ? `${t.payWithAlipay} · ${pack.alipayPriceLabel}`
+ : t.alipayPriceMissing}
+ </button>
+ </div>
</article>
);
})}
@@ -3007,6 +3089,7 @@ function App() {
const [scene, setScene] = useState('All');
const [preview, setPreview] = useState(null);
const [session, setSession] = useState(null);
+ const [authReady, setAuthReady] = useState(!isSupabaseConfigured || !supabase);
const [profile, setProfile] = useState(null);
const [favoriteRows, setFavoriteRows] = useState([]);
const [favoriteBusyId, setFavoriteBusyId] = useState(null);
@@ -3018,6 +3101,8 @@ function App() {
const [adminOpen, setAdminOpen] = useState(false);
const [billingOpen, setBillingOpen] = useState(false);
const [billingNotice, setBillingNotice] = useState('');
+ const [billingReturnOrderId, setBillingReturnOrderId] = useState('');
+ const alipayReturnHandledRef = useRef('');
const { copiedId, copyPrompt, copyText } = useCopy();
const repoUrl = siteData?.repository || fallbackRepoUrl;
const t = copy[language];
@@ -3062,12 +3147,20 @@ function App() {
if (!isSupabaseConfigured || !supabase) return undefined;
let active = true;
- supabase.auth.getSession().then(({ data }) => {
- if (active) setSession(data.session || null);
- });
+ supabase.auth.getSession()
+ .then(({ data }) => {
+ if (active) setSession(data.session || null);
+ })
+ .catch(() => {
+ if (active) setSession(null);
+ })
+ .finally(() => {
+ if (active) setAuthReady(true);
+ });
const { data } = supabase.auth.onAuthStateChange((_event, nextSession) => {
setSession(nextSession || null);
+ setAuthReady(true);
});
return () => {
@@ -3166,6 +3259,18 @@ function App() {
const params = new URLSearchParams(window.location.search);
const billing = params.get('billing');
if (!billing) return;
+ if (billing === 'alipay_return') {
+ const orderId = params.get('order_id') || '';
+ setBillingReturnOrderId(orderId);
+ setBillingNotice(t.alipayReturnPending);
+ setBillingOpen(true);
+
+ const cleanParams = new URLSearchParams({ billing: 'alipay_return' });
+ if (orderId) cleanParams.set('order_id', orderId);
+ const nextUrl = `${window.location.pathname}?${cleanParams.toString()}${window.location.hash}`;
+ window.history.replaceState({}, '', nextUrl);
+ return;
+ }
if (billing === 'success') setBillingNotice(t.billingSuccess);
if (billing === 'cancelled') setBillingNotice(t.billingCancelled);
setBillingOpen(true);
@@ -3174,7 +3279,35 @@ function App() {
const nextSearch = params.toString();
const nextUrl = `${window.location.pathname}${nextSearch ? `?${nextSearch}` : ''}${window.location.hash}`;
window.history.replaceState({}, '', nextUrl);
- }, [t.billingCancelled, t.billingSuccess]);
+ }, [t.alipayReturnPending, t.billingCancelled, t.billingSuccess]);
+
+ useEffect(() => {
+ if (!billingReturnOrderId || !session?.access_token) return undefined;
+ const handledKey = `${billingReturnOrderId}:${session.user?.id || ''}`;
+ if (alipayReturnHandledRef.current === handledKey) return undefined;
+ alipayReturnHandledRef.current = handledKey;
+
+ let cancelled = false;
+ fetch(`/api/billing/alipay/query?orderId=${encodeURIComponent(billingReturnOrderId)}`, {
+ headers: getAuthHeaders(session)
+ })
+ .then(async (response) => {
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) {
+ throw new Error(payload.error || 'ALIPAY_QUERY_FAILED');
+ }
+ if (cancelled) return;
+ if (payload.user) setProfile(payload.user);
+ setBillingNotice(payload.paid ? t.alipayPaymentSuccess : t.alipayPaymentPending);
+ })
+ .catch((error) => {
+ if (!cancelled) setBillingNotice(generationErrorMessage(error.message, language));
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [billingReturnOrderId, language, session?.access_token, session?.user?.id, t.alipayPaymentPending, t.alipayPaymentSuccess]);
const latestCases = useMemo(() => {
if (!siteData) return [];
@@ -3333,6 +3466,43 @@ function App() {
setAccountInitialSection('overview');
}
+ const normalizedPath = window.location.pathname.replace(/\/+$/, '') || '/';
+ const isCommunityRoute = normalizedPath === '/community' || normalizedPath === '/community/result';
+
+ if (isCommunityRoute) {
+ return (
+ <main>
+ <CommunityPage
+ language={language}
+ setLanguage={setLanguage}
+ authReady={authReady}
+ session={session}
+ profile={profile}
+ onSignIn={openAuth}
+ onSignOut={handleSignOut}
+ onOpenAdmin={() => setAdminOpen(true)}
+ />
+ <AuthModal
+ open={authOpen}
+ language={language}
+ initialErrorCode={authErrorCode}
+ onClose={() => {
+ setAuthOpen(false);
+ setAuthErrorCode('');
+ }}
+ />
+ <AdminPanel
+ open={adminOpen}
+ language={language}
+ session={session}
+ casesById={casesById}
+ onClose={() => setAdminOpen(false)}
+ onOpenCase={handleOpenCaseFromAdmin}
+ />
+ </main>
+ );
+ }
+
if (!siteData || !styleLibrary) {
return (
<main>
diff --git a/src/styles.css b/src/styles.css
index e6af5ab..0d97729 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -2833,6 +2833,17 @@ button {
color: #ffffff;
}
+.billingPaymentActions {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.billingCard .alipayButton {
+ background: linear-gradient(135deg, rgba(22, 119, 255, 0.34), rgba(62, 171, 255, 0.2));
+ border-color: rgba(62, 171, 255, 0.48);
+}
+
.billingCard button:disabled,
.portalButton:disabled,
.accountForm button:disabled,
diff --git a/supabase/migrations/20260721090000_alipay_webpay.sql b/supabase/migrations/20260721090000_alipay_webpay.sql
new file mode 100644
index 0000000..546c1eb
--- /dev/null
+++ b/supabase/migrations/20260721090000_alipay_webpay.sql
@@ -0,0 +1,343 @@
+alter table public.credit_packs
+ add column if not exists alipay_amount_cents integer
+ check (alipay_amount_cents is null or alipay_amount_cents > 0);
+
+alter table public.payment_orders
+ add column if not exists payment_provider text not null default 'stripe',
+ add column if not exists provider_trade_no text,
+ add column if not exists provider_refund_request_no text;
+
+alter table public.payment_orders
+ drop constraint if exists payment_orders_payment_provider_check;
+
+alter table public.payment_orders
+ add constraint payment_orders_payment_provider_check
+ check (payment_provider in ('stripe', 'alipay'));
+
+alter table public.payment_orders
+ drop constraint if exists payment_orders_status_check;
+
+alter table public.payment_orders
+ add constraint payment_orders_status_check
+ check (status in (
+ 'created',
+ 'checkout_created',
+ 'completed',
+ 'failed',
+ 'canceled',
+ 'refund_pending',
+ 'refunded'
+ ));
+
+create unique index if not exists payment_orders_provider_trade_no_idx
+ on public.payment_orders (payment_provider, provider_trade_no)
+ where provider_trade_no is not null;
+
+create unique index if not exists payment_orders_provider_refund_request_no_idx
+ on public.payment_orders (payment_provider, provider_refund_request_no)
+ where provider_refund_request_no is not null;
+
+create table if not exists public.alipay_notify_events (
+ id bigint generated by default as identity primary key,
+ order_id uuid not null references public.payment_orders(id) on delete cascade,
+ notify_id text not null unique,
+ trade_no text not null,
+ trade_status text not null,
+ payload jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create unique index if not exists alipay_notify_order_trade_event_idx
+ on public.alipay_notify_events (order_id, trade_no, trade_status, notify_id);
+
+alter table public.alipay_notify_events enable row level security;
+
+revoke all on table public.alipay_notify_events from public, anon, authenticated;
+grant all on table public.alipay_notify_events to service_role;
+grant usage, select on sequence public.alipay_notify_events_id_seq to service_role;
+
+drop function if exists public.complete_alipay_credit_pack_order(uuid, text, integer);
+
+create or replace function public.complete_alipay_credit_pack_order(
+ p_order_id uuid,
+ p_trade_no text,
+ p_paid_amount_cents integer,
+ p_notify_id text default null,
+ p_notify_payload jsonb default '{}'::jsonb
+)
+returns table (
+ completed boolean,
+ credit_balance integer
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.payment_orders%rowtype;
+ v_balance integer;
+begin
+ select po.*
+ into v_order
+ from public.payment_orders as po
+ where po.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'PAYMENT_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ if v_order.payment_provider <> 'alipay' or v_order.product_type <> 'credit_pack' then
+ raise exception 'INVALID_ALIPAY_ORDER' using errcode = 'P0001';
+ end if;
+
+ if p_trade_no is null or btrim(p_trade_no) = '' then
+ raise exception 'ALIPAY_TRADE_NO_REQUIRED' using errcode = 'P0001';
+ end if;
+
+ if p_paid_amount_cents <> v_order.amount_cents then
+ raise exception 'ALIPAY_AMOUNT_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ if p_notify_id is not null and btrim(p_notify_id) <> '' then
+ insert into public.alipay_notify_events (
+ order_id,
+ notify_id,
+ trade_no,
+ trade_status,
+ payload
+ )
+ values (
+ v_order.id,
+ p_notify_id,
+ p_trade_no,
+ coalesce(nullif(p_notify_payload ->> 'trade_status', ''), 'TRADE_SUCCESS'),
+ coalesce(p_notify_payload, '{}'::jsonb)
+ )
+ on conflict (notify_id) do nothing;
+ end if;
+
+ if v_order.status = 'completed' then
+ if v_order.provider_trade_no is not null and v_order.provider_trade_no <> p_trade_no then
+ raise exception 'ALIPAY_TRADE_NO_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ select p.credit_balance
+ into v_balance
+ from public.profiles as p
+ where p.id = v_order.user_id;
+
+ return query select false, v_balance;
+ return;
+ end if;
+
+ if v_order.status not in ('created', 'checkout_created') then
+ raise exception 'ALIPAY_ORDER_NOT_COMPLETABLE' using errcode = 'P0001';
+ end if;
+
+ update public.profiles as p
+ set credit_balance = p.credit_balance + v_order.credits
+ where p.id = v_order.user_id
+ returning p.credit_balance into v_balance;
+
+ if not found then
+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ insert into public.credit_transactions (
+ user_id,
+ amount,
+ type,
+ source,
+ reference_id,
+ metadata
+ )
+ values (
+ v_order.user_id,
+ v_order.credits,
+ 'purchase',
+ 'alipay_webpay',
+ v_order.id,
+ jsonb_build_object(
+ 'alipayTradeNo', p_trade_no,
+ 'productId', v_order.product_id
+ )
+ );
+
+ update public.payment_orders as po
+ set status = 'completed',
+ provider_trade_no = p_trade_no,
+ completed_at = coalesce(po.completed_at, now()),
+ metadata = po.metadata || jsonb_build_object('paidAmountCents', p_paid_amount_cents)
+ where po.id = v_order.id;
+
+ return query select true, v_balance;
+end;
+$$;
+
+create or replace function public.prepare_alipay_credit_pack_refund(
+ p_order_id uuid,
+ p_refund_request_no text
+)
+returns table (
+ refund_request_no text,
+ refund_amount_cents integer,
+ already_prepared boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.payment_orders%rowtype;
+ v_balance integer;
+begin
+ select po.*
+ into v_order
+ from public.payment_orders as po
+ where po.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'PAYMENT_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ if v_order.payment_provider <> 'alipay' or v_order.product_type <> 'credit_pack' then
+ raise exception 'INVALID_ALIPAY_ORDER' using errcode = 'P0001';
+ end if;
+
+ if p_refund_request_no is null or btrim(p_refund_request_no) = '' then
+ raise exception 'REFUND_REQUEST_NO_REQUIRED' using errcode = 'P0001';
+ end if;
+
+ if v_order.status in ('refund_pending', 'refunded') then
+ if v_order.provider_refund_request_no <> p_refund_request_no then
+ raise exception 'REFUND_REQUEST_NO_MISMATCH' using errcode = 'P0001';
+ end if;
+ return query select p_refund_request_no, v_order.amount_cents, true;
+ return;
+ end if;
+
+ if v_order.status <> 'completed' then
+ raise exception 'ALIPAY_ORDER_NOT_REFUNDABLE' using errcode = 'P0001';
+ end if;
+
+ select p.credit_balance
+ into v_balance
+ from public.profiles as p
+ where p.id = v_order.user_id
+ for update;
+
+ if not found then
+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ if v_balance < v_order.credits then
+ raise exception 'PURCHASED_CREDITS_ALREADY_USED' using errcode = 'P0001';
+ end if;
+
+ update public.profiles as p
+ set credit_balance = p.credit_balance - v_order.credits
+ where p.id = v_order.user_id;
+
+ insert into public.credit_transactions (
+ user_id,
+ amount,
+ type,
+ source,
+ reference_id,
+ metadata
+ )
+ values (
+ v_order.user_id,
+ -v_order.credits,
+ 'refund',
+ 'alipay_webpay_refund_reserve',
+ v_order.id,
+ jsonb_build_object(
+ 'refundRequestNo', p_refund_request_no,
+ 'productId', v_order.product_id
+ )
+ );
+
+ update public.payment_orders as po
+ set status = 'refund_pending',
+ provider_refund_request_no = p_refund_request_no,
+ metadata = po.metadata || jsonb_build_object('refundPreparedAt', now())
+ where po.id = v_order.id;
+
+ return query select p_refund_request_no, v_order.amount_cents, false;
+end;
+$$;
+
+create or replace function public.finalize_alipay_credit_pack_refund(
+ p_order_id uuid,
+ p_trade_no text,
+ p_refund_amount_cents integer
+)
+returns table (
+ finalized boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.payment_orders%rowtype;
+begin
+ select po.*
+ into v_order
+ from public.payment_orders as po
+ where po.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'PAYMENT_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ if v_order.payment_provider <> 'alipay' or v_order.product_type <> 'credit_pack' then
+ raise exception 'INVALID_ALIPAY_ORDER' using errcode = 'P0001';
+ end if;
+
+ if v_order.provider_trade_no is not null and v_order.provider_trade_no <> p_trade_no then
+ raise exception 'ALIPAY_TRADE_NO_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ if p_refund_amount_cents is null or p_refund_amount_cents <> v_order.amount_cents then
+ raise exception 'ALIPAY_REFUND_AMOUNT_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ if v_order.status = 'refunded' then
+ return query select false;
+ return;
+ end if;
+
+ if v_order.status <> 'refund_pending' then
+ raise exception 'ALIPAY_REFUND_NOT_PREPARED' using errcode = 'P0001';
+ end if;
+
+ update public.payment_orders as po
+ set status = 'refunded',
+ metadata = po.metadata || jsonb_build_object(
+ 'refundedAt', now(),
+ 'refundAmountCents', p_refund_amount_cents
+ )
+ where po.id = v_order.id;
+
+ return query select true;
+end;
+$$;
+
+revoke execute on function public.complete_alipay_credit_pack_order(uuid, text, integer, text, jsonb)
+ from public, anon, authenticated;
+revoke execute on function public.prepare_alipay_credit_pack_refund(uuid, text)
+ from public, anon, authenticated;
+revoke execute on function public.finalize_alipay_credit_pack_refund(uuid, text, integer)
+ from public, anon, authenticated;
+
+grant execute on function public.complete_alipay_credit_pack_order(uuid, text, integer, text, jsonb)
+ to service_role;
+grant execute on function public.prepare_alipay_credit_pack_refund(uuid, text)
+ to service_role;
+grant execute on function public.finalize_alipay_credit_pack_refund(uuid, text, integer)
+ to service_role;
diff --git a/supabase/migrations/20260722090000_paid_community.sql b/supabase/migrations/20260722090000_paid_community.sql
new file mode 100644
index 0000000..4e3a643
--- /dev/null
+++ b/supabase/migrations/20260722090000_paid_community.sql
@@ -0,0 +1,503 @@
+create table if not exists public.community_orders (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references auth.users(id) on delete cascade,
+ status text not null default 'PENDING'
+ check (status in ('PENDING', 'PAID', 'CLOSED', 'REFUNDED', 'REVOKED')),
+ amount_cents integer not null default 990 check (amount_cents = 990),
+ currency text not null default 'CNY' check (currency = 'CNY'),
+ subject text not null default 'GPT-Image2 付费交流群长期资格',
+ terms_version text not null,
+ alipay_app_id text,
+ alipay_seller_id text,
+ alipay_trade_no text,
+ refund_request_no text,
+ refund_status text not null default 'NONE'
+ check (refund_status in ('NONE', 'PROCESSING', 'SUCCEEDED', 'FAILED')),
+ refund_failure_code text,
+ paid_amount_cents integer check (paid_amount_cents is null or paid_amount_cents = 990),
+ paid_currency text check (paid_currency is null or paid_currency = 'CNY'),
+ metadata jsonb not null default '{}'::jsonb,
+ expires_at timestamptz not null default (now() + interval '30 minutes'),
+ paid_at timestamptz,
+ refund_requested_at timestamptz,
+ refund_checked_at timestamptz,
+ refunded_at timestamptz,
+ revoked_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create unique index if not exists community_orders_one_active_per_user_idx
+ on public.community_orders (user_id)
+ where status in ('PENDING', 'PAID');
+
+create unique index if not exists community_orders_alipay_trade_no_idx
+ on public.community_orders (alipay_trade_no)
+ where alipay_trade_no is not null;
+
+create unique index if not exists community_orders_refund_request_no_idx
+ on public.community_orders (refund_request_no)
+ where refund_request_no is not null;
+
+create index if not exists community_orders_created_at_idx
+ on public.community_orders (created_at desc);
+
+create index if not exists community_orders_status_idx
+ on public.community_orders (status, created_at desc);
+
+create table if not exists public.community_alipay_notify_events (
+ id bigint generated by default as identity primary key,
+ order_id uuid not null references public.community_orders(id) on delete cascade,
+ notify_id text not null unique,
+ trade_no text not null,
+ trade_status text not null,
+ payload jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create unique index if not exists community_alipay_notify_order_trade_event_idx
+ on public.community_alipay_notify_events (order_id, trade_no, trade_status, notify_id);
+
+create table if not exists public.community_group_qr_assets (
+ id uuid primary key default gen_random_uuid(),
+ media_type text not null check (media_type in ('image/png', 'image/jpeg', 'image/webp')),
+ qr_bytes bytea not null,
+ size_bytes integer not null check (size_bytes > 0 and size_bytes <= 2097152),
+ is_current boolean not null default false,
+ uploaded_by uuid not null references auth.users(id),
+ created_at timestamptz not null default now(),
+ retired_at timestamptz
+);
+
+create unique index if not exists community_group_qr_one_current_idx
+ on public.community_group_qr_assets ((true))
+ where is_current;
+
+drop trigger if exists community_orders_set_updated_at on public.community_orders;
+create trigger community_orders_set_updated_at
+ before update on public.community_orders
+ for each row
+ execute function public.set_updated_at();
+
+alter table public.community_orders enable row level security;
+alter table public.community_alipay_notify_events enable row level security;
+alter table public.community_group_qr_assets enable row level security;
+
+revoke all on table public.community_orders from public, anon, authenticated;
+revoke all on table public.community_alipay_notify_events from public, anon, authenticated;
+revoke all on table public.community_group_qr_assets from public, anon, authenticated;
+
+grant all on table public.community_orders to service_role;
+grant all on table public.community_alipay_notify_events to service_role;
+grant all on table public.community_group_qr_assets to service_role;
+grant usage, select on sequence public.community_alipay_notify_events_id_seq to service_role;
+
+create or replace function public.create_or_reuse_community_order(
+ p_user_id uuid,
+ p_terms_version text
+)
+returns public.community_orders
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ if p_user_id is null then
+ raise exception 'COMMUNITY_USER_REQUIRED' using errcode = 'P0001';
+ end if;
+ if p_terms_version is null or btrim(p_terms_version) = '' then
+ raise exception 'COMMUNITY_TERMS_REQUIRED' using errcode = 'P0001';
+ end if;
+
+ perform pg_advisory_xact_lock(hashtext(p_user_id::text));
+
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.user_id = p_user_id
+ and co.status in ('PENDING', 'PAID')
+ order by co.created_at desc
+ limit 1
+ for update;
+
+ if found then
+ return v_order;
+ end if;
+
+ insert into public.community_orders (
+ user_id,
+ status,
+ amount_cents,
+ currency,
+ subject,
+ terms_version
+ )
+ values (
+ p_user_id,
+ 'PENDING',
+ 990,
+ 'CNY',
+ 'GPT-Image2 付费交流群长期资格',
+ p_terms_version
+ )
+ returning * into v_order;
+
+ return v_order;
+end;
+$$;
+
+create or replace function public.mark_community_order_paid(
+ p_order_id uuid,
+ p_trade_no text,
+ p_paid_amount_cents integer,
+ p_paid_currency text,
+ p_notify_id text default null,
+ p_notify_payload jsonb default '{}'::jsonb
+)
+returns table (
+ current_status text,
+ transitioned boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+ if p_trade_no is null or btrim(p_trade_no) = '' then
+ raise exception 'ALIPAY_TRADE_NO_REQUIRED' using errcode = 'P0001';
+ end if;
+ if p_paid_amount_cents <> v_order.amount_cents or p_paid_amount_cents <> 990 then
+ raise exception 'COMMUNITY_AMOUNT_MISMATCH' using errcode = 'P0001';
+ end if;
+ if p_paid_currency <> v_order.currency or p_paid_currency <> 'CNY' then
+ raise exception 'COMMUNITY_CURRENCY_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ if v_order.alipay_trade_no is not null and v_order.alipay_trade_no <> p_trade_no then
+ raise exception 'ALIPAY_TRADE_NO_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ if p_notify_id is not null and btrim(p_notify_id) <> '' then
+ insert into public.community_alipay_notify_events (
+ order_id,
+ notify_id,
+ trade_no,
+ trade_status,
+ payload
+ )
+ values (
+ v_order.id,
+ p_notify_id,
+ p_trade_no,
+ coalesce(nullif(p_notify_payload ->> 'trade_status', ''), 'TRADE_SUCCESS'),
+ coalesce(p_notify_payload, '{}'::jsonb)
+ )
+ on conflict (notify_id) do nothing;
+ end if;
+
+ if v_order.status in ('PAID', 'REFUNDED', 'REVOKED') then
+ return query select v_order.status, false;
+ return;
+ end if;
+ if v_order.status <> 'PENDING' then
+ raise exception 'COMMUNITY_ORDER_NOT_PAYABLE' using errcode = 'P0001';
+ end if;
+
+ update public.community_orders as co
+ set status = 'PAID',
+ alipay_trade_no = p_trade_no,
+ paid_amount_cents = p_paid_amount_cents,
+ paid_currency = p_paid_currency,
+ paid_at = coalesce(co.paid_at, now())
+ where co.id = v_order.id;
+
+ return query select 'PAID'::text, true;
+end;
+$$;
+
+create or replace function public.close_community_order(p_order_id uuid)
+returns table (
+ current_status text,
+ transitioned boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+ if v_order.status <> 'PENDING' then
+ return query select v_order.status, false;
+ return;
+ end if;
+
+ update public.community_orders as co
+ set status = 'CLOSED'
+ where co.id = v_order.id;
+ return query select 'CLOSED'::text, true;
+end;
+$$;
+
+create or replace function public.prepare_community_refund(
+ p_order_id uuid,
+ p_refund_request_no text
+)
+returns table (
+ refund_request_no text,
+ refund_amount_cents integer,
+ already_prepared boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+ if v_order.status = 'REFUNDED' then
+ return query select v_order.refund_request_no, v_order.amount_cents, true;
+ return;
+ end if;
+ if v_order.status <> 'PAID' then
+ raise exception 'COMMUNITY_ORDER_NOT_REFUNDABLE' using errcode = 'P0001';
+ end if;
+ if p_refund_request_no is null or btrim(p_refund_request_no) = '' then
+ raise exception 'REFUND_REQUEST_NO_REQUIRED' using errcode = 'P0001';
+ end if;
+ if v_order.refund_request_no is not null and v_order.refund_request_no <> p_refund_request_no then
+ raise exception 'REFUND_REQUEST_NO_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ update public.community_orders as co
+ set refund_request_no = p_refund_request_no,
+ refund_status = 'PROCESSING',
+ refund_failure_code = null,
+ refund_requested_at = coalesce(co.refund_requested_at, now())
+ where co.id = v_order.id;
+
+ return query select p_refund_request_no, v_order.amount_cents,
+ v_order.refund_status = 'PROCESSING';
+end;
+$$;
+
+create or replace function public.set_community_refund_state(
+ p_order_id uuid,
+ p_refund_status text,
+ p_failure_code text default null
+)
+returns void
+language plpgsql
+security definer
+set search_path = public
+as $$
+begin
+ if p_refund_status not in ('PROCESSING', 'FAILED') then
+ raise exception 'INVALID_REFUND_STATUS' using errcode = 'P0001';
+ end if;
+ update public.community_orders
+ set refund_status = p_refund_status,
+ refund_failure_code = nullif(left(coalesce(p_failure_code, ''), 120), ''),
+ refund_checked_at = now()
+ where id = p_order_id and status = 'PAID';
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_REFUNDABLE' using errcode = 'P0001';
+ end if;
+end;
+$$;
+
+create or replace function public.finalize_community_refund(
+ p_order_id uuid,
+ p_trade_no text,
+ p_refund_request_no text,
+ p_refund_amount_cents integer
+)
+returns table (
+ current_status text,
+ transitioned boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+ if v_order.status = 'REFUNDED' then
+ return query select 'REFUNDED'::text, false;
+ return;
+ end if;
+ if v_order.status <> 'PAID' or v_order.refund_status <> 'PROCESSING' then
+ raise exception 'COMMUNITY_REFUND_NOT_PROCESSING' using errcode = 'P0001';
+ end if;
+ if v_order.alipay_trade_no <> p_trade_no
+ or v_order.refund_request_no <> p_refund_request_no
+ or p_refund_amount_cents <> v_order.amount_cents then
+ raise exception 'COMMUNITY_REFUND_RESULT_MISMATCH' using errcode = 'P0001';
+ end if;
+
+ update public.community_orders as co
+ set status = 'REFUNDED',
+ refund_status = 'SUCCEEDED',
+ refund_failure_code = null,
+ refund_checked_at = now(),
+ refunded_at = coalesce(co.refunded_at, now())
+ where co.id = v_order.id;
+
+ return query select 'REFUNDED'::text, true;
+end;
+$$;
+
+create or replace function public.revoke_community_access(p_order_id uuid)
+returns table (
+ current_status text,
+ transitioned boolean
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_order public.community_orders%rowtype;
+begin
+ select co.*
+ into v_order
+ from public.community_orders as co
+ where co.id = p_order_id
+ for update;
+
+ if not found then
+ raise exception 'COMMUNITY_ORDER_NOT_FOUND' using errcode = 'P0001';
+ end if;
+ if v_order.status = 'REVOKED' then
+ return query select 'REVOKED'::text, false;
+ return;
+ end if;
+ if v_order.status <> 'PAID' or v_order.refund_status = 'PROCESSING' then
+ raise exception 'COMMUNITY_ORDER_NOT_REVOKABLE' using errcode = 'P0001';
+ end if;
+
+ update public.community_orders as co
+ set status = 'REVOKED',
+ revoked_at = coalesce(co.revoked_at, now())
+ where co.id = v_order.id;
+ return query select 'REVOKED'::text, true;
+end;
+$$;
+
+create or replace function public.replace_community_group_qr_asset(
+ p_media_type text,
+ p_qr_bytes bytea,
+ p_uploaded_by uuid
+)
+returns table (
+ id uuid,
+ media_type text,
+ size_bytes integer,
+ created_at timestamptz
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_asset public.community_group_qr_assets%rowtype;
+ v_size integer;
+begin
+ v_size := octet_length(p_qr_bytes);
+ if p_media_type not in ('image/png', 'image/jpeg', 'image/webp') then
+ raise exception 'COMMUNITY_QR_INVALID_TYPE' using errcode = 'P0001';
+ end if;
+ if v_size is null or v_size < 1 or v_size > 2097152 then
+ raise exception 'COMMUNITY_QR_INVALID_SIZE' using errcode = 'P0001';
+ end if;
+ if p_uploaded_by is null then
+ raise exception 'COMMUNITY_QR_UPLOADER_REQUIRED' using errcode = 'P0001';
+ end if;
+
+ perform pg_advisory_xact_lock(hashtext('community_group_qr_current'));
+
+ update public.community_group_qr_assets
+ set is_current = false,
+ retired_at = coalesce(retired_at, now())
+ where is_current;
+
+ insert into public.community_group_qr_assets (
+ media_type,
+ qr_bytes,
+ size_bytes,
+ is_current,
+ uploaded_by
+ )
+ values (p_media_type, p_qr_bytes, v_size, true, p_uploaded_by)
+ returning * into v_asset;
+
+ return query select v_asset.id, v_asset.media_type, v_asset.size_bytes, v_asset.created_at;
+end;
+$$;
+
+revoke execute on function public.create_or_reuse_community_order(uuid, text)
+ from public, anon, authenticated;
+revoke execute on function public.mark_community_order_paid(uuid, text, integer, text, text, jsonb)
+ from public, anon, authenticated;
+revoke execute on function public.close_community_order(uuid)
+ from public, anon, authenticated;
+revoke execute on function public.prepare_community_refund(uuid, text)
+ from public, anon, authenticated;
+revoke execute on function public.set_community_refund_state(uuid, text, text)
+ from public, anon, authenticated;
+revoke execute on function public.finalize_community_refund(uuid, text, text, integer)
+ from public, anon, authenticated;
+revoke execute on function public.revoke_community_access(uuid)
+ from public, anon, authenticated;
+revoke execute on function public.replace_community_group_qr_asset(text, bytea, uuid)
+ from public, anon, authenticated;
+
+grant execute on function public.create_or_reuse_community_order(uuid, text) to service_role;
+grant execute on function public.mark_community_order_paid(uuid, text, integer, text, text, jsonb) to service_role;
+grant execute on function public.close_community_order(uuid) to service_role;
+grant execute on function public.prepare_community_refund(uuid, text) to service_role;
+grant execute on function public.set_community_refund_state(uuid, text, text) to service_role;
+grant execute on function public.finalize_community_refund(uuid, text, text, integer) to service_role;
+grant execute on function public.revoke_community_access(uuid) to service_role;
+grant execute on function public.replace_community_group_qr_asset(text, bytea, uuid) to service_role;
diff --git a/vercel.json b/vercel.json
index 2153a5c..8fec663 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2,5 +2,23 @@
"framework": "vite",
"buildCommand": "npm run build",
"outputDirectory": "dist",
- "cleanUrls": true
+ "cleanUrls": true,
+ "rewrites": [
+ {
+ "source": "/community",
+ "destination": "/index.html"
+ },
+ {
+ "source": "/community/",
+ "destination": "/index.html"
+ },
+ {
+ "source": "/community/result",
+ "destination": "/index.html"
+ },
+ {
+ "source": "/community/result/",
+ "destination": "/index.html"
+ }
+ ]
}
diff --git a/vite.config.js b/vite.config.js
index f1f82cf..1b3e0f3 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,8 +1,9 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
+import { localVercelApi } from './scripts/vite-local-api.mjs';
export default defineConfig({
- plugins: [react()],
+ plugins: [localVercelApi(), react()],
publicDir: 'data',
build: {
outDir: 'dist',