ConnectedAppsSection.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /**
  2. * Settings → API Keys → Connected apps.
  3. *
  4. * Registers external applications that sign users in with their Bambuddy
  5. * account ("Sign in with Bambuddy"). The client secret is shown exactly once,
  6. * at creation or rotation; the list only ever shows the client ID.
  7. */
  8. import { useState } from 'react';
  9. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  10. import { useTranslation } from 'react-i18next';
  11. import { AlertTriangle, Copy, Plus, RefreshCw, Trash2 } from 'lucide-react';
  12. import { api, type ConnectedApp } from '../api/client';
  13. import { useAuth } from '../contexts/AuthContext';
  14. import { useToast } from '../contexts/ToastContext';
  15. import { parseUTCDate } from '../utils/date';
  16. const QUERY_KEY = ['connected-apps'];
  17. function formatDate(iso: string | null): string {
  18. if (!iso) return '—';
  19. const d = parseUTCDate(iso);
  20. return d ? d.toLocaleString() : '—';
  21. }
  22. async function copyToClipboard(value: string): Promise<void> {
  23. // navigator.clipboard needs a secure context; LAN installs are often plain
  24. // http, so fall back to a hidden textarea.
  25. if (navigator.clipboard && window.isSecureContext) {
  26. await navigator.clipboard.writeText(value);
  27. return;
  28. }
  29. const ta = document.createElement('textarea');
  30. ta.value = value;
  31. ta.style.position = 'fixed';
  32. ta.style.opacity = '0';
  33. document.body.appendChild(ta);
  34. try {
  35. ta.select();
  36. document.execCommand('copy');
  37. } finally {
  38. document.body.removeChild(ta);
  39. }
  40. }
  41. function CopyField({ label, value }: { label: string; value: string }) {
  42. const { t } = useTranslation();
  43. const { showToast } = useToast();
  44. return (
  45. <div>
  46. <p className="text-xs text-bambu-gray mb-1">{label}</p>
  47. <div className="flex items-center gap-2">
  48. <code className="flex-1 min-w-0 px-3 py-2 bg-bambu-dark rounded-md text-bambu-green text-xs break-all font-mono select-all">
  49. {value}
  50. </code>
  51. <button
  52. type="button"
  53. onClick={() =>
  54. copyToClipboard(value).then(
  55. () => showToast(t('connectedApps.toast.copied')),
  56. () => showToast(t('connectedApps.toast.copyFailed'), 'error'),
  57. )
  58. }
  59. className="flex items-center gap-2 px-3 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90"
  60. >
  61. <Copy className="w-4 h-4" />
  62. {t('connectedApps.copy')}
  63. </button>
  64. </div>
  65. </div>
  66. );
  67. }
  68. function SecretModal({ app, onClose }: { app: ConnectedApp; onClose: () => void }) {
  69. const { t } = useTranslation();
  70. return (
  71. <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4" role="dialog" aria-modal="true">
  72. <div className="bg-bambu-dark-secondary rounded-lg p-6 max-w-2xl w-full border border-bambu-green/40 space-y-4">
  73. <div className="flex items-start gap-3">
  74. <AlertTriangle className="w-6 h-6 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" />
  75. <div>
  76. <h2 className="text-lg font-semibold text-white">{t('connectedApps.secret.title', { name: app.name })}</h2>
  77. <p className="text-sm text-bambu-gray mt-1">{t('connectedApps.secret.warning')}</p>
  78. </div>
  79. </div>
  80. <CopyField label={t('connectedApps.clientId')} value={app.client_id} />
  81. <CopyField label={t('connectedApps.clientSecret')} value={app.client_secret ?? ''} />
  82. <div className="flex justify-end">
  83. <button
  84. type="button"
  85. onClick={onClose}
  86. className="px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80"
  87. >
  88. {t('connectedApps.secret.dismiss')}
  89. </button>
  90. </div>
  91. </div>
  92. </div>
  93. );
  94. }
  95. function ConfirmModal({
  96. title,
  97. body,
  98. confirmLabel,
  99. onConfirm,
  100. onCancel,
  101. }: {
  102. title: string;
  103. body: string;
  104. confirmLabel: string;
  105. onConfirm: () => void;
  106. onCancel: () => void;
  107. }) {
  108. const { t } = useTranslation();
  109. return (
  110. <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4" role="dialog" aria-modal="true">
  111. <div className="bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full border border-red-500/40">
  112. <div className="flex items-start gap-3 mb-4">
  113. <AlertTriangle className="w-6 h-6 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
  114. <div>
  115. <h2 className="text-lg font-semibold text-white">{title}</h2>
  116. <p className="text-sm text-bambu-gray mt-1">{body}</p>
  117. </div>
  118. </div>
  119. <div className="flex justify-end gap-2">
  120. <button
  121. type="button"
  122. onClick={onCancel}
  123. className="px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80"
  124. >
  125. {t('connectedApps.cancel')}
  126. </button>
  127. <button type="button" onClick={onConfirm} className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600">
  128. {confirmLabel}
  129. </button>
  130. </div>
  131. </div>
  132. </div>
  133. );
  134. }
  135. export function ConnectedAppsSection() {
  136. const { t } = useTranslation();
  137. const { authEnabled } = useAuth();
  138. const { showToast } = useToast();
  139. const queryClient = useQueryClient();
  140. const [name, setName] = useState('');
  141. const [redirectUri, setRedirectUri] = useState('');
  142. const [shownSecret, setShownSecret] = useState<ConnectedApp | null>(null);
  143. const [confirm, setConfirm] = useState<{ app: ConnectedApp; action: 'rotate' | 'delete' } | null>(null);
  144. const { data: apps = [], isLoading } = useQuery({
  145. queryKey: QUERY_KEY,
  146. queryFn: api.listConnectedApps,
  147. enabled: authEnabled,
  148. });
  149. const onError = (err: unknown) =>
  150. showToast(err instanceof Error ? err.message : t('connectedApps.toast.failed'), 'error');
  151. const refresh = () => queryClient.invalidateQueries({ queryKey: QUERY_KEY });
  152. const create = useMutation({
  153. mutationFn: () => api.createConnectedApp({ name: name.trim(), redirect_uri: redirectUri.trim() }),
  154. onSuccess: (app) => {
  155. setName('');
  156. setRedirectUri('');
  157. setShownSecret(app);
  158. showToast(t('connectedApps.toast.created'));
  159. refresh();
  160. },
  161. onError,
  162. });
  163. const toggle = useMutation({
  164. mutationFn: (app: ConnectedApp) => api.updateConnectedApp(app.id, { enabled: !app.enabled }),
  165. onSuccess: (app) => {
  166. showToast(app.enabled ? t('connectedApps.toast.enabled') : t('connectedApps.toast.disabled'));
  167. refresh();
  168. },
  169. onError,
  170. });
  171. const rotate = useMutation({
  172. mutationFn: (app: ConnectedApp) => api.rotateConnectedAppSecret(app.id),
  173. onSuccess: (app) => {
  174. setShownSecret(app);
  175. showToast(t('connectedApps.toast.rotated'));
  176. refresh();
  177. },
  178. onError,
  179. });
  180. const remove = useMutation({
  181. mutationFn: (app: ConnectedApp) => api.deleteConnectedApp(app.id),
  182. onSuccess: () => {
  183. showToast(t('connectedApps.toast.deleted'));
  184. refresh();
  185. },
  186. onError,
  187. });
  188. if (!authEnabled) {
  189. return <p className="text-sm text-bambu-gray">{t('connectedApps.requiresAuth')}</p>;
  190. }
  191. const inputClass =
  192. 'px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none';
  193. return (
  194. <div className="space-y-4">
  195. <p className="text-sm text-bambu-gray">{t('connectedApps.description')}</p>
  196. <form
  197. onSubmit={(e) => {
  198. e.preventDefault();
  199. if (name.trim() && redirectUri.trim()) create.mutate();
  200. }}
  201. className="grid gap-3 md:grid-cols-[1fr_1.5fr_auto]"
  202. >
  203. <input
  204. type="text"
  205. maxLength={100}
  206. required
  207. value={name}
  208. onChange={(e) => setName(e.target.value)}
  209. placeholder={t('connectedApps.namePlaceholder')}
  210. aria-label={t('connectedApps.name')}
  211. className={inputClass}
  212. />
  213. <input
  214. type="url"
  215. maxLength={500}
  216. required
  217. value={redirectUri}
  218. onChange={(e) => setRedirectUri(e.target.value)}
  219. placeholder="http://orders.local:8090/auth/callback"
  220. aria-label={t('connectedApps.callbackUrl')}
  221. className={inputClass}
  222. />
  223. <button
  224. type="submit"
  225. disabled={create.isPending || !name.trim() || !redirectUri.trim()}
  226. className="flex items-center justify-center gap-2 px-4 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90 disabled:opacity-50 disabled:cursor-not-allowed"
  227. >
  228. <Plus className="w-4 h-4" />
  229. {t('connectedApps.add')}
  230. </button>
  231. </form>
  232. <p className="text-xs text-bambu-gray">{t('connectedApps.callbackHint')}</p>
  233. {isLoading ? null : apps.length === 0 ? (
  234. <p className="text-sm text-bambu-gray">{t('connectedApps.empty')}</p>
  235. ) : (
  236. <div className="overflow-x-auto">
  237. <table className="w-full text-sm">
  238. <thead>
  239. <tr className="text-left text-bambu-gray border-b border-bambu-dark-tertiary">
  240. <th className="py-2 px-3 font-medium">{t('connectedApps.name')}</th>
  241. <th className="py-2 px-3 font-medium">{t('connectedApps.clientId')}</th>
  242. <th className="py-2 px-3 font-medium">{t('connectedApps.callbackUrl')}</th>
  243. <th className="py-2 px-3 font-medium">{t('connectedApps.lastUsed')}</th>
  244. <th className="py-2 px-3" />
  245. </tr>
  246. </thead>
  247. <tbody>
  248. {apps.map((app) => (
  249. <tr key={app.id} className="border-b border-bambu-dark-tertiary last:border-b-0">
  250. <td className="py-3 px-3 text-white">
  251. {app.name}
  252. {!app.enabled && (
  253. <span className="ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray">
  254. {t('connectedApps.disabledBadge')}
  255. </span>
  256. )}
  257. </td>
  258. <td className="py-3 px-3 text-bambu-gray font-mono text-xs">{app.client_id}</td>
  259. <td className="py-3 px-3 text-bambu-gray text-xs break-all">{app.redirect_uri}</td>
  260. <td className="py-3 px-3 text-bambu-gray">{formatDate(app.last_used_at)}</td>
  261. <td className="py-3 px-3">
  262. <div className="flex justify-end gap-3 whitespace-nowrap">
  263. <button
  264. type="button"
  265. onClick={() => toggle.mutate(app)}
  266. className="text-sm text-bambu-gray hover:text-white"
  267. >
  268. {app.enabled ? t('connectedApps.disable') : t('connectedApps.enable')}
  269. </button>
  270. <button
  271. type="button"
  272. onClick={() => setConfirm({ app, action: 'rotate' })}
  273. className="inline-flex items-center gap-1 text-sm text-bambu-gray hover:text-white"
  274. >
  275. <RefreshCw className="w-4 h-4" />
  276. {t('connectedApps.rotate')}
  277. </button>
  278. <button
  279. type="button"
  280. onClick={() => setConfirm({ app, action: 'delete' })}
  281. className="inline-flex items-center gap-1 text-sm text-red-700 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300"
  282. >
  283. <Trash2 className="w-4 h-4" />
  284. {t('connectedApps.delete')}
  285. </button>
  286. </div>
  287. </td>
  288. </tr>
  289. ))}
  290. </tbody>
  291. </table>
  292. </div>
  293. )}
  294. {shownSecret && <SecretModal app={shownSecret} onClose={() => setShownSecret(null)} />}
  295. {confirm && (
  296. <ConfirmModal
  297. title={
  298. confirm.action === 'rotate'
  299. ? t('connectedApps.confirmRotate.title')
  300. : t('connectedApps.confirmDelete.title')
  301. }
  302. body={
  303. confirm.action === 'rotate'
  304. ? t('connectedApps.confirmRotate.body', { name: confirm.app.name })
  305. : t('connectedApps.confirmDelete.body', { name: confirm.app.name })
  306. }
  307. confirmLabel={confirm.action === 'rotate' ? t('connectedApps.rotate') : t('connectedApps.delete')}
  308. onCancel={() => setConfirm(null)}
  309. onConfirm={() => {
  310. if (confirm.action === 'rotate') rotate.mutate(confirm.app);
  311. else remove.mutate(confirm.app);
  312. setConfirm(null);
  313. }}
  314. />
  315. )}
  316. </div>
  317. );
  318. }