Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 73,122 Bytes
2e7e617 82cdb59 971c29d 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 89af3b2 dec006b 971c29d 816fa8a 2e7e617 816fa8a 8873406 816fa8a 8873406 816fa8a 971c29d 8873406 971c29d dec006b 816fa8a 8873406 971c29d 8873406 dec006b 8873406 dec006b 8873406 dec006b 816fa8a 8873406 816fa8a 8873406 971c29d 816fa8a 971c29d 816fa8a 971c29d 816fa8a 971c29d 816fa8a 971c29d 2e7e617 816fa8a 971c29d 816fa8a 103a492 2e7e617 971c29d 2e7e617 8873406 816fa8a 103a492 816fa8a dec006b 816fa8a dec006b 816fa8a dec006b 816fa8a 8873406 816fa8a dec006b 816fa8a 103a492 816fa8a 8873406 816fa8a 8873406 dec006b 8873406 dec006b 816fa8a dec006b 816fa8a 971c29d 2e7e617 82cdb59 2e7e617 c1fc133 2e7e617 82cdb59 2e7e617 f11e183 82cdb59 2e7e617 89af3b2 82cdb59 8133df9 816fa8a 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 c1fc133 2e7e617 f11e183 82cdb59 89af3b2 2e7e617 89af3b2 2e7e617 dec006b 971c29d dec006b 971c29d 2e7e617 816fa8a 2e7e617 82cdb59 2e7e617 971c29d 816fa8a 82cdb59 c1fc133 2e7e617 c1fc133 89af3b2 c1fc133 dec006b 2e7e617 82cdb59 07a68d0 2e7e617 816fa8a 07a68d0 816fa8a 2e7e617 89af3b2 2e7e617 816fa8a 8873406 816fa8a 2e7e617 07a68d0 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 07a68d0 2e7e617 816fa8a 2e7e617 dec006b 816fa8a 2e7e617 816fa8a 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 816fa8a 971c29d 2e7e617 971c29d 816fa8a 2e7e617 971c29d 2e7e617 816fa8a 2e7e617 816fa8a 971c29d 82cdb59 c1fc133 dec006b c1fc133 2e7e617 c1fc133 2e7e617 c1fc133 dec006b c1fc133 2e7e617 c1fc133 2e7e617 82cdb59 2e7e617 89af3b2 2e7e617 82cdb59 2e7e617 89af3b2 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 89af3b2 2e7e617 07a68d0 82cdb59 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 82cdb59 2e7e617 89af3b2 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 816fa8a 2e7e617 8133df9 816fa8a 2e7e617 8133df9 2e7e617 8133df9 2e7e617 82cdb59 8133df9 2e7e617 8133df9 2e7e617 8133df9 2e7e617 8133df9 816fa8a 8133df9 82cdb59 2e7e617 82cdb59 2e7e617 816fa8a 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 82cdb59 2e7e617 82cdb59 2e7e617 dec006b 2e7e617 82cdb59 89af3b2 2e7e617 89af3b2 2e7e617 816fa8a dec006b 8873406 2e7e617 82cdb59 07a68d0 2e7e617 07a68d0 2e7e617 07a68d0 2e7e617 07a68d0 2e7e617 07a68d0 2e7e617 dec006b 2e7e617 07a68d0 2e7e617 971c29d 2e7e617 dec006b 971c29d dec006b 971c29d dec006b 971c29d 816fa8a 103a492 07a68d0 8873406 2e7e617 c1fc133 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 c1fc133 2e7e617 816fa8a dec006b 816fa8a dec006b 816fa8a dec006b 8873406 dec006b 816fa8a 8873406 07a68d0 2e7e617 07a68d0 2e7e617 07a68d0 2e7e617 971c29d 2e7e617 dec006b 2e7e617 971c29d 2e7e617 971c29d 07a68d0 8133df9 2e7e617 07a68d0 2e7e617 89af3b2 2e7e617 07a68d0 2e7e617 07a68d0 2e7e617 8133df9 2e7e617 816fa8a 2e7e617 07a68d0 2e7e617 07a68d0 816fa8a 8873406 816fa8a 2e7e617 816fa8a 2e7e617 8133df9 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 07a68d0 8133df9 07a68d0 8133df9 07a68d0 816fa8a 8873406 816fa8a 971c29d 2e7e617 8133df9 971c29d f11e183 2e7e617 f11e183 971c29d f11e183 2e7e617 82cdb59 971c29d 2e7e617 dec006b 2e7e617 82cdb59 2e7e617 89af3b2 2e7e617 89af3b2 2e7e617 89af3b2 2e7e617 82cdb59 971c29d 82cdb59 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 | // settings / ExternalAccessPane.tsx - W63-T06, rulings R4/R14, contract C7.
//
// This is the shared setup pane opened by the Connectors directory. OAuth clients receive the remote
// MCP URL; API-key secrets appear only in the one-time reveal returned by create or rotate. All
// editable metadata is seeded again from the server response.
//
// Setup instructions share one numbered list. Every AI client receives the public starter prompt.
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { FormEvent, ReactNode } from "react";
import { Copy } from "@phosphor-icons/react/dist/csr/Copy";
import { Check } from "@phosphor-icons/react/dist/csr/Check";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract";
import { Mark } from "../shell/Brand";
import { AiClientMark } from "./aiClientMarks";
import { KeyOpenApiRow, openApiDocumentUrl } from "./KeyOpenApiRow";
import { ExpiryPresets, presetToExpiresAt } from "./ExpiryPresets";
import type { ExpiryPreset } from "./ExpiryPresets";
import { parseTutorialGuide } from "../connectors/ConnectTutorial";
import type { TutorialGuide } from "../connectors/ConnectTutorial";
import "../connectors/connectors.css";
import "../styles/sdlc73/connectors.css";
type Access = "read" | "readwrite";
type ResourceScope = string[] | "all";
type ConnectionKind = "mcp" | "key";
// Copyable instructions never interpolate a stored credential.
interface StepAction { label: string; url: string }
export interface GuideStep {
id?: string;
title?: string;
text: ReactNode;
block?: string;
copyValue?: string;
action?: StepAction;
hint?: string;
details?: readonly GuideStep[];
}
function GuideInstruction({ text }: { text: string }) {
// Split only at an existing sentence or sequencing clause, keeping every character.
const boundary = /[.!?](?=\s+[A-Z])|,(?=\s+then\b)/.exec(text);
const end = boundary ? boundary.index + 1 : text.length;
return <p className="external-step-instruction">
<span className="external-step-lead">{text.slice(0, end)}</span>
{end < text.length ? <span className="external-step-detail">{text.slice(end)}</span> : null}
</p>;
}
// S70-T09: the AI setup and connector tutorials share this actual frame and guide renderer.
// Each caller owns its steps, fields and actions; the frame makes no requests.
export function GuideSteps({ steps, tutorial, finalSteps = [], renderCopy, mode = "full" }: {
steps: readonly GuideStep[];
tutorial?: TutorialGuide;
finalSteps?: readonly GuideStep[];
renderCopy?: (value: string, index: number, step: GuideStep) => ReactNode;
/** Short guides keep preparation and test limits outside the numbered instructions. */
mode?: "full" | "short";
}) {
const body: readonly GuideStep[] = tutorial && mode === "full" ? [
{ id: "tutorial-need", text: `What you need: ${tutorial.need}` },
...steps,
...(tutorial.testNote ? [{ id: "tutorial-test", text: `Test: ${tutorial.testNote}` }] : []),
{ id: "tutorial-failure", text: `If it fails: ${tutorial.failureAction}` },
] : steps;
const entries = [...body, ...finalSteps];
if (!entries.length) return null;
const content = (entry: GuideStep, index: number): ReactNode => {
const copyValue = entry.copyValue ?? entry.block;
return <>
<div className={`external-step-content${copyValue && renderCopy ? "" : " external-step-content--wide"}`}>
{entry.title ? <p className="external-step-title">{entry.title}</p>
: typeof entry.text === "string" ? <GuideInstruction text={entry.text} /> : entry.text}
</div>
{copyValue ? renderCopy?.(copyValue, index, entry) : null}
{entry.title ? <p className="external-step-description">{entry.text}</p> : null}
{entry.block ? <pre className="external-step-code">{entry.block}</pre> : null}
{entry.hint ? <p className="external-step-hint" id={entry.id ? `${entry.id}-hint` : undefined}>
{entry.hint}
</p> : null}
{entry.action ? <a className="external-step-action" href={entry.action.url}
target="_blank" rel="noopener noreferrer">{entry.action.label}</a> : null}
{entry.details?.map((detail, detailIndex) => <div className="external-step-details" data-step-id={detail.id} key={detail.id ?? detailIndex}>
{content(detail, detailIndex)}
</div>)}
</>;
};
return <>
{tutorial && mode === "short" ? <p className="external-sub">{tutorial.need}</p> : null}
<ol className="external-steps" role="list" data-guide-renderer="GuideSteps" data-guide-mode={mode}>
{entries.map((entry, index) => {
return <li key={entry.id ?? index} data-step-id={entry.id}
className={entry.copyValue ? "external-step--copy-text" : undefined}>
<span className="external-step-number" aria-hidden="true">{index + 1}</span>
{content(entry, index)}
</li>;
})}
</ol>
{tutorial && mode === "short" ? <div className="external-guide-help">
{tutorial.testNote ? <p className="external-sub">{tutorial.testNote}</p> : null}
<p className="external-sub">{tutorial.failureAction}</p>
</div> : null}
</>;
}
export function ConnectionWizard({ title, titleId, metadata, footer, children }: {
title: string;
titleId: string;
metadata?: ReactNode;
footer?: ReactNode;
children: ReactNode;
}) {
return <section className="external-wizard" aria-labelledby={titleId}>
<header className="external-wizard-head">
<div className="external-wizard-heading">
<h2 id={titleId}>{title}</h2>
{metadata}
</div>
<Mark size={28} />
</header>
<div className="external-wizard-body">{children}</div>
{footer ? <footer className="external-wizard-foot">{footer}</footer> : null}
</section>;
}
// Client identity and grant matching stay stable when the served instructions change.
export const CLIENTS = [
{ id: "claude", label: "Claude.ai", connections: ["mcp"], skill: false, match: ["claude"] },
{ id: "chatgpt", label: "ChatGPT", connections: ["mcp"], skill: false, match: ["chatgpt", "chat gpt"] },
{ id: "claude-code", label: "Claude Code", connections: ["mcp", "key"], skill: true,
match: ["claude code", "claude-code", "claude_code"] },
{ id: "codex", label: "Codex", connections: ["mcp", "key"], skill: true, match: ["codex"] },
{ id: "cursor", label: "Cursor", connections: ["mcp", "key"], skill: true, match: ["cursor"] },
{ id: "muse", label: "Meta Muse", connections: ["key"], skill: false, match: ["muse", "meta muse"] },
] as const satisfies readonly {
id: string;
label: string;
connections: readonly ConnectionKind[];
skill: boolean;
match: readonly string[];
}[];
export type ClientId = (typeof CLIENTS)[number]["id"];
interface ServedStep { title?: string; text: string; block?: string; action?: StepAction }
interface ClientGuide {
verified: string;
documentation?: string;
provenance: string;
need: string;
steps: ServedStep[];
keySteps?: ServedStep[];
caveat: string;
failureAction: string;
testNote: string;
tutorial: TutorialGuide;
keyTutorial?: TutorialGuide;
}
interface ClientStepsResponse {
starterPrompt: string;
clients: Record<ClientId, ClientGuide>;
shared: {
connection: Record<ConnectionKind, string>;
skill: ServedStep;
verification: Record<"mcp" | "key" | "activeKey" | "newKey" | "savedKey" | "noGrant" | "otherGrant", string>;
keySetup: Record<"saved" | "saveNew", string>;
};
}
export function parseClientSteps(value: unknown): ClientStepsResponse | null {
if (!value || typeof value !== "object") return null;
const data = value as Partial<ClientStepsResponse>;
const text = (item: unknown): item is string => typeof item === "string" && item.trim() !== "";
const action = (item: unknown): item is StepAction => {
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
const row = item as Partial<StepAction>;
if (!text(row.label) || row.label !== row.label.trim() || /[\x00-\x1f]/.test(row.label)
|| !text(row.url) || !/^https:\/\/[^/?#]+/.test(row.url) || /[\s\\\x00-\x1f\x7f]/.test(row.url)
|| /%(?![0-9a-fA-F]{2})/.test(row.url)) return false;
try {
const url = new URL(row.url);
return url.protocol === "https:" && !!url.hostname && !url.username && !url.password;
} catch { return false; }
};
const step = (item: unknown): item is ServedStep => {
if (!item || typeof item !== "object") return false;
const row = item as Partial<ServedStep>;
return text(row.text) && (row.block === undefined || text(row.block))
&& (row.action === undefined || action(row.action));
};
const steps = (items: unknown) => Array.isArray(items) && items.length >= 2 && items.length <= 3
&& items.every((item) => step(item) && text(item.title) && item.title.length <= 48 && text(item.block)
&& !/\bTest\s*:/i.test(`${item.title} ${item.text} ${item.block}`));
const shared = data.shared;
if (!text(data.starterPrompt) || data.starterPrompt.length >= 600 || !data.clients
|| !shared || !step(shared.skill) || !text(shared.skill.block)
|| !text(shared.connection?.mcp) || !text(shared.connection?.key)
|| !["mcp", "key", "activeKey", "newKey", "savedKey", "noGrant", "otherGrant"].every(
(key) => text(shared.verification?.[key as keyof typeof shared.verification]))
|| !text(shared.keySetup?.saved) || !text(shared.keySetup?.saveNew)) return null;
const clients = {} as Record<ClientId, ClientGuide>;
for (const client of CLIENTS) {
const guide = data.clients[client.id];
if (!guide || !text(guide.verified) || !/^\d{4}-\d{2}-\d{2}$/.test(guide.verified)
|| !Number.isFinite(Date.parse(guide.verified)) || !text(guide.provenance)
|| (client.id === "muse" ? guide.documentation !== undefined
: !text(guide.documentation) || !/^https:\/\//.test(guide.documentation))
|| !text(guide.caveat) || !steps(guide.steps)
|| (guide.keySteps !== undefined && !steps(guide.keySteps))
|| ((client.connections as readonly ConnectionKind[]).includes("key") && !steps(guide.keySteps))) return null;
const tutorial = parseTutorialGuide({ ...guide, steps: guide.steps.map((entry) => entry.text) }, "ai");
const keyTutorial = (client.connections as readonly ConnectionKind[]).includes("key")
? parseTutorialGuide({ ...guide, steps: guide.keySteps!.map((entry) => entry.text) }, "ai") : null;
if (!tutorial || ((client.connections as readonly ConnectionKind[]).includes("key") && !keyTutorial)) return null;
clients[client.id] = { ...guide, tutorial, ...(keyTutorial ? { keyTutorial } : {}) };
}
return { ...data, clients } as ClientStepsResponse;
}
export function isClientId(value: unknown): value is ClientId {
return typeof value === "string" && CLIENTS.some((entry) => entry.id === value);
}
interface ExternalKeyMetadata {
id: string;
label: string;
created: string;
last_used: string | null;
revoked_at: string | null;
access: Access;
databases: ResourceScope;
expires_at: string | null;
}
interface ScopeDatabase { database: string; label: string }
interface ExternalConnection {
id: string;
// This field holds the grant id; its existing name keeps disconnect URLs addressing the server's connection id.
client: string;
clientId: ClientId | null;
label: string | null;
status: "connected" | "expired" | "disconnected";
created: string | null;
last_used: string | null;
expires_at: string | null;
disconnected_at: string | null;
access: Access | null;
databases: ResourceScope | null;
}
interface KeyListResponse { keys: ExternalKeyMetadata[]; can_mint: boolean }
interface ConnectionListResponse { connections: unknown[] }
interface MintResponse { key: ExternalKeyMetadata; secret: string }
interface KeyDraft {
label: string;
access: Access;
databaseMode: "all" | "subset";
databases: string[];
expiryPreset: ExpiryPreset;
}
const KEY_REFUSALS = {
minted_elsewhere: "This key was minted on another Space. Create a key on this Space",
revoked: "This key was revoked. Create a new key",
expired: "This key expired. Update its expiry or create a new key",
unknown_key: "This key is unknown to your account on this Space. Paste your saved key or create a new one",
} as const;
type KeyRefusal = keyof typeof KEY_REFUSALS;
interface OwnerKeyVerification {
valid: boolean;
cause: KeyRefusal | null;
warning: "store_write_refused" | null;
origin_recorded: boolean | null;
key_id?: string;
}
type VerifyResult = { state: "ok" | "failed"; message: string; cause?: KeyRefusal | "store_write_refused" };
type ConfirmedConnection = { clientId: ClientId } & (
{ kind: "mcp"; grantId: string } | { kind: "key"; keyId: string }
);
type KeyChoice = "create" | "saved";
type ApiResult<T> =
| { ok: true; data: T }
| { ok: false; message: string; status: number };
// The one spelling of the OAuth connections route. The pane reads it on mount and again when
// the MCP step verifies, and two copies of a route are two things to keep in step.
const CONNECTIONS_PATH = "/external/oauth/connections";
function messageFrom(body: unknown, fallback: string): string {
if (!body || typeof body !== "object") return fallback;
const error = (body as { error?: unknown }).error;
if (!error || typeof error !== "object") return fallback;
const message = (error as { message?: unknown }).message;
return typeof message === "string" && message.trim() !== "" ? message : fallback;
}
async function call<T>(path: string, init?: RequestInit): Promise<ApiResult<T>> {
try {
const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
if (checkTenant(response)) {
return { ok: false, message: "This workspace changed. Reloading.", status: 409 };
}
let body: unknown = null;
try { body = await response.json(); } catch { /* Keep non-JSON failures generic. */ }
if (!response.ok) {
if (response.status === 401 && typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
}
return {
ok: false,
status: response.status,
message: response.status >= 500
? "The AI API is unavailable right now."
: messageFrom(body, "That request could not be completed."),
};
}
return { ok: true, data: body as T };
} catch {
return { ok: false, message: "The server could not be reached.", status: 0 };
}
}
function parseKey(value: unknown): ExternalKeyMetadata | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (typeof row.id !== "string" || typeof row.label !== "string" || typeof row.created !== "string") {
return null;
}
const databases = Array.isArray(row.databases) && row.databases.every(
(database): database is string => typeof database === "string" && database.trim() !== "",
) ? row.databases.map((database) => database.trim()) : "all";
return {
id: row.id,
label: row.label,
created: row.created,
last_used: typeof row.last_used === "string" ? row.last_used : null,
revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null,
access: row.access === "read" ? "read" : "readwrite",
databases,
expires_at: typeof row.expires_at === "string" ? row.expires_at : null,
};
}
function parseConnection(value: unknown): ExternalConnection | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (typeof row.id !== "string" || !row.id.trim()) return null;
const label = typeof row.label === "string" ? row.label : null;
// Prefer the longest matching name, so Claude Code resolves before the broader Claude match.
const resolved = CLIENTS.flatMap((entry) => entry.match.map((match) => ({ id: entry.id, match })))
.sort((a, b) => b.match.length - a.match.length)
.find((entry) => label?.toLowerCase().includes(entry.match))?.id;
const expires_at = typeof row.expires_at === "string" ? row.expires_at : null;
const disconnected_at = typeof row.disconnected_at === "string" ? row.disconnected_at : null;
return {
id: row.id,
client: row.id,
clientId: isClientId(resolved) ? resolved : null,
label,
status: disconnected_at ? "disconnected"
: expires_at && Date.parse(expires_at) <= Date.now() ? "expired" : "connected",
created: typeof row.created === "string" ? row.created : null,
last_used: typeof row.last_used === "string" ? row.last_used : null,
expires_at,
disconnected_at,
access: row.access === "read" || row.access === "readwrite" ? row.access : null,
databases: row.databases === "all" ? "all"
: Array.isArray(row.databases) ? row.databases.filter((item): item is string => typeof item === "string")
: null,
};
}
function when(value: string | null): string {
if (!value) return "Never";
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return "Unknown";
return parsed.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
}
function keyExpiryLabel(key: ExternalKeyMetadata): string {
if (!key.expires_at) return "No expiry";
if (Date.parse(key.expires_at) <= Date.now()) return "Expired";
return `Expires ${when(key.expires_at)}`;
}
function draftFor(key: ExternalKeyMetadata): KeyDraft {
return {
label: key.label,
access: key.access,
databaseMode: key.databases === "all" ? "all" : "subset",
databases: key.databases === "all" ? [] : [...key.databases],
expiryPreset: "keep",
};
}
function connectionLabel(connection: ExternalConnection | undefined): string {
if (!connection || connection.status === "disconnected") return "Not connected";
if (connection.status === "connected") return "Connected";
if (connection.status === "expired") return "Reconnect required";
return "Not connected";
}
function SettingsSkeleton({ label }: { label: string }) {
return <div className="set-skeleton" role="status" aria-label={label} aria-busy="true">
<span className="set-skeleton-line" aria-hidden="true" />
<span className="set-skeleton-line" aria-hidden="true" />
<span className="set-skeleton-line" aria-hidden="true" />
</div>;
}
/** The directory selects a client; this pane remains the one setup and credential implementation. */
export default function ExternalAccessPane({
initialClient,
view = "all",
settings = false,
onChanged,
onOpenApi,
}: {
initialClient?: ClientId;
view?: "all" | "client" | "api";
settings?: boolean;
onChanged?: () => void;
onOpenApi?: () => void;
} = {}) {
const initialEntry = CLIENTS.find((entry) => entry.id === initialClient);
const [clientId, setClientId] = useState<ClientId | null>(initialClient ?? null);
const [connection, setConnection] = useState<ConnectionKind | null>(
initialEntry?.connections[0] ?? null,
);
const [showSetup, setShowSetup] = useState(!settings || view === "api");
const [keyChoice, setKeyChoice] = useState<KeyChoice>(view === "client" ? "saved" : "create");
const [selectedKeyId, setSelectedKeyId] = useState("");
const [verifyResult, setVerifyResult] = useState<VerifyResult | null>(null);
const [confirmedConnection, setConfirmedConnection] = useState<ConfirmedConnection | null>(null);
const [verifySecret, setVerifySecret] = useState("");
const verificationVersion = useRef(0);
const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null);
const [keysError, setKeysError] = useState("");
const [connections, setConnections] = useState<ExternalConnection[]>([]);
const [connectionsLoading, setConnectionsLoading] = useState(view !== "api");
const [connectionsError, setConnectionsError] = useState("");
const [clientSteps, setClientSteps] = useState<ClientStepsResponse | null>(null);
const [stepsError, setStepsError] = useState("");
const [stepsLoading, setStepsLoading] = useState(view !== "api");
const [canMint, setCanMint] = useState<boolean | null>(null);
const [label, setLabel] = useState("");
const [access, setAccess] = useState("read");
const [databaseMode, setDatabaseMode] = useState<"all" | "subset">("all");
const [selectedDatabases, setSelectedDatabases] = useState<string[]>([]);
const [expiryPreset, setExpiryPreset] = useState<ExpiryPreset>("1-year");
const [scopeDatabases, setScopeDatabases] = useState<ScopeDatabase[] | null>(null);
const [scopeError, setScopeError] = useState("");
const [scopeRevision, setScopeRevision] = useState(0);
const [editing, setEditing] = useState<string | null>(null);
const [editDraft, setEditDraft] = useState<KeyDraft | null>(null);
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
const [revealed, setRevealed] = useState<MintResponse | null>(null);
// The client view closes its in-step reveal but keeps the secret in memory for the verify step.
const [revealClosed, setRevealClosed] = useState(false);
const [copied, setCopied] = useState("");
const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const savedKeySelect = useRef<HTMLSelectElement | null>(null);
useEffect(() => () => {
if (copyTimer.current !== null) clearTimeout(copyTimer.current);
}, []);
const mcpUrl = useMemo(() => {
const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
return `${origin}${API_V1}/external/mcp`;
}, []);
const openApiUrl = useMemo(() => {
const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
return openApiDocumentUrl(API_V1, origin);
}, []);
const client = CLIENTS.find((entry) => entry.id === clientId);
const guide = client ? clientSteps?.clients[client.id] : undefined;
const sharedSteps = clientSteps?.shared;
// Replace only known text tokens. React escapes the result, including command placeholders.
function instruction(value: string): string {
const base = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
return value.replace(/<base>|<mcpUrl>|<client>/g,
(token) => token === "<base>" ? base : token === "<mcpUrl>" ? mcpUrl : client?.label ?? "");
}
function guideStep(step: ServedStep): GuideStep {
return { title: step.title, text: instruction(step.text), ...(step.block ? { block: instruction(step.block) } : {}),
...(step.action ? { action: step.action } : {}) };
}
const starterPrompt = view === "client" && clientSteps ? instruction(clientSteps.starterPrompt) : null;
const connectionKinds: readonly ConnectionKind[] = client?.connections ?? [];
const selectedKey = keys?.find((key) => key.id === selectedKeyId);
const keyIsActive = (key: ExternalKeyMetadata) => !key.revoked_at
&& (!key.expires_at || Date.parse(key.expires_at) > Date.now());
const selectedKeyIsActive = selectedKey !== undefined && keyIsActive(selectedKey);
// The client view opens on a saved key only when an active one exists.
const shownKeyChoice: KeyChoice = view === "client" && canMint === true && keys !== null
&& !keys.some(keyIsActive) ? "create" : keyChoice;
const stepReveal = view === "client" && !revealClosed ? revealed : null;
// A reveal from a different key must never silently replace the saved key the user chose.
const verificationReveal = revealed?.key.id === selectedKeyId ? revealed : null;
const confirmedGrant = confirmedConnection?.kind === "mcp"
? connections.find((grant) => grant.id === confirmedConnection.grantId && grant.clientId === clientId)
: undefined;
const confirmationIsActive = confirmedConnection?.clientId === clientId && (
connection === "mcp" && confirmedConnection?.kind === "mcp" && !connectionsLoading && !connectionsError
&& confirmedGrant?.status === "connected" && !confirmedGrant.disconnected_at
&& (!confirmedGrant.expires_at || Date.parse(confirmedGrant.expires_at) > Date.now())
|| connection === "key" && confirmedConnection?.kind === "key"
&& confirmedConnection.keyId === selectedKeyId && selectedKeyIsActive
);
const canCopyStarterPrompt = view === "client" && showSetup && confirmationIsActive;
const confirmationExpiresAt = connection === "key" ? selectedKey?.expires_at : confirmedGrant?.expires_at;
useEffect(() => {
if (!confirmedConnection) return;
const invalidate = () => {
verificationVersion.current += 1;
setConfirmedConnection(null); setVerifyResult(null); setCopied("");
};
if (!confirmationIsActive) { invalidate(); return; }
if (!confirmationExpiresAt) return;
let timer: ReturnType<typeof setTimeout>;
const schedule = () => {
const remaining = Date.parse(confirmationExpiresAt) - Date.now();
if (remaining <= 0) { invalidate(); return; }
timer = setTimeout(schedule, Math.min(remaining, 2_147_483_647));
};
schedule();
return () => clearTimeout(timer);
}, [confirmedConnection, confirmationIsActive, confirmationExpiresAt]);
useEffect(() => {
if (revealClosed) savedKeySelect.current?.focus();
}, [revealClosed]);
function resetVerification() {
verificationVersion.current += 1;
setConfirmedConnection(null); setVerifyResult(null); setVerifySecret(""); setCopied("");
}
function chooseClient(id: ClientId) {
const entry = CLIENTS.find((candidate) => candidate.id === id);
if (id !== clientId) {
setClientId(id);
setConnection(entry?.connections[0] ?? null);
resetVerification(); setCopied(""); setError(""); setNotice("");
}
}
function chooseConnection(kind: ConnectionKind) {
if (kind !== connection) {
setConnection(kind); resetVerification(); setCopied(""); setError(""); setNotice("");
}
}
function chooseKey(id: string) {
setSelectedKeyId(id); resetVerification();
}
const load = useCallback(async () => {
setKeysError("");
const result = await call<KeyListResponse>("/external/keys");
if (!result.ok) {
setKeys(null); setCanMint(null); setKeysError(result.message); setError(result.message); return;
}
if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") {
setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response.");
setError("The AI API returned an unreadable response."); return;
}
const parsed = result.data.keys.map(parseKey);
if (parsed.some((row) => row === null)) {
setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response.");
setError("The AI API returned an unreadable response."); return;
}
setKeys(parsed as ExternalKeyMetadata[]);
setCanMint(result.data.can_mint);
setError("");
}, []);
const loadConnections = useCallback(async (confirmClient = true) => {
const version = verificationVersion.current;
if (connection === "mcp") { setConfirmedConnection(null); setVerifyResult(null); setCopied(""); }
setConnectionsLoading(true);
setConnectionsError("");
const result = await call<ConnectionListResponse>(CONNECTIONS_PATH);
setConnectionsLoading(false);
if (version !== verificationVersion.current) return;
if (!result.ok || !Array.isArray(result.data?.connections)) {
// Key management remains usable if OAuth discovery is unavailable.
setConnectionsError(result.ok ? "Connections could not be loaded." : result.message);
return;
}
const parsed = result.data.connections.map(parseConnection);
if (parsed.some((row) => row === null)) {
setConnectionsError("Connections could not be loaded."); return;
}
const grants = parsed as ExternalConnection[];
setConnections(grants);
const matched = grants.find((grant) => grant.clientId === clientId && grant.status === "connected"
&& (!grant.expires_at || Date.parse(grant.expires_at) > Date.now()));
if (confirmClient && connection === "mcp" && clientId && matched) {
setConfirmedConnection({ clientId, kind: "mcp", grantId: matched.id });
}
}, [clientId, connection]);
const loadClientSteps = useCallback(async () => {
setStepsLoading(true); setStepsError(""); setClientSteps(null);
const result = await call<unknown>("/connectors/ai-client-steps");
const parsed = result.ok ? parseClientSteps(result.data) : null;
setStepsLoading(false);
if (!parsed) {
setStepsError(result.ok ? "AI client instructions could not be read." : result.message);
return;
}
setClientSteps(parsed);
}, []);
useEffect(() => {
if (view !== "api") void loadClientSteps();
}, [loadClientSteps, view]);
useEffect(() => {
if (view !== "client" || connection === "key") void load();
}, [load, view, connection]);
useEffect(() => {
if (view !== "api") void loadConnections();
}, [loadConnections, view]);
const visibleConnections = view === "client"
? connections.filter((entry) => entry.clientId === initialClient) : connections;
// Report changed metadata only. Secrets remain inside this pane's one-time reveal.
const changed = useRef(false);
useEffect(() => {
if (changed.current) onChanged?.();
changed.current = true;
}, [keys, connections, onChanged]);
useEffect(() => {
if (canMint !== true) return;
let active = true;
setScopeDatabases(null);
setScopeError("");
void call<{ databases: ScopeDatabase[] }>("/external/scope/databases").then((result) => {
if (!active) return;
if (!result.ok) { setScopeError(result.message); setScopeDatabases([]); return; }
const rows = result.data?.databases;
if (!Array.isArray(rows) || rows.some((row) => !row || typeof row.database !== "string" || !row.database.trim())) {
setScopeError("The database list could not be read."); setScopeDatabases([]); return;
}
setScopeError("");
setScopeDatabases(rows.map((row) => ({
database: row.database,
label: typeof row.label === "string" && row.label.trim() ? row.label : row.database,
})));
});
return () => { active = false; };
}, [canMint, scopeRevision]);
function databaseLabels(databases: ResourceScope): string {
if (databases === "all") return "All databases";
if (databases.length === 0) return "No databases";
const labels = databases.slice(0, 4).map((database) => (
scopeDatabases?.find((row) => row.database === database)?.label || database
));
return labels.join(", ") + (databases.length > 4 ? ` and ${databases.length - 4} more` : "");
}
function selectedScope(mode: "all" | "subset", selected: string[]): ResourceScope {
return mode === "all" ? "all" : selected;
}
function validateDraft(draft: KeyDraft): string {
if (!draft.label.trim()) return "Enter a label for this API key.";
if (draft.databaseMode === "subset" && draft.databases.length === 0) {
return "Choose at least one database for this API key.";
}
return "";
}
async function create(event: FormEvent) {
event.preventDefault();
const draft: KeyDraft = {
label, access: access as Access, databaseMode, databases: selectedDatabases, expiryPreset,
};
const invalid = validateDraft(draft);
if (invalid) { setError(invalid); return; }
const databases = selectedScope(databaseMode, selectedDatabases);
setBusy("create"); setError(""); setNotice("");
resetVerification();
const result = await call<MintResponse>("/external/keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
label: label.trim(), access: access, databases: databases, resources: databases,
expires_at: presetToExpiresAt(expiryPreset, new Date()),
}),
});
setBusy("");
if (!result.ok) { setError(result.message); return; }
const key = parseKey(result.data?.key);
if (!key || typeof result.data?.secret !== "string" || result.data.secret === "") {
setError("The API key was created, but its secret could not be read."); void load(); return;
}
setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]);
setLabel(""); setAccess("read"); setDatabaseMode("all"); setSelectedDatabases([]); setExpiryPreset("1-year");
setCopied(""); setRevealed({ key, secret: result.data.secret });
setSelectedKeyId(key.id); setKeyChoice("saved"); setRevealClosed(false);
}
async function copy(value: string, name: string) {
if (copyTimer.current !== null) clearTimeout(copyTimer.current);
setCopied("");
setBusy(`copy:${name}`);
try {
await navigator.clipboard.writeText(value);
setCopied(name); setError("");
copyTimer.current = setTimeout(() => { setCopied(""); copyTimer.current = null; }, 2000);
}
catch { setCopied(""); setError("That text could not be copied. Select it and copy it manually."); }
finally { setBusy((current) => current === `copy:${name}` ? "" : current); }
}
async function saveEdit(event: FormEvent) {
event.preventDefault();
if (!editing || !editDraft) return;
const invalid = validateDraft(editDraft);
if (invalid) { setError(invalid); return; }
const databases = selectedScope(editDraft.databaseMode, editDraft.databases);
setBusy(`edit:${editing}`); setError(""); setNotice("");
resetVerification();
const result = await call<{ key: ExternalKeyMetadata }>(`/external/keys/${encodeURIComponent(editing)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
label: editDraft.label.trim(), access: editDraft.access, databases: databases,
...(editDraft.expiryPreset === "keep" ? {} : {
expires_at: presetToExpiresAt(editDraft.expiryPreset, new Date()),
}),
}),
});
setBusy("");
if (!result.ok) { setError(result.message); return; }
const saved = parseKey(result.data?.key);
if (!saved) {
setError("The API key was updated, but its metadata could not be read."); void load(); return;
}
setKeys((current) => (current ?? []).map((row) => row.id === saved.id ? saved : row));
setEditing(null); setEditDraft(null); setNotice("API key settings saved.");
}
async function rotate(key: ExternalKeyMetadata) {
if (!window.confirm(`Rotate "${key.label}"? Its current secret will stop working immediately.`)) return;
setBusy(`rotate:${key.id}`); setError(""); setNotice("");
resetVerification();
const result = await call<MintResponse>(`/external/keys/${encodeURIComponent(key.id)}/rotate`, { method: "POST" });
setBusy("");
if (!result.ok) { setError(result.message); return; }
const replacement = parseKey(result.data?.key);
if (!replacement || typeof result.data?.secret !== "string" || !result.data.secret) {
setError("The API key was rotated, but its replacement secret could not be read."); void load(); return;
}
setKeys((current) => (current ?? []).map((row) => row.id === key.id ? replacement : row));
setSelectedKeyId((current) => current === key.id ? replacement.id : current);
setEditing(null); setEditDraft(null); setCopied("");
setRevealed({ key: replacement, secret: result.data.secret });
}
async function revoke(key: ExternalKeyMetadata) {
if (!window.confirm(`Revoke "${key.label}"? Its next request will be refused.`)) return;
setBusy(`revoke:${key.id}`); setError(""); setNotice("");
resetVerification();
const result = await call<{ key: ExternalKeyMetadata }>(
`/external/keys/${encodeURIComponent(key.id)}/revoke`, { method: "POST" },
);
setBusy("");
if (!result.ok) { setError(result.message); return; }
setKeys((current) => (current ?? []).filter((row) => row.id !== key.id));
if (revealed?.key.id === key.id) setRevealed(null);
if (editing === key.id) { setEditing(null); setEditDraft(null); }
setNotice("API key revoked. Its next request will be refused.");
}
async function disconnect(connection: ExternalConnection) {
const name = connection.label?.trim()
|| CLIENTS.find((entry) => entry.id === connection.clientId)?.label || "this AI app";
if (!window.confirm(`Disconnect ${name} from Loopable?`)) return;
setBusy(`disconnect:${connection.client}`); setError("");
resetVerification();
const result = await call<{ connection: unknown }>(
`/external/oauth/connections/${encodeURIComponent(connection.client)}/disconnect`, { method: "POST" },
);
setBusy("");
if (!result.ok) { setError(result.message); return; }
setConnections((current) => current.filter((grant) => grant.id !== connection.id));
void loadConnections(false);
setNotice("AI app disconnected. Its next request will be refused.");
}
async function verifyKey() {
const useSelectedKey = view === "client";
const secret = (useSelectedKey ? verificationReveal?.secret : undefined) ?? verifySecret.trim();
if (!secret || busy !== "" || canMint !== true) return;
setBusy("verify:key"); setConfirmedConnection(null); setVerifyResult(null); setCopied("");
const version = ++verificationVersion.current;
const report = (state: VerifyResult["state"], message: string, cause?: VerifyResult["cause"]) => {
if (version !== verificationVersion.current) return;
setVerifyResult({ state, message, cause });
if (state === "ok" && useSelectedKey && clientId && selectedKeyIsActive) {
setConfirmedConnection({ clientId, kind: "key", keyId: selectedKeyId });
}
};
try {
const result = await call<OwnerKeyVerification>("/external/keys/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: secret }),
});
if (version !== verificationVersion.current) return;
if (!result.ok) {
report("failed", result.status === 403
? "Verifying API keys requires AI apps access. Ask an administrator for access"
: "Could not verify the API key. Try again");
return;
}
const diagnosis = result.data;
if (diagnosis?.valid === false && diagnosis.cause
&& Object.prototype.hasOwnProperty.call(KEY_REFUSALS, diagnosis.cause)) {
report("failed", KEY_REFUSALS[diagnosis.cause], diagnosis.cause);
return;
}
if (diagnosis?.valid !== true || diagnosis.cause !== null
|| typeof diagnosis.origin_recorded !== "boolean" || typeof diagnosis.key_id !== "string"
|| (diagnosis.warning !== null && diagnosis.warning !== "store_write_refused")) {
report("failed", "The AI API returned an unreadable response.");
return;
}
if (useSelectedKey && selectedKeyId && diagnosis.key_id !== selectedKeyId) {
report("failed", "This secret does not match the selected API key.");
return;
}
const warning = diagnosis.warning === "store_write_refused"
? ". The last-used store write was refused. Retry Verify to save it" : "";
const origin = diagnosis.origin_recorded ? ""
: ". This legacy key has no recorded Space origin. Its minting Space cannot be proved";
report("ok", `API key accepted${warning}${origin}`, diagnosis.warning ?? undefined);
} catch {
report("failed", "The server could not be reached.");
} finally {
setVerifySecret("");
setBusy((current) => current === "verify:key" ? "" : current);
}
}
async function verifyMcp() {
if (!client || !sharedSteps || busy !== "" || connection !== "mcp") return;
setBusy("verify:mcp"); setConfirmedConnection(null); setVerifyResult(null); setCopied("");
const version = ++verificationVersion.current;
// OAuth grants belong to the signed-in session, independently of the API-key bearer check.
const result = await call<ConnectionListResponse>(CONNECTIONS_PATH);
setBusy((current) => current === "verify:mcp" ? "" : current);
if (version !== verificationVersion.current) return;
if (!result.ok) {
setVerifyResult({ state: "failed", message: result.status ? `${result.status}: ${result.message}` : result.message });
return;
}
if (!Array.isArray(result.data?.connections)) {
setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." });
return;
}
const parsed = result.data.connections.map(parseConnection);
const grants = parsed.filter((row): row is ExternalConnection => row !== null);
if (grants.length !== parsed.length) {
setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." });
return;
}
setConnections(grants);
setConnectionsError("");
const live = grants.filter((grant) => grant.status === "connected"
&& (!grant.expires_at || Date.parse(grant.expires_at) > Date.now()));
const matched = live.find((grant) => grant.clientId === client.id);
if (matched) {
setConfirmedConnection({ clientId: client.id, kind: "mcp", grantId: matched.id });
setVerifyResult({ state: "ok", message: `Loopable sign-in completed for ${matched.label}. Last used: ${when(matched.last_used)}.` });
} else if (live.length) {
setVerifyResult({ state: "failed", message: `Connected: ${live.map((grant) => grant.label || "Unnamed AI app").join(", ")}. ${instruction(sharedSteps.verification.otherGrant)}` });
} else {
setVerifyResult({ state: "failed", message: instruction(sharedSteps.verification.noGrant) });
}
}
function databaseChecks(selected: string[], change: (next: string[]) => void) {
return (
<div className="set-field" style={{ maxHeight: 216, overflowY: "auto" }}>
{scopeDatabases === null ? <SettingsSkeleton label="Loading databases" /> : null}
{scopeError ? <div className="set-error" role="alert"><span title={scopeError}>Could not read the database list.</span>
<button type="button" className="set-secondary" onClick={() => setScopeRevision(value => value + 1)}>Retry</button></div> : null}
{scopeDatabases?.map((database) => (
<label className="set-check" key={database.database}>
<input type="checkbox" checked={selected.includes(database.database)}
onChange={(event) => change(event.currentTarget.checked
? [...selected, database.database]
: selected.filter((key) => key !== database.database))} />
<span>{database.label || database.database}</span>
</label>
))}
{selected.length === 0 ? <p className="set-help">Choose at least one database for this API key.</p> : null}
</div>
);
}
function codeBlock(value: string, name: string, content?: ReactNode) {
return (
<div className="external-code">
<pre>{content ?? value}</pre>
<button type="button" className="external-code-copy" disabled={busy !== ""}
aria-label={copied === name ? "Copied" : "Copy"} title={copied === name ? "Copied" : "Copy"}
onClick={() => void copy(value, name)}>
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor"
strokeWidth="1.4" aria-hidden="true">
{copied === name ? <path d="M3 8.5l3 3 7-7" /> : <><rect x="5.5" y="5.5" width="8" height="8" rx="1.5" />
<path d="M10.5 5.5V3.5a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h2" /></>}
</svg>
</button>
</div>
);
}
function clientGuide(kind: ConnectionKind): GuideStep[] {
if (!guide) return [];
const tutorial = kind === "mcp" ? guide.tutorial : guide.keyTutorial;
if (!tutorial) return [];
return (kind === "mcp" ? guide.steps : guide.keySteps ?? []).map((step, index) =>
({ ...guideStep({ ...step, text: tutorial.steps[index] }), id: `client-step-${index}` }));
}
function clientSetupSteps(keySteps: GuideStep[], completionSteps: GuideStep[]): GuideStep[] {
if (view === "api") return keySteps;
if (!connection) return [];
const steps = clientGuide(connection);
return steps.map((step, index) => ({ ...step, details: [
...(index === 0 ? keySteps : []),
...(index === steps.length - 1 ? completionSteps : []),
] }));
}
function revealPanel(reveal: MintResponse, close: ReactNode) {
return <>
<p className="set-help">Copy it now. Loopable cannot show this secret again.</p>
<div className="set-field"><label className="set-label" htmlFor="set-external-secret">API key</label>
<input id="set-external-secret" className="set-input" type="text" value={reveal.secret}
readOnly autoComplete="off" spellCheck={false} /></div>
<div className="set-actions">
<button type="button" className="set-primary" disabled={busy !== ""}
onClick={() => void copy(reveal.secret, "secret")}>
{busy === "copy:secret" ? "Copying…" : copied === "secret" ? "Copied" : "Copy API key"}</button>
{close}
</div>
</>;
}
// The client view shows its reveal inside the key step, so only the other views draw this card.
const revealCard = revealed && view !== "client" ? (
<section className="set-card">
<h2 className="set-h4">API key</h2>
{revealPanel(revealed, <button type="button" className="set-secondary" disabled={busy !== ""}
onClick={() => { setRevealed(null); setCopied(""); }}>Done</button>)}
</section>
) : null;
return (
<div className="set-pane external-access-pane" data-connect-tutorial={view === "client" ? clientId : undefined}>
<style>{`
.external-access-pane .set-card { padding: 16px; }
.external-access-pane .set-field { margin-bottom: 16px; }
.external-access-pane .set-label { margin-bottom: 4px; }
.external-access-pane .set-check { gap: 8px; padding: 4px 0; }
.external-access-pane .set-actions { margin-top: 16px; align-items: center; }
.external-access-pane .set-input { padding: 0 8px; }
.external-access-pane textarea.set-input { height: auto; padding: 8px; }
.external-access-pane .pg-select { height: 32px; max-width: 100%; }
.external-clients { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.external-access-pane .external-tile {
display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px;
text-align: left; color: var(--lp-ink); background: var(--lp-surface); cursor: pointer;
border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); font-size: var(--lp-fs-sm);
}
.external-access-pane .external-tile[aria-pressed="true"] {
border-color: var(--lp-ink); background: var(--lp-wash); box-shadow: inset 0 0 0 1px var(--lp-ink);
}
.external-choices { display: grid; gap: 8px; }
.external-access-pane .external-choice { flex-direction: column; align-items: flex-start; gap: 2px; padding: 10px 12px; }
.external-choice span { font-size: var(--lp-fs-xs); color: var(--lp-muted); }
.external-for {
display: flex; align-items: center; gap: 8px; margin: 0 0 16px;
font-size: var(--lp-fs-xs); color: var(--lp-muted);
}
.external-for strong { color: var(--lp-ink); font-weight: 500; }
.external-access-pane kbd {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.92em;
padding: 1px 6px; color: var(--lp-ink); background: var(--lp-wash);
border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm);
}
.external-code {
position: relative; margin-top: 8px; background: var(--lp-wash);
border: 1px solid var(--lp-line); border-radius: var(--lp-r-md);
}
.external-code pre {
margin: 0; padding: 12px 44px 12px 14px; white-space: pre-wrap; overflow-wrap: anywhere;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh);
}
.external-access-pane .external-code-copy {
position: absolute; top: 8px; right: 8px; width: 28px; height: 28px;
display: grid; place-items: center; color: var(--lp-muted); cursor: pointer;
border-radius: var(--lp-r-sm);
}
.external-guide .set-help { margin-top: 16px; }
.external-send { margin: 0; font-size: var(--lp-fs-sm); color: var(--lp-ink); }
.external-instructions {
margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit;
font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh);
}
.external-access-pane .external-command { height: 40px; font-weight: 500; }
.external-guide { min-width: 0; }
.external-guide code { font: inherit; color: var(--lp-ink); }
.external-divider { border-top: 1px solid var(--lp-line); margin-top: 16px; padding-top: 16px; }
.external-access-pane .external-steps .external-verification-result { margin-top: 8px; }
@media (hover: hover) and (pointer: fine) {
.external-access-pane .external-tile:hover:enabled { border-color: var(--lp-line-strong); }
.external-access-pane .external-code-copy:hover:enabled { color: var(--lp-ink); background: var(--lp-surface); }
}
@media (max-width: 560px) { .external-clients { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
`}</style>
{view === "all" ? <h1 className="set-h">Loopable connections</h1> : null}
{error ? <p className="set-error" role="alert">{error}</p> : null}
{notice ? <p className="set-notice" role="status">{notice}</p> : null}
{view !== "api" && connectionsLoading ? <SettingsSkeleton label="Loading connections" /> : null}
{view !== "api" && connectionsError ? (
<div className="set-error" role="alert"><span title={connectionsError}>Could not load connections.</span>
<button type="button" className="set-secondary" disabled={connectionsLoading}
onClick={() => void loadConnections()}>Retry</button></div>
) : null}
{!showSetup && view === "client" && !connectionsLoading ? (
<div className="set-actions"><button type="button" className="set-primary"
onClick={() => setShowSetup(true)}>Connect another</button></div>
) : null}
{showSetup ? <ConnectionWizard titleId="external-step-title"
title={view === "api" ? "Create API key" : "Connect Loopable"}
metadata={view !== "api" && guide ? <p className="set-help" title={guide.provenance}>
{clientId === "muse" ? "Setup guide" : <>
Checked <time dateTime={guide.verified}>{guide.verified}</time>{" · "}
<a href={guide.documentation} target="_blank" rel="noreferrer"
style={{ color: "var(--lp-blue-deep)" }}>Documentation</a>
</>}
</p> : undefined}>
{view !== "api" ? (
<>
<div className="external-clients" role="group" aria-label="Which AI are you using?">
{CLIENTS.map((entry) => (
<button key={entry.id} type="button" className="external-tile" data-client={entry.id}
aria-pressed={clientId === entry.id} disabled={busy !== ""}
onClick={() => chooseClient(entry.id)}>
<AiClientMark id={entry.id} /><span>{entry.label}</span>
</button>
))}
</div>
</>
) : null}
{view !== "api" && client && connectionKinds.length > 1 ? (
<>
<p className="external-sub">How should {client.label} reach Loopable?</p>
<div className="external-choices" aria-label="AI API connection choices">
{connectionKinds.includes("mcp") ? (
<button type="button" className="external-tile external-choice" data-connection="mcp"
disabled={busy !== ""} aria-pressed={connection === "mcp"}
onClick={() => chooseConnection("mcp")}>
<strong>Sign in with Loopable</strong>
{sharedSteps ? <span>{instruction(sharedSteps.connection.mcp)}</span> : null}
</button>
) : null}
{connectionKinds.includes("key") ? (
<button type="button" className="external-tile external-choice" data-connection="key"
disabled={busy !== ""} aria-pressed={connection === "key"}
onClick={() => chooseConnection("key")}>
<strong>API key</strong>
{sharedSteps ? <span>{sharedSteps.connection.key}</span> : null}
</button>
) : null}
</div>
</>
) : null}
<div className="external-guide" title={view !== "api" ? guide?.caveat : undefined}>
{view !== "api" && stepsLoading ? <SettingsSkeleton label="Loading instructions" /> : null}
{view !== "api" && stepsError ? <div className="set-error" role="alert">
<span title={stepsError}>Could not read the instructions.</span>
<button type="button" className="set-secondary" onClick={() => void loadClientSteps()}>
Retry
</button>
</div> : null}
{view === "api" || (guide && sharedSteps) ? <GuideSteps
mode="short"
tutorial={view === "api" ? undefined : connection === "key" ? guide?.keyTutorial : guide?.tutorial}
renderCopy={(value, index, step) => {
const name = `guide:${clientId}:${connection}:${step.id ?? index}`;
const isStarter = step.id === "starter-prompt";
return <button type="button" className="external-step-copy"
disabled={busy !== "" || (isStarter && !canCopyStarterPrompt)}
data-starter-prompt={isStarter || undefined}
aria-describedby={isStarter && !canCopyStarterPrompt ? "starter-prompt-hint" : undefined}
onClick={() => { if (!isStarter || canCopyStarterPrompt) void copy(value, name); }} aria-live="polite">
{copied === name ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
<span>{copied === name ? "Copied" : isStarter ? "Copy starter prompt" : "Copy"}</span>
</button>;
}} steps={clientSetupSteps([
...((connection === "key" && client) || view === "api" ? [{ id: "key-step", text: stepReveal ? (
<div data-key-reveal>
{revealPanel(stepReveal, <button type="button" className="set-secondary" disabled={busy !== ""}
onClick={() => { setRevealClosed(true); setCopied(""); }}>Back to steps</button>)}
</div>
) : <>
{view === "all" || (view === "client" && canMint === true) ? <div className="set-actions"
style={{ marginTop: 0, justifyContent: "flex-start" }} aria-label="API key choices">
<button type="button" className="set-secondary" data-key-choice="create"
aria-pressed={shownKeyChoice === "create"} disabled={canMint !== true || busy !== ""}
onClick={() => { setKeyChoice("create"); resetVerification(); }}>Create a new key</button>
<button type="button" className="set-secondary" data-key-choice="saved"
aria-pressed={shownKeyChoice === "saved"} disabled={!keys?.some(keyIsActive) || busy !== ""}
onClick={() => { setKeyChoice("saved"); resetVerification(); }}>Use a saved key</button>
</div> : null}
{keysError ? (
<div role="alert">
<p className="set-help">{keysError}</p>
<div className="set-actions"><button type="button" className="set-secondary"
disabled={busy !== ""} onClick={() => void load()}>Try again</button></div>
</div>
) : keys === null ? (
<SettingsSkeleton label="Loading API key settings" />
) : keys.length === 0 ? (
<p className="set-help">{view === "client" ? "No saved API keys." : "You have no saved keys yet, so create one here."}</p>
) : !keys.some(keyIsActive) ? (
<p className="set-help">{view === "client" ? "No active API keys." : "No saved key is active. Create one or update its expiry below."}</p>
) : null}
{canMint === false ? (
<p className="set-help">Creating API keys requires AI apps access. Ask an administrator for access</p>
) : null}
{(shownKeyChoice === "create" || view === "api") && canMint === true ? (
<form className="external-divider" onSubmit={(event) => void create(event)}>
<div className="set-field"><label className="set-label" htmlFor="set-external-label">Label</label>
<input id="set-external-label" className="set-input" type="text" maxLength={80} value={label}
autoComplete="off" placeholder="Reporting SDK" onChange={(event) => setLabel(event.currentTarget.value)} /></div>
<div className="set-field"><label className="set-label" htmlFor="set-external-access">Access</label>
<select id="set-external-access" className="pg-select" value={access}
onChange={(event) => setAccess(event.currentTarget.value as Access)}>
<option value="read">Read only</option><option value="readwrite">Read and write</option>
</select></div>
<div className="set-field"><label className="set-label" htmlFor="set-external-databases">Resources</label>
<select id="set-external-databases" className="pg-select" value={databaseMode}
onChange={(event) => setDatabaseMode(event.currentTarget.value as "all" | "subset")}>
<option value="all">All databases</option><option value="subset">Selected databases</option>
</select></div>
{databaseMode === "subset" ? databaseChecks(selectedDatabases, setSelectedDatabases) : null}
<ExpiryPresets id="set-external-expiry" value={expiryPreset} onChange={setExpiryPreset} />
<div className="set-actions"><button type="submit" className="set-primary" disabled={busy !== ""}>
{busy === "create" ? "Creating…" : "Create API key"}</button></div>
</form>
) : null}
{shownKeyChoice === "saved" && client && keys && keys.length > 0 ? (
<div className="set-field external-divider">
<label className="set-label" htmlFor="external-saved-key">Saved key</label>
<select id="external-saved-key" ref={savedKeySelect} className="pg-select" value={selectedKey?.id ?? ""}
disabled={busy !== ""} aria-describedby="external-saved-key-help"
onChange={(event) => chooseKey(event.currentTarget.value)}>
<option value="">Choose a key</option>
{keys.map((key) => (
<option key={key.id} value={key.id}>
{key.label} · {key.access === "read" ? "Read only" : "Read and write"} · {key.expires_at ? "Expires " + when(key.expires_at) : "No expiry"}
{key.revoked_at ? " (Revoked)" : !keyIsActive(key) ? " (Expired)" : ""}
</option>
))}
</select>
<p id="external-saved-key-help" className="set-help">
{sharedSteps ? instruction(sharedSteps.keySetup.saved) : null}
</p>
{verificationReveal && view !== "client" ? <p className="set-help">{sharedSteps?.keySetup.saveNew}</p> : null}
</div>
) : null}
{view === "client" && onOpenApi ? (
<div className="set-actions"><button type="button" className="set-secondary"
disabled={busy !== ""} onClick={onOpenApi}>API key settings</button></div>
) : null}
</> }] : []),
], [
...(view !== "api" && client?.skill && connection && sharedSteps ? [guideStep(sharedSteps.skill)] : []),
...(view !== "api" && client && connection && sharedSteps ? [{ text: <>
{connection === "key" ? (
<>
{selectedKey ? <p className="set-help">Key: {selectedKey.label}</p> : null}
{verificationReveal ? <p className="set-help">{sharedSteps.verification.newKey}</p> : (
<div className="set-field">
<label className="set-label" htmlFor="external-verify-key">Saved API key</label>
<input id="external-verify-key" className="set-input" type="password" value={verifySecret}
autoComplete="off" spellCheck={false} disabled={busy !== "" || canMint !== true}
aria-describedby="external-verify-key-help"
onChange={(event) => { resetVerification(); setVerifySecret(event.currentTarget.value); }} />
<p id="external-verify-key-help" className="set-help">{sharedSteps.verification.savedKey}</p>
</div>
)}
<p className="set-help">{sharedSteps.verification.key}</p>
</>
) : (
<GuideInstruction text={instruction(sharedSteps.verification.mcp)} />
)}
<div className="set-actions">
{connection === "key" ? (
<button type="button" className="set-primary" data-verify="key"
disabled={busy !== "" || canMint !== true || !(verificationReveal?.secret || verifySecret.trim())}
onClick={() => void verifyKey()}>{busy === "verify:key" ? "Verifying…" : "Verify API key"}</button>
) : (
<button type="button" className="set-primary" data-verify="mcp" disabled={busy !== ""}
onClick={() => void verifyMcp()}>{busy === "verify:mcp" ? "Checking…" : "Verify sign-in"}</button>
)}
</div>
{verifyResult ? (
<p className={`external-verification-result ${verifyResult.state === "failed" ? "set-error" : "set-notice"}`}
role="status" data-verify-result data-verify-state={verifyResult.state} data-verify-cause={verifyResult.cause}>
{verifyResult.message}
</p>
) : null}
</> }] : []),
...(starterPrompt ? [{ id: "starter-prompt", text: "Starter prompt", block: starterPrompt,
copyValue: starterPrompt, hint: canCopyStarterPrompt ? undefined : "Verify the connection to copy the starter prompt." }] : []),
])} /> : null}
</div>
</ConnectionWizard> : null}
{revealCard}
{view !== "client" ? <section className="set-card" data-owner-key-verify aria-labelledby="external-verify-title"
aria-busy={busy === "verify:key"}>
<h2 id="external-verify-title" className="set-h4">Verify</h2>
{keysError ? <div className="set-error" role="alert">
<span>Could not load API key access</span>
<button type="button" className="set-secondary" onClick={() => void load()}>Retry</button>
</div> : canMint === null ? <SettingsSkeleton label="Loading Verify access" />
: canMint === false ? <p className="set-help">
Verifying API keys requires AI apps access. Ask an administrator for access
</p> : <form onSubmit={(event) => { event.preventDefault(); void verifyKey(); }}>
<div className="set-field">
<label className="set-label" htmlFor="external-owner-verify-key">API key</label>
<input id="external-owner-verify-key" className="set-input" type="password" value={verifySecret}
autoComplete="off" spellCheck={false} disabled={busy !== ""}
aria-describedby="external-owner-verify-help"
onChange={(event) => { resetVerification(); setVerifySecret(event.currentTarget.value); }} />
<p id="external-owner-verify-help" className="set-help">Paste your saved key, including a revoked or expired key</p>
</div>
<div className="set-actions">
<button type="submit" className="set-primary" data-verify="key"
disabled={busy !== "" || !verifySecret.trim()}>
{busy === "verify:key" ? "Verifying…" : "Verify API key"}
</button>
</div>
</form>}
{verifyResult ? <p className={verifyResult.state === "failed" ? "set-error" : "set-notice"}
role="status" data-verify-result data-verify-state={verifyResult.state} data-verify-cause={verifyResult.cause}>
{verifyResult.message}
</p> : null}
</section> : null}
{view !== "api" && visibleConnections.length > 0 ? (
/* HOTFIX 2026-09-24 (owner: the AI connections list "is really ugly, let's make it look
like a Grid view"). One row per connection in the Data grid's own look: row numbers,
a washed header, hairline cells and a status pill (`index.css` `.ea-grid`). */
<section className="set-card">
<h2 className="set-h4">AI connections</h2>
<div className="ea-grid" role="region" aria-label="AI connections" tabIndex={0}>
<table className="ea-grid-table">
<thead>
<tr>
<th scope="col" className="ea-grid-num"><span className="ea-grid-sr">Row</span></th>
<th scope="col">AI app</th>
<th scope="col">Status</th>
<th scope="col">Access</th>
<th scope="col">Databases</th>
<th scope="col">Connected</th>
<th scope="col">Last used</th>
<th scope="col" className="ea-grid-act"><span className="ea-grid-sr">Actions</span></th>
</tr>
</thead>
<tbody>
{visibleConnections.map((connection, index) => (
<tr key={connection.id}>
<td className="ea-grid-num">{index + 1}</td>
<td>
<span className="ea-grid-app">
{connection.clientId ? <AiClientMark id={connection.clientId} size={16} /> : null}
<span>{connection.label || "Unnamed AI app"}</span>
</span>
</td>
<td><span className={`ea-grid-pill is-${connection.status}`}>{connectionLabel(connection)}</span></td>
<td>{connection.access === null ? "" : connection.access === "read" ? "Read only" : "Read and write"}</td>
<td>{connection.databases === null ? "" : databaseLabels(connection.databases)}</td>
<td>{when(connection.created)}</td>
<td>{when(connection.last_used)}</td>
<td className="ea-grid-act">
{connection.status === "connected" ? (
<button type="button" className="ea-grid-btn" disabled={busy !== ""}
onClick={() => void disconnect(connection)}>
{busy === `disconnect:${connection.client}` ? "Disconnecting…" : "Disconnect"}
</button>
) : null}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
) : null}
{view !== "client" ? <>
<div className="set-perm-sect"><h2 className="set-h4">API keys</h2></div>
{keysError ? <div className="set-error" role="alert"><span title={keysError}>Could not load API keys.</span>
<button type="button" className="set-secondary" disabled={busy !== ""}
onClick={() => void load()}>Retry</button></div>
: keys === null ? <SettingsSkeleton label="Loading API keys" />
: keys.length === 0 ? <p className="set-help">You have no API keys yet.</p> : (
<div aria-label="Active API keys">
{keys.map((key) => (
<section className="set-card" key={key.id}>
{editing === key.id && editDraft ? (
<form onSubmit={(event) => void saveEdit(event)}>
<h2 className="set-h4">Edit API key</h2>
<div className="set-field"><label className="set-label" htmlFor={`key-label-${key.id}`}>Label</label>
<input id={`key-label-${key.id}`} className="set-input" maxLength={80} value={editDraft.label}
onChange={(event) => setEditDraft({ ...editDraft, label: event.currentTarget.value })} /></div>
<div className="set-field"><label className="set-label" htmlFor={`key-access-${key.id}`}>Access</label>
<select id={`key-access-${key.id}`} className="pg-select" value={editDraft.access}
onChange={(event) => setEditDraft({ ...editDraft, access: event.currentTarget.value as Access })}>
<option value="read">Read only</option><option value="readwrite">Read and write</option>
</select></div>
<div className="set-field"><label className="set-label" htmlFor={`key-databases-${key.id}`}>Resources</label>
<select id={`key-databases-${key.id}`} className="pg-select" value={editDraft.databaseMode}
onChange={(event) => setEditDraft({ ...editDraft, databaseMode: event.currentTarget.value as "all" | "subset" })}>
<option value="all">All databases</option><option value="subset">Selected databases</option>
</select></div>
{editDraft.databaseMode === "subset"
? databaseChecks(editDraft.databases, (databases) => setEditDraft({ ...editDraft, databases })) : null}
{keyExpiryLabel(key) === "Expired" ? <p className="set-help">Expired</p> : null}
<ExpiryPresets id={`key-expiry-${key.id}`} value={editDraft.expiryPreset} keepCurrent
onChange={(expiryPreset) => setEditDraft({ ...editDraft, expiryPreset })} />
<div className="set-actions">
<button type="submit" className="set-primary" disabled={busy === `edit:${key.id}`}>
{busy === `edit:${key.id}` ? "Saving…" : "Save changes"}</button>
<button type="button" className="set-secondary" onClick={() => { setEditing(null); setEditDraft(null); }}>Cancel</button>
</div>
</form>
) : (
<>
<h2 className="set-h4">{key.label}</h2>
<div className="pg-drill-row"><span className="pg-drill-key">Access</span>
<span className="pg-drill-val">{key.access === "read" ? "Read only" : "Read and write"}</span></div>
<div className="pg-drill-row"><span className="pg-drill-key">Resources</span>
<span className="pg-drill-val">{databaseLabels(key.databases)}</span></div>
<div className="pg-drill-row"><span className="pg-drill-key">Expiry</span>
<span className="pg-drill-val">{keyExpiryLabel(key)}</span></div>
<div className="pg-drill-row"><span className="pg-drill-key">Last used</span>
<span className="pg-drill-val">{when(key.last_used)}</span></div>
{keyIsActive(key) ? <KeyOpenApiRow documentUrl={openApiUrl}
renderCode={(value, name, content) => codeBlock(value, `openapi:${key.id}:${name}`, content)} /> : null}
<div className="set-actions">
<button type="button" className="set-secondary" onClick={() => { setEditing(key.id); setEditDraft(draftFor(key)); }}>Edit</button>
<button type="button" className="set-secondary" disabled={busy === `rotate:${key.id}`}
onClick={() => void rotate(key)}>{busy === `rotate:${key.id}` ? "Rotating…" : "Rotate"}</button>
<button type="button" className="set-secondary kc-danger" disabled={busy === `revoke:${key.id}`}
onClick={() => void revoke(key)}>{busy === `revoke:${key.id}` ? "Revoking…" : "Revoke"}</button>
</div>
</>
)}
</section>
))}
</div>
)}
</> : null}
</div>
);
}
|