credential-routes.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import express from 'npm:express';
  2. import { getRelayBalanceStatus, queryRelayBalance } from '../../src/relay/relay-billing.ts';
  3. import { getStoredRelayAuth, isUsableAuth, saveStoredRelayCredential, toAuthorization } from '../../src/relay/relay-credential-store.ts';
  4. import { redactSecrets } from '../../src/relay/relay-errors.ts';
  5. const router = express.Router();
  6. router.get('/token', async (_req, res) => {
  7. try {
  8. const auth = await getStoredRelayAuth();
  9. if (!isUsableAuth(auth)) {
  10. return res.status(409).json({ success: false, message: '尚未配置 API 密钥' });
  11. }
  12. res.json({ success: true, data: { authorization: auth } });
  13. } catch (error: any) {
  14. res.status(500).json({ success: false, message: redactSecrets(error?.message || '获取密钥失败') });
  15. }
  16. });
  17. router.get('/status', async (_req, res) => {
  18. try {
  19. const data = await getRelayBalanceStatus();
  20. res.json({ success: true, data });
  21. } catch (error: any) {
  22. res.status(500).json({ success: false, message: redactSecrets(error?.message || '状态查询失败') });
  23. }
  24. });
  25. router.post('/status/refresh', async (_req, res) => {
  26. try {
  27. const data = await getRelayBalanceStatus();
  28. res.json({ success: true, data });
  29. } catch (error: any) {
  30. res.status(500).json({ success: false, message: redactSecrets(error?.message || '状态查询失败') });
  31. }
  32. });
  33. router.post('/credential', async (req, res) => {
  34. try {
  35. const raw = String(req.body?.apiKey || req.body?.key || '').trim();
  36. const auth = toAuthorization(raw);
  37. await queryRelayBalance(auth);
  38. const saved = await saveStoredRelayCredential(raw, req.currentUser?.get?.('username') || req.currentUser?.id || '');
  39. const data = await getRelayBalanceStatus();
  40. res.json({ success: true, data: { ...data, maskedKey: saved.maskedKey } });
  41. } catch (error: any) {
  42. res.status(400).json({ success: false, message: redactSecrets(error?.message || '密钥保存失败') });
  43. }
  44. });
  45. router.get('/health', async (_req, res) => {
  46. const auth = await getStoredRelayAuth();
  47. res.json({ service: 'relay-credential', configured: Boolean(auth), timestamp: new Date().toISOString() });
  48. });
  49. export default router;