@burdenoff/microfe-security 2026.1013.1 → 2026.1013.3

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.
@@ -59,7 +59,7 @@ var r = ({ children: n, variant: r = "default", className: i }) => /* @__PURE__
59
59
  value: i,
60
60
  onChange: (e) => a(e.target.value),
61
61
  disabled: c,
62
- className: e("flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]", "disabled:cursor-not-allowed disabled:opacity-50", s),
62
+ className: e("flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]", "disabled:cursor-not-allowed disabled:opacity-50", "scheme-normal dark:scheme-dark [&_option]:bg-bg-surface [&_option]:text-text-primary", s),
63
63
  children: o.map((e) => /* @__PURE__ */ t("option", {
64
64
  value: e.value,
65
65
  children: e.label
@@ -1 +1 @@
1
- {"version":3,"file":"ui.js","names":[],"sources":["../../../src/security/components/ui.tsx"],"sourcesContent":["import type {\n FC,\n ReactNode,\n ButtonHTMLAttributes,\n InputHTMLAttributes,\n HTMLAttributes,\n} from 'react';\nimport { EmptyState as CanonicalEmptyState } from '@burdenoff/fe-libs/ui';\nimport { cn } from '../utils/cn';\n\n/**\n * Badge component\n */\nexport const Badge: FC<{\n children: ReactNode;\n variant?: 'default' | 'success' | 'warning' | 'destructive' | 'outline';\n className?: string;\n}> = ({ children, variant = 'default', className }) => {\n const variants = {\n default: 'bg-action-primary-bg/10 text-primary',\n success: 'bg-status-success-bg-subtle text-status-success-text',\n warning: 'bg-status-warning-bg-subtle text-status-warning-text',\n destructive: 'bg-status-error-bg-subtle text-status-error-text',\n outline: 'border border-border-subtle text-text-secondary',\n };\n\n return (\n <span\n className={cn(\n 'inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium',\n variants[variant],\n className\n )}\n >\n {children}\n </span>\n );\n};\n\n/**\n * Button component\n */\nexport const Button: FC<\n ButtonHTMLAttributes<HTMLButtonElement> & {\n variant?: 'primary' | 'secondary' | 'outline' | 'ghost' | 'destructive' | 'link';\n size?: 'sm' | 'md' | 'lg';\n }\n> = ({ children, variant = 'primary', size = 'md', className, ...props }) => {\n const variants = {\n primary: 'bg-action-primary-bg text-action-primary-text hover:bg-action-primary-bg/90',\n secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',\n outline: 'border border-border-subtle bg-transparent hover:bg-accent hover:text-text-primary',\n ghost: 'hover:bg-accent hover:text-text-primary',\n destructive: 'bg-status-error-bg text-status-error-text hover:bg-status-error-bg/90',\n link: 'text-primary underline-offset-4 hover:underline h-auto p-0',\n };\n\n const sizes = {\n sm: 'h-8 px-3 text-xs',\n md: 'h-9 px-4 text-sm',\n lg: 'h-10 px-6 text-sm',\n };\n\n return (\n <button\n type=\"button\"\n className={cn(\n 'inline-flex items-center justify-center gap-2 rounded-md font-medium transition-colors',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:pointer-events-none disabled:opacity-50',\n variants[variant],\n variant !== 'link' && sizes[size],\n className\n )}\n {...props}\n >\n {children}\n </button>\n );\n};\n\n/**\n * Input component\n */\nexport const Input: FC<InputHTMLAttributes<HTMLInputElement> & { label?: string }> = ({\n label,\n className,\n id,\n ...props\n}) => {\n return (\n <div className=\"space-y-1.5\">\n {label && (\n <label htmlFor={id} className=\"text-sm font-medium text-text-primary\">\n {label}\n </label>\n )}\n <input\n id={id}\n className={cn(\n 'flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm',\n 'placeholder:text-text-secondary',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:cursor-not-allowed disabled:opacity-50',\n className\n )}\n {...props}\n />\n </div>\n );\n};\n\n/**\n * Card component\n */\nexport const Card: FC<HTMLAttributes<HTMLDivElement> & { onClick?: () => void }> = ({\n children,\n className,\n onClick,\n ...props\n}) => {\n if (onClick) {\n return (\n <button\n type=\"button\"\n className={cn(\n 'block w-full text-left rounded-card border border-border-seam bg-bg-surface text-text-primary shadow-[var(--shadow-pop)]',\n // No-movement policy (Boff UI 2.0): hover only intensifies shadow/border\n // (a calm highlight). Never translate or scale the card.\n 'cursor-pointer transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop-hover)] hover:border-border-strong',\n className\n )}\n onClick={onClick}\n {...(props as HTMLAttributes<HTMLButtonElement>)}\n >\n {children}\n </button>\n );\n }\n\n return (\n <div\n className={cn(\n 'rounded-card border border-border-seam bg-bg-surface text-text-primary shadow-elevation-1',\n className\n )}\n {...props}\n >\n {children}\n </div>\n );\n};\n\n/**\n * Empty state component\n */\nexport const EmptyState: FC<{\n icon?: ReactNode;\n title: string;\n description?: string;\n action?: ReactNode;\n className?: string;\n}> = ({ icon, title, description, action, className }) => {\n return (\n <div className={className}>\n <CanonicalEmptyState icon={icon} title={title} description={description} action={action} />\n </div>\n );\n};\n\n/**\n * Select component\n */\nexport const Select: FC<{\n label?: string;\n value: string;\n onChange: (value: string) => void;\n options: Array<{ value: string; label: string }>;\n className?: string;\n disabled?: boolean;\n id?: string;\n}> = ({ label, value, onChange, options, className, disabled, id }) => {\n return (\n <div className=\"space-y-1.5\">\n {label && (\n <label htmlFor={id} className=\"text-sm font-medium text-text-primary\">\n {label}\n </label>\n )}\n <select\n id={id}\n value={value}\n onChange={(e) => onChange(e.target.value)}\n disabled={disabled}\n className={cn(\n 'flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:cursor-not-allowed disabled:opacity-50',\n className\n )}\n >\n {options.map((opt) => (\n <option key={opt.value} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </div>\n );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EACD;YAEA,EAAQ,KAAK,MACZ,kBAAC,UAAD;GAAwB,OAAO,EAAI;aAChC,EAAI;GACE,EAFI,EAAI,MAER,CACT;EACK,CAAA,CACL"}
1
+ {"version":3,"file":"ui.js","names":[],"sources":["../../../src/security/components/ui.tsx"],"sourcesContent":["import type {\n FC,\n ReactNode,\n ButtonHTMLAttributes,\n InputHTMLAttributes,\n HTMLAttributes,\n} from 'react';\nimport { EmptyState as CanonicalEmptyState } from '@burdenoff/fe-libs/ui';\nimport { cn } from '../utils/cn';\n\n/**\n * Badge component\n */\nexport const Badge: FC<{\n children: ReactNode;\n variant?: 'default' | 'success' | 'warning' | 'destructive' | 'outline';\n className?: string;\n}> = ({ children, variant = 'default', className }) => {\n const variants = {\n default: 'bg-action-primary-bg/10 text-primary',\n success: 'bg-status-success-bg-subtle text-status-success-text',\n warning: 'bg-status-warning-bg-subtle text-status-warning-text',\n destructive: 'bg-status-error-bg-subtle text-status-error-text',\n outline: 'border border-border-subtle text-text-secondary',\n };\n\n return (\n <span\n className={cn(\n 'inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium',\n variants[variant],\n className\n )}\n >\n {children}\n </span>\n );\n};\n\n/**\n * Button component\n */\nexport const Button: FC<\n ButtonHTMLAttributes<HTMLButtonElement> & {\n variant?: 'primary' | 'secondary' | 'outline' | 'ghost' | 'destructive' | 'link';\n size?: 'sm' | 'md' | 'lg';\n }\n> = ({ children, variant = 'primary', size = 'md', className, ...props }) => {\n const variants = {\n primary: 'bg-action-primary-bg text-action-primary-text hover:bg-action-primary-bg/90',\n secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',\n outline: 'border border-border-subtle bg-transparent hover:bg-accent hover:text-text-primary',\n ghost: 'hover:bg-accent hover:text-text-primary',\n destructive: 'bg-status-error-bg text-status-error-text hover:bg-status-error-bg/90',\n link: 'text-primary underline-offset-4 hover:underline h-auto p-0',\n };\n\n const sizes = {\n sm: 'h-8 px-3 text-xs',\n md: 'h-9 px-4 text-sm',\n lg: 'h-10 px-6 text-sm',\n };\n\n return (\n <button\n type=\"button\"\n className={cn(\n 'inline-flex items-center justify-center gap-2 rounded-md font-medium transition-colors',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:pointer-events-none disabled:opacity-50',\n variants[variant],\n variant !== 'link' && sizes[size],\n className\n )}\n {...props}\n >\n {children}\n </button>\n );\n};\n\n/**\n * Input component\n */\nexport const Input: FC<InputHTMLAttributes<HTMLInputElement> & { label?: string }> = ({\n label,\n className,\n id,\n ...props\n}) => {\n return (\n <div className=\"space-y-1.5\">\n {label && (\n <label htmlFor={id} className=\"text-sm font-medium text-text-primary\">\n {label}\n </label>\n )}\n <input\n id={id}\n className={cn(\n 'flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm',\n 'placeholder:text-text-secondary',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:cursor-not-allowed disabled:opacity-50',\n className\n )}\n {...props}\n />\n </div>\n );\n};\n\n/**\n * Card component\n */\nexport const Card: FC<HTMLAttributes<HTMLDivElement> & { onClick?: () => void }> = ({\n children,\n className,\n onClick,\n ...props\n}) => {\n if (onClick) {\n return (\n <button\n type=\"button\"\n className={cn(\n 'block w-full text-left rounded-card border border-border-seam bg-bg-surface text-text-primary shadow-[var(--shadow-pop)]',\n // No-movement policy (Boff UI 2.0): hover only intensifies shadow/border\n // (a calm highlight). Never translate or scale the card.\n 'cursor-pointer transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop-hover)] hover:border-border-strong',\n className\n )}\n onClick={onClick}\n {...(props as HTMLAttributes<HTMLButtonElement>)}\n >\n {children}\n </button>\n );\n }\n\n return (\n <div\n className={cn(\n 'rounded-card border border-border-seam bg-bg-surface text-text-primary shadow-elevation-1',\n className\n )}\n {...props}\n >\n {children}\n </div>\n );\n};\n\n/**\n * Empty state component\n */\nexport const EmptyState: FC<{\n icon?: ReactNode;\n title: string;\n description?: string;\n action?: ReactNode;\n className?: string;\n}> = ({ icon, title, description, action, className }) => {\n return (\n <div className={className}>\n <CanonicalEmptyState icon={icon} title={title} description={description} action={action} />\n </div>\n );\n};\n\n/**\n * Select component\n */\nexport const Select: FC<{\n label?: string;\n value: string;\n onChange: (value: string) => void;\n options: Array<{ value: string; label: string }>;\n className?: string;\n disabled?: boolean;\n id?: string;\n}> = ({ label, value, onChange, options, className, disabled, id }) => {\n return (\n <div className=\"space-y-1.5\">\n {label && (\n <label htmlFor={id} className=\"text-sm font-medium text-text-primary\">\n {label}\n </label>\n )}\n <select\n id={id}\n value={value}\n onChange={(e) => onChange(e.target.value)}\n disabled={disabled}\n className={cn(\n 'flex h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 py-1 text-sm',\n 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]',\n 'disabled:cursor-not-allowed disabled:opacity-50',\n 'scheme-normal dark:scheme-dark [&_option]:bg-bg-surface [&_option]:text-text-primary',\n className\n )}\n >\n {options.map((opt) => (\n <option key={opt.value} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </div>\n );\n};\n"],"mappings":";;;;AAaA,IAAa,KAIP,EAAE,aAAU,aAAU,WAAW,mBAUnC,kBAAC,QAAD;CACE,WAAW,EACT,iFAXW;EACf,SAAS;EACT,SAAS;EACT,SAAS;EACT,aAAa;EACb,SAAS;EACV,CAMc,IACT,EACD;CAEA;CACI,CAAA,EAOE,KAKR,EAAE,aAAU,aAAU,WAAW,UAAO,MAAM,cAAW,GAAG,QAiB7D,kBAAC,UAAD;CACE,MAAK;CACL,WAAW,EACT,0FACA,gGACA,oDArBW;EACf,SAAS;EACT,WAAW;EACX,SAAS;EACT,OAAO;EACP,aAAa;EACb,MAAM;EACP,CAec,IACT,MAAY,UAdJ;EACZ,IAAI;EACJ,IAAI;EACJ,IAAI;EACL,CAUiC,IAC5B,EACD;CACD,GAAI;CAEH;CACM,CAAA,EAOA,KAAyE,EACpF,UACA,cACA,OACA,GAAG,QAGD,kBAAC,OAAD;CAAK,WAAU;WAAf,CACG,KACC,kBAAC,SAAD;EAAO,SAAS;EAAI,WAAU;YAC3B;EACK,CAAA,EAEV,kBAAC,SAAD;EACM;EACJ,WAAW,EACT,0FACA,mCACA,gGACA,mDACA,EACD;EACD,GAAI;EACJ,CAAA,CACE;IAOG,KAAuE,EAClF,aACA,cACA,YACA,GAAG,QAEC,IAEA,kBAAC,UAAD;CACE,MAAK;CACL,WAAW,EACT,4HAGA,sIACA,EACD;CACQ;CACT,GAAK;CAEJ;CACM,CAAA,GAKX,kBAAC,OAAD;CACE,WAAW,EACT,6FACA,EACD;CACD,GAAI;CAEH;CACG,CAAA,EAwBG,KAQP,EAAE,UAAO,UAAO,aAAU,YAAS,cAAW,aAAU,YAE1D,kBAAC,OAAD;CAAK,WAAU;WAAf,CACG,KACC,kBAAC,SAAD;EAAO,SAAS;EAAI,WAAU;YAC3B;EACK,CAAA,EAEV,kBAAC,UAAD;EACM;EACG;EACP,WAAW,MAAM,EAAS,EAAE,OAAO,MAAM;EAC/B;EACV,WAAW,EACT,0FACA,gGACA,mDACA,wFACA,EACD;YAEA,EAAQ,KAAK,MACZ,kBAAC,UAAD;GAAwB,OAAO,EAAI;aAChC,EAAI;GACE,EAFI,EAAI,MAER,CACT;EACK,CAAA,CACL"}
@@ -1 +1 @@
1
- {"version":3,"file":"useImportExport.js","names":[],"sources":["../../../src/security/hooks/useImportExport.ts"],"sourcesContent":["import { useState, useCallback } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation } from '@apollo/client/react';\nimport {\n GetSecretsDocument,\n useBulkCreateSecretsMutation,\n} from '../../generated/wspace-operations';\nimport { SecretType } from '../../generated/wspace-types';\nimport { parseImportFile, type ParsedSecret } from '../utils/fileParser';\n\n/** Maximum length for the truncated server error string we display in the wizard banner. */\nconst MAX_BANNER_ERROR_LENGTH = 140;\n\n/**\n * Truncate raw server error strings before they are interpolated into\n * the wizard's banner. The gateway is supposed to normalise its errors\n * but a raw Prisma message (\"Unique constraint failed on field `key`\")\n * would otherwise leak schema details into the UI. The full text is\n * still available on `results.errors` for the per-row error list.\n *\n * Iterates over Unicode code points via the spread iterator (not the\n * UTF-16 code units that `String.prototype.slice` uses) so a truncation\n * boundary cannot land in the middle of a surrogate pair and produce a\n * mangled emoji or Asian-script character.\n */\nfunction summarizeError(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.length <= MAX_BANNER_ERROR_LENGTH) return trimmed;\n const codepoints = [...trimmed];\n if (codepoints.length <= MAX_BANNER_ERROR_LENGTH) return trimmed;\n return `${codepoints.slice(0, MAX_BANNER_ERROR_LENGTH - 1).join('')}…`;\n}\n\nconst REFETCH_VAULT_SECRETS = [GetSecretsDocument];\n\n/**\n * Lookup table from \"uppercased enum value\" to the canonical SecretType\n * enum entry, derived directly from codegen output. Using a Map keyed by\n * the uppercased value makes this robust regardless of whether the\n * codegen emits values in SCREAMING_SNAKE_CASE (current) or in some\n * other casing in the future. A future enum addition will surface here\n * as a type error rather than as a runtime \"invalid enum value\" rejection\n * from the gateway.\n *\n * Anything we cannot map falls back to TEXT, matching\n * `fileParser.normalizeSecret`'s default for blank columns. Unknown\n * inputs also emit a `console.warn` in non-production builds so a\n * typo in a CSV `type` column (e.g. \"CERTIFCATE\") doesn't silently\n * import the row as TEXT.\n */\nconst SECRET_TYPE_BY_UPPER: ReadonlyMap<string, SecretType> = new Map(\n Object.values(SecretType).map((value) => [value.toUpperCase(), value])\n);\n\nfunction coerceSecretType(input: string | undefined): SecretType {\n if (!input) return SecretType.Text;\n const normalized = input.trim().toUpperCase();\n return SECRET_TYPE_BY_UPPER.get(normalized) ?? SecretType.Text;\n}\n\n/**\n * Walk the parsed-secrets list and emit a single `console.warn`\n * summarising every unrecognised `type` value before the bulk\n * mutation runs, instead of `coerceSecretType` itself logging once\n * per row. This:\n * - de-duplicates noisy retry warnings if the user re-runs\n * `executeImport` against the same parsed file (e.g. after a\n * transient network error)\n * - prevents a typo'd row from silently importing as TEXT without\n * any signal in the browser console\n *\n * Uses one log line containing the full set of bad type values so a\n * 100-row CSV with 50 different typos doesn't spam the console with\n * 50 separate warnings.\n */\nfunction logUnknownSecretTypesOnce(secrets: ReadonlyArray<{ type?: string }>): void {\n const unknown = new Set<string>();\n for (const s of secrets) {\n const raw = s.type?.trim();\n if (!raw) continue;\n if (!SECRET_TYPE_BY_UPPER.has(raw.toUpperCase())) {\n unknown.add(raw);\n }\n }\n if (unknown.size === 0) return;\n // eslint-disable-next-line no-console\n console.warn(\n `[useImportExport] Unrecognized secret types — falling back to TEXT: ` +\n `${[...unknown].join(', ')}. Valid values: ${[...SECRET_TYPE_BY_UPPER.keys()].join(', ')}`\n );\n}\n\nconst CREATE_VAULT_BACKUP_MUTATION = gql`\n mutation CreateVaultBackup($input: CreateVaultBackupInput!) {\n createVaultBackup(input: $input) {\n fileId\n fileName\n downloadUrl\n count\n format\n passwordDelivered\n deliveryStatus\n }\n }\n`;\n\nconst RESTORE_VAULT_BACKUP_MUTATION = gql`\n mutation RestoreVaultBackup($input: RestoreVaultBackupInput!) {\n restoreVaultBackup(input: $input) {\n imported\n skipped\n errors\n }\n }\n`;\n\n/**\n * Wizard state machine for plain/backup imports.\n *\n * `status` is the single source of truth for what the wizard should\n * render. Five terminal states are distinguished so consumers can light\n * up the right affordance without inspecting `results`:\n *\n * - `completed` — at least one row was created, with no row-level\n * errors. Green success banner.\n * - `partial` — at least one row was created AND at least one row\n * errored. Yellow / amber \"imported some but not all\" banner.\n * `error` carries a one-line summary; per-row detail is in\n * `results.errors`.\n * - `skipped` — zero imported, all rows were duplicates and skipped\n * (no row-level errors). Neutral \"nothing to import\" banner.\n * `error` carries a count message.\n * - `error` — zero imported AND every row errored, OR the\n * mutation itself threw. Red failure banner. `error` carries a\n * one-line summary including the first row error message.\n */\nexport interface ImportState {\n file: File | null;\n fileName: string | null;\n parsedSecrets: ParsedSecret[];\n encodedBackup: string | null;\n sourceType: 'plain' | 'backup' | null;\n error: string | null;\n status:\n 'idle' | 'parsing' | 'ready' | 'importing' | 'completed' | 'partial' | 'skipped' | 'error';\n results?: {\n imported: number;\n skipped: number;\n errors: string[];\n };\n}\n\nexport interface BackupExportResult {\n fileId: string;\n fileName: string;\n downloadUrl: string;\n count: number;\n format: string;\n passwordDelivered: boolean;\n deliveryStatus: string;\n}\n\nfunction triggerDownload(url: string, fileName: string): void {\n const link = document.createElement('a');\n link.href = url;\n link.download = fileName;\n link.rel = 'noopener';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n}\n\nexport function useImportExport() {\n const [importState, setImportState] = useState<ImportState>({\n file: null,\n fileName: null,\n parsedSecrets: [],\n encodedBackup: null,\n sourceType: null,\n error: null,\n status: 'idle',\n });\n\n const [bulkCreateMutation, { loading: bulkImporting }] = useBulkCreateSecretsMutation({\n // Refetch the vault's secret list so the detail page shows the freshly\n // imported rows. We deliberately do NOT pass `awaitRefetchQueries: true`\n // here so the success banner appears as soon as the mutation resolves;\n // the cache update happens in the background. The old per-row\n // `useCreateSecret` helper had the same property — it issued a refetch\n // per call but did not block the mutation promise on it.\n refetchQueries: REFETCH_VAULT_SECRETS,\n });\n const [restoreBackupMutation, { loading: restoringBackup }] = useMutation<{\n restoreVaultBackup: { imported: number; skipped: number; errors: string[] };\n }>(RESTORE_VAULT_BACKUP_MUTATION, {\n // Same parity as the bulk-import path: refetch GetSecrets so the\n // vault detail page picks up the restored rows. Background refetch —\n // see the bulkCreateMutation comment for why we don't await it.\n refetchQueries: REFETCH_VAULT_SECRETS,\n });\n const [createBackupMutation, { loading: creatingBackup }] = useMutation<{\n createVaultBackup: BackupExportResult;\n }>(CREATE_VAULT_BACKUP_MUTATION);\n\n const handleFileSelect = useCallback(async (file: File) => {\n setImportState((previous) => ({\n ...previous,\n status: 'parsing',\n file,\n fileName: file.name,\n error: null,\n results: undefined,\n }));\n\n try {\n const parsed = await parseImportFile(file);\n if (parsed.kind === 'backup') {\n setImportState((previous) => ({\n ...previous,\n status: 'ready',\n sourceType: 'backup',\n encodedBackup: parsed.encodedBackup,\n parsedSecrets: [],\n }));\n return;\n }\n\n setImportState((previous) => ({\n ...previous,\n status: 'ready',\n sourceType: 'plain',\n parsedSecrets: parsed.secrets,\n encodedBackup: null,\n }));\n } catch (error) {\n setImportState((previous) => ({\n ...previous,\n status: 'error',\n sourceType: null,\n encodedBackup: null,\n parsedSecrets: [],\n error: error instanceof Error ? error.message : 'Failed to parse file',\n }));\n }\n }, []);\n\n const executeImport = useCallback(\n async (vaultId: string, backupPassword?: string) => {\n if (!vaultId) return;\n\n setImportState((previous) => ({ ...previous, status: 'importing', error: null }));\n\n try {\n if (importState.sourceType === 'backup') {\n if (!importState.encodedBackup) {\n throw new Error('No backup payload is available for restore');\n }\n if (!backupPassword?.trim()) {\n throw new Error('Backup password is required to restore the archive');\n }\n\n const { data } = await restoreBackupMutation({\n variables: {\n input: {\n vaultId,\n data: importState.encodedBackup,\n password: backupPassword,\n overwriteExisting: false,\n },\n },\n });\n\n const result = data?.restoreVaultBackup;\n if (!result) {\n throw new Error('Restore completed without a response');\n }\n\n setImportState((previous) => ({\n ...previous,\n status: 'completed',\n results: result,\n }));\n return;\n }\n\n if (!importState.parsedSecrets.length) {\n throw new Error('No secrets available for import');\n }\n\n // Surface any unrecognized `type` columns once, before the\n // mutation runs, so a typo doesn't silently import the row as\n // TEXT without any signal in the browser console.\n logUnknownSecretTypesOnce(importState.parsedSecrets);\n\n // Plain CSV/JSON upload: hand off to the bulkCreateSecrets mutation\n // so the server batches encryption + version rows in one round-trip\n // and reports per-secret errors. The previous per-secret loop here\n // multiplied gateway calls by N and lost partial-failure detail.\n //\n // overwriteExisting is intentionally not set — the server defaults\n // to false (skip duplicates), and the `skipped` count in the\n // result drives the wizard's `'skipped'` / `'partial'` states.\n // If a future \"overwrite duplicates\" toggle is added to the UI,\n // forward it through here.\n const { data } = await bulkCreateMutation({\n variables: {\n input: {\n vaultId,\n secrets: importState.parsedSecrets.map((s) => ({\n name: s.name,\n key: s.key,\n value: s.value,\n type: coerceSecretType(s.type),\n description: s.description,\n })),\n },\n },\n });\n\n const bulkResult = data?.bulkCreateSecrets;\n if (!bulkResult) {\n throw new Error('Bulk import completed without a response');\n }\n\n const firstError = bulkResult.errors[0] ? summarizeError(bulkResult.errors[0]) : '';\n\n // Resolve the four terminal `status` values from the server's\n // (imported, skipped, errors) tuple. Each branch is mutually\n // exclusive and the resolved status, paired with the `error`\n // string, is the unambiguous signal the wizard renders against.\n const hasImports = bulkResult.imported > 0;\n const hasErrors = bulkResult.errors.length > 0;\n const hasSkips = bulkResult.skipped > 0;\n\n let nextStatus: ImportState['status'] = 'completed';\n let nextError: string | null = null;\n\n if (!hasImports && hasErrors) {\n nextStatus = 'error';\n nextError = `Import failed: ${bulkResult.errors.length} secret${\n bulkResult.errors.length === 1 ? '' : 's'\n } could not be created — ${firstError}`;\n } else if (hasImports && hasErrors) {\n nextStatus = 'partial';\n // Use the row count the user actually uploaded as the denominator\n // — server-side math (imported + errors + skipped) would\n // disagree with the wizard's preview if the gateway dedupes or\n // truncates rows.\n const totalRows = importState.parsedSecrets.length;\n nextError = `Imported ${bulkResult.imported} of ${totalRows} secrets — ${\n bulkResult.errors.length\n } failed${hasSkips ? `, ${bulkResult.skipped} skipped` : ''}. First error: ${firstError}`;\n } else if (!hasImports && hasSkips) {\n nextStatus = 'skipped';\n nextError = `Nothing imported: ${bulkResult.skipped} duplicate secret${\n bulkResult.skipped === 1 ? '' : 's'\n } skipped`;\n } else if (!hasImports && !hasErrors && !hasSkips) {\n // Defensive: server returned an empty result tuple. Should not\n // happen because we guard `parsedSecrets.length > 0` above, but\n // protect the wizard from showing a green \"Import complete\"\n // banner with a \"0 imported\" badge if the gateway ever filters\n // every row out before processing.\n nextStatus = 'skipped';\n nextError = 'Nothing was imported — the server returned an empty result.';\n }\n\n // For the empty-result defensive branch we deliberately omit\n // `results` so the wizard's terminal-state card renders the\n // error message alone, instead of an extra \"0 imported\" badge\n // row that would contradict the message.\n const isEmptyResult = !hasImports && !hasErrors && !hasSkips;\n\n setImportState((previous) => ({\n ...previous,\n status: nextStatus,\n results: isEmptyResult ? undefined : bulkResult,\n error: nextError,\n }));\n } catch (error) {\n setImportState((previous) => ({\n ...previous,\n status: 'error',\n error: error instanceof Error ? error.message : 'Import failed',\n }));\n }\n },\n [\n bulkCreateMutation,\n importState.encodedBackup,\n importState.parsedSecrets,\n importState.sourceType,\n restoreBackupMutation,\n ]\n );\n\n const resetImport = useCallback(() => {\n setImportState({\n file: null,\n fileName: null,\n parsedSecrets: [],\n encodedBackup: null,\n sourceType: null,\n error: null,\n status: 'idle',\n results: undefined,\n });\n }, []);\n\n // INTENTIONALLY NOT IMPLEMENTED: a plain `exportSecrets` query path.\n //\n // The wspace-security-svc schema exposes\n // `exportSecrets(vaultId, passphrase, secretIds)` as a GraphQL query,\n // but a *query* is the wrong transport for a flow that takes a\n // user-supplied passphrase: any persisted-query / GET link config\n // would put the cleartext passphrase on the URL and into HTTP access\n // logs. The dormant `exportSecrets.graphql` operation that used to\n // live in `src/operations/wspace/queries/` was deleted in BOFF-2225\n // for that reason — it had zero callers in `src/` outside the\n // generated codegen output.\n //\n // The export flow now goes exclusively through `createBackup` /\n // `CREATE_VAULT_BACKUP_MUTATION` (a POST mutation) which produces\n // an encrypted backup archive, uploads it via files-svc, and emails\n // the password via channel-svc. If a \"download as encrypted JSON\"\n // UI is needed in the future it should be added as a new mutation,\n // not by re-introducing the query.\n\n const createBackup = useCallback(\n async (vaultId: string, selectedSecretIds?: string[]): Promise<BackupExportResult> => {\n const { data, error } = await createBackupMutation({\n variables: {\n input: {\n vaultId,\n secretIds:\n selectedSecretIds && selectedSecretIds.length > 0 ? selectedSecretIds : undefined,\n },\n },\n });\n\n if (error) {\n throw error;\n }\n\n const result = data?.createVaultBackup;\n if (!result) {\n throw new Error('Backup completed without a response');\n }\n\n triggerDownload(result.downloadUrl, result.fileName);\n return result;\n },\n [createBackupMutation]\n );\n\n return {\n importState,\n importing: bulkImporting || restoringBackup,\n exporting: creatingBackup,\n handleFileSelect,\n executeImport,\n resetImport,\n createBackup,\n };\n}\n"],"mappings":";;;;;;;AAWA,IAAM,IAA0B;AAchC,SAAS,EAAe,GAAqB;CAC3C,IAAM,IAAU,EAAI,MAAM;AAC1B,KAAI,EAAQ,UAAU,EAAyB,QAAO;CACtD,IAAM,IAAa,CAAC,GAAG,EAAQ;AAE/B,QADI,EAAW,UAAU,IAAgC,IAClD,GAAG,EAAW,MAAM,GAAG,IAA0B,EAAE,CAAC,KAAK,GAAG,CAAC;;AAGtE,IAAM,IAAwB,CAAC,EAAmB,EAiB5C,IAAwD,IAAI,IAChE,OAAO,OAAO,EAAW,CAAC,KAAK,MAAU,CAAC,EAAM,aAAa,EAAE,EAAM,CAAC,CACvE;AAED,SAAS,EAAiB,GAAuC;AAC/D,KAAI,CAAC,EAAO,QAAO,EAAW;CAC9B,IAAM,IAAa,EAAM,MAAM,CAAC,aAAa;AAC7C,QAAO,EAAqB,IAAI,EAAW,IAAI,EAAW;;AAkB5D,SAAS,EAA0B,GAAiD;CAClF,IAAM,oBAAU,IAAI,KAAa;AACjC,MAAK,IAAM,KAAK,GAAS;EACvB,IAAM,IAAM,EAAE,MAAM,MAAM;AACrB,QACA,EAAqB,IAAI,EAAI,aAAa,CAAC,IAC9C,EAAQ,IAAI,EAAI;;AAGhB,GAAQ,SAAS,KAErB,QAAQ,KACN,uEACK,CAAC,GAAG,EAAQ,CAAC,KAAK,KAAK,CAAC,kBAAkB,CAAC,GAAG,EAAqB,MAAM,CAAC,CAAC,KAAK,KAAK,GAC3F;;AAGH,IAAM,IAA+B,CAAG;;;;;;;;;;;;GAclC,IAAgC,CAAG;;;;;;;;;AAwDzC,SAAS,EAAgB,GAAa,GAAwB;CAC5D,IAAM,IAAO,SAAS,cAAc,IAAI;AAMxC,CALA,EAAK,OAAO,GACZ,EAAK,WAAW,GAChB,EAAK,MAAM,Y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,IAAY,qBAAqB,EAAW,QAAQ,mBAClD,EAAW,YAAY,IAAI,KAAK,IACjC,aACQ,CAAC,KAAc,CAAC,KAAa,CAAC,MAMvC,IAAa,WACb,IAAY;IAOd,IAAM,IAAgB,CAAC,KAAc,CAAC,KAAa,CAAC;AAEpD,OAAgB,OAAc;KAC5B,GAAG;KACH,QAAQ;KACR,SAAS,IAAgB,KAAA,IAAY;KACrC,OAAO;KACR,EAAE;YACI,GAAO;AACd,OAAgB,OAAc;KAC5B,GAAG;KACH,QAAQ;KACR,OAAO,aAAiB,QAAQ,EAAM,UAAU;KACjD,EAAE;;;IAGP;EACE;EACA,EAAY;EACZ,EAAY;EACZ,EAAY;EACZ;EACD,CACF,EAEK,IAAc,QAAkB;AACpC,IAAe;GACb,MAAM;GACN,UAAU;GACV,eAAe,EAAE;GACjB,eAAe;GACf,YAAY;GACZ,OAAO;GACP,QAAQ;GACR,SAAS,KAAA;GACV,CAAC;IACD,EAAE,CAAC,EAqBA,IAAe,EACnB,OAAO,GAAiB,MAA8D;EACpF,IAAM,EAAE,SAAM,aAAU,MAAM,EAAqB,EACjD,WAAW,EACT,OAAO;GACL;GACA,WACE,KAAqB,EAAkB,SAAS,IAAI,IAAoB,KAAA;GAC3E,EACF,EACF,CAAC;AAEF,MAAI,EACF,OAAM;EAGR,IAAM,IAAS,GAAM;AACrB,MAAI,CAAC,EACH,OAAU,MAAM,sCAAsC;AAIxD,SADA,EAAgB,EAAO,aAAa,EAAO,SAAS,EAC7C;IAET,CAAC,EAAqB,CACvB;AAED,QAAO;EACL;EACA,WAAW,KAAiB;EAC5B,WAAW;EACX;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"useImportExport.js","names":[],"sources":["../../../src/security/hooks/useImportExport.ts"],"sourcesContent":["import { useState, useCallback } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation } from '@apollo/client/react';\nimport {\n GetSecretsDocument,\n useBulkCreateSecretsMutation,\n} from '../../generated/wspace-operations';\nimport { SecretType } from '../../generated/wspace-types';\nimport { parseImportFile, type ParsedSecret } from '../utils/fileParser';\n\n/** Maximum length for the truncated server error string we display in the wizard banner. */\nconst MAX_BANNER_ERROR_LENGTH = 140;\n\n/**\n * Truncate raw server error strings before they are interpolated into\n * the wizard's banner. The gateway is supposed to normalise its errors\n * but a raw Prisma message (\"Unique constraint failed on field `key`\")\n * would otherwise leak schema details into the UI. The full text is\n * still available on `results.errors` for the per-row error list.\n *\n * Iterates over Unicode code points via the spread iterator (not the\n * UTF-16 code units that `String.prototype.slice` uses) so a truncation\n * boundary cannot land in the middle of a surrogate pair and produce a\n * mangled emoji or Asian-script character.\n */\nfunction summarizeError(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.length <= MAX_BANNER_ERROR_LENGTH) return trimmed;\n const codepoints = [...trimmed];\n if (codepoints.length <= MAX_BANNER_ERROR_LENGTH) return trimmed;\n return `${codepoints.slice(0, MAX_BANNER_ERROR_LENGTH - 1).join('')}…`;\n}\n\nconst REFETCH_VAULT_SECRETS = [GetSecretsDocument];\n\n/**\n * Lookup table from \"uppercased enum value\" to the canonical SecretType\n * enum entry, derived directly from codegen output. Using a Map keyed by\n * the uppercased value makes this robust regardless of whether the\n * codegen emits values in SCREAMING_SNAKE_CASE (current) or in some\n * other casing in the future. A future enum addition will surface here\n * as a type error rather than as a runtime \"invalid enum value\" rejection\n * from the gateway.\n *\n * Anything we cannot map falls back to TEXT, matching\n * `fileParser.normalizeSecret`'s default for blank columns. Unknown\n * inputs also emit a `console.warn` in non-production builds so a\n * typo in a CSV `type` column (e.g. \"CERTIFCATE\") doesn't silently\n * import the row as TEXT.\n */\nconst SECRET_TYPE_BY_UPPER: ReadonlyMap<string, SecretType> = new Map(\n Object.values(SecretType).map((value) => [value.toUpperCase(), value])\n);\n\nfunction coerceSecretType(input: string | undefined): SecretType {\n if (!input) return SecretType.Text;\n const normalized = input.trim().toUpperCase();\n return SECRET_TYPE_BY_UPPER.get(normalized) ?? SecretType.Text;\n}\n\n/**\n * Walk the parsed-secrets list and emit a single `console.warn`\n * summarising every unrecognised `type` value before the bulk\n * mutation runs, instead of `coerceSecretType` itself logging once\n * per row. This:\n * - de-duplicates noisy retry warnings if the user re-runs\n * `executeImport` against the same parsed file (e.g. after a\n * transient network error)\n * - prevents a typo'd row from silently importing as TEXT without\n * any signal in the browser console\n *\n * Uses one log line containing the full set of bad type values so a\n * 100-row CSV with 50 different typos doesn't spam the console with\n * 50 separate warnings.\n */\nfunction logUnknownSecretTypesOnce(secrets: ReadonlyArray<{ type?: string }>): void {\n const unknown = new Set<string>();\n for (const s of secrets) {\n const raw = s.type?.trim();\n if (!raw) continue;\n if (!SECRET_TYPE_BY_UPPER.has(raw.toUpperCase())) {\n unknown.add(raw);\n }\n }\n if (unknown.size === 0) return;\n // eslint-disable-next-line no-console\n console.warn(\n `[useImportExport] Unrecognized secret types — falling back to TEXT: ` +\n `${[...unknown].join(', ')}. Valid values: ${[...SECRET_TYPE_BY_UPPER.keys()].join(', ')}`\n );\n}\n\nconst CREATE_VAULT_BACKUP_MUTATION = gql`\n mutation CreateVaultBackup($input: CreateVaultBackupInput!) {\n createVaultBackup(input: $input) {\n fileId\n fileName\n downloadUrl\n count\n format\n passwordDelivered\n deliveryStatus\n }\n }\n`;\n\nconst RESTORE_VAULT_BACKUP_MUTATION = gql`\n mutation RestoreVaultBackup($input: RestoreVaultBackupInput!) {\n restoreVaultBackup(input: $input) {\n imported\n skipped\n errors\n }\n }\n`;\n\n/**\n * Wizard state machine for plain/backup imports.\n *\n * `status` is the single source of truth for what the wizard should\n * render. Five terminal states are distinguished so consumers can light\n * up the right affordance without inspecting `results`:\n *\n * - `completed` — at least one row was created, with no row-level\n * errors. Green success banner.\n * - `partial` — at least one row was created AND at least one row\n * errored. Yellow / amber \"imported some but not all\" banner.\n * `error` carries a one-line summary; per-row detail is in\n * `results.errors`.\n * - `skipped` — zero imported, all rows were duplicates and skipped\n * (no row-level errors). Neutral \"nothing to import\" banner.\n * `error` carries a count message.\n * - `error` — zero imported AND every row errored, OR the\n * mutation itself threw. Red failure banner. `error` carries a\n * one-line summary including the first row error message.\n */\nexport interface ImportState {\n file: File | null;\n fileName: string | null;\n parsedSecrets: ParsedSecret[];\n encodedBackup: string | null;\n sourceType: 'plain' | 'backup' | null;\n error: string | null;\n status:\n | 'idle'\n | 'parsing'\n | 'ready'\n | 'importing'\n | 'completed'\n | 'partial'\n | 'skipped'\n | 'error';\n results?: {\n imported: number;\n skipped: number;\n errors: string[];\n };\n}\n\nexport interface BackupExportResult {\n fileId: string;\n fileName: string;\n downloadUrl: string;\n count: number;\n format: string;\n passwordDelivered: boolean;\n deliveryStatus: string;\n}\n\nfunction triggerDownload(url: string, fileName: string): void {\n const link = document.createElement('a');\n link.href = url;\n link.download = fileName;\n link.rel = 'noopener';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n}\n\nexport function useImportExport() {\n const [importState, setImportState] = useState<ImportState>({\n file: null,\n fileName: null,\n parsedSecrets: [],\n encodedBackup: null,\n sourceType: null,\n error: null,\n status: 'idle',\n });\n\n const [bulkCreateMutation, { loading: bulkImporting }] = useBulkCreateSecretsMutation({\n // Refetch the vault's secret list so the detail page shows the freshly\n // imported rows. We deliberately do NOT pass `awaitRefetchQueries: true`\n // here so the success banner appears as soon as the mutation resolves;\n // the cache update happens in the background. The old per-row\n // `useCreateSecret` helper had the same property — it issued a refetch\n // per call but did not block the mutation promise on it.\n refetchQueries: REFETCH_VAULT_SECRETS,\n });\n const [restoreBackupMutation, { loading: restoringBackup }] = useMutation<{\n restoreVaultBackup: { imported: number; skipped: number; errors: string[] };\n }>(RESTORE_VAULT_BACKUP_MUTATION, {\n // Same parity as the bulk-import path: refetch GetSecrets so the\n // vault detail page picks up the restored rows. Background refetch —\n // see the bulkCreateMutation comment for why we don't await it.\n refetchQueries: REFETCH_VAULT_SECRETS,\n });\n const [createBackupMutation, { loading: creatingBackup }] = useMutation<{\n createVaultBackup: BackupExportResult;\n }>(CREATE_VAULT_BACKUP_MUTATION);\n\n const handleFileSelect = useCallback(async (file: File) => {\n setImportState((previous) => ({\n ...previous,\n status: 'parsing',\n file,\n fileName: file.name,\n error: null,\n results: undefined,\n }));\n\n try {\n const parsed = await parseImportFile(file);\n if (parsed.kind === 'backup') {\n setImportState((previous) => ({\n ...previous,\n status: 'ready',\n sourceType: 'backup',\n encodedBackup: parsed.encodedBackup,\n parsedSecrets: [],\n }));\n return;\n }\n\n setImportState((previous) => ({\n ...previous,\n status: 'ready',\n sourceType: 'plain',\n parsedSecrets: parsed.secrets,\n encodedBackup: null,\n }));\n } catch (error) {\n setImportState((previous) => ({\n ...previous,\n status: 'error',\n sourceType: null,\n encodedBackup: null,\n parsedSecrets: [],\n error: error instanceof Error ? error.message : 'Failed to parse file',\n }));\n }\n }, []);\n\n const executeImport = useCallback(\n async (vaultId: string, backupPassword?: string) => {\n if (!vaultId) return;\n\n setImportState((previous) => ({ ...previous, status: 'importing', error: null }));\n\n try {\n if (importState.sourceType === 'backup') {\n if (!importState.encodedBackup) {\n throw new Error('No backup payload is available for restore');\n }\n if (!backupPassword?.trim()) {\n throw new Error('Backup password is required to restore the archive');\n }\n\n const { data } = await restoreBackupMutation({\n variables: {\n input: {\n vaultId,\n data: importState.encodedBackup,\n password: backupPassword,\n overwriteExisting: false,\n },\n },\n });\n\n const result = data?.restoreVaultBackup;\n if (!result) {\n throw new Error('Restore completed without a response');\n }\n\n setImportState((previous) => ({\n ...previous,\n status: 'completed',\n results: result,\n }));\n return;\n }\n\n if (!importState.parsedSecrets.length) {\n throw new Error('No secrets available for import');\n }\n\n // Surface any unrecognized `type` columns once, before the\n // mutation runs, so a typo doesn't silently import the row as\n // TEXT without any signal in the browser console.\n logUnknownSecretTypesOnce(importState.parsedSecrets);\n\n // Plain CSV/JSON upload: hand off to the bulkCreateSecrets mutation\n // so the server batches encryption + version rows in one round-trip\n // and reports per-secret errors. The previous per-secret loop here\n // multiplied gateway calls by N and lost partial-failure detail.\n //\n // overwriteExisting is intentionally not set — the server defaults\n // to false (skip duplicates), and the `skipped` count in the\n // result drives the wizard's `'skipped'` / `'partial'` states.\n // If a future \"overwrite duplicates\" toggle is added to the UI,\n // forward it through here.\n const { data } = await bulkCreateMutation({\n variables: {\n input: {\n vaultId,\n secrets: importState.parsedSecrets.map((s) => ({\n name: s.name,\n key: s.key,\n value: s.value,\n type: coerceSecretType(s.type),\n description: s.description,\n })),\n },\n },\n });\n\n const bulkResult = data?.bulkCreateSecrets;\n if (!bulkResult) {\n throw new Error('Bulk import completed without a response');\n }\n\n const firstError = bulkResult.errors[0] ? summarizeError(bulkResult.errors[0]) : '';\n\n // Resolve the four terminal `status` values from the server's\n // (imported, skipped, errors) tuple. Each branch is mutually\n // exclusive and the resolved status, paired with the `error`\n // string, is the unambiguous signal the wizard renders against.\n const hasImports = bulkResult.imported > 0;\n const hasErrors = bulkResult.errors.length > 0;\n const hasSkips = bulkResult.skipped > 0;\n\n let nextStatus: ImportState['status'] = 'completed';\n let nextError: string | null = null;\n\n if (!hasImports && hasErrors) {\n nextStatus = 'error';\n nextError = `Import failed: ${bulkResult.errors.length} secret${\n bulkResult.errors.length === 1 ? '' : 's'\n } could not be created — ${firstError}`;\n } else if (hasImports && hasErrors) {\n nextStatus = 'partial';\n // Use the row count the user actually uploaded as the denominator\n // — server-side math (imported + errors + skipped) would\n // disagree with the wizard's preview if the gateway dedupes or\n // truncates rows.\n const totalRows = importState.parsedSecrets.length;\n nextError = `Imported ${bulkResult.imported} of ${totalRows} secrets — ${\n bulkResult.errors.length\n } failed${hasSkips ? `, ${bulkResult.skipped} skipped` : ''}. First error: ${firstError}`;\n } else if (!hasImports && hasSkips) {\n nextStatus = 'skipped';\n nextError = `Nothing imported: ${bulkResult.skipped} duplicate secret${\n bulkResult.skipped === 1 ? '' : 's'\n } skipped`;\n } else if (!hasImports && !hasErrors && !hasSkips) {\n // Defensive: server returned an empty result tuple. Should not\n // happen because we guard `parsedSecrets.length > 0` above, but\n // protect the wizard from showing a green \"Import complete\"\n // banner with a \"0 imported\" badge if the gateway ever filters\n // every row out before processing.\n nextStatus = 'skipped';\n nextError = 'Nothing was imported — the server returned an empty result.';\n }\n\n // For the empty-result defensive branch we deliberately omit\n // `results` so the wizard's terminal-state card renders the\n // error message alone, instead of an extra \"0 imported\" badge\n // row that would contradict the message.\n const isEmptyResult = !hasImports && !hasErrors && !hasSkips;\n\n setImportState((previous) => ({\n ...previous,\n status: nextStatus,\n results: isEmptyResult ? undefined : bulkResult,\n error: nextError,\n }));\n } catch (error) {\n setImportState((previous) => ({\n ...previous,\n status: 'error',\n error: error instanceof Error ? error.message : 'Import failed',\n }));\n }\n },\n [\n bulkCreateMutation,\n importState.encodedBackup,\n importState.parsedSecrets,\n importState.sourceType,\n restoreBackupMutation,\n ]\n );\n\n const resetImport = useCallback(() => {\n setImportState({\n file: null,\n fileName: null,\n parsedSecrets: [],\n encodedBackup: null,\n sourceType: null,\n error: null,\n status: 'idle',\n results: undefined,\n });\n }, []);\n\n // INTENTIONALLY NOT IMPLEMENTED: a plain `exportSecrets` query path.\n //\n // The wspace-security-svc schema exposes\n // `exportSecrets(vaultId, passphrase, secretIds)` as a GraphQL query,\n // but a *query* is the wrong transport for a flow that takes a\n // user-supplied passphrase: any persisted-query / GET link config\n // would put the cleartext passphrase on the URL and into HTTP access\n // logs. The dormant `exportSecrets.graphql` operation that used to\n // live in `src/operations/wspace/queries/` was deleted in BOFF-2225\n // for that reason — it had zero callers in `src/` outside the\n // generated codegen output.\n //\n // The export flow now goes exclusively through `createBackup` /\n // `CREATE_VAULT_BACKUP_MUTATION` (a POST mutation) which produces\n // an encrypted backup archive, uploads it via files-svc, and emails\n // the password via channel-svc. If a \"download as encrypted JSON\"\n // UI is needed in the future it should be added as a new mutation,\n // not by re-introducing the query.\n\n const createBackup = useCallback(\n async (vaultId: string, selectedSecretIds?: string[]): Promise<BackupExportResult> => {\n const { data, error } = await createBackupMutation({\n variables: {\n input: {\n vaultId,\n secretIds:\n selectedSecretIds && selectedSecretIds.length > 0 ? selectedSecretIds : undefined,\n },\n },\n });\n\n if (error) {\n throw error;\n }\n\n const result = data?.createVaultBackup;\n if (!result) {\n throw new Error('Backup completed without a response');\n }\n\n triggerDownload(result.downloadUrl, result.fileName);\n return result;\n },\n [createBackupMutation]\n );\n\n return {\n importState,\n importing: bulkImporting || restoringBackup,\n exporting: creatingBackup,\n handleFileSelect,\n executeImport,\n resetImport,\n createBackup,\n };\n}\n"],"mappings":";;;;;;;AAWA,IAAM,IAA0B;AAchC,SAAS,EAAe,GAAqB;CAC3C,IAAM,IAAU,EAAI,MAAM;AAC1B,KAAI,EAAQ,UAAU,EAAyB,QAAO;CACtD,IAAM,IAAa,CAAC,GAAG,EAAQ;AAE/B,QADI,EAAW,UAAU,IAAgC,IAClD,GAAG,EAAW,MAAM,GAAG,IAA0B,EAAE,CAAC,KAAK,GAAG,CAAC;;AAGtE,IAAM,IAAwB,CAAC,EAAmB,EAiB5C,IAAwD,IAAI,IAChE,OAAO,OAAO,EAAW,CAAC,KAAK,MAAU,CAAC,EAAM,aAAa,EAAE,EAAM,CAAC,CACvE;AAED,SAAS,EAAiB,GAAuC;AAC/D,KAAI,CAAC,EAAO,QAAO,EAAW;CAC9B,IAAM,IAAa,EAAM,MAAM,CAAC,aAAa;AAC7C,QAAO,EAAqB,IAAI,EAAW,IAAI,EAAW;;AAkB5D,SAAS,EAA0B,GAAiD;CAClF,IAAM,oBAAU,IAAI,KAAa;AACjC,MAAK,IAAM,KAAK,GAAS;EACvB,IAAM,IAAM,EAAE,MAAM,MAAM;AACrB,QACA,EAAqB,IAAI,EAAI,aAAa,CAAC,IAC9C,EAAQ,IAAI,EAAI;;AAGhB,GAAQ,SAAS,KAErB,QAAQ,KACN,uEACK,CAAC,GAAG,EAAQ,CAAC,KAAK,KAAK,CAAC,kBAAkB,CAAC,GAAG,EAAqB,MAAM,CAAC,CAAC,KAAK,KAAK,GAC3F;;AAGH,IAAM,IAA+B,CAAG;;;;;;;;;;;;GAclC,IA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denoff/microfe-security",
3
- "version": "2026.1013.1",
3
+ "version": "2026.1013.3",
4
4
  "description": "Security vault management microfrontend",
5
5
  "type": "module",
6
6
  "files": [