Authentication
When you purchase a dynamic_api (Dynamic API Quota Sales) type product in APayShop, the system will automatically generate an exclusive API Key for you. You need to use this Key to call the corresponding service interfaces.
Web Single-Session Policy
When the system setting disable_multi_device_login is enabled, only the most recently established browser Cookie session remains active for each user. Password login, registration, OAuth, Minimal upstream login, and Qingpu checkout handoff all use the same core session issuer.
An older browser session receives HTTP 401 with data.code = "SESSION_REPLACED" on its next protected API request. GET /api/auth/session-status also returns the replacement notice for the global UI, including the new login's device category, browser, operating system, UTC login time, IP, and available location snapshot.
API Tokens, MCP OAuth/scoped tokens (apay_mcp_), Qingpu extension/desktop device tokens, admin sessions, and delegated employee sessions have independent lifecycles and are not revoked by this browser-only policy.
Independent Native App Sessions
Server-side native login callers use issueNativeSession. The existing sealed nuxt-session Cookie and account APIs remain compatible. Native sessions have a 90-day expiry, are individually checked for revocation and account status, and do not update the web login pointer. POST /api/auth/logout revokes only the current native session; replaying its old Cookie is rejected. Existing cookies without a session kind remain web sessions until reauthentication.
Browser-based app authorization uses a separate ten-minute, browser-bound transaction. Themes create it with beginAppAuthorization; password/registration requests explicitly carry X-App-Authorization, while Google/GitHub bind the transaction to an independent OAuth state. A successful authorization returns {success,appAuthorization:true,returnPath,user} instead of establishing a competing web login. consumeAppAuthorization atomically consumes the authorization before the theme issues an app callback code. A pending transaction alone is not an account login and does not change ordinary web sign-in behavior.
Apply the additive native-session core migration and upgrade all validators before enabling issuance. Detailed integration, release and rollback guidance: docs/native-app-sessions.md. Regression: npm run check:native-sessions.
Core MCP OAuth 2.1 & Scoped Token System
APay provides a core Model Context Protocol (MCP) authorization and Streamable HTTP server so MCP clients (Claude Desktop, Cursor, Windsurf, VS Code Copilot, WorkBuddy, etc.) can authenticate securely with least-privilege scopes instead of full-account keys.
1. OAuth 2.1 & RFC 9728 / RFC 8414 Discovery
- Protected Resource Metadata (RFC 9728):
GET /.well-known/oauth-protected-resource(and/.well-known/oauth-protected-resource/api/mcp) - Authorization Server Metadata (RFC 8414):
GET /.well-known/oauth-authorization-server - Dynamic Client Registration (RFC 7591):
POST /api/oauth/register(issues HMAC-signedmcp_client_...client IDs bound to validatedredirect_uris) - Browser Authorization & Consent:
- Consent UI:
/user/mcp-authorize - Inspection & Approval API:
GET /api/oauth/authorize&POST /api/oauth/authorize(requires PKCEcode_challenge_method=S256)
- Consent UI:
- Token Exchange & Refresh Rotation:
POST /api/oauth/token- Supports
grant_type=authorization_code(single-use atomic consumption + PKCES256verification) andgrant_type=refresh_token(rotates both refresh and access tokens).
- Supports
- Token Revocation (RFC 7009):
POST /api/oauth/revoke
2. Scoped MCP Access Tokens (apay_mcp_) & Scope Gate
- At-Rest Hashing: All
apay_mcp_access tokens, OAuth authorization codes, and refresh tokens are stored inuser_tokens.tokenas SHA-256 hashes (apay_mcp_sha256_<hex>/mcp_oauth_sha256_<hex>). Raw secrets are never persisted in the database. - Supported Scopes:
mcp:tools: Invoke/api/mcpJSON-RPC 2.0 endpointmcp:profile:read: Read basic user profile (/api/auth/me,/api/users/profile)mcp:orders:read: Read order history and fulfillment statusmcp:subscriptions:read: Read active subscriptionsmcp:notifications:read: Read notificationsmcp:tickets:read/mcp:tickets:write: Read or create/reply to support ticketsmcp:theme:read/mcp:theme:plan: Read theme user state or generate assistant plans (confirm/execute endpoints still require human confirmation in the web UI)
- Hard-Denied High-Risk Endpoints: Regardless of granted scopes, scoped tokens are unconditionally blocked at
server/middleware/auth.tsfrom accessing/api/admin/**,/api/users/tokens,/api/users/password,/api/users/email,/api/users/account-deletion,/api/users/billing,/api/users/wallet,/api/orders/checkout,/api/orders/topup,/api/payments/**,/api/qingpu/stores, and/api/qingpu/device-tokens. - Manual Issuance: Users can also manually mint and revoke scoped
apay_mcp_tokens from/user/tokens(GET/POST /api/users/tokens,DELETE /api/users/tokens/:id), which includes one-clickmcpServersJSON config snippets for Claude Desktop, Cursor, and Windsurf. - Admin Emergency Revocation: Administrators can revoke all active API/MCP tokens and clear all refresh tokens for a user via
POST /api/admin/users/:id/revoke-tokens.
3. Core MCP Endpoint (/api/mcp)
- Endpoint:
POST /api/mcp(Streamable HTTP JSON-RPC 2.0) - Authentication: Strictly requires
Authorization: Bearer <token>orX-Api-Key: <token>. Browser cookies alone are rejected with401and aWWW-Authenticate: Bearer resource_metadata="..."header to prevent cross-site CSRF against MCP tools. - Built-in Tools:
apay_get_profile/apay_get_account_profile(mcp:profile:read)apay_list_products(mcp:tools)apay_list_orders/apay_get_order_detail(mcp:orders:read)apay_list_subscriptions(mcp:subscriptions:read)apay_list_notifications(mcp:notifications:read)apay_list_tickets/apay_get_ticket_detail(mcp:tickets:read)apay_create_ticket/apay_reply_ticket(mcp:tickets:write)- Theme extensions can register additional tools via
registerMcpTool()inserver/utils/mcpServer.ts.
Account Deletion & Permanent Archival Lifecycle
APay provides a core user-requested and admin-reviewed account deletion pipeline (account_deletion_requests + users.status = -1) that preserves historical financial ledgers and order foreign keys while permanently sealing the identity.
- User Endpoints (owner web browser session required; blocked for API/MCP tokens and delegated employee sessions):
GET /api/users/account-deletion: Returns account status, password/OAuth verification mode, asset pre-check metrics (available balance, active subscriptions, paid orders), pending request, and request history.POST /api/users/account-deletion: Submits a pending deletion request after verifyingpassword(for password accounts) orconfirmEmail(for OAuth-only accounts), capturing an immutable account snapshot.POST /api/users/account-deletion/cancel: Withdraws an unreviewed'pending'deletion request.- Core UI:
/user/account(<AccountDeletionPanel />anduseAccountDeletion()).
- Admin Review & Direct Archival Endpoints (
customers:view/customers:edit):GET /api/admin/users/deletion-requests: Paginated list of deletion requests with status/keyword filtering and global summary counts.POST /api/admin/users/deletion-requests/:id/review: Approves (action = "approve") or declines (action = "reject", sending an in-app notification withreviewNote) a pending request.DELETE /api/admin/users/:id: Directly archives and seals a user account without breaking foreign-key references.
- Permanent Seal & Login Interception (
users.status = -1):- Upon approval or direct archival,
users.statusbecomes-1,currentSessionIdis cleared, all activeuser_sessions(web, native, app authorization) are revoked, single-use/OAuth refresh tokens are deleted, all remaining API/MCP/device tokens are marked revoked, active subscriptions are set tocancelAtPeriodEnd = true, anduser.deletedis emitted. - Archived accounts receive
401/403(data.code = "ACCOUNT_ARCHIVED") across web cookie validation, native session validation, Bearer API/MCP tokens, password login, OAuth login/linking, password reset,find-or-create, and re-registration.
- Upon approval or direct archival,
Authentication Method
APayShop uses the standard HTTP Authorization header for authentication. When sending API requests, please include your API Key as a Bearer Token in the request header.
Format Requirements
Header Name: Authorization
Header Value: Bearer YOUR_API_KEY
Example Request
Below is an example of sending an authenticated request using cURL:
curl -X GET https://yourdomain.com/api/v1/some-service \
-H "Authorization: Bearer sk_test_1234567890abcdef" \
-H "Content-Type: application/json"
How to get an API Key?
- Purchase a
dynamic_apitype product in the storefront and complete the payment. - After successful payment, go to the "Order History" page.
- Click on the details of the corresponding order, and you will directly see the API Key allocated to you by the system and the available quota in the Fulfillment Result area.
⚠️ Security Warning
Please keep your API Key as safe as a password. Absolutely never hardcode it in client-side code (such as browser-side JS, mobile Apps), and do not commit it to public GitHub repositories. If your key is leaked, please contact the administrator immediately to invalidate it in the backend and generate a new one.
Quota Consumption Mechanism
Every time you successfully call a billing interface using a valid API Key, the system will automatically deduct the corresponding value from your available quota.
When the quota is exhausted, the API will refuse service and return a 402 Payment Required or 403 Forbidden status code. You can purchase the product again to replenish your quota.