@asteby/metacore-runtime-react 53.6.0 → 53.7.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @asteby/metacore-runtime-react
2
2
 
3
+ ## 53.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b0fa35b: AddonConfigSurface: los campos de credencial ya guardados abren bloqueados (lápiz para editar, ojo para ver; el ojo de un secreto solo con `canRevealSecrets`, vía `GET /integrations/:provider/values/:key/reveal`) y el navegador ya no los rellena (solo lectura hasta enfocar, `name` estable, `autocomplete` por tipo). Al cambiar el selector de entorno (`environment`/`mode`/`env`) los campos por entorno se intercambian por los guardados para ese entorno (`GET …/values?environment=`) en vez de pedirlos de nuevo.
8
+
3
9
  ## 53.6.0
4
10
 
5
11
  ### Minor Changes
@@ -87,6 +87,12 @@ export interface AddonConfigSurfaceProps {
87
87
  * Default true.
88
88
  */
89
89
  canManageIssuer?: boolean;
90
+ /**
91
+ * Owner-only: lets the eye on a stored secret fetch its value on demand
92
+ * (GET /integrations/:provider/values/:key/reveal). Default false: the
93
+ * secret stays write-only and the eye is hidden.
94
+ */
95
+ canRevealSecrets?: boolean;
90
96
  /** Active branch (for per-branch settings); null/absent hides the branch picker. */
91
97
  activeBranch?: {
92
98
  id: string;
@@ -115,5 +121,5 @@ export interface AddonConfigSurfaceProps {
115
121
  }
116
122
  /** Drops the shared option-lookup cache (called when the surface closes). */
117
123
  export declare function clearConnectorLookupCache(): void;
118
- export declare function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer, activeBranch, ensureAddonBundle, notify, client, expectedOptionKinds, displayName, onConnectOAuth, }: AddonConfigSurfaceProps): import("react").JSX.Element;
124
+ export declare function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer, canRevealSecrets, activeBranch, ensureAddonBundle, notify, client, expectedOptionKinds, displayName, onConnectOAuth, }: AddonConfigSurfaceProps): import("react").JSX.Element;
119
125
  //# sourceMappingURL=addon-config-surface.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"addon-config-surface.d.ts","sourceRoot":"","sources":["../../src/setup/addon-config-surface.tsx"],"names":[],"mappings":"AAsCA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAI3C,OAAO,EAOL,KAAK,kBAAkB,EACxB,MAAM,0BAA0B,CAAA;AASjC,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,OAAO,CAAC,EAAE;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC7C,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,oEAAoE;IACpE,YAAY,CAAC,EAAE,WAAW,CAAA;IAC1B,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,4DAA4D;IAC5D,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,YAAY,CAAC,EAAE,MAAM,CAAA;QACrB,aAAa,CAAC,EAAE,eAAe,EAAE,CAAA;KAClC,CAAA;CACF;AAED,MAAM,WAAW,wBAAwB;IACvC,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CA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Ac,GACf,EAAE,uBAAuB,+BA++BzB"}
@@ -17,7 +17,7 @@ import { createContext, useContext, useEffect, useId, useRef, useState } from 'r
17
17
  import { useMutation } from '@tanstack/react-query';
18
18
  import { useTranslation } from 'react-i18next';
19
19
  import { toast } from 'sonner';
20
- import { AlertCircle, Cable, Check, Link2, Loader2, RefreshCw, Settings } from 'lucide-react';
20
+ import { AlertCircle, Cable, Check, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, X } from 'lucide-react';
21
21
  import { Badge, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, } from '@asteby/metacore-ui/primitives';
22
22
  import { cn } from '@asteby/metacore-ui/lib';
23
23
  import { useApi } from '../api-context';
@@ -50,7 +50,7 @@ const ConnectorFormStateContext = createContext({
50
50
  idPrefix: 'addon-config',
51
51
  expectedOptionKinds: {},
52
52
  });
53
- function ConnectorCredentialFieldControl({ field, value, connected, provider, onChange, }) {
53
+ function ConnectorCredentialFieldControl({ field, value, connected, provider, onChange, stored = false, onReveal, resetKey, }) {
54
54
  const { t } = useTranslation();
55
55
  const st = useSetupT();
56
56
  const form = useContext(ConnectorFormStateContext);
@@ -64,6 +64,58 @@ function ConnectorCredentialFieldControl({ field, value, connected, provider, on
64
64
  : '';
65
65
  const isSecret = isSecretCredential(field);
66
66
  const isDynamic = field.type === 'dynamic_select' || !!field.options_source;
67
+ // A stored field opens LOCKED (pencil to edit, eye to view) so a value is
68
+ // never changed by accident; a fresh field is editable straight away.
69
+ const [editing, setEditing] = useState(false);
70
+ const [visible, setVisible] = useState(false);
71
+ const [revealed, setRevealed] = useState(null);
72
+ const [revealing, setRevealing] = useState(false);
73
+ const [armed, setArmed] = useState(false);
74
+ const initial = useRef('');
75
+ const locked = stored && !editing;
76
+ useEffect(() => {
77
+ setEditing(false);
78
+ setVisible(false);
79
+ setRevealed(null);
80
+ }, [resetKey]);
81
+ const canEye = isSecret ? (locked ? !!onReveal : true) : false;
82
+ const toggleEye = async () => {
83
+ if (visible) {
84
+ setVisible(false);
85
+ setRevealed(null);
86
+ return;
87
+ }
88
+ if (locked && onReveal) {
89
+ setRevealing(true);
90
+ try {
91
+ setRevealed(await onReveal(field.key));
92
+ setVisible(true);
93
+ }
94
+ catch {
95
+ setRevealed(null);
96
+ }
97
+ finally {
98
+ setRevealing(false);
99
+ }
100
+ return;
101
+ }
102
+ setVisible(true);
103
+ };
104
+ const startEdit = () => {
105
+ initial.current = value;
106
+ if (isSecret)
107
+ onChange('');
108
+ setVisible(false);
109
+ setRevealed(null);
110
+ setArmed(true);
111
+ setEditing(true);
112
+ requestAnimationFrame(() => document.getElementById(`${form.idPrefix}-cred-${field.key}`)?.focus());
113
+ };
114
+ const cancelEdit = () => {
115
+ onChange(initial.current);
116
+ setVisible(false);
117
+ setEditing(false);
118
+ };
67
119
  const error = form.errors[field.key];
68
120
  const mismatch = shapeMismatch(field, value, form.fields);
69
121
  const target = mismatch?.suggestedKey
@@ -74,10 +126,11 @@ function ConnectorCredentialFieldControl({ field, value, connected, provider, on
74
126
  ? 'installed_addons.shape_public_key'
75
127
  : 'installed_addons.shape_secret_key', { target: target ? labelOf(target) : '' })
76
128
  : '';
77
- return (_jsxs("div", { className: 'flex flex-col gap-1', "data-field": field.key, children: [_jsxs(Label, { htmlFor: `${form.idPrefix}-cred-${field.key}`, children: [label, field.required ? _jsx("span", { className: 'text-destructive', children: " *" }) : null] }), isDynamic ? (_jsx(DynamicConnectorSelect, { field: field, value: value, provider: provider, connected: connected, onChange: onChange })) : field.type === 'select' && field.options?.length ? (_jsxs(Select, { value: value, onValueChange: onChange, children: [_jsx(SelectTrigger, { id: `${form.idPrefix}-cred-${field.key}`, "aria-invalid": !!error || undefined, children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: field.options.map((o) => (_jsx(SelectItem, { value: o.value, children: t(o.label, { defaultValue: o.value }) }, o.value))) })] })) : (_jsx(Input, { id: `${form.idPrefix}-cred-${field.key}`, type: isSecret ? 'password' : 'text',
78
- // A secret must never be offered to (or filled by) the browser's
79
- // password manager: "new-password" is the value browsers respect.
80
- autoComplete: isSecret ? 'new-password' : 'off', "data-1p-ignore": isSecret ? true : undefined, "data-lpignore": isSecret ? 'true' : undefined, spellCheck: false, autoCapitalize: 'off', "aria-invalid": !!error || undefined, "aria-describedby": error ? `${form.idPrefix}-cred-${field.key}-error` : undefined, className: cn(error && 'border-destructive focus-visible:ring-destructive/40'), placeholder: connected && isSecret ? '••••••••' : '', value: value, onChange: (e) => onChange(e.target.value) })), error ? (_jsx("p", { id: `${form.idPrefix}-cred-${field.key}-error`, role: 'alert', className: 'text-xs text-destructive', children: error })) : null, warning ? (_jsx("p", { className: 'text-xs text-amber-600 dark:text-amber-400', role: 'status', children: warning })) : null, help ? _jsx(HelpText, { text: help }) : null] }));
129
+ return (_jsxs("div", { className: 'flex flex-col gap-1', "data-field": field.key, children: [_jsxs(Label, { htmlFor: `${form.idPrefix}-cred-${field.key}`, children: [label, field.required ? _jsx("span", { className: 'text-destructive', children: " *" }) : null] }), isDynamic ? (_jsx(DynamicConnectorSelect, { field: field, value: value, provider: provider, connected: connected, onChange: onChange })) : field.type === 'select' && field.options?.length ? (_jsxs(Select, { value: value, onValueChange: onChange, children: [_jsx(SelectTrigger, { id: `${form.idPrefix}-cred-${field.key}`, "aria-invalid": !!error || undefined, children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: field.options.map((o) => (_jsx(SelectItem, { value: o.value, children: t(o.label, { defaultValue: o.value }) }, o.value))) })] })) : (_jsxs("div", { className: 'flex items-center gap-1.5', children: [_jsx(Input, { id: `${form.idPrefix}-cred-${field.key}`, name: `cfg_${field.key}`, type: isSecret && !visible ? 'password' : 'text',
130
+ // Browsers ignore autocomplete=off and fill the text field that
131
+ // precedes a password input; a field stays read-only until the user
132
+ // focuses it (and while locked) so nothing is filled behind their back.
133
+ autoComplete: isSecret ? 'new-password' : 'off', "data-1p-ignore": true, "data-lpignore": 'true', "data-form-type": 'other', readOnly: locked || !armed, onFocus: () => setArmed(true), spellCheck: false, autoCapitalize: 'off', "aria-invalid": !!error || undefined, "aria-describedby": error ? `${form.idPrefix}-cred-${field.key}-error` : undefined, className: cn(error && 'border-destructive focus-visible:ring-destructive/40', locked && 'bg-muted/40 text-muted-foreground'), placeholder: (connected || stored) && isSecret ? '••••••••' : '', value: locked && isSecret ? (revealed ?? '') : value, onChange: (e) => onChange(e.target.value) }), canEye && (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', disabled: revealing, "aria-label": visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' }), onClick: () => void toggleEye(), children: revealing ? _jsx(Loader2, { className: 'size-4 animate-spin' }) : visible ? _jsx(EyeOff, { className: 'size-4' }) : _jsx(Eye, { className: 'size-4' }) })), locked ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_edit', { defaultValue: 'Editar' }), onClick: startEdit, children: _jsx(Pencil, { className: 'size-4' }) })) : stored ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' }), onClick: cancelEdit, children: _jsx(X, { className: 'size-4' }) })) : null] })), error ? (_jsx("p", { id: `${form.idPrefix}-cred-${field.key}-error`, role: 'alert', className: 'text-xs text-destructive', children: error })) : null, warning ? (_jsx("p", { className: 'text-xs text-amber-600 dark:text-amber-400', role: 'status', children: warning })) : null, help ? _jsx(HelpText, { text: help }) : null] }));
81
134
  }
82
135
  // useApi() hands every component its own wrapper object, so the cache cannot be
83
136
  // keyed by client: it is module-level, keyed by provider + export, and dropped
@@ -163,7 +216,7 @@ function DynamicConnectorSelect({ field, value, provider, connected, onChange, }
163
216
  // Fixed header + footer, scrollable body — a connector can declare many fields
164
217
  // (env, keys, RFC, régimen, CP, base_url, stamp/cancel path) that would
165
218
  // otherwise overflow the viewport.
166
- export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer = true, activeBranch = null, ensureAddonBundle, notify = toast, client, expectedOptionKinds = NO_OPTION_KINDS, displayName, onConnectOAuth, }) {
219
+ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer = true, canRevealSecrets = false, activeBranch = null, ensureAddonBundle, notify = toast, client, expectedOptionKinds = NO_OPTION_KINDS, displayName, onConnectOAuth, }) {
167
220
  const idPrefix = useId();
168
221
  const { t, i18n } = useTranslation();
169
222
  const st = useSetupT();
@@ -198,6 +251,14 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
198
251
  // credentials not saved yet (an action tests what is STORED: it saves first).
199
252
  const [blockResults, setBlockResults] = useState({});
200
253
  const [credDirty, setCredDirty] = useState(false);
254
+ // Credential keys the backend already holds (non-secret values + secrets_set).
255
+ const [storedKeys, setStoredKeys] = useState(new Set());
256
+ // Credentials that differ between sandbox and production (served by /values) and
257
+ // the environment the stored values were loaded for: flipping the selector swaps them.
258
+ const envScoped = useRef(new Set());
259
+ const loadedEnv = useRef(null);
260
+ const envField = credFields.find((f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key));
261
+ const envValue = envField ? (credValues[envField.key] ?? '') : '';
201
262
  const stepHeadingRef = useRef(null);
202
263
  const stepMoved = useRef(false);
203
264
  const setCred = (key, val) => {
@@ -258,6 +319,9 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
258
319
  setFieldErrors({});
259
320
  setBlockResults({});
260
321
  setCredDirty(false);
322
+ setStoredKeys(new Set());
323
+ envScoped.current = new Set();
324
+ loadedEnv.current = null;
261
325
  if (!canManageIssuer || !connector?.provider || credFields.length === 0)
262
326
  return;
263
327
  let cancelled = false;
@@ -267,6 +331,11 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
267
331
  const stored = (res.data?.data?.values ?? {});
268
332
  if (cancelled)
269
333
  return;
334
+ const secretsSet = (res.data?.data?.secrets_set ?? []);
335
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []));
336
+ if (envField)
337
+ loadedEnv.current = stored[envField.key] ?? '';
338
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]));
270
339
  // Only fields the user has not touched yet.
271
340
  setCredValues((prev) => {
272
341
  const next = { ...prev };
@@ -289,6 +358,40 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
289
358
  };
290
359
  // eslint-disable-next-line react-hooks/exhaustive-deps
291
360
  }, [open, connector?.provider, canManageIssuer]);
361
+ // Sandbox and production keep their own credentials: flipping the selector
362
+ // swaps the environment-scoped fields for the ones stored for that environment
363
+ // (locked when it has them, empty when it does not) instead of making the
364
+ // operator paste every key again. Nothing is saved until «Guardar».
365
+ useEffect(() => {
366
+ if (!open || !envField || !envValue || !canManageIssuer || !connector?.provider)
367
+ return;
368
+ if (loadedEnv.current === null || loadedEnv.current === envValue)
369
+ return;
370
+ let cancelled = false;
371
+ api
372
+ .get(`/integrations/${connector.provider}/values?environment=${encodeURIComponent(envValue)}`)
373
+ .then((res) => {
374
+ if (cancelled)
375
+ return;
376
+ const stored = (res.data?.data?.values ?? {});
377
+ const secretsSet = (res.data?.data?.secrets_set ?? []);
378
+ loadedEnv.current = envValue;
379
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]));
380
+ setCredValues((prev) => {
381
+ const next = { ...prev };
382
+ for (const k of envScoped.current)
383
+ next[k] = stored[k] ?? '';
384
+ return next;
385
+ });
386
+ })
387
+ .catch(() => {
388
+ /* keep what is on screen */
389
+ });
390
+ return () => {
391
+ cancelled = true;
392
+ };
393
+ // eslint-disable-next-line react-hooks/exhaustive-deps
394
+ }, [open, envValue]);
292
395
  // Load stored settings values + definitions. The backend returns the
293
396
  // manifest's setting definitions alongside the stored values; fall back to
294
397
  // the manifest we already have so custom (declarative) addons whose lifecycle
@@ -523,7 +626,22 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
523
626
  defaultValue: 'Solo un administrador de la organización puede ver y guardar los datos del emisor y el certificado. Pide a un administrador que los configure.',
524
627
  }) }));
525
628
  const canSync = !!connector?.sync_endpoint && !!connector?.connected;
526
- const renderCred = (f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key));
629
+ const revealSecret = async (key) => {
630
+ try {
631
+ const res = await api.get(`/integrations/${connector?.provider}/values/${encodeURIComponent(key)}/reveal${envValue ? `?environment=${encodeURIComponent(envValue)}` : ''}`);
632
+ return String(res.data?.data?.value ?? '');
633
+ }
634
+ catch (err) {
635
+ notify.error(st('installed_addons.field_reveal_error', { defaultValue: 'No se pudo mostrar el valor.' }));
636
+ throw err;
637
+ }
638
+ };
639
+ const storedProps = (key) => ({
640
+ stored: storedKeys.has(key),
641
+ resetKey: envValue,
642
+ onReveal: canRevealSecrets ? revealSecret : undefined,
643
+ });
644
+ const renderCred = (f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key));
527
645
  // One setting control, shared by the flat layout and the wizard's last step.
528
646
  const renderSetting = (def) => {
529
647
  const id = `${idPrefix}-setting-${def.key}`;
@@ -657,6 +775,6 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
657
775
  const fields = credFields.filter((f) => f.section === sec.key);
658
776
  if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0)
659
777
  return null;
660
- return (_jsxs("div", { className: 'flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3', children: [sec.title && (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx("h4", { className: 'text-sm font-medium', children: t(sec.title, { defaultValue: sec.title }) }), sec.description && (_jsx(HelpText, { text: addonText(sec.description) }))] })), renderBlocks(leadBlocks(sec.blocks)), fields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), renderBlocks(trailBlocks(sec.blocks))] }, sec.key));
661
- })) : (_jsxs(_Fragment, { children: [requiredFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), advancedFields.length > 0 && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: advancedFields.some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: advancedFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', className: 'max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', className: 'grid shrink-0 grid-cols-2 gap-2 border-t pt-3 sm:flex sm:flex-row sm:justify-end sm:border-t-0 sm:pt-0', children: nothingToSave ? (_jsx(Button, { className: 'col-span-2 h-11 sm:h-9', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs(Button, { className: 'order-first col-span-2 h-11 sm:order-last sm:h-9', onClick: useStepper && !isLastStep ? handleNext : handleSave, disabled: !(useStepper && !isLastStep) && (saveMutation.isPending || loading), children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), useStepper && !isLastStep ? st('common.next') : st('common.save')] }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), _jsx(Button, { variant: 'ghost', className: cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2'), onClick: () => onOpenChange(false), children: st('common.cancel') })] })) })] }) }) }));
778
+ return (_jsxs("div", { className: 'flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3', children: [sec.title && (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx("h4", { className: 'text-sm font-medium', children: t(sec.title, { defaultValue: sec.title }) }), sec.description && (_jsx(HelpText, { text: addonText(sec.description) }))] })), renderBlocks(leadBlocks(sec.blocks)), fields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), renderBlocks(trailBlocks(sec.blocks))] }, sec.key));
779
+ })) : (_jsxs(_Fragment, { children: [requiredFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), advancedFields.length > 0 && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: advancedFields.some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: advancedFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', className: 'max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', className: 'grid shrink-0 grid-cols-2 gap-2 border-t pt-3 sm:flex sm:flex-row sm:justify-end sm:border-t-0 sm:pt-0', children: nothingToSave ? (_jsx(Button, { className: 'col-span-2 h-11 sm:h-9', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs(Button, { className: 'order-first col-span-2 h-11 sm:order-last sm:h-9', onClick: useStepper && !isLastStep ? handleNext : handleSave, disabled: !(useStepper && !isLastStep) && (saveMutation.isPending || loading), children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), useStepper && !isLastStep ? st('common.next') : st('common.save')] }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), _jsx(Button, { variant: 'ghost', className: cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2'), onClick: () => onOpenChange(false), children: st('common.cancel') })] })) })] }) }) }));
662
780
  }
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IAkJ/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IA+I/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IAuJ/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IAoJ/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
@@ -142,6 +142,11 @@ export const SETUP_MESSAGES_ES = {
142
142
  'installed_addons.whole_org': 'Toda la organización',
143
143
  'installed_addons.only_branch': 'Solo {{name}}',
144
144
  'installed_addons.secret_stored': 'Hay un valor guardado. Déjalo vacío para conservarlo.',
145
+ 'installed_addons.field_view': 'Ver',
146
+ 'installed_addons.field_hide': 'Ocultar',
147
+ 'installed_addons.field_edit': 'Editar',
148
+ 'installed_addons.field_cancel_edit': 'Cancelar edición',
149
+ 'installed_addons.field_reveal_error': 'No se pudo mostrar el valor.',
145
150
  'common.back': 'Atrás',
146
151
  'common.next': 'Siguiente',
147
152
  'common.cancel': 'Cancelar',
@@ -285,6 +290,11 @@ export const SETUP_MESSAGES_EN = {
285
290
  'installed_addons.whole_org': 'Whole organization',
286
291
  'installed_addons.only_branch': 'Only {{name}}',
287
292
  'installed_addons.secret_stored': 'A value is stored. Leave it empty to keep it.',
293
+ 'installed_addons.field_view': 'View',
294
+ 'installed_addons.field_hide': 'Hide',
295
+ 'installed_addons.field_edit': 'Edit',
296
+ 'installed_addons.field_cancel_edit': 'Cancel editing',
297
+ 'installed_addons.field_reveal_error': 'Could not show the value.',
288
298
  'common.back': 'Back',
289
299
  'common.next': 'Next',
290
300
  'common.cancel': 'Cancel',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "53.6.0",
3
+ "version": "53.7.0",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -112,6 +112,61 @@ describe('AddonConfigSurface', () => {
112
112
  expect(onSaved).toHaveBeenCalled()
113
113
  })
114
114
 
115
+ it('stored fields open locked: pencil unlocks, eye reveals a secret only for owners', async () => {
116
+ const values = { 'GET /integrations/mp/values': { data: { values: { public_key: 'APP_USR-x' }, secrets_set: ['access_token'] } } }
117
+ const reveal = { 'GET /integrations/mp/values/access_token/reveal?environment=sandbox': { data: { value: 'APP_USR-secret' } } }
118
+ const { calls } = setup({ connector, canRevealSecrets: true }, { ...values, ...reveal })
119
+ const pub = (await screen.findByLabelText(/Llave pública/)) as HTMLInputElement
120
+ const secret = screen.getByLabelText(/Token/) as HTMLInputElement
121
+ await waitFor(() => expect(pub.readOnly).toBe(true))
122
+ expect(secret.readOnly).toBe(true)
123
+ // eye on the locked secret fetches the value on demand
124
+ fireEvent.click(screen.getAllByLabelText('Ver')[0])
125
+ await waitFor(() => expect(secret.value).toBe('APP_USR-secret'))
126
+ expect(calls.some((c) => c.url === '/integrations/mp/values/access_token/reveal?environment=sandbox')).toBe(true)
127
+ // pencil unlocks the public key for editing
128
+ fireEvent.click(screen.getAllByLabelText('Editar')[0])
129
+ await waitFor(() => expect(pub.readOnly).toBe(false))
130
+ })
131
+
132
+ it('flipping the environment swaps the scoped fields for that environment\'s stored ones', async () => {
133
+ const conn: ConnectorEntry = {
134
+ ...connector,
135
+ credentials: [connector.credentials![2], connector.credentials![0], connector.credentials![1]].map((f) =>
136
+ f.key === 'env' ? { ...f, default: 'sandbox' } : f,
137
+ ),
138
+ }
139
+ const { calls } = setup(
140
+ { connector: conn },
141
+ {
142
+ 'GET /integrations/mp/values': { data: { values: { public_key: 'TEST-pub', env: 'sandbox' }, secrets_set: ['access_token'], env_scoped: ['public_key', 'access_token'] } },
143
+ 'GET /integrations/mp/values?environment=prod': { data: { values: {}, secrets_set: [], env_scoped: ['public_key', 'access_token'] } },
144
+ },
145
+ )
146
+ const pub = (await screen.findByLabelText(/Llave pública/)) as HTMLInputElement
147
+ await waitFor(() => expect(pub.value).toBe('TEST-pub'))
148
+ expect(pub.readOnly).toBe(true)
149
+ // flip to production: the sandbox keys go away, the fields open empty (nothing stored there yet)
150
+ const trigger = screen.getByRole('combobox')
151
+ fireEvent.pointerDown(trigger)
152
+ fireEvent.click(trigger)
153
+ fireEvent.click(await screen.findByText('prod'))
154
+ await waitFor(() => expect(calls.some((c) => c.url === '/integrations/mp/values?environment=prod')).toBe(true))
155
+ await waitFor(() => expect(pub.value).toBe(''))
156
+ expect(screen.queryByLabelText('Editar')).toBeNull()
157
+ })
158
+
159
+ it('without owner rights a locked secret has no eye and nothing is fetched', async () => {
160
+ const { calls } = setup(
161
+ { connector },
162
+ { 'GET /integrations/mp/values': { data: { values: { public_key: 'APP_USR-x' }, secrets_set: ['access_token'] } } },
163
+ )
164
+ const secret = (await screen.findByLabelText(/Token/)) as HTMLInputElement
165
+ await waitFor(() => expect(secret.readOnly).toBe(true))
166
+ expect(screen.queryByLabelText('Ver')).toBeNull()
167
+ expect(calls.some((c) => c.url.endsWith('/reveal'))).toBe(false)
168
+ })
169
+
115
170
  it('does not fetch stored values for non-admins and explains why', async () => {
116
171
  const { calls } = setup({ connector, canManageIssuer: false })
117
172
  expect(await screen.findByText(/Solo un administrador de la organización/)).toBeTruthy()
@@ -16,7 +16,7 @@ import { createContext, useContext, useEffect, useId, useRef, useState } from 'r
16
16
  import { useMutation } from '@tanstack/react-query'
17
17
  import { useTranslation } from 'react-i18next'
18
18
  import { toast } from 'sonner'
19
- import { AlertCircle, Cable, Check, Link2, Loader2, RefreshCw, Settings } from 'lucide-react'
19
+ import { AlertCircle, Cable, Check, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, X } from 'lucide-react'
20
20
  import {
21
21
  Badge,
22
22
  Button,
@@ -151,6 +151,12 @@ export interface AddonConfigSurfaceProps {
151
151
  * Default true.
152
152
  */
153
153
  canManageIssuer?: boolean
154
+ /**
155
+ * Owner-only: lets the eye on a stored secret fetch its value on demand
156
+ * (GET /integrations/:provider/values/:key/reveal). Default false: the
157
+ * secret stays write-only and the eye is hidden.
158
+ */
159
+ canRevealSecrets?: boolean
154
160
  /** Active branch (for per-branch settings); null/absent hides the branch picker. */
155
161
  activeBranch?: { id: string; name?: string } | null
156
162
  /** Pulls the addon's own i18n bundle when its labels do not resolve yet. */
@@ -218,12 +224,21 @@ function ConnectorCredentialFieldControl({
218
224
  connected,
219
225
  provider,
220
226
  onChange,
227
+ stored = false,
228
+ onReveal,
229
+ resetKey,
221
230
  }: {
222
231
  field: ConnectorCredentialField
223
232
  value: string
224
233
  connected: boolean
225
234
  provider: string
226
235
  onChange: (value: string) => void
236
+ /** The backend already holds a value for this field (secret or not). */
237
+ stored?: boolean
238
+ /** Fetches a stored secret's value (owner only); absent → no eye while locked. */
239
+ onReveal?: (key: string) => Promise<string>
240
+ /** Changes when the stored values were swapped (environment flipped): relock. */
241
+ resetKey?: string
227
242
  }) {
228
243
  const { t } = useTranslation()
229
244
  const st = useSetupT()
@@ -240,6 +255,55 @@ function ConnectorCredentialFieldControl({
240
255
  : ''
241
256
  const isSecret = isSecretCredential(field)
242
257
  const isDynamic = field.type === 'dynamic_select' || !!field.options_source
258
+ // A stored field opens LOCKED (pencil to edit, eye to view) so a value is
259
+ // never changed by accident; a fresh field is editable straight away.
260
+ const [editing, setEditing] = useState(false)
261
+ const [visible, setVisible] = useState(false)
262
+ const [revealed, setRevealed] = useState<string | null>(null)
263
+ const [revealing, setRevealing] = useState(false)
264
+ const [armed, setArmed] = useState(false)
265
+ const initial = useRef('')
266
+ const locked = stored && !editing
267
+ useEffect(() => {
268
+ setEditing(false)
269
+ setVisible(false)
270
+ setRevealed(null)
271
+ }, [resetKey])
272
+ const canEye = isSecret ? (locked ? !!onReveal : true) : false
273
+ const toggleEye = async () => {
274
+ if (visible) {
275
+ setVisible(false)
276
+ setRevealed(null)
277
+ return
278
+ }
279
+ if (locked && onReveal) {
280
+ setRevealing(true)
281
+ try {
282
+ setRevealed(await onReveal(field.key))
283
+ setVisible(true)
284
+ } catch {
285
+ setRevealed(null)
286
+ } finally {
287
+ setRevealing(false)
288
+ }
289
+ return
290
+ }
291
+ setVisible(true)
292
+ }
293
+ const startEdit = () => {
294
+ initial.current = value
295
+ if (isSecret) onChange('')
296
+ setVisible(false)
297
+ setRevealed(null)
298
+ setArmed(true)
299
+ setEditing(true)
300
+ requestAnimationFrame(() => document.getElementById(`${form.idPrefix}-cred-${field.key}`)?.focus())
301
+ }
302
+ const cancelEdit = () => {
303
+ onChange(initial.current)
304
+ setVisible(false)
305
+ setEditing(false)
306
+ }
243
307
  const error = form.errors[field.key]
244
308
  const mismatch = shapeMismatch(field, value, form.fields)
245
309
  const target = mismatch?.suggestedKey
@@ -282,23 +346,69 @@ function ConnectorCredentialFieldControl({
282
346
  </SelectContent>
283
347
  </Select>
284
348
  ) : (
285
- <Input
286
- id={`${form.idPrefix}-cred-${field.key}`}
287
- type={isSecret ? 'password' : 'text'}
288
- // A secret must never be offered to (or filled by) the browser's
289
- // password manager: "new-password" is the value browsers respect.
290
- autoComplete={isSecret ? 'new-password' : 'off'}
291
- data-1p-ignore={isSecret ? true : undefined}
292
- data-lpignore={isSecret ? 'true' : undefined}
293
- spellCheck={false}
294
- autoCapitalize='off'
295
- aria-invalid={!!error || undefined}
296
- aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
297
- className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
298
- placeholder={connected && isSecret ? '••••••••' : ''}
299
- value={value}
300
- onChange={(e) => onChange(e.target.value)}
301
- />
349
+ <div className='flex items-center gap-1.5'>
350
+ <Input
351
+ id={`${form.idPrefix}-cred-${field.key}`}
352
+ name={`cfg_${field.key}`}
353
+ type={isSecret && !visible ? 'password' : 'text'}
354
+ // Browsers ignore autocomplete=off and fill the text field that
355
+ // precedes a password input; a field stays read-only until the user
356
+ // focuses it (and while locked) so nothing is filled behind their back.
357
+ autoComplete={isSecret ? 'new-password' : 'off'}
358
+ data-1p-ignore
359
+ data-lpignore='true'
360
+ data-form-type='other'
361
+ readOnly={locked || !armed}
362
+ onFocus={() => setArmed(true)}
363
+ spellCheck={false}
364
+ autoCapitalize='off'
365
+ aria-invalid={!!error || undefined}
366
+ aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
367
+ className={cn(
368
+ error && 'border-destructive focus-visible:ring-destructive/40',
369
+ locked && 'bg-muted/40 text-muted-foreground',
370
+ )}
371
+ placeholder={(connected || stored) && isSecret ? '••••••••' : ''}
372
+ value={locked && isSecret ? (revealed ?? '') : value}
373
+ onChange={(e) => onChange(e.target.value)}
374
+ />
375
+ {canEye && (
376
+ <Button
377
+ type='button'
378
+ variant='ghost'
379
+ size='icon'
380
+ className='size-9 shrink-0'
381
+ disabled={revealing}
382
+ aria-label={visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' })}
383
+ onClick={() => void toggleEye()}
384
+ >
385
+ {revealing ? <Loader2 className='size-4 animate-spin' /> : visible ? <EyeOff className='size-4' /> : <Eye className='size-4' />}
386
+ </Button>
387
+ )}
388
+ {locked ? (
389
+ <Button
390
+ type='button'
391
+ variant='ghost'
392
+ size='icon'
393
+ className='size-9 shrink-0'
394
+ aria-label={st('installed_addons.field_edit', { defaultValue: 'Editar' })}
395
+ onClick={startEdit}
396
+ >
397
+ <Pencil className='size-4' />
398
+ </Button>
399
+ ) : stored ? (
400
+ <Button
401
+ type='button'
402
+ variant='ghost'
403
+ size='icon'
404
+ className='size-9 shrink-0'
405
+ aria-label={st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' })}
406
+ onClick={cancelEdit}
407
+ >
408
+ <X className='size-4' />
409
+ </Button>
410
+ ) : null}
411
+ </div>
302
412
  )}
303
413
  {error ? (
304
414
  <p id={`${form.idPrefix}-cred-${field.key}-error`} role='alert' className='text-xs text-destructive'>
@@ -482,6 +592,7 @@ export function AddonConfigSurface({
482
592
  onOpenChange,
483
593
  onSaved,
484
594
  canManageIssuer = true,
595
+ canRevealSecrets = false,
485
596
  activeBranch = null,
486
597
  ensureAddonBundle,
487
598
  notify = toast,
@@ -526,6 +637,16 @@ export function AddonConfigSurface({
526
637
  // credentials not saved yet (an action tests what is STORED: it saves first).
527
638
  const [blockResults, setBlockResults] = useState<Record<string, BlockResult | undefined>>({})
528
639
  const [credDirty, setCredDirty] = useState(false)
640
+ // Credential keys the backend already holds (non-secret values + secrets_set).
641
+ const [storedKeys, setStoredKeys] = useState<Set<string>>(new Set())
642
+ // Credentials that differ between sandbox and production (served by /values) and
643
+ // the environment the stored values were loaded for: flipping the selector swaps them.
644
+ const envScoped = useRef<Set<string>>(new Set())
645
+ const loadedEnv = useRef<string | null>(null)
646
+ const envField = credFields.find(
647
+ (f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key),
648
+ )
649
+ const envValue = envField ? (credValues[envField.key] ?? '') : ''
529
650
  const stepHeadingRef = useRef<HTMLHeadingElement>(null)
530
651
  const stepMoved = useRef(false)
531
652
  const setCred = (key: string, val: string) => {
@@ -586,6 +707,9 @@ export function AddonConfigSurface({
586
707
  setFieldErrors({})
587
708
  setBlockResults({})
588
709
  setCredDirty(false)
710
+ setStoredKeys(new Set())
711
+ envScoped.current = new Set()
712
+ loadedEnv.current = null
589
713
  if (!canManageIssuer || !connector?.provider || credFields.length === 0) return
590
714
  let cancelled = false
591
715
  api
@@ -593,6 +717,12 @@ export function AddonConfigSurface({
593
717
  .then((res) => {
594
718
  const stored = (res.data?.data?.values ?? {}) as Record<string, string>
595
719
  if (cancelled) return
720
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
721
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []) as string[])
722
+ if (envField) loadedEnv.current = stored[envField.key] ?? ''
723
+ setStoredKeys(
724
+ new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]),
725
+ )
596
726
  // Only fields the user has not touched yet.
597
727
  setCredValues((prev) => {
598
728
  const next = { ...prev }
@@ -614,6 +744,37 @@ export function AddonConfigSurface({
614
744
  // eslint-disable-next-line react-hooks/exhaustive-deps
615
745
  }, [open, connector?.provider, canManageIssuer])
616
746
 
747
+ // Sandbox and production keep their own credentials: flipping the selector
748
+ // swaps the environment-scoped fields for the ones stored for that environment
749
+ // (locked when it has them, empty when it does not) instead of making the
750
+ // operator paste every key again. Nothing is saved until «Guardar».
751
+ useEffect(() => {
752
+ if (!open || !envField || !envValue || !canManageIssuer || !connector?.provider) return
753
+ if (loadedEnv.current === null || loadedEnv.current === envValue) return
754
+ let cancelled = false
755
+ api
756
+ .get(`/integrations/${connector.provider}/values?environment=${encodeURIComponent(envValue)}`)
757
+ .then((res) => {
758
+ if (cancelled) return
759
+ const stored = (res.data?.data?.values ?? {}) as Record<string, string>
760
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
761
+ loadedEnv.current = envValue
762
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]))
763
+ setCredValues((prev) => {
764
+ const next = { ...prev }
765
+ for (const k of envScoped.current) next[k] = stored[k] ?? ''
766
+ return next
767
+ })
768
+ })
769
+ .catch(() => {
770
+ /* keep what is on screen */
771
+ })
772
+ return () => {
773
+ cancelled = true
774
+ }
775
+ // eslint-disable-next-line react-hooks/exhaustive-deps
776
+ }, [open, envValue])
777
+
617
778
  // Load stored settings values + definitions. The backend returns the
618
779
  // manifest's setting definitions alongside the stored values; fall back to
619
780
  // the manifest we already have so custom (declarative) addons whose lifecycle
@@ -865,12 +1026,32 @@ export function AddonConfigSurface({
865
1026
  )
866
1027
  const canSync = !!connector?.sync_endpoint && !!connector?.connected
867
1028
 
1029
+ const revealSecret = async (key: string) => {
1030
+ try {
1031
+ const res = await api.get(
1032
+ `/integrations/${connector?.provider}/values/${encodeURIComponent(key)}/reveal${
1033
+ envValue ? `?environment=${encodeURIComponent(envValue)}` : ''
1034
+ }`,
1035
+ )
1036
+ return String(res.data?.data?.value ?? '')
1037
+ } catch (err) {
1038
+ notify.error(st('installed_addons.field_reveal_error', { defaultValue: 'No se pudo mostrar el valor.' }))
1039
+ throw err
1040
+ }
1041
+ }
1042
+ const storedProps = (key: string) => ({
1043
+ stored: storedKeys.has(key),
1044
+ resetKey: envValue,
1045
+ onReveal: canRevealSecrets ? revealSecret : undefined,
1046
+ })
1047
+
868
1048
  const renderCred = (f: ConnectorCredentialField) => (
869
1049
  <ConnectorCredentialFieldControl
870
1050
  key={f.key}
871
1051
  field={f}
872
1052
  connected={!!connector?.connected}
873
1053
  provider={connector?.provider ?? ''}
1054
+ {...storedProps(f.key)}
874
1055
  value={credValues[f.key] ?? ''}
875
1056
  onChange={(val) => setCred(f.key, val)}
876
1057
  />
@@ -1298,6 +1479,7 @@ export function AddonConfigSurface({
1298
1479
  field={f}
1299
1480
  connected={!!connector?.connected}
1300
1481
  provider={connector?.provider ?? ''}
1482
+ {...storedProps(f.key)}
1301
1483
  value={credValues[f.key] ?? ''}
1302
1484
  onChange={(val) => setCred(f.key, val)}
1303
1485
  />
@@ -1314,6 +1496,7 @@ export function AddonConfigSurface({
1314
1496
  field={f}
1315
1497
  connected={!!connector?.connected}
1316
1498
  provider={connector?.provider ?? ''}
1499
+ {...storedProps(f.key)}
1317
1500
  value={credValues[f.key] ?? ''}
1318
1501
  onChange={(val) => setCred(f.key, val)}
1319
1502
  />
@@ -1333,6 +1516,7 @@ export function AddonConfigSurface({
1333
1516
  field={f}
1334
1517
  connected={!!connector?.connected}
1335
1518
  provider={connector?.provider ?? ''}
1519
+ {...storedProps(f.key)}
1336
1520
  value={credValues[f.key] ?? ''}
1337
1521
  onChange={(val) => setCred(f.key, val)}
1338
1522
  />
@@ -147,6 +147,11 @@ export const SETUP_MESSAGES_ES: Dict = {
147
147
  'installed_addons.whole_org': 'Toda la organización',
148
148
  'installed_addons.only_branch': 'Solo {{name}}',
149
149
  'installed_addons.secret_stored': 'Hay un valor guardado. Déjalo vacío para conservarlo.',
150
+ 'installed_addons.field_view': 'Ver',
151
+ 'installed_addons.field_hide': 'Ocultar',
152
+ 'installed_addons.field_edit': 'Editar',
153
+ 'installed_addons.field_cancel_edit': 'Cancelar edición',
154
+ 'installed_addons.field_reveal_error': 'No se pudo mostrar el valor.',
150
155
  'common.back': 'Atrás',
151
156
  'common.next': 'Siguiente',
152
157
  'common.cancel': 'Cancelar',
@@ -292,6 +297,11 @@ export const SETUP_MESSAGES_EN: Dict = {
292
297
  'installed_addons.whole_org': 'Whole organization',
293
298
  'installed_addons.only_branch': 'Only {{name}}',
294
299
  'installed_addons.secret_stored': 'A value is stored. Leave it empty to keep it.',
300
+ 'installed_addons.field_view': 'View',
301
+ 'installed_addons.field_hide': 'Hide',
302
+ 'installed_addons.field_edit': 'Edit',
303
+ 'installed_addons.field_cancel_edit': 'Cancel editing',
304
+ 'installed_addons.field_reveal_error': 'Could not show the value.',
295
305
  'common.back': 'Back',
296
306
  'common.next': 'Next',
297
307
  'common.cancel': 'Cancel',