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-signed mcp_client_... client IDs bound to validated redirect_uris)
  • Browser Authorization & Consent:
    • Consent UI: /user/mcp-authorize
    • Inspection & Approval API: GET /api/oauth/authorize & POST /api/oauth/authorize (requires PKCE code_challenge_method=S256)
  • Token Exchange & Refresh Rotation: POST /api/oauth/token
    • Supports grant_type=authorization_code (single-use atomic consumption + PKCE S256 verification) and grant_type=refresh_token (rotates both refresh and access tokens).
  • 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 in user_tokens.token as 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/mcp JSON-RPC 2.0 endpoint
    • mcp:profile:read: Read basic user profile (/api/auth/me, /api/users/profile)
    • mcp:orders:read: Read order history and fulfillment status
    • mcp:subscriptions:read: Read active subscriptions
    • mcp:notifications:read: Read notifications
    • mcp:tickets:read / mcp:tickets:write: Read or create/reply to support tickets
    • mcp: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.ts from 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-click mcpServers JSON 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> or X-Api-Key: <token>. Browser cookies alone are rejected with 401 and a WWW-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() in server/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 verifying password (for password accounts) or confirmEmail (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 /> and useAccountDeletion()).
  • 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 with reviewNote) 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.status becomes -1, currentSessionId is cleared, all active user_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 to cancelAtPeriodEnd = true, and user.deleted is 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.

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?

  1. Purchase a dynamic_api type product in the storefront and complete the payment.
  2. After successful payment, go to the "Order History" page.
  3. 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.