@huaweidevtools/aishell-dsh-client-credentials 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -457,67 +457,511 @@ function AishellHeroChip(props) {
457
457
  */
458
458
  const CREDENTIAL_URL = "https://console.huaweicloud.com/apiexplorer/#/openapi/IAM/doc?version=v3&api=CreateTemporaryAccessKeyByToken";
459
459
 
460
+ //#endregion
461
+ //#region src/login-status.ts
462
+ /**
463
+ * Header the reachability probe sends, to force a CORS preflight.
464
+ *
465
+ * Any non-safelisted header would do it; this one names why. Declared here
466
+ * because both halves need the same string and neither owns it: the browser
467
+ * half sends it on the loopback fetch, the host's listener must allow it in
468
+ * its preflight answer, and a mismatch between the two is a probe that fails
469
+ * on a route that would actually work — the entry hidden for no reason.
470
+ */
471
+ const PROBE_HEADER = "x-aishell-probe";
472
+ /**
473
+ * Read an outcome back out of the document.
474
+ *
475
+ * Anything unreadable reads as no outcome: a corrupt field should show
476
+ * nothing, not a spurious success.
477
+ *
478
+ * @param raw - the stored string, if any.
479
+ * @returns the outcome, or `undefined` when there is none usable.
480
+ */
481
+ function decodeOutcome(raw) {
482
+ if (raw === void 0 || raw === "") return void 0;
483
+ let parsed;
484
+ try {
485
+ parsed = JSON.parse(raw);
486
+ } catch {
487
+ return void 0;
488
+ }
489
+ if (parsed === null || typeof parsed !== "object") return void 0;
490
+ const candidate = parsed;
491
+ if (candidate.kind === "succeeded" && typeof candidate.accountName === "string") return {
492
+ kind: "succeeded",
493
+ accountName: candidate.accountName
494
+ };
495
+ if (candidate.kind === "failed" && typeof candidate.error === "string") return {
496
+ kind: "failed",
497
+ error: candidate.error
498
+ };
499
+ return void 0;
500
+ }
501
+
502
+ //#endregion
503
+ //#region src/client/login-flow.ts
504
+ /**
505
+ * A signal that fires on the timeout, on the caller's abort, or not at all.
506
+ *
507
+ * `AbortSignal.timeout` alone would ignore the caller's signal, so a card
508
+ * closed mid-probe would leave its request running for the rest of the
509
+ * timeout. The two are combined rather than choosing one because both apply:
510
+ * the request may be abandoned, and it may also hang.
511
+ *
512
+ * @param ms - the timeout.
513
+ * @param caller - the caller's signal, if any.
514
+ */
515
+ function withTimeout(ms, caller) {
516
+ const timeout = AbortSignal.timeout(ms);
517
+ if (caller === void 0) return timeout;
518
+ if (typeof AbortSignal.any !== "function") return timeout;
519
+ return AbortSignal.any([timeout, caller]);
520
+ }
521
+ /**
522
+ * How long either call may take.
523
+ *
524
+ * Short, because both are expected to be immediate: a loopback request that
525
+ * works answers in well under a millisecond. The bound exists so an access
526
+ * route that cannot do this says so rather than leaving the card mid-check.
527
+ */
528
+ const CALL_TIMEOUT_MS = 3e3;
529
+ /** Routes the browser half drives a login through. */
530
+ const LOGIN_PROBE_ROUTE = "api/aishell/credentials/login/probe";
531
+ const LOGIN_START_ROUTE = "api/aishell/credentials/login/start";
532
+ const LOGIN_CANCEL_ROUTE = "api/aishell/credentials/login/cancel";
533
+ /** POST an empty body to a host route and read its JSON answer. */
534
+ async function post(route) {
535
+ try {
536
+ const response = await fetch(route, {
537
+ method: "POST",
538
+ headers: { "content-type": "application/json" },
539
+ body: JSON.stringify({}),
540
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS)
541
+ });
542
+ return await response.json();
543
+ } catch {
544
+ return void 0;
545
+ }
546
+ }
547
+ /**
548
+ * The probe's answer, for as long as this page lives.
549
+ *
550
+ * ## Why cached here
551
+ *
552
+ * The question is whether a browser on this machine can reach a socket on the
553
+ * host, and it is a property of how this page is reached rather than of any
554
+ * one card:
555
+ * closing the card and opening it again does not move either machine. Asking
556
+ * per card meant a bound port, a loopback request and a CORS preflight every
557
+ * time — for an answer that had not changed.
558
+ *
559
+ * ## Why a promise, not the boolean
560
+ *
561
+ * Stored as the in-flight promise so two cards opened in quick succession share
562
+ * one probe rather than racing two. The second caller joins the first's answer.
563
+ *
564
+ * ## Why it lives in the module and not the component
565
+ *
566
+ * The component remounts on every open — that is how a fresh card gets fresh
567
+ * state — so anything held in its state is re-derived each time. A module-level
568
+ * value survives that, which is the whole point.
569
+ *
570
+ * ## What invalidates it
571
+ *
572
+ * Nothing, for the life of the page. A person who sets up a tunnel to fix a
573
+ * failed probe reloads, and a reload is the natural boundary: it is the same
574
+ * act that re-establishes the page's connection to the host. A remembered
575
+ * "no" that could never be revisited would be worse than the repeated probe;
576
+ * a remembered "no" that lasts only until reload is not.
577
+ *
578
+ * ## The one thing not remembered
579
+ *
580
+ * A failure to reach the **host** at all. That is not an answer about the
581
+ * route — the host may be mid-reload — and caching it would leave the card
582
+ * saying "unsupported" for the rest of the page's life. So `runRouteProbe`
583
+ * reports it as `undefined`, and only real answers are kept.
584
+ */
585
+ let routeProbe;
586
+ /**
587
+ * Ask whether a browser here can reach a loopback listener.
588
+ *
589
+ * ## What it tests, and why only this can
590
+ *
591
+ * The cloud posts a credential to `127.0.0.1` **as the browser's machine
592
+ * resolves it**, so the flow works only when that browser can reach a listener
593
+ * on this host. Neither side can tell by looking: an SSH-forwarded session
594
+ * makes a distant browser look local to the host, and a distant host look local
595
+ * to the page. So the host borrows a port, this page fetches it, and the fetch
596
+ * *is* the answer — resolving means a socket here was reached, rejecting means
597
+ * it was not.
598
+ *
599
+ * The port is released by the host as soon as it is reached, or after a short
600
+ * window. Nothing is kept for the login that may follow: that binds its own
601
+ * port, so a card read and abandoned holds nothing.
602
+ *
603
+ * ## Why the request carries a header
604
+ *
605
+ * The header makes it a non-simple request, so the browser sends a CORS
606
+ * preflight first and only proceeds if the answer is right. The cloud's
607
+ * callback is a JSON POST and therefore *always* preflights, so a plain GET
608
+ * would test a path the callback never takes — and could pass on a route where
609
+ * the real preflight fails, which is the one wrong answer this must not
610
+ * give.
611
+ *
612
+ * @returns whether the route works here. Answered once per page, except when
613
+ * the host could not be reached — see {@link routeProbe}.
614
+ */
615
+ async function probeBrowserRoute(signal) {
616
+ routeProbe ??= runRouteProbe(signal);
617
+ const answer = await routeProbe;
618
+ if (answer === void 0) routeProbe = void 0;
619
+ return answer ?? false;
620
+ }
621
+ /**
622
+ * One probe, from borrowing the port to reading the answer.
623
+ *
624
+ * @param signal - aborts the loopback request when the card that asked goes
625
+ * away. The host's port is not released by this — it never learns the page
626
+ * gave up — but the request stops, and the host's own window closes it. The
627
+ * result is still cached: the route did not change because a card closed.
628
+ */
629
+ async function runRouteProbe(signal) {
630
+ const answer = await post(LOGIN_PROBE_ROUTE);
631
+ if (answer === void 0) return void 0;
632
+ if (answer.ok !== true || typeof answer.probeUrl !== "string" || answer.probeUrl === "") return false;
633
+ try {
634
+ const reached = await fetch(answer.probeUrl, {
635
+ method: "GET",
636
+ headers: { [PROBE_HEADER]: "1" },
637
+ signal: withTimeout(CALL_TIMEOUT_MS, signal)
638
+ });
639
+ return reached.ok;
640
+ } catch {
641
+ if (signal?.aborted === true) return void 0;
642
+ return false;
643
+ }
644
+ }
645
+ /**
646
+ * Begin a login, now that the person has asked for one.
647
+ *
648
+ * Binds a port and fetches a URL projected for it at this moment, which is why
649
+ * the URL is not stale however long the card sat open before the click.
650
+ *
651
+ * @returns a handle for the login in flight, or `undefined` when the host
652
+ * could not start one.
653
+ */
654
+ async function startBrowserLogin() {
655
+ const started = await post(LOGIN_START_ROUTE);
656
+ if (started?.ok !== true || typeof started.loginUrl !== "string" || started.loginUrl === "") return void 0;
657
+ return {
658
+ loginUrl: started.loginUrl,
659
+ providerName: started.providerName ?? "",
660
+ expiresInSeconds: started.expiresInSeconds ?? 0,
661
+ cancel: () => {
662
+ fetch(LOGIN_CANCEL_ROUTE, { method: "POST" }).catch(() => {});
663
+ }
664
+ };
665
+ }
666
+ /**
667
+ * Open a blank tab, subject to the current user gesture.
668
+ *
669
+ * @returns the handle, or `undefined` when a blocker refused.
670
+ */
671
+ function openLoginWindow() {
672
+ const opened = window.open("", "_blank");
673
+ if (opened === null) return void 0;
674
+ try {
675
+ opened.opener = null;
676
+ } catch {}
677
+ return {
678
+ navigate: (url) => {
679
+ try {
680
+ opened.location.href = url;
681
+ } catch {}
682
+ },
683
+ close: () => {
684
+ try {
685
+ opened.close();
686
+ } catch {}
687
+ }
688
+ };
689
+ }
690
+
691
+ //#endregion
692
+ //#region src/client/card-state.ts
693
+ /**
694
+ * The button's label and enabled state.
695
+ *
696
+ * @param phase - the probe's answer and whether a login is in flight.
697
+ * @param hasCountdown - whether a countdown is being shown. Unused by the
698
+ * label, which names the action rather than the remaining time — the
699
+ * countdown sits above the button where it can be read without the label
700
+ * changing under the pointer. Kept in the signature so callers pass the same
701
+ * pair the render does, and so a future state that does depend on it has
702
+ * somewhere to say so.
703
+ * @returns the label key and whether the button is disabled.
704
+ */
705
+ function browserButton(phase, hasCountdown) {
706
+ switch (phase) {
707
+ case "checking":
708
+ case "starting":
709
+ case "ready": return {
710
+ label: "form.browser.action",
711
+ disabled: phase !== "ready"
712
+ };
713
+ case "unsupported": return {
714
+ label: "form.browser.unsupportedLabel",
715
+ disabled: true
716
+ };
717
+ case "running": return {
718
+ label: "form.browser.cancelLabel",
719
+ disabled: false
720
+ };
721
+ default: return {
722
+ label: "form.browser.action",
723
+ disabled: false
724
+ };
725
+ }
726
+ }
727
+ /**
728
+ * Render a countdown as `m:ss`.
729
+ *
730
+ * Language-neutral on purpose: the sentence around it is localised, and a
731
+ * number with a colon needs no translation — spelling out a unit would put a
732
+ * second copy of it in both dictionaries for no gain. Tabular figures are
733
+ * applied at the call site so the digits do not jitter as they change.
734
+ *
735
+ * @param seconds - seconds remaining; negative reads as zero.
736
+ */
737
+ function formatCountdown(seconds) {
738
+ const whole = Math.max(0, Math.floor(seconds));
739
+ const minutes = Math.floor(whole / 60);
740
+ const rest = whole % 60;
741
+ return `${String(minutes)}:${String(rest).padStart(2, "0")}`;
742
+ }
743
+
460
744
  //#endregion
461
745
  //#region src/client/CredentialRequestForm.tsx
462
746
  /**
463
- * The masked credential form.
747
+ * The credential card.
464
748
  *
465
- * Submitting saves through the Host route; the Host then tells the waiting tool
466
- * call there is now a credential, and clears the pending flag this component
467
- * renders from — so a successful submit does not need to unmount itself. A
468
- * manually-opened form has no request behind it, so it closes itself after a
469
- * successful save (the chip flipping to the account name is the feedback).
749
+ * Submitting saves through the Host route; the card then closes itself, and the
750
+ * chip flipping to the account name is the feedback that it worked.
470
751
  */
471
752
  function CredentialRequestForm(props) {
472
753
  const t = props.t;
473
- const { save, clear, dismiss, closeManual } = props;
754
+ const { save, clear, close, cancel } = props;
474
755
  const status = props.useCredentials((snapshot) => snapshot);
475
756
  const [ak, setAk] = (0, react.useState)("");
476
757
  const [sk, setSk] = (0, react.useState)("");
477
758
  const [token, setToken] = (0, react.useState)("");
478
759
  const [saving, setSaving] = (0, react.useState)(false);
479
760
  const [clearing, setClearing] = (0, react.useState)(false);
480
- const [error, setError] = (0, react.useState)(void 0);
481
- const pending = props.pendingInteraction;
482
- const manual = pending?.manual === true;
761
+ /** A failure of whichever route produced it; each section renders its own. */
762
+ const [browserError, setBrowserError] = (0, react.useState)(void 0);
763
+ const [manualError, setManualError] = (0, react.useState)(void 0);
764
+ /** Whether the fields were seeded from the environment, so the notice is honest. */
765
+ const [prefilled, setPrefilled] = (0, react.useState)(false);
766
+ const [login, setLogin] = (0, react.useState)(void 0);
767
+ const [phase, setPhase] = (0, react.useState)("checking");
768
+ const [secondsLeft, setSecondsLeft] = (0, react.useState)(void 0);
769
+ /**
770
+ * Whether a credential is stored, read live rather than captured.
771
+ *
772
+ * Live because the card changes state under the person's hands: a successful
773
+ * save or login moves it to the signed-in view without a reopen, and a clear
774
+ * moves it back.
775
+ */
776
+ const signedIn = status.hasAccessKey || status.hasSecretKey;
777
+ (0, react.useEffect)(() => {
778
+ let live = true;
779
+ props.readPrefill().then((prefill) => {
780
+ const { accessKeyId, secretAccessKey } = prefill;
781
+ if (!live || accessKeyId === void 0 || secretAccessKey === void 0) return;
782
+ setAk((current) => current === "" ? accessKeyId : current);
783
+ setSk((current) => current === "" ? secretAccessKey : current);
784
+ setToken((current) => current === "" ? prefill.securityToken ?? "" : current);
785
+ setPrefilled(true);
786
+ }).catch(() => {});
787
+ return () => {
788
+ live = false;
789
+ };
790
+ }, []);
791
+ (0, react.useEffect)(() => {
792
+ const controller = new AbortController();
793
+ props.probeBrowserRoute(controller.signal).then((reachable) => {
794
+ if (controller.signal.aborted) return;
795
+ setPhase(reachable ? "ready" : "unsupported");
796
+ }).catch(() => {
797
+ if (!controller.signal.aborted) setPhase("unsupported");
798
+ });
799
+ return () => {
800
+ controller.abort();
801
+ };
802
+ }, []);
803
+ /**
804
+ * Whether this card is still on screen.
805
+ *
806
+ * A start that is in flight when the card closes must not be forgotten: the
807
+ * host binds its listener before it answers, so a request whose reply nobody
808
+ * reads leaves a port bound until the login's own deadline — ten minutes —
809
+ * expires. Read after the await, alongside the handle it carried.
810
+ *
811
+ * Re-armed in the effect body, not just set once. This effect is keyed on the
812
+ * handle, so it re-runs when a login starts or is cancelled; a flag only ever
813
+ * lowered in the cleanup would stay `false` after that re-run, and the next
814
+ * login would close its own tab and release its port on the spot.
815
+ */
816
+ const mounted = (0, react.useRef)(true);
817
+ (0, react.useEffect)(() => {
818
+ mounted.current = true;
819
+ return () => {
820
+ mounted.current = false;
821
+ login?.cancel();
822
+ };
823
+ }, [login]);
824
+ (0, react.useEffect)(() => {
825
+ if (phase !== "running" || secondsLeft === void 0) return;
826
+ const deadline = Date.now() + secondsLeft * 1e3;
827
+ const timer = window.setInterval(() => {
828
+ const left = Math.max(0, Math.round((deadline - Date.now()) / 1e3));
829
+ setSecondsLeft(left);
830
+ if (left === 0) {
831
+ window.clearInterval(timer);
832
+ setPhase("ready");
833
+ setBrowserError(t("form.browser.expired"));
834
+ }
835
+ }, 1e3);
836
+ return () => {
837
+ window.clearInterval(timer);
838
+ };
839
+ }, [phase]);
840
+ (0, react.useEffect)(() => {
841
+ if (phase !== "running") setSecondsLeft(void 0);
842
+ }, [phase]);
843
+ const outcomeRaw = props.useLoginOutcome((snapshot) => snapshot);
844
+ /**
845
+ * The outcome already recorded when this card opened.
846
+ *
847
+ * The document keeps the last login's outcome, so a card opened later would
848
+ * otherwise react to a result that has nothing to do with it: after a success
849
+ * the next open would close itself on the spot, and after a failure it would
850
+ * show that error before the person did anything.
851
+ */
852
+ const outcomeAtMount = (0, react.useRef)(null);
853
+ if (outcomeAtMount.current === null) outcomeAtMount.current = outcomeRaw;
854
+ (0, react.useEffect)(() => {
855
+ if (outcomeRaw === outcomeAtMount.current) return;
856
+ const outcome = decodeOutcome(outcomeRaw);
857
+ if (outcome === void 0) return;
858
+ if (outcome.kind === "succeeded") {
859
+ setAk("");
860
+ setSk("");
861
+ setToken("");
862
+ close();
863
+ return;
864
+ }
865
+ setPhase("ready");
866
+ setBrowserError(outcome.error === "" ? t("form.browser.failed") : outcome.error);
867
+ }, [outcomeRaw]);
868
+ /**
869
+ * Start a sign-in, because the person asked for one.
870
+ *
871
+ * The URL is fetched now rather than when the card opened: it names the port
872
+ * this login binds, and the service only promises it for a window. A card
873
+ * that sat open for a while still offers a URL that works, which is the whole
874
+ * reason probe and start are separate.
875
+ */
876
+ const onBrowserLogin = async () => {
877
+ if (phase === "running" || phase === "starting") return;
878
+ setBrowserError(void 0);
879
+ const tab = openLoginWindow();
880
+ if (tab === void 0) {
881
+ setBrowserError(t("form.browser.blocked"));
882
+ return;
883
+ }
884
+ setPhase("starting");
885
+ const handle = await props.startBrowserLogin();
886
+ if (!mounted.current) {
887
+ tab.close();
888
+ handle?.cancel();
889
+ return;
890
+ }
891
+ if (handle === void 0) {
892
+ tab.close();
893
+ setPhase("ready");
894
+ setBrowserError(t("form.browser.startFailed"));
895
+ return;
896
+ }
897
+ tab.navigate(handle.loginUrl);
898
+ setLogin(handle);
899
+ setPhase("running");
900
+ setSecondsLeft(handle.expiresInSeconds > 0 ? handle.expiresInSeconds : void 0);
901
+ };
902
+ /**
903
+ * Abandon the login in flight.
904
+ *
905
+ * Releases the host's listener — the URL on screen is dead from this moment —
906
+ * and returns the button, so the person can try again or fall back to pasting
907
+ * a key. Not a refusal of the card itself: `取消` does that, and it is a
908
+ * separate button below.
909
+ */
910
+ const onCancelLogin = (0, react.useCallback)(() => {
911
+ login?.cancel();
912
+ setLogin(void 0);
913
+ setPhase("ready");
914
+ setBrowserError(void 0);
915
+ }, [login]);
916
+ /** Put the sign-in URL on the clipboard when the tab did not open. */
917
+ const onCopyLink = () => {
918
+ if (login === null || login === void 0) return;
919
+ navigator.clipboard.writeText(login.loginUrl).then(
920
+ () => {
921
+ setBrowserError(void 0);
922
+ },
923
+ // A denied clipboard — no permission, or an insecure origin — leaves the
924
+ // person with nothing, so say what happened rather than failing silently.
925
+ () => {
926
+ setBrowserError(t("form.browser.copyFailed"));
927
+ }
928
+ );
929
+ };
483
930
  const onSubmit = async (event) => {
484
931
  event.preventDefault();
485
932
  setSaving(true);
486
- setError(void 0);
933
+ setManualError(void 0);
487
934
  try {
488
935
  const verdict = await save(ak, sk, token === "" ? void 0 : token);
489
936
  if (!verdict.ok) {
490
- setError(verdict.error ?? t("form.failed"));
937
+ setManualError(verdict.error ?? t("form.failed"));
491
938
  return;
492
939
  }
493
940
  setAk("");
494
941
  setSk("");
495
942
  setToken("");
496
- if (manual) closeManual();
943
+ close();
497
944
  } catch (err) {
498
- setError(err instanceof Error ? err.message : String(err));
945
+ setManualError(err instanceof Error ? err.message : String(err));
499
946
  } finally {
500
947
  setSaving(false);
501
948
  }
502
949
  };
503
950
  const onClear = async () => {
504
951
  setClearing(true);
505
- setError(void 0);
952
+ setManualError(void 0);
506
953
  try {
507
954
  const verdict = await clear();
508
- if (!verdict.ok) setError(verdict.error ?? t("form.clear.failed"));
955
+ if (!verdict.ok) setManualError(verdict.error ?? t("form.clear.failed"));
509
956
  } catch (err) {
510
- setError(err instanceof Error ? err.message : String(err));
957
+ setManualError(err instanceof Error ? err.message : String(err));
511
958
  } finally {
512
959
  setClearing(false);
513
960
  }
514
961
  };
515
962
  const onCancel = () => {
516
- if (manual) {
517
- closeManual();
518
- return;
519
- }
520
- dismiss();
963
+ login?.cancel();
964
+ cancel();
521
965
  };
522
966
  const fieldStyle = {
523
967
  display: "flex",
@@ -525,18 +969,17 @@ function CredentialRequestForm(props) {
525
969
  gap: 6
526
970
  };
527
971
  const labelStyle = {
528
- display: "inline-flex",
529
- alignItems: "center",
530
- gap: 10,
531
- fontSize: 12,
532
- lineHeight: "18px",
972
+ fontSize: 11,
973
+ lineHeight: "16px",
533
974
  fontWeight: 500,
534
- color: "var(--dsw-alias-label-secondary)"
975
+ letterSpacing: "0.04em",
976
+ textTransform: "uppercase",
977
+ color: "var(--dsw-alias-label-tertiary)"
535
978
  };
536
- const inputStyle = {
979
+ const inputStyle = (disabled) => ({
537
980
  boxSizing: "border-box",
538
981
  width: "100%",
539
- height: 32,
982
+ height: 34,
540
983
  padding: "0 10px",
541
984
  border: "0.5px solid var(--dsw-alias-border-l4)",
542
985
  borderRadius: 8,
@@ -544,24 +987,62 @@ function CredentialRequestForm(props) {
544
987
  fontSize: 14,
545
988
  lineHeight: "22px",
546
989
  background: "var(--dsw-alias-bg-layer-1)",
547
- color: "var(--dsw-alias-label-primary)"
548
- };
549
- const buttonStyle = (disabled$1) => ({
550
- height: 32,
551
- padding: "0 14px",
552
- border: "none",
990
+ color: "var(--dsw-alias-label-primary)",
991
+ opacity: disabled ? .5 : 1,
992
+ cursor: disabled ? "not-allowed" : "text"
993
+ });
994
+ const buttonStyle = (disabled, kind = "secondary") => ({
995
+ height: 34,
996
+ padding: "0 16px",
553
997
  borderRadius: 8,
554
998
  font: "inherit",
555
999
  fontSize: 14,
556
- cursor: disabled$1 ? "default" : "pointer",
557
- opacity: disabled$1 ? .5 : 1
1000
+ cursor: disabled ? "default" : "pointer",
1001
+ opacity: disabled ? .45 : 1,
1002
+ border: kind === "primary" ? "none" : "0.5px solid var(--dsw-alias-border-l4)",
1003
+ background: kind === "primary" ? "var(--dsw-alias-button-primary-fill)" : kind === "quiet" ? "transparent" : "var(--dsw-alias-bg-layer-1)",
1004
+ color: kind === "primary" ? "var(--dsw-alias-label-primary-foreground)" : "var(--dsw-alias-label-primary)"
1005
+ });
1006
+ const divider = (text) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1007
+ style: {
1008
+ display: "flex",
1009
+ alignItems: "center",
1010
+ gap: 10
1011
+ },
1012
+ children: [
1013
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: {
1014
+ flex: 1,
1015
+ height: 1,
1016
+ background: "var(--dsw-alias-border-l4)"
1017
+ } }),
1018
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1019
+ style: {
1020
+ fontSize: 12,
1021
+ color: "var(--dsw-alias-label-tertiary)"
1022
+ },
1023
+ children: text
1024
+ }),
1025
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: {
1026
+ flex: 1,
1027
+ height: 1,
1028
+ background: "var(--dsw-alias-border-l4)"
1029
+ } })
1030
+ ]
558
1031
  });
1032
+ const notice = {
1033
+ margin: 0,
1034
+ fontSize: 12,
1035
+ lineHeight: "18px",
1036
+ color: "var(--dsw-alias-state-warn-label)"
1037
+ };
559
1038
  const busy = saving || clearing;
560
- const disabled = busy || !ak || !sk;
561
- const hasCredentials = status.hasAccessKey || status.hasSecretKey;
1039
+ /** While a login runs, the other route is disabled — both write one record. */
1040
+ const manualDisabled = busy || phase === "running";
1041
+ const submitDisabled = manualDisabled || !ak || !sk;
1042
+ const button = browserButton(phase, secondsLeft !== void 0);
562
1043
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
563
1044
  role: "group",
564
- "aria-label": t(manual ? "form.title.manual" : "form.title"),
1045
+ "aria-label": t("form.title"),
565
1046
  style: {
566
1047
  padding: "6px calc(var(--dsh-composer-side-clearance) + 16px) 10px",
567
1048
  display: "flex",
@@ -579,157 +1060,258 @@ function CredentialRequestForm(props) {
579
1060
  padding: "16px 20px",
580
1061
  display: "flex",
581
1062
  flexDirection: "column",
582
- gap: 12
1063
+ gap: 14
583
1064
  },
584
- children: [
1065
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1066
+ style: {
1067
+ fontSize: 14,
1068
+ fontWeight: 600,
1069
+ lineHeight: "22px"
1070
+ },
1071
+ children: t("form.title")
1072
+ }), signedIn ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
585
1073
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
586
1074
  style: {
587
1075
  display: "flex",
588
- flexDirection: "column",
589
- gap: 4
1076
+ alignItems: "center",
1077
+ gap: 8
590
1078
  },
591
1079
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1080
+ "aria-hidden": true,
1081
+ style: {
1082
+ width: 8,
1083
+ height: 8,
1084
+ borderRadius: "50%",
1085
+ background: "var(--dsw-alias-state-success-primary)",
1086
+ flex: "none"
1087
+ }
1088
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
592
1089
  style: {
593
1090
  fontSize: 14,
594
- fontWeight: 500,
595
1091
  lineHeight: "22px"
596
1092
  },
597
- children: t(manual ? "form.title.manual" : "form.title")
598
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
599
- style: {
600
- fontSize: 12,
601
- lineHeight: "18px",
602
- color: "var(--dsw-alias-label-tertiary)"
603
- },
604
- children: [
605
- t("section.credentials.hint.prefix"),
606
- " ",
607
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
608
- href: CREDENTIAL_URL,
609
- target: "_blank",
610
- rel: "noreferrer noopener",
611
- style: {
612
- color: "var(--dsw-alias-button-primary-fill)",
613
- textDecoration: "underline"
614
- },
615
- children: t("section.credentials.hint.link")
616
- }),
617
- " ",
618
- t("section.credentials.hint.suffix")
619
- ]
1093
+ children: status.accessKeyIdHint === "" ? t("form.signedIn") : status.accessKeyIdHint
620
1094
  })]
621
1095
  }),
1096
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1097
+ style: { display: "flex" },
1098
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1099
+ type: "button",
1100
+ onClick: () => {
1101
+ onClear();
1102
+ },
1103
+ disabled: busy,
1104
+ style: buttonStyle(busy),
1105
+ children: clearing ? t("form.clearing") : t("form.logout")
1106
+ })
1107
+ }),
1108
+ manualError !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1109
+ style: notice,
1110
+ children: manualError
1111
+ })
1112
+ ] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
622
1113
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
623
- style: fieldStyle,
624
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
625
- style: labelStyle,
626
- children: [t("section.field.accessKey"), status.accessKeyIdHint && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1114
+ style: {
1115
+ display: "flex",
1116
+ flexDirection: "column",
1117
+ gap: 8
1118
+ },
1119
+ children: [
1120
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1121
+ style: {
1122
+ fontSize: 13,
1123
+ fontWeight: 500,
1124
+ color: "var(--dsw-alias-label-secondary)"
1125
+ },
1126
+ children: t("form.browser.section")
1127
+ }),
1128
+ phase === "running" && secondsLeft !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1129
+ role: "status",
627
1130
  style: {
628
- color: "var(--dsw-alias-label-tertiary)",
629
- fontWeight: 400
1131
+ fontSize: 13,
1132
+ lineHeight: "20px",
1133
+ textAlign: "center"
1134
+ },
1135
+ children: t("form.browser.running", { time: formatCountdown(secondsLeft) })
1136
+ }),
1137
+ phase === "checking" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1138
+ style: {
1139
+ fontSize: 12,
1140
+ lineHeight: "18px",
1141
+ color: "var(--dsw-alias-label-tertiary)"
1142
+ },
1143
+ children: t("form.browser.checking")
1144
+ }),
1145
+ phase === "unsupported" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1146
+ role: "status",
1147
+ style: notice,
1148
+ children: t("form.browser.unsupported")
1149
+ }),
1150
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1151
+ style: {
1152
+ display: "flex",
1153
+ alignItems: "center",
1154
+ gap: 8
1155
+ },
1156
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1157
+ type: "button",
1158
+ onClick: phase === "running" ? onCancelLogin : onBrowserLogin,
1159
+ disabled: button.disabled,
1160
+ style: {
1161
+ ...buttonStyle(button.disabled, button.disabled ? "secondary" : "primary"),
1162
+ flex: 1
1163
+ },
1164
+ children: t(button.label)
1165
+ })
1166
+ }),
1167
+ phase === "running" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1168
+ style: {
1169
+ fontSize: 12,
1170
+ lineHeight: "18px",
1171
+ color: "var(--dsw-alias-label-tertiary)"
630
1172
  },
631
1173
  children: [
632
- "(",
633
- status.accessKeyIdHint,
634
- ")"
1174
+ t("form.browser.notOpened"),
1175
+ " ",
1176
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1177
+ type: "button",
1178
+ onClick: onCopyLink,
1179
+ style: {
1180
+ border: "none",
1181
+ background: "none",
1182
+ padding: 0,
1183
+ font: "inherit",
1184
+ color: "var(--dsw-alias-button-primary-fill)",
1185
+ textDecoration: "underline",
1186
+ cursor: "pointer"
1187
+ },
1188
+ children: t("form.browser.copyLink")
1189
+ })
635
1190
  ]
636
- })]
637
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
638
- type: "password",
639
- value: ak,
640
- onChange: (e) => setAk(e.target.value),
641
- style: inputStyle,
642
- placeholder: t("section.field.accessKey.placeholder"),
643
- "aria-label": t("section.field.accessKey"),
644
- autoComplete: "off",
645
- autoFocus: true
646
- })]
647
- }),
648
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
649
- style: fieldStyle,
650
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
651
- style: labelStyle,
652
- children: t("section.field.secretKey")
653
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
654
- type: "password",
655
- value: sk,
656
- onChange: (e) => setSk(e.target.value),
657
- style: inputStyle,
658
- placeholder: t("section.field.secretKey.placeholder"),
659
- "aria-label": t("section.field.secretKey"),
660
- autoComplete: "off"
661
- })]
662
- }),
663
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
664
- style: fieldStyle,
665
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
666
- style: labelStyle,
667
- children: t("section.field.token")
668
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
669
- type: "password",
670
- value: token,
671
- onChange: (e) => setToken(e.target.value),
672
- style: inputStyle,
673
- placeholder: t("section.field.token.placeholder"),
674
- "aria-label": t("section.field.token"),
675
- autoComplete: "off"
676
- })]
677
- }),
678
- error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
679
- style: {
680
- margin: 0,
681
- fontSize: 12,
682
- lineHeight: "18px",
683
- color: "var(--dsw-alias-state-warn-label)"
684
- },
685
- children: error
1191
+ }),
1192
+ browserError !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1193
+ style: notice,
1194
+ children: browserError
1195
+ })
1196
+ ]
686
1197
  }),
1198
+ divider(t("form.or")),
687
1199
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
688
1200
  style: {
689
1201
  display: "flex",
690
- gap: 8
1202
+ flexDirection: "column",
1203
+ gap: 10
691
1204
  },
692
1205
  children: [
693
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
694
- type: "submit",
695
- disabled,
1206
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
696
1207
  style: {
697
- ...buttonStyle(disabled),
698
- background: "var(--dsw-alias-button-primary-fill)",
699
- color: "var(--dsw-alias-label-primary-foreground)"
1208
+ fontSize: 13,
1209
+ fontWeight: 500,
1210
+ color: "var(--dsw-alias-label-secondary)"
700
1211
  },
701
- children: saving ? t("section.credentials.saving") : t("form.submit")
1212
+ children: t("form.manual.section")
702
1213
  }),
703
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
704
- type: "button",
705
- onClick: onCancel,
706
- disabled: busy,
1214
+ prefilled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1215
+ style: notice,
1216
+ children: t("form.prefilledFromEnv")
1217
+ }),
1218
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
707
1219
  style: {
708
- ...buttonStyle(busy),
709
- background: "transparent",
710
- color: "var(--dsw-alias-label-primary)",
711
- border: "0.5px solid var(--dsw-alias-border-l4)"
1220
+ fontSize: 12,
1221
+ lineHeight: "18px",
1222
+ color: "var(--dsw-alias-label-tertiary)"
712
1223
  },
713
- children: t("form.dismiss")
1224
+ children: [
1225
+ t("section.credentials.hint.prefix"),
1226
+ " ",
1227
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
1228
+ href: CREDENTIAL_URL,
1229
+ target: "_blank",
1230
+ rel: "noreferrer noopener",
1231
+ style: {
1232
+ color: "var(--dsw-alias-button-primary-fill)",
1233
+ textDecoration: "underline"
1234
+ },
1235
+ children: t("section.credentials.hint.link")
1236
+ }),
1237
+ " ",
1238
+ t("section.credentials.hint.suffix")
1239
+ ]
714
1240
  }),
715
- hasCredentials && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
716
- type: "button",
717
- onClick: () => {
718
- onClear();
719
- },
720
- disabled: busy,
1241
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1242
+ style: fieldStyle,
1243
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1244
+ style: labelStyle,
1245
+ children: t("section.field.accessKey")
1246
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1247
+ type: "password",
1248
+ value: ak,
1249
+ disabled: manualDisabled,
1250
+ onChange: (e) => setAk(e.target.value),
1251
+ style: inputStyle(manualDisabled),
1252
+ placeholder: t("section.field.accessKey.placeholder"),
1253
+ "aria-label": t("section.field.accessKey"),
1254
+ autoComplete: "off",
1255
+ autoFocus: true
1256
+ })]
1257
+ }),
1258
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1259
+ style: fieldStyle,
1260
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1261
+ style: labelStyle,
1262
+ children: t("section.field.secretKey")
1263
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1264
+ type: "password",
1265
+ value: sk,
1266
+ disabled: manualDisabled,
1267
+ onChange: (e) => setSk(e.target.value),
1268
+ style: inputStyle(manualDisabled),
1269
+ placeholder: t("section.field.secretKey.placeholder"),
1270
+ "aria-label": t("section.field.secretKey"),
1271
+ autoComplete: "off"
1272
+ })]
1273
+ }),
1274
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1275
+ style: fieldStyle,
1276
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1277
+ style: labelStyle,
1278
+ children: t("section.field.token")
1279
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1280
+ type: "password",
1281
+ value: token,
1282
+ disabled: manualDisabled,
1283
+ onChange: (e) => setToken(e.target.value),
1284
+ style: inputStyle(manualDisabled),
1285
+ placeholder: t("section.field.token.placeholder"),
1286
+ "aria-label": t("section.field.token"),
1287
+ autoComplete: "off"
1288
+ })]
1289
+ }),
1290
+ manualError !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1291
+ style: notice,
1292
+ children: manualError
1293
+ }),
1294
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
721
1295
  style: {
722
- ...buttonStyle(busy),
723
- background: "transparent",
724
- color: "var(--dsw-alias-label-primary)",
725
- border: "0.5px solid var(--dsw-alias-border-l4)",
726
- marginLeft: "auto"
1296
+ display: "flex",
1297
+ gap: 8
727
1298
  },
728
- children: clearing ? t("form.clearing") : t("form.clear")
1299
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1300
+ type: "submit",
1301
+ disabled: submitDisabled,
1302
+ style: buttonStyle(submitDisabled, "primary"),
1303
+ children: saving ? t("section.credentials.saving") : t("form.submit")
1304
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1305
+ type: "button",
1306
+ onClick: onCancel,
1307
+ disabled: busy,
1308
+ style: buttonStyle(busy),
1309
+ children: t("form.dismiss")
1310
+ })]
729
1311
  })
730
1312
  ]
731
1313
  })
732
- ]
1314
+ ] })]
733
1315
  })
734
1316
  });
735
1317
  }
@@ -742,15 +1324,13 @@ let nextKey = 0;
742
1324
  * Build an interaction for one session.
743
1325
  *
744
1326
  * @param sessionId - the conversation the form belongs to.
745
- * @param manual - true when a chip opened the form (no request behind it).
746
1327
  */
747
- function credentialFormInteraction(sessionId, manual) {
1328
+ function credentialFormInteraction(sessionId) {
748
1329
  nextKey += 1;
749
1330
  return {
750
1331
  kind: "aishell-credential-form",
751
1332
  key: `aishell-credential-form:${String(nextKey)}`,
752
- sessionId,
753
- manual
1333
+ sessionId
754
1334
  };
755
1335
  }
756
1336
  /**
@@ -765,15 +1345,35 @@ function credentialFormInteraction(sessionId, manual) {
765
1345
  function isCredentialForm(value) {
766
1346
  return value?.kind === "aishell-credential-form";
767
1347
  }
1348
+
1349
+ //#endregion
1350
+ //#region src/form-request.ts
768
1351
  /**
769
- * Route the Host exposes to abandon a pending credential request.
1352
+ * Read a request back out of the document.
770
1353
  *
771
- * Sits with the other credential routes: `clear`, `reset`, and this one all end
772
- * a credential state, and keeping them together is what makes the route table
773
- * readable. Without it a person who does not want to enter credentials would
774
- * leave the blocked tool call waiting until the turn ended.
1354
+ * Anything unreadable reads as no request: a corrupt field should show nothing,
1355
+ * not open a form bound to a session that does not exist.
1356
+ *
1357
+ * @param raw - the stored string, if any.
1358
+ * @returns the request, or `undefined` when there is none usable.
775
1359
  */
776
- const DISMISS_ROUTE = "api/aishell/credentials/dismiss";
1360
+ function decodeRequest(raw) {
1361
+ if (raw === void 0 || raw === "") return void 0;
1362
+ let parsed;
1363
+ try {
1364
+ parsed = JSON.parse(raw);
1365
+ } catch {
1366
+ return void 0;
1367
+ }
1368
+ if (parsed === null || typeof parsed !== "object") return void 0;
1369
+ const candidate = parsed;
1370
+ if (typeof candidate.token !== "string" || candidate.token === "") return void 0;
1371
+ if (typeof candidate.sessionId !== "string" || candidate.sessionId === "") return void 0;
1372
+ return {
1373
+ token: candidate.token,
1374
+ sessionId: candidate.sessionId
1375
+ };
1376
+ }
777
1377
 
778
1378
  //#endregion
779
1379
  //#region src/client/credential-form-visibility.ts
@@ -785,43 +1385,21 @@ const DISMISS_ROUTE = "api/aishell/credentials/dismiss";
785
1385
  function createCredentialFormVisibility(publish) {
786
1386
  let open;
787
1387
  let withdraw;
788
- let manual = false;
789
1388
  const clear = () => {
790
1389
  withdraw?.();
791
1390
  withdraw = void 0;
792
1391
  open = void 0;
793
- manual = false;
794
- };
795
- const publishFor = (sessionId, isManual) => {
796
- withdraw?.();
797
- const interaction = credentialFormInteraction(sessionId, isManual);
798
- open = interaction;
799
- manual = isManual;
800
- withdraw = publish(interaction);
801
- return interaction;
802
1392
  };
803
1393
  return {
804
1394
  current: () => open,
805
- manual: () => manual && open !== void 0,
806
- sync: (sessionId) => {
807
- if (sessionId === "") {
808
- if (open === void 0) return;
809
- clear();
810
- return;
811
- }
812
- if (open?.sessionId === sessionId) {
813
- if (!manual) return;
814
- publishFor(sessionId, false);
815
- return;
816
- }
817
- publishFor(sessionId, false);
818
- },
819
1395
  open: (sessionId) => {
820
1396
  if (open !== void 0) return;
821
- publishFor(sessionId, true);
1397
+ const interaction = credentialFormInteraction(sessionId);
1398
+ open = interaction;
1399
+ withdraw = publish(interaction);
822
1400
  },
823
1401
  close: () => {
824
- if (open === void 0 || !manual) return;
1402
+ if (open === void 0) return;
825
1403
  clear();
826
1404
  },
827
1405
  dispose: () => {
@@ -848,24 +1426,39 @@ const zh = {
848
1426
  "mode.unavailable": "权限模式不可用",
849
1427
  "mode.readonly.hint": "当前:只读 — 只允许查询云资源,点击切换为读写",
850
1428
  "mode.readwrite.hint": "当前:读写 — 允许变更云资源,点击切换为只读",
851
- "mode.unavailable.hint": "无法从 MCP 服务器读取权限模式;切换按钮暂不可用",
1429
+ "mode.unavailable.hint": "无法读取权限模式;切换按钮暂不可用",
852
1430
  "mode.switchToReadonly": "切换为只读模式",
853
1431
  "mode.switchToReadwrite": "切换为读写模式",
854
1432
  "section.credentials.hint.prefix": "需要进行华为云 IAM 认证,建议从",
855
1433
  "section.credentials.hint.link": "API Explorer",
856
1434
  "section.credentials.hint.suffix": "获取临时凭据,避免使用永久凭据。",
857
1435
  "section.credentials.saving": "保存中…",
858
- "form.title": "需要华为云凭据",
859
- "form.title.manual": "配置华为云凭据",
1436
+ "form.title": "华为云 IAM 认证",
1437
+ "form.or": "或者",
1438
+ "form.signedIn": "已登录",
1439
+ "form.logout": "退出",
1440
+ "form.browser.section": "选项一:浏览器登录",
1441
+ "form.browser.action": "登录",
1442
+ "form.browser.checking": "环境检测中…",
1443
+ "form.browser.unsupported": "当前环境不支持该方式。",
1444
+ "form.browser.unsupportedLabel": "不支持",
1445
+ "form.browser.cancelLabel": "取消登录",
1446
+ "form.browser.running": "登录中({time})",
1447
+ "form.browser.notOpened": "若浏览器未自动打开,请",
1448
+ "form.browser.copyLink": "手动复制链接到浏览器打开",
1449
+ "form.browser.blocked": "浏览器拦截了新标签页,请允许弹出窗口后重试。",
1450
+ "form.browser.copyFailed": "无法复制链接,请手动从浏览器地址栏重试。",
1451
+ "form.browser.failed": "浏览器登录未完成。",
1452
+ "form.browser.startFailed": "无法启动浏览器登录,请改用 AK/SK 或稍后重试。",
1453
+ "form.browser.expired": "登录超时,请重试。",
1454
+ "form.manual.section": "选项二:配置 AK/SK",
1455
+ "form.prefilledFromEnv": "已填入检测到的环境变量",
860
1456
  "form.submit": "提交",
861
1457
  "form.dismiss": "取消",
862
1458
  "form.failed": "保存凭据失败",
863
- "form.clear": "清除",
864
1459
  "form.clearing": "清除中…",
865
1460
  "form.clear.failed": "清除凭据失败",
866
1461
  "error.unreachable": "无法连接宿主凭据服务:",
867
- "error.clear.serverFailed": "本机凭据已清除,但服务端凭据未清除(HTTP {status})",
868
- "error.clear.serverUnreachable": "本机凭据已清除,但无法连接 MCP 服务器清除服务端凭据:",
869
1462
  "section.field.accessKey": "Access Key",
870
1463
  "section.field.accessKey.placeholder": "华为云 Access Key",
871
1464
  "section.field.accessKey.hint": "Access Key 与 Secret Key 须同时填写,只填其一时不会保存。",
@@ -884,24 +1477,39 @@ const en = {
884
1477
  "mode.unavailable": "Mode unavailable",
885
1478
  "mode.readonly.hint": "Read-only — cloud queries only. Click for read-write",
886
1479
  "mode.readwrite.hint": "Read-write — cloud changes allowed. Click for read-only",
887
- "mode.unavailable.hint": "Could not read the permission mode from the MCP server; the toggle is unavailable",
1480
+ "mode.unavailable.hint": "Could not read the permission mode; the toggle is unavailable",
888
1481
  "mode.switchToReadonly": "Switch to read-only mode",
889
1482
  "mode.switchToReadwrite": "Switch to read-write mode",
890
1483
  "section.credentials.hint.prefix": "Authenticate against Huawei Cloud IAM. Obtain temporary credentials from",
891
1484
  "section.credentials.hint.link": "API Explorer",
892
1485
  "section.credentials.hint.suffix": "and avoid permanent ones.",
893
1486
  "section.credentials.saving": "Saving…",
894
- "form.title": "Huawei Cloud credentials required",
895
- "form.title.manual": "Configure Huawei Cloud credentials",
1487
+ "form.title": "Huawei Cloud IAM authentication",
1488
+ "form.or": "or",
1489
+ "form.signedIn": "Signed in",
1490
+ "form.logout": "Logout",
1491
+ "form.browser.section": "Option 1: sign in with a browser",
1492
+ "form.browser.action": "Sign in",
1493
+ "form.browser.checking": "Checking this environment…",
1494
+ "form.browser.unsupported": "This environment does not support that method.",
1495
+ "form.browser.unsupportedLabel": "Unsupported",
1496
+ "form.browser.cancelLabel": "Cancel sign-in",
1497
+ "form.browser.running": "Signing in ({time})",
1498
+ "form.browser.notOpened": "If the browser did not open,",
1499
+ "form.browser.copyLink": "copy the link into your browser",
1500
+ "form.browser.blocked": "The browser blocked the new tab. Allow pop-ups for this page, then try again.",
1501
+ "form.browser.copyFailed": "Could not copy the link. Try again from the browser address bar.",
1502
+ "form.browser.failed": "The browser sign-in did not complete.",
1503
+ "form.browser.startFailed": "Could not start the browser sign-in. Use an AK/SK instead, or try again.",
1504
+ "form.browser.expired": "The sign-in timed out. Try again.",
1505
+ "form.manual.section": "Option 2: configure an AK/SK",
1506
+ "form.prefilledFromEnv": "Filled in from detected environment variables",
896
1507
  "form.submit": "Submit",
897
1508
  "form.dismiss": "Cancel",
898
1509
  "form.failed": "Could not save credentials",
899
- "form.clear": "Clear",
900
1510
  "form.clearing": "Clearing…",
901
1511
  "form.clear.failed": "Could not clear credentials",
902
1512
  "error.unreachable": "Could not reach the host credential service: ",
903
- "error.clear.serverFailed": "Local credentials were cleared, but the server copy was not (HTTP {status})",
904
- "error.clear.serverUnreachable": "Local credentials were cleared, but the MCP server could not be reached to clear the server copy: ",
905
1513
  "section.field.accessKey": "Access Key",
906
1514
  "section.field.accessKey.placeholder": "Huawei Access Key",
907
1515
  "section.field.accessKey.hint": "Access Key and Secret Key are stored as a pair; one without the other is not saved.",
@@ -926,20 +1534,10 @@ const AISHELL_CREDENTIALS_NS = "aishell-client-credentials";
926
1534
  const CREDENTIALS_ROUTE = "api/aishell/credentials";
927
1535
  /** Clear route; the Host's fetch registry has no DELETE, so clearing is a POST. */
928
1536
  const CLEAR_ROUTE = "api/aishell/credentials/clear";
929
- /**
930
- * The MCP server's own credential store, cleared through the ops-deploy
931
- * plugin's route.
932
- *
933
- * Clearing is a two-store operation: this plugin's store (CLEAR_ROUTE) and the
934
- * MCP server's, which keeps its own copy scoped to this client. Only the first
935
- * existed until the scope work made the second reachable, and the half-cleared
936
- * state it left — the chip showing "no credentials" while cloud calls still
937
- * worked — is the bug this fixes.
938
- *
939
- * An absolute host route owned by another package, reached the same way the
940
- * permission-mode route already is: by URL, not by import.
941
- */
942
- const SERVER_CREDENTIALS_ROUTE = "api/aishell/credentials/reset";
1537
+ /** Cancel route; names the request token the person declined. */
1538
+ const CANCEL_ROUTE = "api/aishell/credentials/cancel";
1539
+ /** Prefill route; returns the values the host's environment already holds. */
1540
+ const PREFILL_ROUTE = "api/aishell/credentials/prefill";
943
1541
  /**
944
1542
  * POST one JSON body to a Host credential route and read back its verdict.
945
1543
  * A non-JSON or unreadable body is reported as a transport failure rather than
@@ -969,55 +1567,55 @@ async function postJson(route, t, body) {
969
1567
  /**
970
1568
  * Store one credential through the Host route.
971
1569
  *
972
- * Both ways the form comes up — a chip click and a blocked MCP call — go
1570
+ * Both ways the form comes up — a chip click and a blocked tool call — go
973
1571
  * through this, so there is exactly one body shape for the credential route.
974
1572
  *
975
1573
  * An absent SecurityToken is omitted rather than sent empty: the Host reads an
976
1574
  * empty string as absent anyway, so sending it would only make the wire shape
977
1575
  * depend on which form was used.
978
1576
  */
979
- function saveCredential(t, accessKeyId, secretAccessKey, securityToken) {
1577
+ function saveCredential(t, accessKeyId, secretAccessKey, securityToken, requestToken) {
980
1578
  return postJson(CREDENTIALS_ROUTE, t, {
981
1579
  accessKeyId,
982
1580
  secretAccessKey,
983
- ...securityToken === void 0 ? {} : { securityToken }
1581
+ ...securityToken === void 0 ? {} : { securityToken },
1582
+ ...requestToken === void 0 ? {} : { requestToken }
984
1583
  });
985
1584
  }
986
1585
  /**
987
- * Clear both credential stores, reporting the first failure.
1586
+ * Clear the stored credentials.
988
1587
  *
989
- * The order matters: this plugin's store goes first, because it is the one
990
- * whose absence *stops* the chat from authenticating. A failure there leaves
991
- * both stores intact (nothing cleared, nothing to misreport). A failure on the
992
- * second leaves a state the user can still act on — no credentials locally, a
993
- * server copy that a second attempt or a server restart will clear — which is
994
- * why the message names which half failed rather than saying "clear failed".
995
- *
996
- * The second store is best-effort by design: if the MCP server is unreachable
997
- * or older than `credential/reset`, the local clear has already succeeded and
998
- * saying so is more accurate than reporting the whole action as failed.
1588
+ * One store, one write: the credentials live in the host's keyring and nowhere
1589
+ * else, so this is the local clear and its failure is the only one there is to
1590
+ * report.
999
1591
  *
1000
1592
  * @param t - the form's translator; the failure copy is user-visible.
1001
1593
  */
1002
1594
  async function clearBothStores(t) {
1003
- const local = await postJson(CLEAR_ROUTE, t);
1004
- if (!local.ok) return local;
1595
+ return postJson(CLEAR_ROUTE, t);
1596
+ }
1597
+ /**
1598
+ * Read the credential prefills the host has in its environment.
1599
+ *
1600
+ * Failure is not an event: a host with nothing in its environment answers an
1601
+ * empty object, and a route that cannot be reached answers `{}` too, because a
1602
+ * form that starts empty is exactly the behaviour before this existed.
1603
+ *
1604
+ * @returns the prefills, or an empty object.
1605
+ */
1606
+ async function readPrefill() {
1005
1607
  try {
1006
- const response = await fetch(SERVER_CREDENTIALS_ROUTE, { method: "POST" });
1007
- if (!response.ok) {
1008
- const body = await response.json();
1009
- return {
1010
- ok: false,
1011
- error: typeof body.error === "string" ? body.error : t("error.clear.serverFailed", { status: String(response.status) })
1012
- };
1013
- }
1014
- } catch (error) {
1015
- return {
1016
- ok: false,
1017
- error: t("error.clear.serverUnreachable") + (error instanceof Error ? error.message : String(error))
1018
- };
1608
+ const response = await fetch(PREFILL_ROUTE, { headers: { accept: "application/json" } });
1609
+ if (!response.ok) return {};
1610
+ const body = await response.json();
1611
+ return typeof body.accessKeyId === "string" && body.accessKeyId !== "" && typeof body.secretAccessKey === "string" && body.secretAccessKey !== "" ? {
1612
+ accessKeyId: body.accessKeyId,
1613
+ secretAccessKey: body.secretAccessKey,
1614
+ ...typeof body.securityToken === "string" && body.securityToken !== "" ? { securityToken: body.securityToken } : {}
1615
+ } : {};
1616
+ } catch {
1617
+ return {};
1019
1618
  }
1020
- return { ok: true };
1021
1619
  }
1022
1620
  /** Required services. */
1023
1621
  const inject = [
@@ -1054,16 +1652,67 @@ function apply(ctx) {
1054
1652
  };
1055
1653
  ctx.effect(() => form.subscribe(derive), "aishell-credentials: credential presence");
1056
1654
  derive();
1655
+ const loginOutcome = (0, __deepseek_ai_dsh_client_store.createSnapshotStore)(form.getSnapshot().value?.loginOutcome ?? "");
1656
+ ctx.effect(() => form.subscribe(() => {
1657
+ loginOutcome.set(form.getSnapshot().value?.loginOutcome ?? "");
1658
+ }), "aishell-credentials: login outcome");
1057
1659
  const publishCredentialForm = ctx.uiSession.registerPendingInteraction(() => 0);
1058
1660
  const visibility = createCredentialFormVisibility((interaction) => publishCredentialForm(interaction, () => Promise.resolve()));
1059
- const syncCredentialForm = () => {
1060
- visibility.sync(form.getSnapshot().value?.credentialRequestSession ?? "");
1661
+ /** The last request the browser acted on, so a re-read is not a re-open. */
1662
+ let lastRequestToken;
1663
+ /**
1664
+ * The token of the request this form is currently answering, if any.
1665
+ *
1666
+ * A chip-opened form has none: nothing asked for it, so a cancel must not
1667
+ * report one — a submit or cancel names a request, and there is no request to
1668
+ * name.
1669
+ */
1670
+ let pendingRequestToken;
1671
+ /**
1672
+ * Whether the first pass over the document has run.
1673
+ *
1674
+ * The document is persisted, so on a fresh page load it still holds whatever
1675
+ * request the previous session left there. Acting on that would open the form
1676
+ * for a question nobody is asking — the same bug the host clears the field
1677
+ * for at startup, and this half must not open it in the window before that
1678
+ * write lands. The first pass establishes the baseline: whatever is already
1679
+ * in the document when this page loads is not a request addressed to it.
1680
+ */
1681
+ let primed = false;
1682
+ const applyFormRequest = () => {
1683
+ const request = decodeRequest(form.getSnapshot().value?.credentialFormRequest);
1684
+ if (!primed) {
1685
+ primed = true;
1686
+ lastRequestToken = request?.token;
1687
+ return;
1688
+ }
1689
+ if (request === void 0 || request.token === lastRequestToken) return;
1690
+ lastRequestToken = request.token;
1691
+ pendingRequestToken = request.token;
1692
+ visibility.open(request.sessionId);
1061
1693
  };
1062
- ctx.effect(() => form.subscribe(syncCredentialForm), "aishell-credentials: credential form visibility");
1063
- syncCredentialForm();
1694
+ ctx.effect(() => form.subscribe(applyFormRequest), "aishell-credentials: form requests");
1695
+ applyFormRequest();
1064
1696
  ctx.effect(() => () => {
1065
1697
  visibility.dispose();
1066
1698
  }, "aishell-credentials: credential form teardown");
1699
+ /**
1700
+ * Record a cancel against the request it belongs to.
1701
+ *
1702
+ * Only when this form was opened by a request: a chip-opened form has no
1703
+ * request behind it, and recording a cancel for one would make the *next*
1704
+ * `auth` call believe the person refused a question nobody asked.
1705
+ */
1706
+ const cancelRequest = () => {
1707
+ const token = pendingRequestToken;
1708
+ pendingRequestToken = void 0;
1709
+ if (token === void 0) return;
1710
+ fetch(CANCEL_ROUTE, {
1711
+ method: "POST",
1712
+ headers: { "content-type": "application/json" },
1713
+ body: JSON.stringify({ token })
1714
+ }).catch(() => {});
1715
+ };
1067
1716
  ctx.effect(() => ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
1068
1717
  name: "conversation.composer.dock",
1069
1718
  id: "aishell-account",
@@ -1097,13 +1746,20 @@ function apply(ctx) {
1097
1746
  select: ({ pendingInteraction }) => isCredentialForm(pendingInteraction) ? pendingInteraction : null,
1098
1747
  locale: NS,
1099
1748
  inject: () => ({
1100
- hooks: { credentials: status },
1101
- save: (ak, sk, token) => saveCredential(t, ak, sk, token),
1749
+ hooks: {
1750
+ credentials: status,
1751
+ loginOutcome
1752
+ },
1753
+ save: (ak, sk, token) => saveCredential(t, ak, sk, token, pendingRequestToken),
1754
+ readPrefill: () => readPrefill(),
1755
+ probeBrowserRoute: (signal) => probeBrowserRoute(signal),
1756
+ startBrowserLogin: () => startBrowserLogin(),
1102
1757
  clear: () => clearBothStores(t),
1103
- dismiss: () => {
1104
- fetch(DISMISS_ROUTE, { method: "POST" });
1758
+ close: () => {
1759
+ visibility.close();
1105
1760
  },
1106
- closeManual: () => {
1761
+ cancel: () => {
1762
+ cancelRequest();
1107
1763
  visibility.close();
1108
1764
  }
1109
1765
  })