@camstack/addon-admin-ui 1.2.503 → 1.2.504

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.
Files changed (81) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/assets/{AddonAssetIcon-DRZmNGlG.js → AddonAssetIcon-NEsi-wOP.js} +1 -1
  3. package/dist/assets/Addons-BBTz7bMK.js +5 -0
  4. package/dist/assets/{AdminPage-Bn1s1Zyw.js → AdminPage-aCyydhgN.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-OHmEcMxM.js → AdminSectionedPage-DQApNUvC.js} +1 -1
  6. package/dist/assets/{AiProfiles-CrsCHAWJ.js → AiProfiles-BE-rCiys.js} +1 -1
  7. package/dist/assets/{BrokerEditorDialog-0I2FqCxl.js → BrokerEditorDialog-DaJ4BMP-.js} +1 -1
  8. package/dist/assets/{Build-vzgL6An-.js → Build-BEJ9LiOb.js} +3 -3
  9. package/dist/assets/{Calendars-CdAizSco.js → Calendars-DwmEazlr.js} +1 -1
  10. package/dist/assets/{Cluster-Bg0lO7ax.js → Cluster-DXvpkuQ_.js} +1 -1
  11. package/dist/assets/{CompositionBlockEditor-CP3_SX84.js → CompositionBlockEditor-Dn1dNrUj.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-DfjSU7uD.js → CompositionEditorPage-BAtIrfop.js} +1 -1
  13. package/dist/assets/{Data-D2dSu7s6.js → Data-CxbvhxJ0.js} +2 -2
  14. package/dist/assets/DeviceDetail-1SsTjU6R.js +2 -0
  15. package/dist/assets/{DeviceDoActionFields-CHeeEoE0.js → DeviceDoActionFields-CbeCW7Ej.js} +1 -1
  16. package/dist/assets/{Devices-gen3hRHJ.js → Devices-P2Awkb88.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-rhZJ1QKl.js → EmbedPlayerPage-DHx71JZg.js} +1 -1
  18. package/dist/assets/{HelperWizard-QNL7ojgt.js → HelperWizard-dV1HzKlU.js} +2 -2
  19. package/dist/assets/{History-D84HQRm3.js → History-COrccgVX.js} +1 -1
  20. package/dist/assets/{Identity-CxluBwKM.js → Identity-DwNJielZ.js} +1 -1
  21. package/dist/assets/IntegrationDetail-B62OySBK.js +1 -0
  22. package/dist/assets/{IntegrationHub-DXhDIgkG.js → IntegrationHub-DkSP6wag.js} +1 -1
  23. package/dist/assets/Integrations-BOcxxDmP.js +1 -0
  24. package/dist/assets/Integrations-qJr63PpD.js +1 -0
  25. package/dist/assets/{Library-BYQs9rzN.js → Library-BV1qzsuk.js} +1 -1
  26. package/dist/assets/{Locations-LcX-LYMF.js → Locations-CZB5AlmP.js} +1 -1
  27. package/dist/assets/{Logs-BEZRwDcR.js → Logs-GyrX39DG.js} +1 -1
  28. package/dist/assets/MyAccess-CX7W9s59.js +2 -0
  29. package/dist/assets/Network-hBrZTqKM.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-DEdzDp8P.js → NodeAddonsSettingsPanel-DcAc9h3n.js} +1 -1
  31. package/dist/assets/Notifications-CVo2lV8_.js +1 -0
  32. package/dist/assets/{Pipeline-DanfCspn.js → Pipeline-ULrA6vbR.js} +1 -1
  33. package/dist/assets/{Recordings-DPC7wBK7.js → Recordings-O3tK-kRN.js} +1 -1
  34. package/dist/assets/{ScanNetworkModal-DYNrpcKO.js → ScanNetworkModal-DRTFnUxd.js} +1 -1
  35. package/dist/assets/{SessionsList-_-3LQsWm.js → SessionsList-CmkI6hmY.js} +2 -2
  36. package/dist/assets/{Showroom-Cb8HIezy.js → Showroom-PcX3gurw.js} +1 -1
  37. package/dist/assets/{System-CmmWc699.js → System-74cpSs_X.js} +1 -1
  38. package/dist/assets/{Terminal-B-DbiagD.js → Terminal-BzqwEea0.js} +1 -1
  39. package/dist/assets/{Viewer-h_DWBxgH.js → Viewer-DhjS-14b.js} +1 -1
  40. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-ChYA9pOs.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bj_EUdNV.js} +1 -1
  41. package/dist/assets/{addon-icons-context-aYGMdVc6.js → addon-icons-context-BfGPQ4xZ.js} +1 -1
  42. package/dist/assets/{assignment-candidates-C73e9ykO.js → assignment-candidates-BWSRqjeY.js} +1 -1
  43. package/dist/assets/{authed-media-OiQVKexs.js → authed-media-CCu_0Mkk.js} +1 -1
  44. package/dist/assets/{board-model-CCAK2YmC.js → board-model-D0x2o-FF.js} +1 -1
  45. package/dist/assets/{device-integration-icon-BStZ5ytk.js → device-integration-icon-RKJ1i9-y.js} +1 -1
  46. package/dist/assets/device-picker-model-CCtDoCaE.js +1 -0
  47. package/dist/assets/{format-XZs_xh1r.js → format-BrcsXZgx.js} +1 -1
  48. package/dist/assets/framework-packages-B7oma9J4.js +1 -0
  49. package/dist/assets/{hostInit-Dugn9T0N.js → hostInit-C9UJbeBX.js} +1 -1
  50. package/dist/assets/i18n-DNh4GW93.js +1 -0
  51. package/dist/assets/index-DOFPItyi.css +2 -0
  52. package/dist/assets/{index-pzq9LOji.js → index-Dm-ruGxs.js} +3 -3
  53. package/dist/assets/{linked-devices-model-CNnR_mjb.js → linked-devices-model-Bd2asZR8.js} +1 -1
  54. package/dist/assets/{location-owned-usage-Cwiz3bVN.js → location-owned-usage-AoW2HSuk.js} +1 -1
  55. package/dist/assets/{mf-entry-bootstrap-0-e18bf152.js → mf-entry-bootstrap-0-44b53b1c.js} +2 -2
  56. package/dist/assets/mount-CCtDoCaE.js +1 -0
  57. package/dist/assets/remoteEntry-CFFHRTAl.js +1 -0
  58. package/dist/assets/{src-DlnTixq9.js → src-DY9QaWNW.js} +1 -1
  59. package/dist/assets/{step-inspector-model-DP-n2a-m.js → step-inspector-model-_xqNTlQX.js} +1 -1
  60. package/dist/assets/{use-scenes-feed-Px1hbQDA.js → use-scenes-feed-Co3WLAh1.js} +1 -1
  61. package/dist/assets/{use-stationary-objects-WqiRmYIc.js → use-stationary-objects-o-ZgylqM.js} +1 -1
  62. package/dist/assets/useEventInvalidation-CCtDoCaE.js +1 -0
  63. package/dist/assets/{useNodeUrlSelection-DW98VTZs.js → useNodeUrlSelection--XA1ndxK.js} +1 -1
  64. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CoUIkQxD.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CX8JLNds.js} +2 -2
  65. package/dist/index.html +7 -7
  66. package/dist/server/addon.js +1 -1
  67. package/package.json +1 -1
  68. package/dist/assets/Addons-RW0QdiVT.js +0 -5
  69. package/dist/assets/DeviceDetail-Dd1ulCyf.js +0 -2
  70. package/dist/assets/IntegrationDetail-2QlbVLE7.js +0 -1
  71. package/dist/assets/Integrations-Cs-b-69p.js +0 -1
  72. package/dist/assets/Integrations-DT3z5Q5Q.js +0 -1
  73. package/dist/assets/MyAccess-ChxQGXAk.js +0 -2
  74. package/dist/assets/Network-C7jEJlX5.js +0 -1
  75. package/dist/assets/Notifications-Dk-cpsUG.js +0 -1
  76. package/dist/assets/device-picker-model-DuRGlFHX.js +0 -1
  77. package/dist/assets/i18n-uD14huY2.js +0 -1
  78. package/dist/assets/index-WAVCQxxk.css +0 -2
  79. package/dist/assets/mount-DuRGlFHX.js +0 -1
  80. package/dist/assets/remoteEntry-C4v7BKsX.js +0 -1
  81. package/dist/assets/useEventInvalidation-DuRGlFHX.js +0 -1
@@ -1 +1 @@
1
- import{C as e,K as t,S as n,Y as r,et as i,i as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{En as s,Ht as c,Tr as l,ct as u,dt as d,fr as f,gt as p,ki as m,pa as h,st as g,xn as _}from"./player-overlays-B4lehTI4.js";import{_r as v,la as y}from"./client-C6c46gRD.js";import{A as b,C as x,Cn as S,Cr as C,D as w,Do as T,Dr as E,E as D,Er as O,Lr as k,M as A,Md as ee,N as j,O as M,Or as N,P as te,Pr as ne,S as re,Sn as P,Tr as F,Vr as I,Yr as L,_ as ie,_r as ae,b as R,bn as z,d as oe,dr as se,f as ce,fn as le,fr as ue,gr as de,h as fe,hr as pe,j as me,k as he,lu as ge,m as _e,no as ve,pn as ye,pr as be,ri as B,to as xe,u as Se,v as Ce,w as we,x as V}from"./src-DlnTixq9.js";import{t as H}from"./useTranslation-BJr-n0es.js";import{gr as Te}from"./index-pzq9LOji.js";import{t as Ee}from"./AdminPage-Bn1s1Zyw.js";i();function U(e,t){return e.scope===``?e.displayName:`${e.displayName} · ${t?.(e)??e.scope}`}function De(e,t,n){let r=[];for(let{device:t,series:i}of e)for(let e of i){let i={subject:{kind:`device`,deviceId:t.id},key:e.key,scope:e.scope};r.push({id:V(i),ref:i,info:e,subjectName:t.name,location:t.location??``,nodeId:``,metric:U(e,n)})}for(let{node:e,series:i}of t)for(let t of i){let i={subject:{kind:`node`,nodeId:e.id},key:t.key,scope:t.scope};r.push({id:V(i),ref:i,info:t,subjectName:e.name,location:``,nodeId:e.id,metric:U(t,n)})}return r}function Oe(e){return[e.subjectName,e.location,e.metric,e.info.key,e.info.unit??``,e.nodeId].join(` `)}function W(e,t,n){if(e.ref.subject.kind!==`device`||t===null)return e.subjectName;let r=t.byId.get(e.ref.subject.deviceId);return r===void 0?e.subjectName:ne(r,`compact`,t,n)}var ke=[`energy`,`temperatures`,`nodes`,`storage`],Ae=new Set([`cap:temperature-sensor.temperature`,`cap:climate-control.currentTemp`]),G=[`addon:metrics-native/node-cpu-percent`,`addon:metrics-native/node-memory-percent`],je=`addon:storage-orchestrator/location-used-percent`;function Me(e,t){let n=(e,n)=>{let r=t.filter(e);return R((n?[...r].sort(n):r).map(e=>e.ref))};switch(e){case`energy`:return n(e=>e.ref.subject.kind===`device`&&e.info.key===`derived:energy.kwh`);case`temperatures`:return n(e=>e.ref.subject.kind===`device`&&Ae.has(e.info.key)&&e.info.scope===``,(e,t)=>e.location.localeCompare(t.location)||e.subjectName.localeCompare(t.subjectName));case`nodes`:return n(e=>e.ref.subject.kind===`node`&&G.includes(e.info.key)&&e.info.scope===``,(e,t)=>G.indexOf(e.info.key)-G.indexOf(t.info.key)||e.subjectName.localeCompare(t.subjectName));case`storage`:return n(e=>e.ref.subject.kind===`node`&&e.info.key===je)}}function Ne(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=[],a=[],o=[];for(let t of R(e)){let e=n.get(V(t));if(e===void 0){o.push(t);continue}e.info.key===`derived:energy.kwh`?a.push(e):e.info.kind===`boolean`||e.info.kind===`enum`?i.push(e):r.push(e)}return{lines:r,states:i,energy:a,missing:o}}function K(e){return e.subject.kind===`device`?{deviceId:e.subject.deviceId,key:e.key,scope:e.scope}:{forNodeId:e.subject.nodeId,key:e.key,scope:e.scope}}var q=`history-page`;function Pe({part:r,window:i}){let{t:a}=H(),o=h(),s=I(),c=k(),l=e=>`${W(e,s,c)} · ${e.metric}`,u=t(()=>[...r.lines,...r.states,...r.energy],[r]),d=_e(t(()=>u.map(e=>K(e.ref)),[u]),i,!1),f=e=>d.status===`ok`?d.data.current.get(ce(K(e.ref))):void 0,p=e=>{let t=f(e);return t?.ok?t.result:void 0};if(u.length===0)return n(O,{icon:m,title:a(`history.page.emptyTitle`,`Pick series to compare`),description:a(`history.page.emptyHint`,`Choose up to 24 series on the left, or start from a panel above.`)});if(d.status===`error`)return n(F,{title:a(`history.page.readFailed`,`History could not be read`),message:d.error});let g=d.status===`pending`,_=u.map(e=>({c:e,e:f(e)})).filter(e=>e.e?.ok===!1),v=r.lines.map((e,t)=>{let n=p(e),r=w(e.info,n,i.from);return{id:e.id,label:l(e),unit:e.info.unit,colorIndex:t,points:r.points,gapMs:r.gapMs,interpolation:r.held&&n?.resolution===`raw`?`step`:`linear`}}),y=r.states.map((e,t)=>{let n=M(e.info,p(e),i.from,i.to),r=we(e.info.key,o);return{id:e.id,label:l(e),kind:e.info.kind===`boolean`?`boolean`:`enum`,colorIndex:e.info.kind===`boolean`?t:0,states:n.states,segments:n.segments,totals:n.totals,stateLabel:e.info.kind===`boolean`?e=>e===`true`?r.on:r.off:void 0}}),b=r.energy.map(e=>({c:e,...D(p(e))})),x=b[0]?.bucketMs??36e5,S=[...new Set(b.flatMap(e=>e.buckets.map(e=>e.t)))].sort((e,t)=>e-t).map(e=>({t:e,values:b.map(t=>t.buckets.find(t=>t.t===e)?.values[0]??null)}));return e(`div`,{className:`space-y-5 min-w-0`,children:[_.length>0&&n(F,{title:a(`history.page.someFailed`,`Some series could not be read`),message:_.map(e=>`${l(e.c)}: ${e.e.error}`).join(` · `)}),v.length>0&&n(te,{title:a(`history.page.lines`,`Measurements`),series:v,range:i,height:260,syncKey:q,pending:g}),b.length>0&&n(C,{title:a(`history.page.energy`,`Energy`),layers:b.map((e,t)=>({id:e.c.id,label:W(e.c,s,c),colorIndex:t})),buckets:S,bucketMs:x,range:i,unit:`kWh`,showTotal:!0,height:160,syncKey:q,pending:g}),y.length>0&&n(j,{title:y.length===1?y[0]?.label??``:a(`history.page.states`,`States`),rows:y,range:i,syncKey:q,pending:g})]})}function Fe(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function Ie(e,t){let n=[];for(let r of Fe(e,50))try{let{results:e}=await t(r),i=new Map(e.map(e=>[e.seriesId,e]));for(let e of r)n.push(i.get(e)??{seriesId:e,ok:!1,reason:`not-found`})}catch(e){let t=e instanceof Error?e.message:String(e);for(let e of r)n.push({seriesId:e,ok:!1,reason:`request-failed`,message:t})}return n}function J(e){return e.raw+e[`5m`]+e[`1h`]+e[`1d`]}function Le(e){return e.reduce((e,t)=>t.ok?{...e,deleted:e.deleted+1,points:e.points+J(t.deleted)}:{...e,refused:e.refused+1},{deleted:0,refused:0,points:0})}function Re(e,t){let n=new Map(e.map(e=>[e.seriesId,e]));return t.flatMap(e=>{let t=n.get(e.seriesId);return t===void 0?[]:[{series:t,outcome:e}]})}var Y=e=>new Date(e).toLocaleDateString(void 0,{dateStyle:`short`});function X(e,t,n){let r=t.get(e.deviceId);return r===void 0?e.reason===`device-gone`?n(`history.orphans.deviceRemoved`,`#{{id}} (removed)`,{id:e.deviceId}):n(`history.orphans.deviceId`,`#{{id}}`,{id:e.deviceId}):r}function Z(e){let t=e.displayName??e.key;return e.scope===``?t:`${t} · ${e.scope}`}function Q(t,r,i){return{key:`series`,header:i(`history.orphans.colSeries`,`Series`),render:a=>{let o=t(a);return e(`div`,{className:`min-w-0 max-w-[16rem]`,children:[n(`div`,{className:`truncate text-foreground`,title:o.key,children:Z(o)}),n(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:X(o,r,i)})]})},sortValue:e=>`${X(t(e),r,i)} ${Z(t(e))}`}}var ze=[`raw`,`5m`,`1h`,`1d`];function Be(e,t){return e===`raw`?t(`history.orphans.colRaw`,`Raw points`):e===`5m`?t(`history.orphans.col5m`,`5 min`):e===`1h`?t(`history.orphans.col1h`,`1 h`):t(`history.orphans.col1d`,`1 day`)}function Ve(t,r){return[Q(e=>e,t,r),{key:`reason`,header:r(`history.orphans.colReason`,`Reason`),render:t=>e(`div`,{className:`flex flex-col items-start gap-0.5`,children:[n(B,{variant:t.reason===`device-gone`?`warning`:`neutral`,className:`text-[10px]`,children:t.reason===`device-gone`?r(`history.orphans.deviceGone`,`Device removed`):r(`history.orphans.undeclared`,`No longer declared`)}),t.missingSince!==null&&n(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`history.orphans.since`,`since {{date}}`,{date:Y(t.missingSince)})})]}),sortValue:e=>e.reason},{key:`span`,header:r(`history.orphans.colSpan`,`Recorded`),render:t=>e(`span`,{className:`tabular-nums text-foreground-muted`,children:[Y(t.firstTs),` → `,Y(t.lastTs)]}),sortValue:e=>e.lastTs},...ze.map(e=>({key:`rows-${e}`,header:Be(e,r),align:`right`,render:t=>n(`span`,{className:`tabular-nums text-foreground-muted`,children:t.rows[e].toLocaleString()}),sortValue:t=>t.rows[e]}))]}function He(e,t){if(e.ok)return n(B,{variant:`success`,className:`text-[10px]`,children:t(`history.orphans.deleted`,{count:J(e.deleted),points:J(e.deleted).toLocaleString(),defaultValue_one:`Deleted · {{points}} point`,defaultValue_other:`Deleted · {{points}} points`})});let r=e.reason===`request-failed`?t(`history.orphans.requestFailed`,`Not sent: {{message}}`,{message:e.message}):e.reason===`not-orphan`?t(`history.orphans.refusedNotOrphan`,`Kept: no longer orphan`):e.reason===`not-found`?t(`history.orphans.refusedNotFound`,`Already gone`):t(`history.orphans.refusedFailed`,`The hub could not delete it`);return n(B,{variant:e.reason===`not-found`?`neutral`:`warning`,className:`text-[10px]`,children:r})}function Ue(e,t){return[Q(e=>e.series,e,t),{key:`result`,header:t(`history.orphans.colResult`,`Result`),render:e=>He(e.outcome,t),sortValue:e=>+!e.outcome.ok}]}i();function We({open:i,onClose:a,list:o,deviceNames:l,onDelete:u,onRefresh:d,refreshing:p}){let{t:m}=H(),h=g(),[_,v]=r(new Set),[y,b]=r(!1),[x,C]=r([]),w=t(()=>Ve(l,m),[l,m]),T=t(()=>Ue(l,m),[l,m]),E=t(()=>new Set(o.series.map(e=>String(e.seriesId))),[o.series]),D=[..._].filter(e=>E.has(e)).map(Number),O=Le(x.map(e=>e.outcome)),k=async()=>{if(await h({title:m(`history.orphans.confirmTitle`,{count:D.length,defaultValue_one:`Delete {{count}} series`,defaultValue_other:`Delete {{count}} series`}),message:m(`history.orphans.confirmMessage`,`Every recorded point of these series is removed from the hub. This cannot be undone.`),confirmLabel:m(`history.orphans.confirmLabel`,`Delete`),variant:`danger`})){b(!0);try{let e=await Ie(D,u);C(Re(o.series,e)),v(new Set)}finally{b(!1),d()}}};return n(se,{open:i,onOpenChange:e=>!e&&a(),children:e(be,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`orphan-series-dialog`,children:[n(de,{children:n(ae,{children:m(`history.orphans.title`,`Series no longer linked to a device`)})}),e(ue,{className:`space-y-3`,children:[n(`p`,{className:`text-xs text-foreground-muted`,children:m(`history.orphans.intro`,`Nothing records into these series any more: their device was removed, or no capability declares them now. Select the ones to delete.`)}),o.truncated&&e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`orphan-truncated`,children:[n(`p`,{className:`text-xs text-warning`,children:m(`history.orphans.truncated`,`More series are unlinked than are listed here. Delete these, then load the rest.`)}),e(L,{size:`sm`,variant:`outline`,onClick:d,disabled:p,children:[n(s,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.loadAgain`,`Load again`)]})]}),x.length>0&&e(`div`,{className:`space-y-2`,"data-testid":`orphan-outcomes`,children:[n(`p`,{className:`text-xs text-foreground`,"aria-live":`polite`,children:m(`history.orphans.summary`,{count:O.deleted,refused:O.refused,points:O.points.toLocaleString(),defaultValue_one:`{{count}} series deleted ({{points}} points), {{refused}} kept.`,defaultValue_other:`{{count}} series deleted ({{points}} points), {{refused}} kept.`})}),n(P,{columns:T,rows:x,rowKey:e=>String(e.series.seriesId),minWidthPx:420,maxBodyHeight:`max-h-[60vh]`,emptyMessage:``})]}),n(P,{columns:w,rows:o.series,rowKey:e=>String(e.seriesId),minWidthPx:760,maxBodyHeight:S,defaultSort:{columnKey:`series`,dir:`asc`},emptyMessage:m(`history.orphans.empty`,`Every series is linked to a device.`),selection:{selected:_,onChange:v,rowLabel:e=>`${Z(e)} — ${X(e,l,m)}`,pageLabel:m(`history.orphans.selectAll`,`Select every listed series`)}})]}),e(pe,{children:[n(`span`,{className:`mr-auto text-[11px] tabular-nums text-foreground`,"aria-live":`polite`,children:m(`history.orphans.selected`,{count:D.length,defaultValue_one:`{{count}} selected`,defaultValue_other:`{{count}} selected`})}),n(L,{variant:`ghost`,size:`sm`,onClick:a,children:m(`history.orphans.close`,`Close`)}),e(L,{variant:`danger`,size:`sm`,disabled:D.length===0||y,onClick:()=>void k(),children:[y?n(f,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):n(c,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.deleteSelected`,`Delete selected`)]})]})]})})}i();var Ge=5*6e4;function Ke({enabled:i}){let{t:a}=H(),[s,c]=r(!1),l=ve({},{enabled:i,staleTime:Ge}),u=T({projection:`slim`},{enabled:i}),d=xe(),f=t(()=>new Map((u.data??[]).map(e=>[e.id,e.name])),[u.data]),p=e=>d.mutateAsync({seriesIds:[...e]});if(!i||l.status===`pending`)return null;if(l.status===`error`)return n(F,{variant:`warning`,title:a(`history.orphans.checkFailedTitle`,`Could not check for unlinked series`),message:l.error.message,onRetry:()=>void l.refetch()});let m=l.data;if(m.series.length===0&&!s)return null;let h=m.series.length;return e(o,{children:[h>0&&n(F,{variant:`warning`,message:m.truncated?a(`history.orphans.noticeMore`,{count:h,defaultValue_one:`More than {{count}} series are no longer linked to a device.`,defaultValue_other:`More than {{count}} series are no longer linked to a device.`}):a(`history.orphans.notice`,{count:h,defaultValue_one:`{{count}} series is no longer linked to a device.`,defaultValue_other:`{{count}} series are no longer linked to a device.`}),action:n(L,{size:`sm`,variant:`outline`,onClick:()=>c(!0),children:a(`history.orphans.review`,`Review`)})}),n(We,{open:s,onClose:()=>c(!1),list:m,deviceNames:f,onDelete:p,onRefresh:()=>void l.refetch(),refreshing:l.isFetching})]})}i();var qe=`device`,Je=`node`;function Ye({catalog:r,selected:i,onChange:a,loading:o}){let{t:s}=H(),c=I(),l=k(),u=e=>W(e,c,l),d=le(r,{searchText:e=>[Oe(e)],facetGroups:[{id:`subject`,value:e=>e.ref.subject.kind===`device`?qe:Je},{id:`room`,value:e=>e.location},{id:`unit`,value:e=>e.info.unit??``}]}),f=t(()=>[{key:`metric`,header:s(`history.picker.series`,`Series`),render:t=>e(`div`,{className:`min-w-0`,children:[n(`div`,{className:`truncate text-foreground`,children:t.metric}),n(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:t.location===``?u(t):`${u(t)} · ${t.location}`})]}),sortValue:e=>`${e.subjectName} ${e.metric}`},{key:`unit`,header:s(`history.picker.unit`,`Unit`),render:e=>n(`span`,{className:`text-foreground-muted`,children:e.info.unit??`—`}),sortValue:e=>e.info.unit??``}],[s,c,l]),p=i.size>=24;return e(`div`,{className:`space-y-2 min-w-0`,children:[n(ye,{state:d.state,facets:[],groups:[{...d.groups.find(e=>e.id===`subject`)??{id:`subject`,facets:[],selected:[]},label:s(`history.picker.subject`,`Source`),facetLabel:e=>e===qe?s(`history.picker.devices`,`Devices`):s(`history.picker.nodes`,`Nodes`)},{...d.groups.find(e=>e.id===`room`)??{id:`room`,facets:[],selected:[]},label:s(`history.picker.room`,`Room`),facetLabel:e=>e===``?s(`history.picker.noRoom`,`No room`):e},{...d.groups.find(e=>e.id===`unit`)??{id:`unit`,facets:[],selected:[]},label:s(`history.picker.metricType`,`Unit`),facetLabel:e=>e===``?s(`history.picker.noUnit`,`States & counts`):e}],labels:{searchPlaceholder:s(`history.picker.search`,`Search device, room, metric or node…`),searchLabel:s(`history.picker.searchLabel`,`Search series`),facetsLabel:s(`history.picker.facets`,`Filters`),clearLabel:s(`history.picker.clear`,`Clear`)},onSearch:d.setSearch,onToggleFacet:d.toggleFacet,onToggleGroupFacet:d.toggleGroupFacet,onClear:d.clear}),n(`p`,{className:`text-[10px] text-foreground-subtle`,"aria-live":`polite`,children:s(`history.picker.count`,`{{count}} of {{max}} selected`,{count:i.size,max:24})}),n(P,{columns:f,rows:d.rows,rowKey:e=>e.id,maxBodyHeight:S,pageSize:50,defaultSort:{columnKey:`metric`,dir:`asc`},emptyMessage:o?s(`history.picker.loading`,`Reading the series of every device…`):d.active?s(`history.picker.emptyFiltered`,`No series match these filters.`):s(`history.picker.empty`,`Nothing is recorded yet.`),selection:{selected:i,onChange:e=>{let t=[...e].filter(e=>i.has(e)),n=[...e].filter(e=>!i.has(e));a(new Set([...t,...n].slice(0,24)))},isSelectable:e=>i.has(e.id)||!p,rowLabel:e=>`${u(e)} · ${e.metric}`,pageLabel:s(`history.picker.selectPage`,`Select every series on this page`)}})]})}i();var Xe=new Set([y.Hub,y.Container]),$=5*6e4;function Ze(){let{t:r}=H(),i=E(`device-history`),[a,o]=Te(),s=t(()=>R(a.getAll(`s`).flatMap(e=>{let t=ie(e);return t===null?[]:[t]})),[a]),c=a.get(`window`),d=me(c)?c:`7d`,f=he(a.get(`range`)),h=(e,t,n)=>{let r=new URLSearchParams;for(let t of R(e))r.append(`s`,Ce(t));t!==`7d`&&r.set(`window`,t);let i=n===void 0?a.get(`range`):n;t===`custom`&&i&&r.set(`range`,i),o(r,{replace:!0})},v=Qe(i===`present`),y=A(d,Date.now(),f),S=A(d,oe(Date.now(),y.to-y.from),f),C=t(()=>Ne(s,v.candidates),[s,v.candidates]),w=t(()=>new Set(s.map(V)),[s]),T=Se(),D=u(),k=g(),ee=async()=>{let e=await D({title:r(`history.page.saveTitle`,`Save as panel`),label:r(`history.page.saveName`,`Panel name`),confirmLabel:r(`history.page.save`,`Save`)});e===null||e.trim()===``||await T.update(t=>re(t,{id:`panel-${Date.now().toString(36)}`,name:e.trim().slice(0,80),window:d,selection:[...s]}))},j=async(e,t)=>{await k({title:r(`history.page.deleteTitle`,`Delete panel`),message:r(`history.page.deleteMessage`,`The panel "{{name}}" is removed from your account.`,{name:t}),confirmLabel:r(`history.page.delete`,`Delete`),variant:`danger`})&&await T.update(t=>x(t,e))},M=e=>e===`energy`?r(`history.panels.energy`,`Total energy`):e===`temperatures`?r(`history.panels.temperatures`,`Temperatures by room`):e===`nodes`?r(`history.panels.nodes`,`Cluster nodes`):r(`history.panels.storage`,`Storage locations`);return n(Ee,{icon:m,title:r(`history.page.title`,`History`),subtitle:r(`history.page.subtitle`,`What devices, nodes and storage recorded over time, side by side.`),actions:i===`present`?e(L,{size:`sm`,variant:`outline`,onClick:()=>void ee(),disabled:s.length===0||!T.writable,children:[n(_,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),r(`history.page.saveTitle`,`Save as panel`)]}):void 0,children:i===`pending`?n(N,{className:`h-64 w-full`}):i===`unknown`?n(F,{title:r(`history.page.presenceUnknownTitle`,`Could not reach the hub`),message:r(`history.page.presenceUnknown`,`The hub did not say whether device history is installed. Try again in a moment.`)}):i===`absent`?n(O,{icon:l,title:r(`history.page.absentTitle`,`Device history is not running on this hub`),description:r(`history.page.absent`,`Nothing is recorded until the device-history system addon is enabled.`)}):e(`div`,{className:`space-y-3 sm:space-y-4`,children:[n(Ke,{enabled:i===`present`}),e(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":r(`history.page.panels`,`Panels`),children:[ke.map(e=>n(L,{size:`sm`,variant:`outline`,disabled:v.status!==`ok`,onClick:()=>h(Me(e,v.candidates),d),children:M(e)},e)),T.value.panels.map(t=>e(`span`,{className:`inline-flex items-center`,children:[n(L,{size:`sm`,variant:`secondary`,onClick:()=>h(t.selection,t.window,null),children:t.name}),n(L,{size:`sm`,variant:`ghost`,"aria-label":r(`history.page.deleteNamed`,`Delete panel {{name}}`,{name:t.name}),onClick:()=>void j(t.id,t.name),disabled:!T.writable,children:n(p,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]},t.id))]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:gap-4 xl:grid-cols-5`,children:[n(`div`,{className:`min-w-0 xl:col-span-2`,children:n(z,{headingId:`history-picker`,title:r(`history.picker.title`,`Series`),children:n(`div`,{className:`p-2 sm:p-3`,children:v.status===`error`?n(F,{message:v.error}):n(Ye,{catalog:v.candidates,loading:v.status===`pending`,selected:w,onChange:e=>{let t=s.filter(t=>e.has(V(t))),n=v.candidates.filter(t=>e.has(t.id)&&!w.has(t.id)).map(e=>e.ref);h([...t,...n],d)}})})})}),n(`div`,{className:`min-w-0 xl:col-span-3`,children:n(z,{headingId:`history-overlay`,title:r(`history.page.overlay`,`Overlay`),actions:s.length>0?n(L,{size:`sm`,variant:`ghost`,onClick:()=>h([],d),children:r(`history.page.clear`,`Clear`)}):void 0,children:e(`div`,{className:`p-2 sm:p-3 space-y-3 min-w-0`,children:[n(fe,{value:d,onChange:e=>h(s,e),custom:f,onCustomChange:e=>h(s,`custom`,b(e))}),v.status===`pending`&&s.length>0?n(N,{className:`h-64 w-full`}):n(Pe,{part:C,window:S}),C.missing.length>0&&v.status===`ok`&&n(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`history.page.missing`,{count:C.missing.length,defaultValue_one:`{{count}} selected series is no longer recorded.`,defaultValue_other:`{{count}} selected series are no longer recorded.`})})]})})})]})]})})}function Qe(e){let{t:n}=H(),r=n(`history.picker.wholeFrame`,`Whole frame`),i=d().trpcClient,o=T({projection:`slim`},{enabled:e}),{nodes:s}=ee(),c=t(()=>(o.data??[]).filter(e=>!Xe.has(String(e.type))),[o.data]),l=a({queries:c.map(t=>({queryKey:[`device-history`,`listSeries`,t.id],queryFn:()=>i.deviceHistory.listSeries.query({deviceId:t.id}),enabled:e,staleTime:$}))}),u=a({queries:s.map(t=>({queryKey:[`device-history`,`listNodeSeries`,t.id],queryFn:()=>i.deviceHistory.listNodeSeries.query({forNodeId:t.id}),enabled:e,staleTime:$}))}),f=ge({},{enabled:e,staleTime:$}),p=t(()=>new Map((f?.data??[]).map(e=>[e.id,e.displayName])),[f?.data]),m=l.map(e=>e.data),h=u.map(e=>e.data),g=t(()=>De(c.flatMap((e,t)=>{let n=m[t];return n===void 0?[]:[{device:{id:e.id,name:e.name,location:e.location??null},series:n}]}),s.flatMap((e,t)=>{let n=h[t];return n===void 0?[]:[{node:{id:e.id,name:e.name},series:n}]}),e=>{if(e.key!==`addon:pipeline-analytics/occupancy`)return p.get(e.scope)??e.scope;let{zoneId:t,className:n}=v(e.scope),i=t===``?r:t;return n===void 0?i:`${i} · ${n}`}),[c,s,p,[...l,...u].map(e=>e.dataUpdatedAt).join(`,`),r]);return o.status===`error`?{status:`error`,error:o.error.message,candidates:[]}:{status:o.status===`pending`||l.some(e=>e.isPending)||u.some(e=>e.isPending)?`pending`:`ok`,error:``,candidates:g}}export{Ze as HistoryPage};
1
+ import{C as e,K as t,S as n,Y as r,et as i,i as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{En as s,Ht as c,Tr as l,ct as u,dt as d,fr as f,gt as p,ki as m,pa as h,st as g,xn as _}from"./player-overlays-B4lehTI4.js";import{_r as v,la as y}from"./client-C6c46gRD.js";import{A as b,C as x,Cn as S,Cr as C,D as w,Do as T,Dr as E,E as D,Er as O,Lr as k,M as A,Md as ee,N as j,O as M,Or as N,P as te,Pr as ne,S as re,Sn as P,Tr as F,Vr as I,Yr as L,_ as ie,_r as ae,b as R,bn as z,d as oe,dr as se,f as ce,fn as le,fr as ue,gr as de,h as fe,hr as pe,j as me,k as he,lu as ge,m as _e,no as ve,pn as ye,pr as be,ri as B,to as xe,u as Se,v as Ce,w as we,x as V}from"./src-DY9QaWNW.js";import{t as H}from"./useTranslation-BJr-n0es.js";import{yr as Te}from"./index-Dm-ruGxs.js";import{t as Ee}from"./AdminPage-aCyydhgN.js";i();function U(e,t){return e.scope===``?e.displayName:`${e.displayName} · ${t?.(e)??e.scope}`}function De(e,t,n){let r=[];for(let{device:t,series:i}of e)for(let e of i){let i={subject:{kind:`device`,deviceId:t.id},key:e.key,scope:e.scope};r.push({id:V(i),ref:i,info:e,subjectName:t.name,location:t.location??``,nodeId:``,metric:U(e,n)})}for(let{node:e,series:i}of t)for(let t of i){let i={subject:{kind:`node`,nodeId:e.id},key:t.key,scope:t.scope};r.push({id:V(i),ref:i,info:t,subjectName:e.name,location:``,nodeId:e.id,metric:U(t,n)})}return r}function Oe(e){return[e.subjectName,e.location,e.metric,e.info.key,e.info.unit??``,e.nodeId].join(` `)}function W(e,t,n){if(e.ref.subject.kind!==`device`||t===null)return e.subjectName;let r=t.byId.get(e.ref.subject.deviceId);return r===void 0?e.subjectName:ne(r,`compact`,t,n)}var ke=[`energy`,`temperatures`,`nodes`,`storage`],Ae=new Set([`cap:temperature-sensor.temperature`,`cap:climate-control.currentTemp`]),G=[`addon:metrics-native/node-cpu-percent`,`addon:metrics-native/node-memory-percent`],je=`addon:storage-orchestrator/location-used-percent`;function Me(e,t){let n=(e,n)=>{let r=t.filter(e);return R((n?[...r].sort(n):r).map(e=>e.ref))};switch(e){case`energy`:return n(e=>e.ref.subject.kind===`device`&&e.info.key===`derived:energy.kwh`);case`temperatures`:return n(e=>e.ref.subject.kind===`device`&&Ae.has(e.info.key)&&e.info.scope===``,(e,t)=>e.location.localeCompare(t.location)||e.subjectName.localeCompare(t.subjectName));case`nodes`:return n(e=>e.ref.subject.kind===`node`&&G.includes(e.info.key)&&e.info.scope===``,(e,t)=>G.indexOf(e.info.key)-G.indexOf(t.info.key)||e.subjectName.localeCompare(t.subjectName));case`storage`:return n(e=>e.ref.subject.kind===`node`&&e.info.key===je)}}function Ne(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=[],a=[],o=[];for(let t of R(e)){let e=n.get(V(t));if(e===void 0){o.push(t);continue}e.info.key===`derived:energy.kwh`?a.push(e):e.info.kind===`boolean`||e.info.kind===`enum`?i.push(e):r.push(e)}return{lines:r,states:i,energy:a,missing:o}}function K(e){return e.subject.kind===`device`?{deviceId:e.subject.deviceId,key:e.key,scope:e.scope}:{forNodeId:e.subject.nodeId,key:e.key,scope:e.scope}}var q=`history-page`;function Pe({part:r,window:i}){let{t:a}=H(),o=h(),s=I(),c=k(),l=e=>`${W(e,s,c)} · ${e.metric}`,u=t(()=>[...r.lines,...r.states,...r.energy],[r]),d=_e(t(()=>u.map(e=>K(e.ref)),[u]),i,!1),f=e=>d.status===`ok`?d.data.current.get(ce(K(e.ref))):void 0,p=e=>{let t=f(e);return t?.ok?t.result:void 0};if(u.length===0)return n(O,{icon:m,title:a(`history.page.emptyTitle`,`Pick series to compare`),description:a(`history.page.emptyHint`,`Choose up to 24 series on the left, or start from a panel above.`)});if(d.status===`error`)return n(F,{title:a(`history.page.readFailed`,`History could not be read`),message:d.error});let g=d.status===`pending`,_=u.map(e=>({c:e,e:f(e)})).filter(e=>e.e?.ok===!1),v=r.lines.map((e,t)=>{let n=p(e),r=w(e.info,n,i.from);return{id:e.id,label:l(e),unit:e.info.unit,colorIndex:t,points:r.points,gapMs:r.gapMs,interpolation:r.held&&n?.resolution===`raw`?`step`:`linear`}}),y=r.states.map((e,t)=>{let n=M(e.info,p(e),i.from,i.to),r=we(e.info.key,o);return{id:e.id,label:l(e),kind:e.info.kind===`boolean`?`boolean`:`enum`,colorIndex:e.info.kind===`boolean`?t:0,states:n.states,segments:n.segments,totals:n.totals,stateLabel:e.info.kind===`boolean`?e=>e===`true`?r.on:r.off:void 0}}),b=r.energy.map(e=>({c:e,...D(p(e))})),x=b[0]?.bucketMs??36e5,S=[...new Set(b.flatMap(e=>e.buckets.map(e=>e.t)))].sort((e,t)=>e-t).map(e=>({t:e,values:b.map(t=>t.buckets.find(t=>t.t===e)?.values[0]??null)}));return e(`div`,{className:`space-y-5 min-w-0`,children:[_.length>0&&n(F,{title:a(`history.page.someFailed`,`Some series could not be read`),message:_.map(e=>`${l(e.c)}: ${e.e.error}`).join(` · `)}),v.length>0&&n(te,{title:a(`history.page.lines`,`Measurements`),series:v,range:i,height:260,syncKey:q,pending:g}),b.length>0&&n(C,{title:a(`history.page.energy`,`Energy`),layers:b.map((e,t)=>({id:e.c.id,label:W(e.c,s,c),colorIndex:t})),buckets:S,bucketMs:x,range:i,unit:`kWh`,showTotal:!0,height:160,syncKey:q,pending:g}),y.length>0&&n(j,{title:y.length===1?y[0]?.label??``:a(`history.page.states`,`States`),rows:y,range:i,syncKey:q,pending:g})]})}function Fe(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function Ie(e,t){let n=[];for(let r of Fe(e,50))try{let{results:e}=await t(r),i=new Map(e.map(e=>[e.seriesId,e]));for(let e of r)n.push(i.get(e)??{seriesId:e,ok:!1,reason:`not-found`})}catch(e){let t=e instanceof Error?e.message:String(e);for(let e of r)n.push({seriesId:e,ok:!1,reason:`request-failed`,message:t})}return n}function J(e){return e.raw+e[`5m`]+e[`1h`]+e[`1d`]}function Le(e){return e.reduce((e,t)=>t.ok?{...e,deleted:e.deleted+1,points:e.points+J(t.deleted)}:{...e,refused:e.refused+1},{deleted:0,refused:0,points:0})}function Re(e,t){let n=new Map(e.map(e=>[e.seriesId,e]));return t.flatMap(e=>{let t=n.get(e.seriesId);return t===void 0?[]:[{series:t,outcome:e}]})}var Y=e=>new Date(e).toLocaleDateString(void 0,{dateStyle:`short`});function X(e,t,n){let r=t.get(e.deviceId);return r===void 0?e.reason===`device-gone`?n(`history.orphans.deviceRemoved`,`#{{id}} (removed)`,{id:e.deviceId}):n(`history.orphans.deviceId`,`#{{id}}`,{id:e.deviceId}):r}function Z(e){let t=e.displayName??e.key;return e.scope===``?t:`${t} · ${e.scope}`}function Q(t,r,i){return{key:`series`,header:i(`history.orphans.colSeries`,`Series`),render:a=>{let o=t(a);return e(`div`,{className:`min-w-0 max-w-[16rem]`,children:[n(`div`,{className:`truncate text-foreground`,title:o.key,children:Z(o)}),n(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:X(o,r,i)})]})},sortValue:e=>`${X(t(e),r,i)} ${Z(t(e))}`}}var ze=[`raw`,`5m`,`1h`,`1d`];function Be(e,t){return e===`raw`?t(`history.orphans.colRaw`,`Raw points`):e===`5m`?t(`history.orphans.col5m`,`5 min`):e===`1h`?t(`history.orphans.col1h`,`1 h`):t(`history.orphans.col1d`,`1 day`)}function Ve(t,r){return[Q(e=>e,t,r),{key:`reason`,header:r(`history.orphans.colReason`,`Reason`),render:t=>e(`div`,{className:`flex flex-col items-start gap-0.5`,children:[n(B,{variant:t.reason===`device-gone`?`warning`:`neutral`,className:`text-[10px]`,children:t.reason===`device-gone`?r(`history.orphans.deviceGone`,`Device removed`):r(`history.orphans.undeclared`,`No longer declared`)}),t.missingSince!==null&&n(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`history.orphans.since`,`since {{date}}`,{date:Y(t.missingSince)})})]}),sortValue:e=>e.reason},{key:`span`,header:r(`history.orphans.colSpan`,`Recorded`),render:t=>e(`span`,{className:`tabular-nums text-foreground-muted`,children:[Y(t.firstTs),` → `,Y(t.lastTs)]}),sortValue:e=>e.lastTs},...ze.map(e=>({key:`rows-${e}`,header:Be(e,r),align:`right`,render:t=>n(`span`,{className:`tabular-nums text-foreground-muted`,children:t.rows[e].toLocaleString()}),sortValue:t=>t.rows[e]}))]}function He(e,t){if(e.ok)return n(B,{variant:`success`,className:`text-[10px]`,children:t(`history.orphans.deleted`,{count:J(e.deleted),points:J(e.deleted).toLocaleString(),defaultValue_one:`Deleted · {{points}} point`,defaultValue_other:`Deleted · {{points}} points`})});let r=e.reason===`request-failed`?t(`history.orphans.requestFailed`,`Not sent: {{message}}`,{message:e.message}):e.reason===`not-orphan`?t(`history.orphans.refusedNotOrphan`,`Kept: no longer orphan`):e.reason===`not-found`?t(`history.orphans.refusedNotFound`,`Already gone`):t(`history.orphans.refusedFailed`,`The hub could not delete it`);return n(B,{variant:e.reason===`not-found`?`neutral`:`warning`,className:`text-[10px]`,children:r})}function Ue(e,t){return[Q(e=>e.series,e,t),{key:`result`,header:t(`history.orphans.colResult`,`Result`),render:e=>He(e.outcome,t),sortValue:e=>+!e.outcome.ok}]}i();function We({open:i,onClose:a,list:o,deviceNames:l,onDelete:u,onRefresh:d,refreshing:p}){let{t:m}=H(),h=g(),[_,v]=r(new Set),[y,b]=r(!1),[x,C]=r([]),w=t(()=>Ve(l,m),[l,m]),T=t(()=>Ue(l,m),[l,m]),E=t(()=>new Set(o.series.map(e=>String(e.seriesId))),[o.series]),D=[..._].filter(e=>E.has(e)).map(Number),O=Le(x.map(e=>e.outcome)),k=async()=>{if(await h({title:m(`history.orphans.confirmTitle`,{count:D.length,defaultValue_one:`Delete {{count}} series`,defaultValue_other:`Delete {{count}} series`}),message:m(`history.orphans.confirmMessage`,`Every recorded point of these series is removed from the hub. This cannot be undone.`),confirmLabel:m(`history.orphans.confirmLabel`,`Delete`),variant:`danger`})){b(!0);try{let e=await Ie(D,u);C(Re(o.series,e)),v(new Set)}finally{b(!1),d()}}};return n(se,{open:i,onOpenChange:e=>!e&&a(),children:e(be,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`orphan-series-dialog`,children:[n(de,{children:n(ae,{children:m(`history.orphans.title`,`Series no longer linked to a device`)})}),e(ue,{className:`space-y-3`,children:[n(`p`,{className:`text-xs text-foreground-muted`,children:m(`history.orphans.intro`,`Nothing records into these series any more: their device was removed, or no capability declares them now. Select the ones to delete.`)}),o.truncated&&e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`orphan-truncated`,children:[n(`p`,{className:`text-xs text-warning`,children:m(`history.orphans.truncated`,`More series are unlinked than are listed here. Delete these, then load the rest.`)}),e(L,{size:`sm`,variant:`outline`,onClick:d,disabled:p,children:[n(s,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.loadAgain`,`Load again`)]})]}),x.length>0&&e(`div`,{className:`space-y-2`,"data-testid":`orphan-outcomes`,children:[n(`p`,{className:`text-xs text-foreground`,"aria-live":`polite`,children:m(`history.orphans.summary`,{count:O.deleted,refused:O.refused,points:O.points.toLocaleString(),defaultValue_one:`{{count}} series deleted ({{points}} points), {{refused}} kept.`,defaultValue_other:`{{count}} series deleted ({{points}} points), {{refused}} kept.`})}),n(P,{columns:T,rows:x,rowKey:e=>String(e.series.seriesId),minWidthPx:420,maxBodyHeight:`max-h-[60vh]`,emptyMessage:``})]}),n(P,{columns:w,rows:o.series,rowKey:e=>String(e.seriesId),minWidthPx:760,maxBodyHeight:S,defaultSort:{columnKey:`series`,dir:`asc`},emptyMessage:m(`history.orphans.empty`,`Every series is linked to a device.`),selection:{selected:_,onChange:v,rowLabel:e=>`${Z(e)} — ${X(e,l,m)}`,pageLabel:m(`history.orphans.selectAll`,`Select every listed series`)}})]}),e(pe,{children:[n(`span`,{className:`mr-auto text-[11px] tabular-nums text-foreground`,"aria-live":`polite`,children:m(`history.orphans.selected`,{count:D.length,defaultValue_one:`{{count}} selected`,defaultValue_other:`{{count}} selected`})}),n(L,{variant:`ghost`,size:`sm`,onClick:a,children:m(`history.orphans.close`,`Close`)}),e(L,{variant:`danger`,size:`sm`,disabled:D.length===0||y,onClick:()=>void k(),children:[y?n(f,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):n(c,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.deleteSelected`,`Delete selected`)]})]})]})})}i();var Ge=5*6e4;function Ke({enabled:i}){let{t:a}=H(),[s,c]=r(!1),l=ve({},{enabled:i,staleTime:Ge}),u=T({projection:`slim`},{enabled:i}),d=xe(),f=t(()=>new Map((u.data??[]).map(e=>[e.id,e.name])),[u.data]),p=e=>d.mutateAsync({seriesIds:[...e]});if(!i||l.status===`pending`)return null;if(l.status===`error`)return n(F,{variant:`warning`,title:a(`history.orphans.checkFailedTitle`,`Could not check for unlinked series`),message:l.error.message,onRetry:()=>void l.refetch()});let m=l.data;if(m.series.length===0&&!s)return null;let h=m.series.length;return e(o,{children:[h>0&&n(F,{variant:`warning`,message:m.truncated?a(`history.orphans.noticeMore`,{count:h,defaultValue_one:`More than {{count}} series are no longer linked to a device.`,defaultValue_other:`More than {{count}} series are no longer linked to a device.`}):a(`history.orphans.notice`,{count:h,defaultValue_one:`{{count}} series is no longer linked to a device.`,defaultValue_other:`{{count}} series are no longer linked to a device.`}),action:n(L,{size:`sm`,variant:`outline`,onClick:()=>c(!0),children:a(`history.orphans.review`,`Review`)})}),n(We,{open:s,onClose:()=>c(!1),list:m,deviceNames:f,onDelete:p,onRefresh:()=>void l.refetch(),refreshing:l.isFetching})]})}i();var qe=`device`,Je=`node`;function Ye({catalog:r,selected:i,onChange:a,loading:o}){let{t:s}=H(),c=I(),l=k(),u=e=>W(e,c,l),d=le(r,{searchText:e=>[Oe(e)],facetGroups:[{id:`subject`,value:e=>e.ref.subject.kind===`device`?qe:Je},{id:`room`,value:e=>e.location},{id:`unit`,value:e=>e.info.unit??``}]}),f=t(()=>[{key:`metric`,header:s(`history.picker.series`,`Series`),render:t=>e(`div`,{className:`min-w-0`,children:[n(`div`,{className:`truncate text-foreground`,children:t.metric}),n(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:t.location===``?u(t):`${u(t)} · ${t.location}`})]}),sortValue:e=>`${e.subjectName} ${e.metric}`},{key:`unit`,header:s(`history.picker.unit`,`Unit`),render:e=>n(`span`,{className:`text-foreground-muted`,children:e.info.unit??`—`}),sortValue:e=>e.info.unit??``}],[s,c,l]),p=i.size>=24;return e(`div`,{className:`space-y-2 min-w-0`,children:[n(ye,{state:d.state,facets:[],groups:[{...d.groups.find(e=>e.id===`subject`)??{id:`subject`,facets:[],selected:[]},label:s(`history.picker.subject`,`Source`),facetLabel:e=>e===qe?s(`history.picker.devices`,`Devices`):s(`history.picker.nodes`,`Nodes`)},{...d.groups.find(e=>e.id===`room`)??{id:`room`,facets:[],selected:[]},label:s(`history.picker.room`,`Room`),facetLabel:e=>e===``?s(`history.picker.noRoom`,`No room`):e},{...d.groups.find(e=>e.id===`unit`)??{id:`unit`,facets:[],selected:[]},label:s(`history.picker.metricType`,`Unit`),facetLabel:e=>e===``?s(`history.picker.noUnit`,`States & counts`):e}],labels:{searchPlaceholder:s(`history.picker.search`,`Search device, room, metric or node…`),searchLabel:s(`history.picker.searchLabel`,`Search series`),facetsLabel:s(`history.picker.facets`,`Filters`),clearLabel:s(`history.picker.clear`,`Clear`)},onSearch:d.setSearch,onToggleFacet:d.toggleFacet,onToggleGroupFacet:d.toggleGroupFacet,onClear:d.clear}),n(`p`,{className:`text-[10px] text-foreground-subtle`,"aria-live":`polite`,children:s(`history.picker.count`,`{{count}} of {{max}} selected`,{count:i.size,max:24})}),n(P,{columns:f,rows:d.rows,rowKey:e=>e.id,maxBodyHeight:S,pageSize:50,defaultSort:{columnKey:`metric`,dir:`asc`},emptyMessage:o?s(`history.picker.loading`,`Reading the series of every device…`):d.active?s(`history.picker.emptyFiltered`,`No series match these filters.`):s(`history.picker.empty`,`Nothing is recorded yet.`),selection:{selected:i,onChange:e=>{let t=[...e].filter(e=>i.has(e)),n=[...e].filter(e=>!i.has(e));a(new Set([...t,...n].slice(0,24)))},isSelectable:e=>i.has(e.id)||!p,rowLabel:e=>`${u(e)} · ${e.metric}`,pageLabel:s(`history.picker.selectPage`,`Select every series on this page`)}})]})}i();var Xe=new Set([y.Hub,y.Container]),$=5*6e4;function Ze(){let{t:r}=H(),i=E(`device-history`),[a,o]=Te(),s=t(()=>R(a.getAll(`s`).flatMap(e=>{let t=ie(e);return t===null?[]:[t]})),[a]),c=a.get(`window`),d=me(c)?c:`7d`,f=he(a.get(`range`)),h=(e,t,n)=>{let r=new URLSearchParams;for(let t of R(e))r.append(`s`,Ce(t));t!==`7d`&&r.set(`window`,t);let i=n===void 0?a.get(`range`):n;t===`custom`&&i&&r.set(`range`,i),o(r,{replace:!0})},v=Qe(i===`present`),y=A(d,Date.now(),f),S=A(d,oe(Date.now(),y.to-y.from),f),C=t(()=>Ne(s,v.candidates),[s,v.candidates]),w=t(()=>new Set(s.map(V)),[s]),T=Se(),D=u(),k=g(),ee=async()=>{let e=await D({title:r(`history.page.saveTitle`,`Save as panel`),label:r(`history.page.saveName`,`Panel name`),confirmLabel:r(`history.page.save`,`Save`)});e===null||e.trim()===``||await T.update(t=>re(t,{id:`panel-${Date.now().toString(36)}`,name:e.trim().slice(0,80),window:d,selection:[...s]}))},j=async(e,t)=>{await k({title:r(`history.page.deleteTitle`,`Delete panel`),message:r(`history.page.deleteMessage`,`The panel "{{name}}" is removed from your account.`,{name:t}),confirmLabel:r(`history.page.delete`,`Delete`),variant:`danger`})&&await T.update(t=>x(t,e))},M=e=>e===`energy`?r(`history.panels.energy`,`Total energy`):e===`temperatures`?r(`history.panels.temperatures`,`Temperatures by room`):e===`nodes`?r(`history.panels.nodes`,`Cluster nodes`):r(`history.panels.storage`,`Storage locations`);return n(Ee,{icon:m,title:r(`history.page.title`,`History`),subtitle:r(`history.page.subtitle`,`What devices, nodes and storage recorded over time, side by side.`),actions:i===`present`?e(L,{size:`sm`,variant:`outline`,onClick:()=>void ee(),disabled:s.length===0||!T.writable,children:[n(_,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),r(`history.page.saveTitle`,`Save as panel`)]}):void 0,children:i===`pending`?n(N,{className:`h-64 w-full`}):i===`unknown`?n(F,{title:r(`history.page.presenceUnknownTitle`,`Could not reach the hub`),message:r(`history.page.presenceUnknown`,`The hub did not say whether device history is installed. Try again in a moment.`)}):i===`absent`?n(O,{icon:l,title:r(`history.page.absentTitle`,`Device history is not running on this hub`),description:r(`history.page.absent`,`Nothing is recorded until the device-history system addon is enabled.`)}):e(`div`,{className:`space-y-3 sm:space-y-4`,children:[n(Ke,{enabled:i===`present`}),e(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":r(`history.page.panels`,`Panels`),children:[ke.map(e=>n(L,{size:`sm`,variant:`outline`,disabled:v.status!==`ok`,onClick:()=>h(Me(e,v.candidates),d),children:M(e)},e)),T.value.panels.map(t=>e(`span`,{className:`inline-flex items-center`,children:[n(L,{size:`sm`,variant:`secondary`,onClick:()=>h(t.selection,t.window,null),children:t.name}),n(L,{size:`sm`,variant:`ghost`,"aria-label":r(`history.page.deleteNamed`,`Delete panel {{name}}`,{name:t.name}),onClick:()=>void j(t.id,t.name),disabled:!T.writable,children:n(p,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]},t.id))]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:gap-4 xl:grid-cols-5`,children:[n(`div`,{className:`min-w-0 xl:col-span-2`,children:n(z,{headingId:`history-picker`,title:r(`history.picker.title`,`Series`),children:n(`div`,{className:`p-2 sm:p-3`,children:v.status===`error`?n(F,{message:v.error}):n(Ye,{catalog:v.candidates,loading:v.status===`pending`,selected:w,onChange:e=>{let t=s.filter(t=>e.has(V(t))),n=v.candidates.filter(t=>e.has(t.id)&&!w.has(t.id)).map(e=>e.ref);h([...t,...n],d)}})})})}),n(`div`,{className:`min-w-0 xl:col-span-3`,children:n(z,{headingId:`history-overlay`,title:r(`history.page.overlay`,`Overlay`),actions:s.length>0?n(L,{size:`sm`,variant:`ghost`,onClick:()=>h([],d),children:r(`history.page.clear`,`Clear`)}):void 0,children:e(`div`,{className:`p-2 sm:p-3 space-y-3 min-w-0`,children:[n(fe,{value:d,onChange:e=>h(s,e),custom:f,onCustomChange:e=>h(s,`custom`,b(e))}),v.status===`pending`&&s.length>0?n(N,{className:`h-64 w-full`}):n(Pe,{part:C,window:S}),C.missing.length>0&&v.status===`ok`&&n(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`history.page.missing`,{count:C.missing.length,defaultValue_one:`{{count}} selected series is no longer recorded.`,defaultValue_other:`{{count}} selected series are no longer recorded.`})})]})})})]})]})})}function Qe(e){let{t:n}=H(),r=n(`history.picker.wholeFrame`,`Whole frame`),i=d().trpcClient,o=T({projection:`slim`},{enabled:e}),{nodes:s}=ee(),c=t(()=>(o.data??[]).filter(e=>!Xe.has(String(e.type))),[o.data]),l=a({queries:c.map(t=>({queryKey:[`device-history`,`listSeries`,t.id],queryFn:()=>i.deviceHistory.listSeries.query({deviceId:t.id}),enabled:e,staleTime:$}))}),u=a({queries:s.map(t=>({queryKey:[`device-history`,`listNodeSeries`,t.id],queryFn:()=>i.deviceHistory.listNodeSeries.query({forNodeId:t.id}),enabled:e,staleTime:$}))}),f=ge({},{enabled:e,staleTime:$}),p=t(()=>new Map((f?.data??[]).map(e=>[e.id,e.displayName])),[f?.data]),m=l.map(e=>e.data),h=u.map(e=>e.data),g=t(()=>De(c.flatMap((e,t)=>{let n=m[t];return n===void 0?[]:[{device:{id:e.id,name:e.name,location:e.location??null},series:n}]}),s.flatMap((e,t)=>{let n=h[t];return n===void 0?[]:[{node:{id:e.id,name:e.name},series:n}]}),e=>{if(e.key!==`addon:pipeline-analytics/occupancy`)return p.get(e.scope)??e.scope;let{zoneId:t,className:n}=v(e.scope),i=t===``?r:t;return n===void 0?i:`${i} · ${n}`}),[c,s,p,[...l,...u].map(e=>e.dataUpdatedAt).join(`,`),r]);return o.status===`error`?{status:`error`,error:o.error.message,candidates:[]}:{status:o.status===`pending`||l.some(e=>e.isPending)||u.some(e=>e.isPending)?`pending`:`ok`,error:``,candidates:g}}export{Ze as HistoryPage};
@@ -1 +1 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{D as f,En as p,Fn as m,Ht as h,Vn as g,Wr as _,Xr as v,Zi as y,_n as b,an as x,bi as S,br as C,ct as w,dn as T,dt as E,fr as D,gt as O,hr as k,jt as A,lr as ee,mn as j,pn as M,st as N,yn as P,zt as F}from"./player-overlays-B4lehTI4.js";import{Qa as I,Xa as L,Za as R,da as te,s as ne,ua as z}from"./client-C6c46gRD.js";import{i as B,n as re,r as ie,t as ae}from"./key-B1puhv1a.js";import{d as oe,l as se,s as ce}from"./video-B-2RwuDj.js";import{t as le}from"./key-round-DmUg5DWL.js";import{t as ue}from"./monitor-smartphone-DJqsZ1_F.js";import{t as de}from"./unlink-Chgtl9c5.js";import{$u as fe,Bn as pe,Cn as me,Do as V,Er as he,Fi as H,Hn as ge,Ju as _e,Ld as U,Or as ve,Pi as ye,Qs as be,Qu as xe,R as Se,Rn as Ce,Sn as we,Tr as W,Un as Te,Vn as Ee,Wn as De,Xu as Oe,Yr as G,Ys as ke,Yu as Ae,Zu as je,_r as Me,ad as Ne,bn as Pe,dd as Fe,dr as Ie,ed as Le,fd as Re,fr as ze,ft as Be,gd as Ve,gr as He,hd as Ue,hn as We,hr as Ge,id as Ke,lr as qe,md as Je,mn as Ye,mt as Xe,nc as Ze,nd as Qe,or as $e,pd as et,pr as tt,qs as nt,rd as rt,ri as K,rt as it,tc as at,td as ot,xn as q,xt as st}from"./src-DlnTixq9.js";import{t as J}from"./i18n-uD14huY2.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{S as ct,a as lt,d as ut,dr as dt,er as ft,fr as pt,gr as mt,i as ht,l as gt,mr as _t,ur as vt}from"./index-pzq9LOji.js";import{t as yt}from"./AdminSectionedPage-OHmEcMxM.js";import{t as bt}from"./AdminPage-Bn1s1Zyw.js";import{A as xt,C as St,D as Ct,E as wt,O as X,S as Tt,T as Et,a as Dt,b as Ot,c as kt,d as At,f as jt,g as Mt,h as Nt,i as Pt,k as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,s as Vt,t as Ht,u as Ut,v as Wt,w as Gt,x as Kt,y as qt}from"./SessionsList-_-3LQsWm.js";import{i as Jt,n as Yt,r as Xt,t as Zt}from"./IntegrationHub-DXhDIgkG.js";import{n as Qt,t as $t}from"./addon-display-names-BkwMrExv.js";c();function en(){let{t:e}=Y(),t=N(),r=U.useUtils(),a=xt(),{data:s,isLoading:c}=Le(),l=n(()=>s??[],[s]),u=U.useQueries(e=>l.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),d=U.auth.listLoginMethods.useQuery(),[f,p]=o(null),m=Ke({onSuccess:()=>void r.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=n(()=>new Map((d.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[d.data]),g=l.flatMap((e,t)=>u[t]?.data??[]),_=g.map(e=>({...Tt(e,a),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Kt(e)===n.id);r!==void 0&&await t({title:e(`access.externalIdentitiesSection.removeSignInLink`,`Remove sign-in link`),message:e(`access.externalIdentitiesSection.willNoLongerBeAble`,`"{{ownerName}}" will no longer be able to sign in with this {{kind}} account.`,{ownerName:n.ownerName,kind:n.kind}),confirmLabel:e(`common.remove`,`Remove`),variant:`danger`})&&(p(null),m.mutate({userId:r.userId,provider:r.provider,subject:r.subject}))};return i(X,{notice:Ft(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:oe,description:e(`access.externalIdentitiesSection.externalAccountsSingleSignOn`,`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`),children:i(Et,{rows:_,label:`sign-in links`,isLoading:c||u.some(e=>e.isLoading),loadError:u.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:e(`common.remove`,`Remove`),icon:de,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}c();var tn={key:`access.nouns.linkedApp`};function nn(e){if(e.type===`category`){let t=e.target??``;return t===`device`?J.t(`access.linkedAppsSection.allDevices`):J.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function rn(){let{t:e}=Y(),t=N(),r=l(),a=fe(),[s,c]=o(null),u=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),d=Qe({onSuccess:u,onError:e=>c(`Revoke failed: ${e.message}`)}),f=wt(tn,u),p=n(()=>(a.data??[]).map(e=>St(e,e.scopes.map(nn).join(`, `))),[a.data]),m=async n=>{await t({title:e(`access.linkedAppsSection.revokeTheLink`,`Revoke the "{{name}}" link?`,{name:n.name}),message:e(`access.linkedAppsSection.losesAccessForOnIts`,`{{name}} loses access for {{ownerName}} on its next call. Linking it again needs the account-link flow from the start.`,{name:n.name,ownerName:n.ownerName}),confirmLabel:e(`access.linkedAppsSection.revoke`,`Revoke`),variant:`danger`})&&(c(null),d.mutate({id:n.id}))},g=d.isPending?d.variables?.id??null:null;return i(X,{notice:Ft(s,f.outcome),onDismissNotice:()=>{c(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:k,description:e(`access.linkedAppsSection.externalIntegrationsAlexaLinkedTo`,`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call. Already-revoked rows can be selected and removed from the list.`),children:i(Et,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:a.isLoading,loadError:a.isError?a.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:e(`access.linkedAppsSection.revoke`,`Revoke`),icon:h,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:g,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:tn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}c();var an={key:`access.nouns.session`};function on(){let{t:e}=Y(),t=N(),r=U.useUtils(),a=xt(),s=U.auth.listSessions.useQuery(),[c,l]=o(null),u=()=>void r.auth.listSessions.invalidate(),d=U.auth.revokeSessions.useMutation({onSuccess:u,onError:e=>l(`Sign out failed: ${e.message}`)}),f=wt(an,u),p=n(()=>(s.data??[]).map(e=>Gt(e,a,{client:e=>Wt(e).label,method:qt})),[s.data,a]),m=async n=>{await t({title:e(`access.loginSessionsSection.signOutThisSession`,`Sign out this session`),message:e(`access.loginSessionsSection.onWillHaveToSign`,`{{ownerName}} on {{name}} will have to sign in again.`,{ownerName:n.ownerName,name:n.name}),confirmLabel:e(`access.loginSessionsSection.signOut`,`Sign out`),variant:`danger`})&&(l(null),d.mutate({id:n.id}))};return i(X,{notice:Ft(c,f.outcome),onDismissNotice:()=>{l(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:ue,description:e(`access.loginSessionsSection.everyBrowserAndAppSigned`,`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`),children:i(Et,{rows:p,label:e(`common.sessionsLabel`),isLoading:s.isLoading,loadError:s.isError?s.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:e(`access.loginSessionsSection.signOut`,`Sign out`),icon:ce,isAvailable:e=>e.status===`active`,onRun:e=>void m(e),busyId:d.isPending&&d.variables!==void 0&&`id`in d.variables?d.variables.id:null,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:an,isSelectable:e=>e.status===`active`}})})}var sn={"by-id":`helpers.authAuditWording.bulkNoun.credential`,"share-link":`helpers.authAuditWording.bulkNoun.shareLink`,"admin-token":`helpers.authAuditWording.bulkNoun.adminToken`,"login-session":`helpers.authAuditWording.bulkNoun.loginSession`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function cn(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function ln(e){let t=Z(e,`prefix`);return t===null?null:J.t(`helpers.authAuditWording.prefix`,{prefix:t})}function un(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenCreated`,{name:cn(n,t)}),details:Q([ln(n),typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:J.t(`helpers.authAuditWording.tokenUsed`,{name:cn(n,t)}),details:Q([ln(n),e===null?null:J.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenMinted`,{name:cn(n,t)}),details:Q([typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`token-revoked`:return{title:J.t(`helpers.authAuditWording.anyTokenRevoked`,{name:cn(n,t)}),details:[]};case`admin-token-revoked`:return{title:J.t(`helpers.authAuditWording.tokenRevoked`,{name:cn(n,t)}),details:Q([ln(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=sn[e],a=i===void 0?`${e}s`:J.t(i);return{title:J.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?J.t(`helpers.authAuditWording.skipped`,{count:r}):null,Z(n,`ids`)===null?null:J.t(`helpers.authAuditWording.ids`,{ids:Z(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:J.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:J.t(`helpers.authAuditWording.signedInWith`,{method:qt(e)}),t===null?null:J.t(`helpers.authAuditWording.skippedFactors`,{factors:t.split(`,`).join(`, `)})])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}c();var dn=100;function fn(){let{user:e}=ft();return e?.isAdmin?i(mn,{}):null}function pn(){let{data:e}=Le(),{data:t}=U.auth.listTokens.useQuery(void 0);return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.label);return{userNameById:n,tokenNameById:r}},[e,t])}function mn(){let{t}=Y(),n=U.auth.listAuthAudit.useQuery({limit:dn}),{userNameById:r,tokenNameById:a}=pn(),o=n.data??[];return e(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[e(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[i(P,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`div`,{className:`text-xs font-semibold text-foreground`,children:t(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:t(`auth.authAuditSection.latest`,{count:dn})})]}),i(`div`,{className:`p-4`,children:n.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):n.isError?e(`div`,{className:`text-[11px] text-danger`,children:[t(`auth.authAuditSection.couldNotLoadTheAudit`,`Could not load the audit trail:`),` `,n.error?.message??t(`auth.authAuditSection.requestFailed`,`Request failed`)]}):o.length===0?e(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[i(`div`,{children:t(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),i(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:t(`auth.authAuditSection.thisTrailRecordsAdminToken`,`This trail records admin-token create/use/revoke, trusted-network 2FA skips, and credential revokes (including single share-link revoke). Browser password logins are not listed here.`)})]}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:o.map(e=>i(hn,{record:e,userName:e.userId===void 0?null:r.get(e.userId)??e.userId,tokenNameById:a},e.id))})})]})}function hn({record:t,userName:n,tokenNameById:r}){let a=un(t,r);return e(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[i(`span`,{className:`font-medium text-foreground`,children:a.title}),i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Ot(t.at)})]}),e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&i(`span`,{className:`text-foreground`,children:n}),t.ip!==void 0&&i(`span`,{className:`font-mono`,children:t.ip}),a.details.map(e=>i(`span`,{className:`font-mono`,children:e},e))]})]})}c();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,externalIdentities:`external-identities`,audit:`auth-audit`},gn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function _n(){return[{id:$.loginSessions,label:J.t(`system.access.loginSessions`,`Login sessions`),icon:ue,render:()=>i(on,{})},{id:$.linkedApps,label:J.t(`system.access.linkedApps`,`Linked apps`),icon:k,render:()=>i(rn,{})},{id:$.tokens,label:J.t(`system.access.tokens`,`Tokens`),icon:le,render:({createRequested:e,onCreateConsumed:t})=>i(Nt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:J.t(`system.access.signInLinks`,`Sign-in links`),icon:oe,render:()=>i(en,{})},{id:$.audit,label:J.t(`system.access.audit`,`Audit`),icon:P,render:()=>i(fn,{})}]}function vn({createRequested:t=!1,onCreateConsumed:r}){let{t:a}=Y(),o=n(()=>_n(),[]),s=Jt({ids:n(()=>o.map(e=>e.id),[o]),answered:!0}),c=_t(),[l]=mt(),u=l.get(`integration`),d=u===null?void 0:gn[u];if(d!==void 0){let e=new URLSearchParams(l);return e.set(`integration`,d),i(pt,{to:`?${e.toString()}`,replace:!0})}let f=o.find(e=>e.id===s.selectedId)??o[0];return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[i(Ce,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{c(`?${ut(l,e,null,null).toString()}`)},children:i(pe,{"aria-label":a(`system.access.credentialKinds`,`Credential kinds`),children:o.map(t=>e(Ee,{value:t.id,"data-testid":`access-kind-${t.id}`,children:[i(t.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),t.label]},t.id))})}),f===void 0?null:i(`div`,{role:`region`,"aria-label":f.label,"data-testid":`access-kind-body`,children:f.render({createRequested:t&&f.id===$.tokens,onCreateConsumed:r??(()=>void 0)})},f.id)]})}function yn(t,n){if(t===$.tokens)return e(G,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:n,children:[i(le,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`system.access.newToken`,`New token`)]})}function bn(){let[e,t]=o(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}c();var xn=[`oidcConnections`,`listConnections`],Sn=[`oidcConnections`,`connectionFormSchema`],Cn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},wn=/^[a-z0-9][a-z0-9-]{0,63}$/;function Tn(e){return e instanceof Error?e.message:String(e)}function En(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(R(e))return L;if(typeof e==`string`&&e.length>0)return e;I(e)}function Dn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function On({addonId:c}){let{t:f}=Y(),p=E(),g=l(),_=N(),v=Be({editKey:`oidcEdit`,newKey:`oidcNew`}),[y,b]=o(!1),[x,S]=o(null),[C,w]=o(``),[T,D]=o({...Cn}),O=t(null),k=s({queryKey:[...xn,c],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),A=s({queryKey:Sn,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),ee=k.data??[],j=Dn(A.data)?A.data:void 0,P=v.state,F=P.mode===`edit`?ee.find(e=>e.id===P.id)??null:null;a(()=>{if(v.state.mode===`edit`&&F!==null){let e=`edit:${F.id}`;if(O.current===e)return;O.current=e,S(null),w(F.id),D(F.formValues===void 0?{...Cn}:{...F.formValues});return}if(v.state.mode===`new`){if(O.current===`new`)return;O.current=`new`,S(null),w(``),D({...Cn})}},[F,v.state]);let I=r(async()=>{await g.invalidateQueries({queryKey:xn})},[g]),L=u({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>I()}),R=r(async e=>{await _({title:f(`system.oidcSettingsConnections.deleteOidcConnection`,`Delete OIDC connection?`),message:f(`system.oidcSettingsConnections.removeTheLoginButtonAnd`,`Remove “{{displayName}}” ({{id}}). The login button and IdP credentials for this id are dropped.`,{displayName:e.displayName,id:e.id}),confirmLabel:f(`common.delete`,`Delete`),cancelLabel:f(`common.cancel`,`Cancel`),variant:`danger`})&&(await L.mutateAsync(e.id),v.state.mode===`edit`&&v.state.id===e.id&&(v.close(),O.current=null))},[_,L,v,f]),te=r(async()=>{let e=T.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){S(`Display name is required.`);return}let n=v.state.mode===`new`,r=n?C.trim():F?.id??``;if(n&&!wn.test(r)){S(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){S(`That connection is no longer available.`);return}let i=En(T.clientSecret,n),a=T.icon,o=T.issuerUrl,s=T.clientId,c=T.redirectUri,l=T.scopes,u=T.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;b(!0),S(null);try{n&&await p.trpcClient.oidcConnections.createConnection.mutate({id:r,displayName:t}),await p.trpcClient.oidcConnections.updateConnection.mutate({id:r,displayName:t,icon:typeof a==`string`?a:`shield-check`,issuerUrl:typeof o==`string`?o:``,clientId:typeof s==`string`?s:``,...i===void 0?{}:{clientSecret:i},redirectUri:typeof c==`string`?c:``,scopes:typeof l==`string`?l:`openid profile email`,usernameClaim:d}),await I(),v.close(),O.current=null}catch(e){S(Tn(e))}finally{b(!1)}},[C,F?.id,v,T,I,p]),ne=n(()=>[{key:`id`,header:f(`system.oidcSettingsConnections.id`,`Id`),sortValue:e=>e.id,render:e=>i(`span`,{className:`font-mono text-xs text-foreground`,children:e.id})},{key:`name`,header:f(`system.oidcSettingsConnections.name`,`Name`),sortValue:e=>e.displayName,render:e=>i(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:f(`system.oidcSettingsConnections.issuer`,`Issuer`),sortValue:e=>e.issuerUrl,render:e=>i(`span`,{className:`truncate text-xs text-foreground-muted`,children:e.issuerUrl===``?`—`:e.issuerUrl})},{key:`status`,header:f(`system.oidcSettingsConnections.status`,`Status`),notSortableReason:`Badge`,render:e=>i(K,{variant:e.configured?`success`:`warning`,children:e.configured?f(`system.oidcSettingsConnections.configured`,`Configured`):f(`system.oidcSettingsConnections.notConfigured`,`Not configured`)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[i(G,{type:`button`,size:`sm`,variant:`secondary`,onClick:e=>{e.stopPropagation(),v.openEdit(t.id)},children:f(`common.edit`,`Edit`)}),i(G,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":f(`system.oidcSettingsConnections.delete`,`Delete {{displayName}}`,{displayName:t.displayName}),title:f(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),R(t)},children:i(h,{className:`h-3.5 w-3.5 text-danger`})})]})}],[v,R,f]),z=v.state.mode===`new`,B=z||F!==null,re=z?`new`:F===null?`closed`:`edit:${F.id}:${F.configured?`cfg`:`empty`}`,ie=`/addon/${c}/<id>/callback`;return e(`div`,{className:`flex min-h-0 flex-col gap-3`,"data-testid":`oidc-settings-connections`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[e(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.eachRowIsOneIdp`,`Each row is one IdP. Redirect URI:`),` `,i(`span`,{className:`font-mono text-xs`,children:ie})]}),e(G,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>v.openNew(),children:[i(m,{className:`h-3.5 w-3.5`}),f(`system.oidcSettingsConnections.addConnection`,`Add connection`)]})]}),k.isError?i(`p`,{className:`text-sm text-danger`,children:f(`system.oidcSettingsConnections.couldNotLoadConnections`,`Could not load connections.`)}):null,k.isPending?i(ve,{className:`h-32 w-full`}):i(we,{columns:ne,rows:ee,rowKey:e=>e.id,pageSize:25,emptyMessage:f(`system.oidcSettingsConnections.noOidcConnectionsYetAdd`,`No OIDC connections yet. Add one to register an IdP.`),onRowClick:e=>v.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),i(Xe,{open:B,onClose:()=>{v.close(),S(null),O.current=null},title:z?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:F?.displayName??`connection`}),icon:M,width:`xl`,testId:`oidc-connection-editor`,error:x,footer:i(G,{type:`button`,size:`sm`,disabled:y||z&&C.trim()===``,onClick:()=>void te(),children:y?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:B?e(d,{children:[z?e(`div`,{children:[i(De,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),i(Ve,{id:`oidc-connection-id`,value:C,onChange:e=>w(e.target.value),placeholder:`authentik`,autoComplete:`off`}),i(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:f(`system.oidcSettingsConnections.urlSlugAppearsInAddon`,`URL slug — appears in /addon/{{addonId}}/<id>/callback. Stable; renaming is not supported after save.`,{addonId:c})})]}):e(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.instanceId2`,`Instance id:`),` `,i(`span`,{className:`font-mono`,children:F?.id})]}),j===void 0?i(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):i($e,{schema:j,values:T,onChange:D,bare:!0},re)]}):null})]})}c();var kn=3e4,An=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],jn={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function Mn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:re,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:se,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Choose a stable instance id (slug). Set the IdP redirect URI to `https://<this-hub>/addon/auth-oidc/<id>/callback`.",`In Settings below, Add connection — enter the id, issuer, and credentials; Save.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:se,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:x,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:x,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:M,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Nn(){let{t:e}=Y(),t=H({capName:An[0].capName},{refetchInterval:kn}),r=H({capName:An[1].capName},{refetchInterval:kn}),a=ye(void 0,{refetchInterval:kn}),o=n(()=>$t(a.data??[]),[a.data]),s=n(()=>{let e=[],n=[t.data??[],r.data??[]];for(let[t,r]of An.entries())for(let i of n[t]??[])e.push({addonId:i.addonId,displayName:o.get(i.addonId)??i.addonId,isActive:i.isActive,capName:r.capName,stageBadge:r.stageBadge});return e},[t.data,r.data,o]),c=[{id:`authentication`,label:e(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:An[0].capName,label:e(jn.installLabelKey)},entries:s.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:M,...Qt(t.isActive),render:()=>i(Yt,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:i(K,{variant:`info`,className:Xt,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?i(On,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Mn(t.addonId).icon,content:i(Pn,{addonId:t.addonId})}]})}))}];return i(Zt,{embedded:!0,icon:M,title:e(jn.titleKey),subtitle:e(jn.subtitleKey),groups:c,isLoading:t.isLoading||r.isLoading,emptyTitle:e(jn.emptyTitleKey),emptyDescription:e(jn.emptyDescriptionKey)})}function Pn({addonId:t}){let{t:n}=Y(),r=Mn(t),a=r.icon;return e(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[e(`div`,{className:`flex items-start gap-2.5`,children:[i(a,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),i(`div`,{className:`text-xs text-foreground font-medium`,children:r.headline})]}),i(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:r.bullets.map((e,t)=>i(`li`,{children:e},t))}),r.setupSteps&&r.setupSteps.length>0&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[e(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[i(B,{className:`h-3 w-3`}),n(`system.authentication.setupSteps`,`Setup steps`)]}),i(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:r.setupSteps.map((e,t)=>i(`li`,{children:e},t))})]}),t===`local-auth`&&e(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[i(C,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),i(`span`,{children:i(vt,{i18nKey:`system.authentication.totpNote`,components:{access:i(dt,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:i(dt,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}function Fn({isPending:t,error:n,what:r,onRetry:a,children:o}){let{t:s}=Y();return t?e(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.queryBody.reading`,{what:r})]}):n===null?o:i(W,{title:s(`certificates.queryBody.couldNotRead`,`Could not read {{what}}`,{what:r}),message:n.message.length>0?n.message:s(`certificates.queryBody.requestFailed`,`Request failed`),onRetry:a})}function In(){let{t}=Y(),n=U.deviceCredentials.getDeviceCaStatus.useQuery({}),r=n.data;return i(X,{id:`device-ca`,title:t(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:M,description:t(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:i(Fn,{isPending:n.isPending,error:n.error,what:`the device CA`,onRetry:()=>void n.refetch(),children:r!==void 0&&e(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[e(q,{label:t(`certificates.deviceCaCard.state`,`State`),children:[r.state===`ready`&&i(K,{variant:`success`,children:t(`certificates.deviceCaCard.ready`,`Ready`)}),r.state===`absent`&&i(K,{variant:`default`,children:t(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),r.state===`unavailable`&&i(K,{variant:`danger`,children:t(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),r.state===`ready`&&e(d,{children:[i(q,{label:t(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:r.subject}),i(q,{label:t(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:r.fingerprintSha256}),i(q,{label:t(`certificates.deviceCaCard.validUntil`,`Valid until`),children:r.validTo})]}),r.state===`unavailable`&&i(q,{label:t(`certificates.deviceCaCard.reason`,`Reason`),children:i(`span`,{className:`text-danger`,children:r.reason})})]})})})}c();function Ln(){let{t}=Y(),n=U.useUtils(),r=U.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[a,s]=o(null),c=U.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{s(null),n.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>s(`Could not save: ${e.message}`)});return i(Fn,{isPending:r.isPending,error:r.error,what:`the enrollment setting`,onRetry:()=>void r.refetch(),children:r.data!==void 0&&e(q,{label:t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:i(ge,{checked:r.data.selfEnrollment===`allowed`,disabled:c.isPending,"aria-label":t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>c.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r.data.selfEnrollment===`allowed`?t(`certificates.deviceSettingsRow.allowedAUserSignedIn`,`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`):t(`certificates.deviceSettingsRow.disabledOnlyAnAdminCan`,`Disabled - only an admin can pair a device, with a QR code.`)}),a!==null&&i(`span`,{className:`block text-[11px] text-danger`,children:a})]})})}c();function Rn(e){let[t,n]=o(()=>Date.now());return a(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}c();var zn=80,Bn=208;function Vn({open:t,users:n,onClose:r,onPaired:a}){let{t:s}=Y(),c=U.deviceCredentials.startEnrollment.useMutation({onSuccess:a}),[l,u]=o(``),[d,f]=o(``),p=l===``?n[0]?.id??``:l,m=c.data,h=()=>{c.reset(),f(``),r()};return i(Xe,{open:t,onClose:h,title:s(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:x,width:`md`,testId:`pair-device-dialog`,error:c.isError?c.error.message:null,footer:m===void 0?e(G,{type:`button`,onClick:()=>{let e=d.trim();p===``||e===``||c.mutate({userId:p,deviceName:e})},disabled:c.isPending||p===``||d.trim()===``,children:[c.isPending&&i(D,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):i(G,{type:`button`,variant:`outline`,onClick:h,children:s(`certificates.pairDeviceDialog.done`,`Done`)}),children:m===void 0?e(`div`,{className:`space-y-3`,children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`certificates.pairDeviceDialog.createsAOneTimeCode`,`Creates a one-time code for a phone you hold. Scan it with the CamStack app on that phone; the phone then stays signed in as the chosen user until you revoke it.`)}),i(st,{label:s(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:i(Fe,{value:p,onChange:e=>u(e.target.value),options:n.map(e=>({value:e.id,label:e.username}))})}),i(st,{label:s(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:s(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:i(Ve,{value:d,maxLength:zn,onChange:e=>f(e.target.value),placeholder:s(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):i(Hn,{enrollUrl:m.enrollUrl,expiresAt:m.expiresAt,hubKnown:m.hubOrigin!==null,onRestart:()=>c.reset()})})}function Hn({enrollUrl:t,expiresAt:n,hubKnown:r,onRestart:a}){let{t:o}=Y(),s=zt(n,Rn(1e3));return i(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:e(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[i(`div`,{className:s.expired?`opacity-30`:void 0,children:i(qe,{value:t,size:Bn,alt:o(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),e(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`Open the CamStack app on the phone and scan this code. It works once.`)}),i(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:s.expired?o(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):o(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:s.label})}),e(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[i(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:t}),i(Ye,{value:t,srLabel:`Enrollment link`})]}),!r&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[i(F,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),i(`span`,{children:o(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),s.expired&&i(G,{type:`button`,variant:`outline`,size:`sm`,onClick:a,children:o(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}c();var Un={key:`access.nouns.device`};function Wn({pairOpen:t,onPairClose:r}){let{t:a}=Y(),s=N(),c=w(),l=U.useUtils(),u=U.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),d=Le(),[f,p]=o(null),[m,_]=o(null),v=()=>void l.deviceCredentials.listDeviceCredentials.invalidate(),b=e=>t=>{_(null),p(`${e} failed: ${t.message}`)},S=()=>{_(null),v()},C=U.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:b(`Revoke`)}),T=U.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&p(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),S()},onError:b(`Delete`)}),E=U.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:S,onError:b(`Rename`)}),D=Ct(Un,e=>C.mutateAsync({id:e}),v),O=D.busy||m!==null,k=n(()=>(u.data??[]).map(Rt),[u.data]),A=async e=>{await s({title:a(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:a(`certificates.devicesCard.sDeviceStopsSigningIn`,`{{ownerName}}'s device stops signing in at once and its open sessions end. To use it again it has to be paired anew. This cannot be undone.`,{ownerName:e.ownerName}),confirmLabel:a(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(p(null),_(e.id),C.mutate({id:e.id}))},ee=async e=>{await s({title:a(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:a(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`})&&(p(null),_(e.id),T.mutate({id:e.id}))},j=async e=>{let t=(await c({title:a(`certificates.devicesCard.renameDevice`,`Rename device`),label:a(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:a(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(p(null),_(e.id),E.mutate({id:e.id,deviceName:t}))},M={label:a(`certificates.devicesCard.revoke2`,`Revoke`),icon:y,isAvailable:Dt,onRun:e=>void A(e),busyId:C.isPending?m:null,disabled:O},P=[{label:a(`certificates.devicesCard.rename`,`Rename`),icon:g,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void j(e),busyId:E.isPending?m:null,disabled:O},{label:a(`common.delete`,`Delete`),icon:h,isAvailable:Pt,onRun:e=>void ee(e),busyId:T.isPending?m:null,disabled:O}];return e(X,{id:`devices`,title:a(`certificates.devicesCard.devices`,`Devices`),icon:x,description:a(`certificates.devicesCard.phonesThatStaySignedIn`,`Phones that stay signed in with a certificate instead of a login. Revoking one signs it out at once; it has to be paired again.`),notice:Ft(f,D.outcome),onDismissNotice:()=>{p(null),D.dismiss()},children:[i(Ln,{}),i(Et,{rows:k,label:a(`certificates.devicesCard.label`),isLoading:u.isPending,loadError:u.error===null?null:u.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:M,extraActions:P,bulk:{revoke:D,noun:Un,isSelectable:Dt}}),i(Vn,{open:t,users:d.data??[],onClose:r,onPaired:v})]})}var Gn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Kn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,qn={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function Jn(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Kn.exec(t);return e===null?Gn.test(t)?J.t(`helpers.pemFile.isCert`):J.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?J.t(`helpers.pemFile.encrypted`):null}return Gn.test(t)?e===`certificate`&&Kn.test(t)?J.t(`helpers.pemFile.certHasKey`):null:Kn.test(t)?J.t(`helpers.pemFile.isKey`):J.t(`helpers.pemFile.notCert`)}function Yn(e){return e.text()}c();function Xn({kind:n,label:r,value:a,onChange:s,rows:c=6}){let{t:l}=Y(),u=t(null),[d,f]=o(null),[p,m]=o(null),h=p??Jn(n,a),g=`pem-${n}`,_=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t!==void 0){f(t.name);try{let e=await Yn(t);m(null),s(e)}catch(e){m(`Could not read ${t.name}: ${e instanceof Error?e.message:String(e)}`)}}};return e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`label`,{htmlFor:g,className:`text-[11px] text-foreground-subtle`,children:r}),e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[d!==null&&i(`span`,{className:`truncate font-mono text-[10px] text-foreground-subtle`,"data-testid":`${g}-file-name`,children:d}),i(`input`,{ref:u,type:`file`,accept:qn[n],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),e(G,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>u.current?.click(),children:[i(ie,{className:`mr-1 h-3 w-3`}),l(`system.pemField.chooseFile`,`Choose file`)]})]})]}),i(`textarea`,{id:g,value:a,onChange:e=>{f(null),m(null),s(e.target.value)},rows:c,"aria-invalid":h!==null,className:`w-full rounded border border-border bg-surface px-2 py-1 font-mono text-[11px]`}),h!==null&&i(`p`,{className:`text-[11px] text-danger`,role:`alert`,children:h})]})}c();var Zn=30;function Qn(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<Zn*864e5}function $n(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function er(){let{t}=Y(),n=l(),r=nt(void 0,{refetchInterval:15e3}),a=ke({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=be({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),c=Ze({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),u=at({onSuccess:()=>{m(!1),g(``),v(``),b(``),n.invalidateQueries({queryKey:[[`localNetwork`]]})}}),d=r.data,[p,m]=o(!1),[h,g]=o(``),[_,v]=o(``),[y,b]=o(``),x=()=>{if(!d?.caCertPem)return;let e=new Blob([d.caCertPem],{type:`application/x-pem-file`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`camstack-ca.crt`,n.click(),URL.revokeObjectURL(t)},S=d?.mode===`uploaded`?`Uploaded`:d?.mode===`generated`?`Generated local CA`:`TLS disabled`;return i(Pe,{headingId:`local-access-certificate`,title:t(`system.localAccess.certificate`,`Certificate`),icon:T,children:e(`div`,{className:`${f} space-y-3`,children:[r.isError&&i(`p`,{className:`text-xs text-danger`,children:t(`system.localAccess.couldNotReadTlsStatus`,`Could not read TLS status.`)}),d?.reissueError&&i(W,{variant:`warning`,title:t(`system.localAccess.certificateReissue`,`Certificate reissue`),message:d.reissueError}),d?.restartRequired&&i(W,{variant:`warning`,title:t(`system.localAccess.restartRequired`,`Restart required`),message:t(`system.localAccess.theHttpsListenerStillServes`,`The HTTPS listener still serves the previous certificate. Restart the hub to apply it.`)}),d?.caMissing===!0&&i(W,{variant:`warning`,title:t(`system.localAccess.caMissingTitle`,`CA missing - devices cannot trust this hub`),message:t(`system.localAccess.caMissingBody`,"The uploaded certificate was not issued by a public CA and no CA was stored with it, so Download CA has nothing to hand out. Upload the certificate again together with its CA (for mkcert, the rootCA.pem in the folder `mkcert -CAROOT` prints).")}),d?.caReplacedAt!=null&&Qn(d.caReplacedAt)&&i(W,{variant:`warning`,title:t(`system.localAccess.caReplacedTitle`,`The local CA was replaced - re-install it on your devices`),message:t(`system.localAccess.caReplacedBody`,`The previous local CA had no name constraints: if its key ever leaked it could vouch for any website. The hub now uses a CA limited to private addresses and local names. Download it again and trust it on every phone and computer that used the old one (replaced {{when}}).`,{when:new Date(d.caReplacedAt).toLocaleString()})}),e(`dl`,{className:`grid grid-cols-1 gap-2 text-xs sm:grid-cols-2`,children:[e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.mode`,`Mode`)}),i(`dd`,{className:`font-medium`,children:S})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.validTo`,`Valid to`)}),i(`dd`,{className:`font-mono`,children:d?.validTo?new Date(d.validTo).toLocaleString():`—`})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.leafSha256`,`Leaf SHA-256`)}),i(`dd`,{className:`font-mono`,title:d?.leafFingerprintSha256??void 0,children:$n(d?.leafFingerprintSha256??null)})]}),d?.storedUpload!=null&&e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.storedUpload`,`Stored upload`)}),i(`dd`,{className:`font-medium`,children:t(`system.localAccess.storedUploadValue`,`valid to {{validTo}}, {{ca}}`,{validTo:new Date(d.storedUpload.validTo).toLocaleDateString(),ca:d.storedUpload.hasCa?t(`system.localAccess.storedUploadWithCa`,`with its CA`):t(`system.localAccess.storedUploadNoCa`,`no CA`)})})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.caSha256`,`CA SHA-256`)}),i(`dd`,{className:`font-mono`,title:d?.caFingerprintSha256??void 0,children:d?.mode===`uploaded`&&d.caFingerprintSha256===null?i(`span`,{className:`font-sans text-foreground-subtle`,children:t(`system.localAccess.issuerNotIncludedInThe`,`Issuer not included in the upload (not the local CA)`)}):$n(d?.caFingerprintSha256??null)})]})]}),d&&d.sans.length>0&&i(`div`,{className:`flex flex-wrap gap-1`,children:d.sans.map(e=>i(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 font-mono text-[10px] text-foreground-subtle`,children:e},e))}),e(`div`,{className:`flex flex-wrap gap-2`,children:[i(We,{label:t(`system.localAccess.regenerate`,`Regenerate`),title:t(`system.localAccess.issueANewLeaf`,`Issue a new leaf?`),description:t(`system.localAccess.issuesANewLeafUnder`,`Issues a new leaf under the current local CA. Clients that trust the CA keep working. The HTTPS listener reloads.`),confirmLabel:t(`system.localAccess.regenerate`,`Regenerate`),disabled:d?.mode===`uploaded`||a.isPending,action:()=>a.mutateAsync({})}),i(G,{size:`sm`,variant:`outline`,onClick:()=>m(e=>!e),children:t(`system.localAccess.upload`,`Upload`)}),d?.caCertPem&&i(G,{size:`sm`,variant:`outline`,onClick:x,children:t(`system.localAccess.downloadCa`,`Download CA`)}),d?.mode===`uploaded`&&i(We,{label:t(`system.localAccess.revertToGenerated`,`Revert to generated`),title:t(`system.localAccess.revertTitle`,`Switch back to the generated certificate?`),description:t(`system.localAccess.keepsTheUploadedPair`,`Returns to the generated local CA. The uploaded certificate and its CA stay stored here; you can select them again.`),confirmLabel:t(`system.localAccess.revert`,`Revert`),disabled:s.isPending,action:()=>s.mutateAsync({})}),d?.mode===`generated`&&d.storedUpload!=null&&i(We,{label:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),title:t(`system.localAccess.useUploadedTitle`,`Serve the stored upload again?`),description:t(`system.localAccess.useUploadedDescription`,`The stored uploaded certificate replaces the generated one on the HTTPS listener. The generated certificate stays stored.`),confirmLabel:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),disabled:c.isPending,action:()=>c.mutateAsync(void 0)})]}),p&&e(`div`,{className:`space-y-2 border-t border-border pt-3`,children:[i(Xn,{kind:`certificate`,label:t(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:h,onChange:g}),i(Xn,{kind:`privateKey`,label:t(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:_,onChange:v}),i(Xn,{kind:`ca`,label:t(`system.localAccess.caPemRequired`,`CA (PEM) - required unless the certificate comes from a public CA`),value:y,onChange:b,rows:4}),i(G,{size:`sm`,disabled:!h.trim()||!_.trim()||Jn(`certificate`,h)!==null||Jn(`privateKey`,_)!==null||Jn(`ca`,y)!==null||u.isPending,onClick:()=>u.mutate({certPem:h,keyPem:_,...y.trim()?{caPem:y}:{}}),children:t(`system.localAccess.saveCertificate`,`Save certificate`)}),u.isError&&i(`p`,{className:`text-xs text-danger`,children:u.error instanceof Error?u.error.message:t(`system.localAccess.uploadFailed`,`Upload failed`)})]})]})})}var tr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function nr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function rr({https:t,mesh:n,now:r}){let{t:a}=Y(),o=nt().data?.caCertPem??``,s=()=>{if(o===``)return;let e=URL.createObjectURL(new Blob([o],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},c=n?.ca,l=c?.state===`ready`?Date.parse(c.validTo):null,u=n?.listener;return e(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[i(q,{label:a(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[nr(t)??`—`,o!==``&&e(G,{type:`button`,variant:`ghost`,size:`sm`,onClick:s,children:[i(v,{className:`h-3 w-3`,"aria-hidden":!0}),a(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),i(q,{label:a(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:c===void 0?`—`:c.state===`ready`?c.fingerprintSha256:i(`span`,{className:`text-danger`,children:a(`certificates.caStrip.unavailable`,{reason:c.reason})})}),c?.state===`ready`&&e(q,{label:a(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[c.validTo,l!==null&&!Number.isNaN(l)&&e(`span`,{className:`ml-2 text-[10px] ${tr[Ut(l,r)]}`,children:[`(`,kt(l,r),`)`]})]}),u!==void 0&&e(q,{label:a(`certificates.caStrip.nodeListener`,`Node listener`),children:[u.state===`open`&&i(K,{variant:`success`,children:a(`certificates.caStrip.open`,`Open`)}),u.state===`not-started`&&i(K,{variant:`default`,children:a(`certificates.caStrip.notStarted`,`Not started`)}),u.state===`closed`&&e(`span`,{className:`text-danger`,children:[a(`certificates.caStrip.closedSince`,{when:At(u.since)}),` `,u.reason]})]}),n!==void 0&&!n.registryAvailable&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[i(F,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),i(`span`,{children:a(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function ir(e,t){let n=new Set;for(let t of e)n.add(t.nodeId);for(let e of t?.nodes??[])n.add(e.nodeId);return[...n].map(n=>{let r=e.find(e=>e.nodeId===n)??null,i=t?.nodes.find(e=>e.nodeId===n)??null;return{nodeId:n,isHub:r?.isHub??n===`hub`,online:r?.online??i?.online??!1,https:r,mesh:i}}).toSorted((e,t)=>Number(t.isHub)-Number(e.isHub)||e.nodeId.localeCompare(t.nodeId))}function ar(e){return e.isHub?J.t(`helpers.nodesModel.hubReissued`):e.mesh===null?J.t(`helpers.nodesModel.noCertRecorded`):e.online?null:J.t(`helpers.certificateModel.nodeOffline`)}function or(e){return e.isHub||e.mesh===null?ar(e):null}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},cr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},lr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function ur(e){let t=e.https?.https;return t?.kind===`served`?Vt(t.status.validTo):null}function dr({ms:t,now:n}){return t===null?i(`span`,{className:`text-foreground-subtle`,children:`—`}):e(`div`,{children:[i(`div`,{children:At(t)}),i(`div`,{className:`text-[10px] ${sr[Ut(t,n)]}`,children:kt(t,n)})]})}function fr({row:t}){let{t:n}=Y(),r=t.https?.https;return r===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):r.kind===`served`?e(`div`,{title:r.status.leafFingerprintSha256??``,children:[i(K,{variant:`success`,className:`text-[10px]`,children:n(`certificates.nodesColumns.served`,`Served`)}),i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:lr[r.status.mode]}),i(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Bt(r.status.leafFingerprintSha256)}),r.status.sans.length>0&&i(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:r.status.sans.join(`, `),children:r.status.sans.join(`, `)})]}):e(`div`,{className:`max-w-[16rem]`,children:[i(K,{variant:r.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:r.kind===`unreadable`?n(`certificates.nodesColumns.unreadable`,`Unreadable`):n(`certificates.nodesColumns.notServed`,`Not served`)}),i(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:r.reason})]})}function pr({row:t}){let{t:n}=Y(),r=t.mesh?.current??null;if(r===null)return i(`span`,{className:`text-foreground-subtle`,children:n(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let a=t.mesh?.history.length??0;return e(`div`,{children:[i(`div`,{className:`font-mono text-[11px]`,title:r.serial,children:Lt(r.serial)}),i(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:r.fingerprintSha256,children:Bt(r.fingerprintSha256)}),e(`div`,{className:`text-[10px] text-foreground-subtle`,children:[cr[r.issuedVia],a>0?` · ${n(`certificates.nodesColumns.earlier`,{count:a})}`:``]})]})}function mr({row:e}){let{t}=Y(),n=e.mesh?.presentingCurrent??null;return n===null?i(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?i(K,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):i(K,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function hr(t){let n=t.icon;return e(G,{type:`button`,variant:`ghost`,size:`sm`,className:t.danger?`text-danger hover:bg-danger/10`:void 0,disabled:t.reason!==null||t.busy,title:t.reason??void 0,"aria-label":t.ariaLabel,onClick:t.onClick,children:[t.spinning?i(D,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):i(n,{className:`h-3 w-3`,"aria-hidden":!0}),t.label]})}function gr({reasons:t}){let{t:n}=Y();return e(et,{className:`inline-block`,children:[i(Ue,{children:i(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:n(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),i(Je,{children:i(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:t.map(e=>i(`li`,{children:e},e))})})]})}function _r({row:t,o:n}){let{t:r}=Y(),a=t.https===null?`No HTTPS inventory for this node.`:jt(t.https).reason,o=ar(t),s=or(t),c=e=>n.running?.nodeId===t.nodeId&&n.running.action===e,l=e=>!t.isHub||e===null,u=[a,o,s].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);return e(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[e(`div`,{className:`flex flex-col items-end gap-0.5`,children:[l(a)&&i(hr,{label:r(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:r(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:t.nodeId}),icon:p,reason:a,busy:n.busy,spinning:c(`renew-https`),danger:!1,onClick:()=>n.onRenewHttps(t)}),l(o)&&i(hr,{label:c(`renew-identity`)?r(`certificates.nodesColumns.renewing`,`Renewing…`):r(`certificates.nodesColumns.renewIdentity`,`Renew identity`),ariaLabel:r(`certificates.nodesColumns.renewTheClusterCertificateOf`,`Renew the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:p,reason:o,busy:n.busy,spinning:c(`renew-identity`),danger:!1,onClick:()=>n.onRenewIdentity(t)}),l(s)&&i(hr,{label:r(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:r(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:y,reason:s,busy:n.busy,spinning:c(`revoke-identity`),danger:!0,onClick:()=>n.onRevokeIdentity(t)})]}),t.isHub&&u.length>0&&i(gr,{reasons:u}),!t.isHub&&a!==null&&t.https!==null&&i(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${t.nodeId}`,children:a}),!t.isHub&&o!==null&&i(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${t.nodeId}`,children:o})]})}function vr(t){return[{key:`node`,header:J.t(`certificates.nodesColumns.node`,`Node`),sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:t=>e(`div`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`font-medium text-foreground`,children:t.nodeId}),t.nodeId===`hub`&&i(K,{variant:`info`,className:`text-[10px]`,children:J.t(`common.hubWord`)}),!t.online&&i(K,{variant:`default`,className:`text-[10px]`,children:J.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>i(fr,{row:e})},{key:`https-expires`,header:J.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>ur(e),render:e=>i(dr,{ms:ur(e),now:t.now})},{key:`identity`,header:J.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>i(pr,{row:e})},{key:`identity-expires`,header:J.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:e=>i(dr,{ms:e.mesh?.current?.notAfter??null,now:t.now})},{key:`presenting`,header:J.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>i(mr,{row:e})},{key:`actions`,header:J.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:e=>i(_r,{row:e,o:t})}]}c();function yr(){let{t}=Y(),r=N(),a=U.useUtils(),s=Rn(6e4),c=U.certificates.listHttpsCertificates.useQuery(),l=U.certificates.getMeshCertificates.useQuery(),[u,d]=o(null),[f,p]=o(null),[m,h]=o(null),g=()=>{h(null),a.certificates.listHttpsCertificates.invalidate(),a.certificates.getMeshCertificates.invalidate()},_=e=>(t,n)=>{h(null),d(`${n.nodeId}: ${e} - ${t.message}`)},v=U.certificates.renewHttpsOnNode.useMutation({onSuccess:(e,n)=>{p({tone:`success`,message:e.restartRequired?t(`certificates.nodesCard.newCertificateIssuedRestartThe`,`{{nodeId}}: new certificate issued. Restart the node to serve it.`,{nodeId:n.nodeId}):t(`certificates.nodesCard.newCertificateIssuedAndServed`,`{{nodeId}}: new certificate issued and served.`,{nodeId:n.nodeId})}),g()},onError:_(`renewal failed`)}),y=U.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(It(e)),g()},onError:_(`renewal could not start`)}),x=U.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}`}),g()},onError:_(`revoke failed`)}),S=v.isPending||y.isPending||x.isPending,C=(e,t)=>{d(null),p(null),h({nodeId:e,action:t})},w=async e=>{await r({title:t(`certificates.nodesCard.renewHttpsOn`,`Renew HTTPS on "{{nodeId}}"?`,{nodeId:e.nodeId}),message:e.isHub?t(`certificates.nodesCard.aNewCertificateIsIssued`,`A new certificate is issued from the local CA. Clients that trust the CA keep working.`):t(`certificates.nodesCard.theNodeMakesANew`,`The node makes a new key, the hub signs it and the node switches over without a restart. It keeps serving what it had if anything fails.`),confirmLabel:t(`certificates.nodesCard.renew`,`Renew`)})&&(C(e.nodeId,`renew-https`),v.mutate({nodeId:e.nodeId}))},T=e=>{C(e.nodeId,`renew-identity`),y.mutate({nodeId:e.nodeId})},E=async e=>{await r({title:t(`certificates.nodesCard.revokeTheIdentityOf`,`Revoke the identity of "{{nodeId}}"?`,{nodeId:e.nodeId}),message:t(`certificates.nodesCard.isDisconnectedAtOnceAnd`,`{{nodeId}} is disconnected at once and can no longer connect. To bring it back it must be paired again from System → Cluster → Agents. It stays in the node list until you forget it on the Cluster page. This cannot be undone.`,{nodeId:e.nodeId}),confirmLabel:t(`certificates.nodesCard.revokeAndDisconnect`,`Revoke and disconnect`),variant:`danger`})&&(C(e.nodeId,`revoke-identity`),x.mutate({nodeId:e.nodeId}))},D=vr({now:s,busy:S,running:m,onRenewHttps:e=>void w(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),O=n(()=>ir(c.data??[],l.data),[c.data,l.data]),k=l.data?.registryAvailable??!0;return i(X,{id:`nodes`,title:t(`certificates.nodesCard.nodes`,`Nodes`),icon:b,description:t(`certificates.nodesCard.eachNodeHoldsTwoCertificates`,`Each node holds two certificates: one it serves over HTTPS, one that proves its identity to the hub. Renewing replaces a certificate without a gap; revoking an identity cuts the node off until it re-joins.`),notice:Ft(u,f),onDismissNotice:()=>{d(null),p(null)},children:i(Fn,{isPending:c.isPending||l.isPending,error:c.error??l.error,what:`node certificates`,onRetry:()=>{c.refetch(),l.refetch()},children:e(`div`,{className:`space-y-3`,children:[i(rr,{https:c.data??[],mesh:l.data,now:s}),i(we,{columns:D,rows:O,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:me,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:k?t(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):t(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function br({pairOpen:t,onPairClose:n}){return e(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[i(Wn,{pairOpen:t,onPairClose:n}),i(In,{}),i(er,{}),i(yr,{})]})}function xr({userId:t,username:n,onClose:r}){let{t:a}=Y(),o=N(),s=U.useUtils(),c=xe({userId:t}),l=U.auth.listLoginMethods.useQuery(),u=Ke({onSuccess:()=>void s.userManagement.listExternalIdentities.invalidate()}),d=new Map((l.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=c.data??[],p=async(e,r)=>{await o({title:a(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:a(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:n,label:r}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&u.mutate({userId:t,provider:e.provider,subject:e.subject})};return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(k,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.externalIdentitiesModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),i(ze,{className:`space-y-3`,children:c.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),a(`common.loading`,`Loading…`)]}):f.length===0?i(`p`,{className:`text-xs text-foreground-subtle`,children:a(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`No linked accounts. Only the user can link one, from their own profile page.`)}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:f.map(t=>{let n=d.get(t.provider),r=n??t.provider;return e(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[e(`div`,{className:`flex-1 min-w-0`,children:[e(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&i(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:a(`users.externalIdentitiesModal.providerUnavailable`,`provider unavailable`)})]}),e(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[t.label??t.subject,` ·`,` `,new Date(t.linkedAt).toLocaleDateString()]})]}),e(`button`,{onClick:()=>void p(t,r),disabled:u.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[i(de,{className:`h-3 w-3`}),a(`common.remove`,`Remove`)]})]},`${t.provider}|${t.subject}`)})})}),i(Ge,{children:i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)})})]})})}function Sr({userId:t,username:n,onClose:r}){let{t:a}=Y(),o=l(),s=N(),c=je({userId:t}),u=c.data,f=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),p=Oe({onSuccess:()=>{f(),r()}}),m=c.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(x,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.totpModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),e(ze,{className:`space-y-4`,children:[m===`loading`&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),a(`users.totpModal.checkingStatus`,`Checking status…`)]}),m===`not_enrolled`&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[i(C,{className:`h-4 w-4 mt-0.5 shrink-0`}),e(`div`,{children:[i(`div`,{className:`font-medium text-foreground`,children:a(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),i(`p`,{className:`mt-0.5`,children:a(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),m===`enrolled`&&u&&e(d,{children:[e(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[i(S,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),e(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[i(`div`,{className:`font-medium`,children:a(`users.totpModal.2faIsActive`,`2FA is active`)}),i(`div`,{className:`text-foreground-subtle`,children:a(`common.enrolledOn`,{when:u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`})})]})]}),i(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`users.totpModal.removingHereClearsTheServer`,`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`)}),e(`div`,{className:`flex justify-end gap-2`,children:[i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)}),e(`button`,{onClick:async()=>{await s({title:a(`users.totpModal.remove2fa`,`Remove 2FA`),message:a(`users.totpModal.removeTwoFactorAuthenticationFor`,`Remove two-factor authentication for "{{username}}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,{username:n}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&p.mutate({userId:t})},disabled:p.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[p.isPending?i(D,{className:`h-3 w-3 animate-spin`}):i(O,{className:`h-3 w-3`}),a(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}c();function Cr({userId:t,username:n,onClose:r}){let{t:a}=Y(),{user:s,logout:c}=ft(),l=s?.id===t,u=N(),d=U.useUtils(),f=U.auth.listSessions.useQuery({userId:t}),[p,m]=o(null),h=U.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(l&&`userId`in t){c();return}d.auth.listSessions.invalidate()},onError:e=>m(`Sign out failed: ${e.message}`)}),g=async e=>{await u({title:a(`users.userSessionsModal.signOutThisSession`,`Sign out this session`),message:a(`users.userSessionsModal.onWillHaveToSign`,`"{{username}}" on {{label}} will have to sign in again.`,{username:n,label:Wt(e.client).label}),confirmLabel:a(`users.userSessionsModal.signOut`,`Sign out`),variant:`danger`})&&(m(null),h.mutate({id:e.id}))},_=async()=>{await u({title:a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),message:l?a(`users.userSessionsModal.everySessionOfYourOwn`,`Every session of your own account ends, this browser included: you will be signed out here too.`):a(`users.userSessionsModal.everySessionOfEndsAt`,`Every session of "{{username}}" ends at once; each device has to sign in again.`,{username:n}),confirmLabel:a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),variant:`danger`})&&(m(null),h.mutate({userId:t}))},v=h.isPending&&h.variables!==void 0&&`id`in h.variables?h.variables.id:null;return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(ue,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.userSessionsModal.activeSessions`,`Active sessions`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.userSessionsModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),e(ze,{className:`space-y-3`,children:[p!==null&&i(`div`,{className:`text-[11px] text-danger`,children:p}),i(Ht,{sessions:f.data??[],isLoading:f.isLoading,loadError:f.isError?f.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:v})]}),e(Ge,{className:`justify-between`,children:[e(`button`,{onClick:()=>void _(),disabled:h.isPending||(f.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[h.isPending&&v===null?i(D,{className:`h-3 w-3 animate-spin`}):i(ce,{className:`h-3 w-3`}),a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)})]})]})})}function wr({scopes:t,invalidReason:n}){let{t:r}=Y(),a=E(),o=s({queryKey:[`auth`,`previewScope`,t,!1],enabled:n===null,queryFn:()=>a.trpcClient.auth.previewScope.query({scopes:[...t],isAdmin:!1})}),{data:c}=V({projection:`slim`}),l=c?.length??null;if(n!==null)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,"data-testid":`role-preview`,children:[i(j,{className:`h-3 w-3 shrink-0`}),n]});if(o.isLoading)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,"data-testid":`role-preview`,children:[i(D,{className:`h-3 w-3 shrink-0 animate-spin`}),r(`users.rolePreview.resolving`)]});if(o.isError||!o.data)return i(`p`,{className:`text-[11px] text-danger`,"data-testid":`role-preview`,children:r(`users.rolePreview.couldNotResolve`)});let u=o.data.viewableDeviceCount,d=o.data.device.view.all?r(`users.rolePreview.everyDevice`,{count:u}):l===null?r(`users.rolePreview.devicesVisible`,{count:u}):r(`users.rolePreview.devicesVisibleOf`,{count:u,total:l});return e(`p`,{className:`flex items-center gap-1.5 text-[11px] ${u===0?`text-warning`:`text-foreground`}`,"data-testid":`role-preview`,children:[u===0?i(j,{className:`h-3 w-3 shrink-0`}):i(_,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u===0?r(`users.rolePreview.noDevice`):d]})}function Tr(e){let t=ne(e.scopes??[]);if(t===null)return{role:e.isAdmin?`admin`:`viewer`,mode:`except`,pickedIds:[],viewer:z,unconfigured:!e.isAdmin};let n=Mr(t);return{role:e.isAdmin?`admin`:`viewer`,mode:n.mode,pickedIds:n.pickedIds,viewer:Nr(n.mode,n.pickedIds,t.features),unconfigured:!1}}function Er(e,t){return{...e,role:t}}function Dr(e,t){return{...e,mode:t,viewer:Nr(t,e.pickedIds,e.viewer.features)}}function Or(e,t){let n=Pr(t);return{...e,pickedIds:n,viewer:Nr(e.mode,n,e.viewer.features)}}function kr(e,t,n){let r=e.viewer.features.filter(e=>e!==t),i=n?[...r,t]:r;return{...e,viewer:Nr(e.mode,e.pickedIds,i)}}function Ar(e){return e.role===`viewer`&&e.mode===`only`&&e.pickedIds.length===0?`no-allowed-device`:null}function jr(e){return Ar(e)===null?e.role===`admin`?{isAdmin:!0,scopes:[]}:{isAdmin:!1,scopes:[e.viewer]}:null}function Mr(e){if(e.allow===`*`)return{mode:`except`,pickedIds:e.block};let t=new Set(e.block);return{mode:`only`,pickedIds:e.allow.filter(e=>!t.has(e))}}function Nr(e,t,n){let r=Pr(t);return e===`except`?{type:`viewer`,allow:`*`,block:r,features:[...n]}:{type:`viewer`,allow:r,block:[],features:[...n]}}function Pr(e){return[...new Set(e)]}c();var Fr=`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`;function Ir(e,t){return e?`failed`:t===void 0?`pending`:`answered`}function Lr(e){let t=[];for(let n of e)n.parentDeviceId===null&&t.push({id:n.id,name:n.name,type:String(n.type),...n.location===null?{}:{location:n.location}});return t}function Rr({user:t,isSelf:r,onClose:a,onSubmit:s,submitting:c,error:l}){let{t:u}=Y(),[f,p]=o(n(()=>Tr(t),[t])),m=V({projection:`slim`}),h=m.data,g=Ir(m.isError,h),_=n(()=>Lr(h??[]),[h]),v=n(()=>({state:g,devices:g===`answered`?(h??[]).map(e=>({id:e.id,name:e.name})):void 0}),[g,h]),y=Ar(f),b=jr(f),x=y===`no-allowed-device`?u(`users.userAccessModal.pickAllowedDevice`):null,S=e=>{p(Er(f,e))},C=[{value:`except`,label:u(`users.userAccessModal.modeExcept`)},{value:`only`,label:u(`users.userAccessModal.modeOnly`)}];return i(Ie,{open:!0,onOpenChange:e=>!e&&a(),children:e(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[i(He,{children:i(Me,{children:u(`users.userAccessModal.title`,{name:t.username})})}),e(ze,{className:`space-y-4`,children:[f.unconfigured&&f.role===`viewer`&&i(W,{variant:`warning`,title:u(`users.userAccessModal.noAccessYet`),message:u(`users.userAccessModal.noAccessYetDetail`,{name:t.username})}),e(`section`,{className:`space-y-2`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.role`)}),e(`div`,{role:`radiogroup`,"aria-label":u(`users.userAccessModal.role`),className:`grid gap-1.5 sm:grid-cols-2`,children:[i(zr,{name:`admin`,checked:f.role===`admin`,label:u(`users.userAccessModal.admin`),description:u(`users.userAccessModal.adminDescription`),onPick:()=>S(`admin`)}),i(zr,{name:`viewer`,checked:f.role===`viewer`,disabled:r,label:u(`users.userAccessModal.viewer`),description:u(r?`users.userAccessModal.cannotDemoteSelf`:`users.userAccessModal.viewerDescription`),onPick:()=>S(`viewer`)})]})]}),f.role===`viewer`&&e(d,{children:[e(`section`,{className:`space-y-3`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.devices`)}),i(it,{label:u(`users.userAccessModal.whichDevices`),value:f.mode,options:C,onChange:e=>p(Dr(f,e))}),i(Se,{devices:_,listState:g,fleet:v,value:[...f.pickedIds],onChange:e=>p(Or(f,e)),emptyMeansAll:f.mode===`except`,noun:`device`,testId:`viewer-device-picker`}),i(wr,{scopes:b?.scopes??[],invalidReason:x})]}),e(`section`,{className:`space-y-2`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.features`)}),i(`div`,{className:`space-y-1`,children:te.map(t=>e(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md p-1.5 hover:bg-surface-hover`,children:[i(Te,{className:`mt-0.5`,checked:f.viewer.features.includes(t.id),onChange:e=>p(kr(f,t.id,e.target.checked))}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block text-[12px] font-medium text-foreground`,children:u(`users.viewerFeatures.${t.id}.label`,t.label)}),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:u(`users.viewerFeatures.${t.id}.description`,t.description)})]})]},t.id))})]})]}),l!==null&&i(W,{message:l})]}),e(Ge,{children:[i(G,{variant:`outline`,size:`sm`,onClick:a,children:u(`common.cancel`,`Cancel`)}),i(G,{size:`sm`,onClick:()=>b!==null&&s(b),disabled:c||b===null,children:c?i(D,{className:`h-3 w-3 animate-spin`}):u(`users.userAccessModal.saveAccess`)})]})]})})}function zr({name:t,checked:n,disabled:r=!1,label:a,description:o,onPick:s}){return e(`label`,{className:`flex items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-surface-hover`} ${r?`cursor-not-allowed opacity-60`:`cursor-pointer`}`,children:[i(`input`,{type:`radio`,name:`user-role`,value:t,checked:n,disabled:r,onChange:s,className:`mt-0.5`}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block text-[12px] font-medium text-foreground`,children:a}),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:o})]})]})}c();var Br=8;function Vr(){return{username:``,password:``,isAdmin:!1}}function Hr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Ur(e){return e instanceof Error?e.message:J.t(`admin.system.users.genericError`)}function Wr(){let{t}=Y(),n=l(),{user:r}=ft(),{state:s,openNew:c,openEdit:u,close:f}=Be(),[p,_]=o(null),[v,y]=o(null),[b,S]=o(!1),{data:C,isLoading:T,isError:E,error:O,refetch:ee}=Le(),j=N(),P=w(),F=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),I=_e(),L=Ae({onSuccess:F}),R=Ne({onSuccess:F}),te=ot({onSuccess:F}),ne=rt(),[z,B]=o(null),[re,ie]=o(!1),[oe,se]=o(null),[ce,le]=o(null),[de,fe]=o(null),[pe,me]=o(null),V=C??[],H=s.mode===`edit`?V.find(e=>e.id===s.id)??null:null,ge=()=>{_(null),y(null),S(!1),I.reset(),R.reset(),f()};a(()=>{if(s.mode===`closed`){_(null),y(null),S(!1);return}if(s.mode===`new`){_(e=>e!==null&&e.id===void 0?e:Vr());return}if(H===null){T||f();return}_(e=>e?.id===H.id?e:Hr(H))},[s,H,T,f]);let U=s.mode===`new`&&p!==null&&p.id===void 0||s.mode===`edit`&&p!==null&&H!==null;async function ve(e){await j({title:t(`admin.system.users.deleteUser`,`Delete user`),message:t(`admin.system.users.permanentlyDeleteUserThisCannot`,`Permanently delete user "{{username}}"? This cannot be undone — any active sessions will be revoked on next request.`,{username:e.username}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&(L.mutate({id:e.id}),s.mode===`edit`&&s.id===e.id&&ge())}async function ye(e){let n=await P({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.setANewPasswordFor`,`Set a new password for "{{username}}".`,{username:e.username}),label:t(`admin.system.users.newPassword`,`New password`),inputType:`password`,placeholder:t(`admin.system.users.atLeast8Characters`,`At least 8 characters`),confirmLabel:t(`admin.system.users.continue`,`Continue`),validate:e=>e.length<Br?J.t(`admin.system.users.passwordTooShort`,{min:Br}):null});n===null||n.length===0||await j({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.resetThePasswordForThey`,`Reset the password for "{{username}}"? They will need to use the new password on their next login.`,{username:e.username}),confirmLabel:t(`common.reset`,`Reset`)})&&te.mutate({id:e.id,newPassword:n})}function be(e){se(null),B(e)}async function xe(e,t){ie(!0),se(null);try{t.isAdmin!==e.isAdmin&&await R.mutateAsync({id:e.id,isAdmin:t.isAdmin}),await ne.mutateAsync({userId:e.id,scopes:[...t.scopes]}),B(null)}catch(e){se(Ur(e))}finally{ie(!1),F()}}async function Se(){if(p!==null){y(null);try{if(p.id===void 0){let e=p.username.trim();if(e===``||p.password.length<Br)return;await I.mutateAsync({username:e,password:p.password,isAdmin:p.isAdmin})}else await R.mutateAsync({id:p.id,isAdmin:p.isAdmin});F(),ge()}catch(e){y(Ur(e))}}}function Ce(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let Te=I.isPending||R.isPending,Ee=p!==null&&p.id===void 0&&p.username.trim()!==``&&p.password.length>=Br,De=p!==null&&p.id!==void 0,Oe=Te||(p?.id===void 0?!Ee:!De),ke=e=>L.isPending&&L.variables?.id===e.id||R.isPending&&R.variables?.id===e.id||te.isPending&&te.variables?.id===e.id,je=[{key:`username`,header:t(`admin.system.users.username`,`Username`),sortValue:e=>e.username,render:e=>i(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`scopes`,header:t(`admin.system.users.access`,`Access`),sortValue:e=>Gr(e),render:n=>i(`span`,{onClick:e=>e.stopPropagation(),children:e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>be(n),disabled:ke(n),title:t(`admin.system.users.configureAccess`,`Configure access`),"data-testid":`user-access-${n.id}`,children:[i(M,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),i(Kr,{user:n})]})})},{key:`createdAt`,header:t(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>i(`span`,{className:`text-foreground-subtle`,children:Ce(e.createdAt)})},{key:`actions`,header:t(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:n=>{let a=ke(n),o=n.id!==r?.id&&n.totpEnabled;return e(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(n.id),disabled:a,title:t(`admin.system.users.editUser`,`Edit user`),children:[i(g,{className:`h-3 w-3`}),t(`common.edit`,`Edit`)]}),o&&e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>le(n),disabled:a,title:t(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[i(x,{className:`h-3 w-3`}),t(`admin.system.users.remove2fa`,`Remove 2FA`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>fe(n),disabled:a,title:t(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[i(k,{className:`h-3 w-3`}),t(`admin.system.users.signInLinks`,`Sign-in links`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>me(n),disabled:a,title:t(`admin.system.users.activeSessions`,`Active sessions`),children:[i(ue,{className:`h-3 w-3`}),t(`admin.system.users.sessions`,`Sessions`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ye(n),disabled:a,title:t(`admin.system.users.resetPassword`,`Reset password`),children:[i(ae,{className:`h-3 w-3`}),t(`admin.system.users.resetPassword`,`Reset password`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ve(n),disabled:a,title:t(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[a?i(D,{className:`h-3 w-3 animate-spin`}):i(h,{className:`h-3 w-3`}),t(`common.delete`,`Delete`)]})]})}}];return e(bt,{embedded:!0,icon:A,title:t(`admin.system.users.users`,`Users`),subtitle:t(`admin.system.users.hubAccountsAdminFlagAccess`,`Hub accounts, admin flag, access scopes, sessions and sign-in links.`),actions:e(G,{size:`sm`,type:`button`,onClick:()=>{y(null),c()},children:[i(m,{className:`h-3.5 w-3.5`}),t(`admin.system.users.createUser`,`Create User`)]}),children:[E&&i(W,{title:t(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Ur(O),onRetry:()=>void ee()}),T&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`common.loading`,`Loading…`)]}),!T&&!E&&V.length===0&&i(he,{icon:A,title:t(`admin.system.users.noUsersYet`,`No users yet`),description:t(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!T&&!E&&V.length>0&&i(we,{columns:je,rows:V,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>u(e.id)}),i(Xe,{open:U,onClose:ge,title:p?.id===void 0?t(`admin.system.users.createUser`,`Create User`):t(`admin.system.users.edit`,`Edit {{value1}}`,{value1:p.username||`user`}),icon:A,error:v,testId:`user-form-dialog`,footer:i(G,{size:`sm`,type:`button`,disabled:Oe,onClick:()=>void Se(),children:Te?e(d,{children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`admin.system.users.saving`,`Saving…`)]}):p?.id===void 0?t(`admin.system.users.create`,`Create`):t(`common.save`,`Save`)}),children:p!==null&&e(`div`,{className:`space-y-3`,children:[i(st,{label:t(`admin.system.users.username`,`Username`),required:p.id===void 0,children:i(Ve,{value:p.username,onChange:e=>_({...p,username:e.target.value}),placeholder:`john`,autoFocus:p.id===void 0,disabled:p.id!==void 0,"data-testid":`user-form-username`})}),p.id===void 0&&i(st,{label:t(`admin.system.users.password`,`Password`),required:!0,description:t(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Br)}),children:i(Re,{value:p.password,onValueChange:e=>_({...p,password:e}),shown:b,onToggleShown:()=>S(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),i(st,{label:t(`admin.system.users.admin`,`Admin`),description:t(`admin.system.users.unrestrictedAccessToEveryCapability`,`Unrestricted access to every capability and device.`),children:e(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(`input`,{type:`checkbox`,checked:p.isAdmin,onChange:e=>_({...p,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),i(`span`,{children:t(`admin.system.users.admin`,`Admin`)})]})}),p.id!==void 0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`admin.system.users.toChangeThePasswordUse`,`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`)})]})}),ce&&i(Sr,{userId:ce.id,username:ce.username,onClose:()=>le(null)}),de&&i(xr,{userId:de.id,username:de.username,onClose:()=>fe(null)}),pe&&i(Cr,{userId:pe.id,username:pe.username,onClose:()=>me(null)}),z&&i(Rr,{user:z,isSelf:z.id===r?.id,onClose:()=>B(null),onSubmit:e=>void xe(z,e),submitting:re,error:oe})]})}function Gr(e){let t=Tr(e);return t.role===`admin`?0:t.unconfigured?2:1}function Kr({user:t}){let{t:n}=Y(),r=Tr(t);if(r.role===`admin`)return i(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.admin`)});if(r.unconfigured)return i(`span`,{className:`font-medium text-warning`,children:n(`admin.system.users.noAccess`,`No access`)});let{allow:a,block:o,features:s}=r.viewer,c=a===`*`?n(`users.accessSummary.allDevices`):n(`users.accessSummary.devices`,{count:a.length});return e(`span`,{className:`text-foreground-subtle`,children:[i(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.viewer`)}),` ·`,` `,c,o.length>0&&e(d,{children:[` · `,n(`users.accessSummary.blocked`,{count:o.length})]}),s.length>0&&e(d,{children:[` · `,n(`users.accessSummary.features`,{count:s.length})]})]})}c();var qr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Jr=`certificates`;function Yr(t){return e(G,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:t,children:[i(x,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Xr(){let{t:e}=Y(),[t]=mt(),n=bn(),[r,a]=o(!1),s=qr[t.get(`tab`)??``];if(s!==void 0)return i(pt,{to:gt(`access`,{integration:s}),replace:!0});let c=ct(`/system/identity`,{t:e,isAdmin:!0})??{icon:ee,title:e(`system.identity`,`Identity & Access`)},l=t.get(`tab`)??`users`,u=t.get(`integration`),d=l===lt.access.tab?yn(u,n.requestCreate):l===`certificates`?Yr(()=>a(!0)):void 0;return i(yt,{icon:c.icon,title:c.title,defaultSection:`users`,sectionsLabel:`${c.title} sections`,actions:d,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:i(Wr,{})},{id:lt.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),ownedParams:ht.concat([Mt.token,Mt.scoped,Mt.admin]),content:i(vn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate})},{id:Jr,label:e(`systemPage.identity.certificates`,`Certificates`),content:i(br,{pairOpen:r,onPairClose:()=>a(!1)})},{id:lt.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:i(Nn,{}),ownedParams:ht}]})}export{Xr as IdentityPage};
1
+ import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{D as f,En as p,Fn as m,Ht as h,Vn as g,Wr as _,Xr as v,Zi as y,_n as b,an as x,bi as S,br as C,ct as w,dn as T,dt as E,fr as D,gt as O,hr as k,jt as A,lr as ee,mn as j,pn as M,st as N,yn as P,zt as F}from"./player-overlays-B4lehTI4.js";import{Qa as I,Xa as L,Za as R,da as te,s as ne,ua as z}from"./client-C6c46gRD.js";import{i as B,n as re,r as ie,t as ae}from"./key-B1puhv1a.js";import{d as oe,l as se,s as ce}from"./video-B-2RwuDj.js";import{t as le}from"./key-round-DmUg5DWL.js";import{t as ue}from"./monitor-smartphone-DJqsZ1_F.js";import{t as de}from"./unlink-Chgtl9c5.js";import{$u as fe,Bn as pe,Cn as me,Do as V,Er as he,Fi as H,Hn as ge,Ju as _e,Ld as U,Or as ve,Pi as ye,Qs as be,Qu as xe,R as Se,Rn as Ce,Sn as we,Tr as W,Un as Te,Vn as Ee,Wn as De,Xu as Oe,Yr as G,Ys as ke,Yu as Ae,Zu as je,_r as Me,ad as Ne,bn as Pe,dd as Fe,dr as Ie,ed as Le,fd as Re,fr as ze,ft as Be,gd as Ve,gr as He,hd as Ue,hn as We,hr as Ge,id as Ke,lr as qe,md as Je,mn as Ye,mt as Xe,nc as Ze,nd as Qe,or as $e,pd as et,pr as tt,qs as nt,rd as rt,ri as K,rt as it,tc as at,td as ot,xn as q,xt as st}from"./src-DY9QaWNW.js";import{t as J}from"./i18n-DNh4GW93.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{T as ct,_r as lt,a as ut,d as dt,hr as ft,i as pt,l as mt,mr as ht,pr as gt,rr as _t,yr as vt}from"./index-Dm-ruGxs.js";import{t as yt}from"./AdminSectionedPage-DQApNUvC.js";import{t as bt}from"./AdminPage-aCyydhgN.js";import{A as xt,C as St,D as Ct,E as wt,O as X,S as Tt,T as Et,a as Dt,b as Ot,c as kt,d as At,f as jt,g as Mt,h as Nt,i as Pt,k as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,s as Vt,t as Ht,u as Ut,v as Wt,w as Gt,x as Kt,y as qt}from"./SessionsList-CmkI6hmY.js";import{i as Jt,n as Yt,r as Xt,t as Zt}from"./IntegrationHub-DkSP6wag.js";import{n as Qt,t as $t}from"./addon-display-names-BkwMrExv.js";c();function en(){let{t:e}=Y(),t=N(),r=U.useUtils(),a=xt(),{data:s,isLoading:c}=Le(),l=n(()=>s??[],[s]),u=U.useQueries(e=>l.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),d=U.auth.listLoginMethods.useQuery(),[f,p]=o(null),m=Ke({onSuccess:()=>void r.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=n(()=>new Map((d.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[d.data]),g=l.flatMap((e,t)=>u[t]?.data??[]),_=g.map(e=>({...Tt(e,a),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Kt(e)===n.id);r!==void 0&&await t({title:e(`access.externalIdentitiesSection.removeSignInLink`,`Remove sign-in link`),message:e(`access.externalIdentitiesSection.willNoLongerBeAble`,`"{{ownerName}}" will no longer be able to sign in with this {{kind}} account.`,{ownerName:n.ownerName,kind:n.kind}),confirmLabel:e(`common.remove`,`Remove`),variant:`danger`})&&(p(null),m.mutate({userId:r.userId,provider:r.provider,subject:r.subject}))};return i(X,{notice:Ft(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:oe,description:e(`access.externalIdentitiesSection.externalAccountsSingleSignOn`,`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`),children:i(Et,{rows:_,label:`sign-in links`,isLoading:c||u.some(e=>e.isLoading),loadError:u.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:e(`common.remove`,`Remove`),icon:de,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}c();var tn={key:`access.nouns.linkedApp`};function nn(e){if(e.type===`category`){let t=e.target??``;return t===`device`?J.t(`access.linkedAppsSection.allDevices`):J.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function rn(){let{t:e}=Y(),t=N(),r=l(),a=fe(),[s,c]=o(null),u=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),d=Qe({onSuccess:u,onError:e=>c(`Revoke failed: ${e.message}`)}),f=wt(tn,u),p=n(()=>(a.data??[]).map(e=>St(e,e.scopes.map(nn).join(`, `))),[a.data]),m=async n=>{await t({title:e(`access.linkedAppsSection.revokeTheLink`,`Revoke the "{{name}}" link?`,{name:n.name}),message:e(`access.linkedAppsSection.losesAccessForOnIts`,`{{name}} loses access for {{ownerName}} on its next call. Linking it again needs the account-link flow from the start.`,{name:n.name,ownerName:n.ownerName}),confirmLabel:e(`access.linkedAppsSection.revoke`,`Revoke`),variant:`danger`})&&(c(null),d.mutate({id:n.id}))},g=d.isPending?d.variables?.id??null:null;return i(X,{notice:Ft(s,f.outcome),onDismissNotice:()=>{c(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:k,description:e(`access.linkedAppsSection.externalIntegrationsAlexaLinkedTo`,`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call. Already-revoked rows can be selected and removed from the list.`),children:i(Et,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:a.isLoading,loadError:a.isError?a.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:e(`access.linkedAppsSection.revoke`,`Revoke`),icon:h,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:g,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:tn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}c();var an={key:`access.nouns.session`};function on(){let{t:e}=Y(),t=N(),r=U.useUtils(),a=xt(),s=U.auth.listSessions.useQuery(),[c,l]=o(null),u=()=>void r.auth.listSessions.invalidate(),d=U.auth.revokeSessions.useMutation({onSuccess:u,onError:e=>l(`Sign out failed: ${e.message}`)}),f=wt(an,u),p=n(()=>(s.data??[]).map(e=>Gt(e,a,{client:e=>Wt(e).label,method:qt})),[s.data,a]),m=async n=>{await t({title:e(`access.loginSessionsSection.signOutThisSession`,`Sign out this session`),message:e(`access.loginSessionsSection.onWillHaveToSign`,`{{ownerName}} on {{name}} will have to sign in again.`,{ownerName:n.ownerName,name:n.name}),confirmLabel:e(`access.loginSessionsSection.signOut`,`Sign out`),variant:`danger`})&&(l(null),d.mutate({id:n.id}))};return i(X,{notice:Ft(c,f.outcome),onDismissNotice:()=>{l(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:ue,description:e(`access.loginSessionsSection.everyBrowserAndAppSigned`,`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`),children:i(Et,{rows:p,label:e(`common.sessionsLabel`),isLoading:s.isLoading,loadError:s.isError?s.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:e(`access.loginSessionsSection.signOut`,`Sign out`),icon:ce,isAvailable:e=>e.status===`active`,onRun:e=>void m(e),busyId:d.isPending&&d.variables!==void 0&&`id`in d.variables?d.variables.id:null,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:an,isSelectable:e=>e.status===`active`}})})}var sn={"by-id":`helpers.authAuditWording.bulkNoun.credential`,"share-link":`helpers.authAuditWording.bulkNoun.shareLink`,"admin-token":`helpers.authAuditWording.bulkNoun.adminToken`,"login-session":`helpers.authAuditWording.bulkNoun.loginSession`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function cn(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function ln(e){let t=Z(e,`prefix`);return t===null?null:J.t(`helpers.authAuditWording.prefix`,{prefix:t})}function un(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenCreated`,{name:cn(n,t)}),details:Q([ln(n),typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:J.t(`helpers.authAuditWording.tokenUsed`,{name:cn(n,t)}),details:Q([ln(n),e===null?null:J.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenMinted`,{name:cn(n,t)}),details:Q([typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`token-revoked`:return{title:J.t(`helpers.authAuditWording.anyTokenRevoked`,{name:cn(n,t)}),details:[]};case`admin-token-revoked`:return{title:J.t(`helpers.authAuditWording.tokenRevoked`,{name:cn(n,t)}),details:Q([ln(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=sn[e],a=i===void 0?`${e}s`:J.t(i);return{title:J.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?J.t(`helpers.authAuditWording.skipped`,{count:r}):null,Z(n,`ids`)===null?null:J.t(`helpers.authAuditWording.ids`,{ids:Z(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:J.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:J.t(`helpers.authAuditWording.signedInWith`,{method:qt(e)}),t===null?null:J.t(`helpers.authAuditWording.skippedFactors`,{factors:t.split(`,`).join(`, `)})])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}c();var dn=100;function fn(){let{user:e}=_t();return e?.isAdmin?i(mn,{}):null}function pn(){let{data:e}=Le(),{data:t}=U.auth.listTokens.useQuery(void 0);return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.label);return{userNameById:n,tokenNameById:r}},[e,t])}function mn(){let{t}=Y(),n=U.auth.listAuthAudit.useQuery({limit:dn}),{userNameById:r,tokenNameById:a}=pn(),o=n.data??[];return e(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[e(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[i(P,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`div`,{className:`text-xs font-semibold text-foreground`,children:t(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:t(`auth.authAuditSection.latest`,{count:dn})})]}),i(`div`,{className:`p-4`,children:n.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):n.isError?e(`div`,{className:`text-[11px] text-danger`,children:[t(`auth.authAuditSection.couldNotLoadTheAudit`,`Could not load the audit trail:`),` `,n.error?.message??t(`auth.authAuditSection.requestFailed`,`Request failed`)]}):o.length===0?e(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[i(`div`,{children:t(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),i(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:t(`auth.authAuditSection.thisTrailRecordsAdminToken`,`This trail records admin-token create/use/revoke, trusted-network 2FA skips, and credential revokes (including single share-link revoke). Browser password logins are not listed here.`)})]}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:o.map(e=>i(hn,{record:e,userName:e.userId===void 0?null:r.get(e.userId)??e.userId,tokenNameById:a},e.id))})})]})}function hn({record:t,userName:n,tokenNameById:r}){let a=un(t,r);return e(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[i(`span`,{className:`font-medium text-foreground`,children:a.title}),i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Ot(t.at)})]}),e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&i(`span`,{className:`text-foreground`,children:n}),t.ip!==void 0&&i(`span`,{className:`font-mono`,children:t.ip}),a.details.map(e=>i(`span`,{className:`font-mono`,children:e},e))]})]})}c();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,externalIdentities:`external-identities`,audit:`auth-audit`},gn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function _n(){return[{id:$.loginSessions,label:J.t(`system.access.loginSessions`,`Login sessions`),icon:ue,render:()=>i(on,{})},{id:$.linkedApps,label:J.t(`system.access.linkedApps`,`Linked apps`),icon:k,render:()=>i(rn,{})},{id:$.tokens,label:J.t(`system.access.tokens`,`Tokens`),icon:le,render:({createRequested:e,onCreateConsumed:t})=>i(Nt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:J.t(`system.access.signInLinks`,`Sign-in links`),icon:oe,render:()=>i(en,{})},{id:$.audit,label:J.t(`system.access.audit`,`Audit`),icon:P,render:()=>i(fn,{})}]}function vn({createRequested:t=!1,onCreateConsumed:r}){let{t:a}=Y(),o=n(()=>_n(),[]),s=Jt({ids:n(()=>o.map(e=>e.id),[o]),answered:!0}),c=lt(),[l]=vt(),u=l.get(`integration`),d=u===null?void 0:gn[u];if(d!==void 0){let e=new URLSearchParams(l);return e.set(`integration`,d),i(ft,{to:`?${e.toString()}`,replace:!0})}let f=o.find(e=>e.id===s.selectedId)??o[0];return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[i(Ce,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{c(`?${dt(l,e,null,null).toString()}`)},children:i(pe,{"aria-label":a(`system.access.credentialKinds`,`Credential kinds`),children:o.map(t=>e(Ee,{value:t.id,"data-testid":`access-kind-${t.id}`,children:[i(t.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),t.label]},t.id))})}),f===void 0?null:i(`div`,{role:`region`,"aria-label":f.label,"data-testid":`access-kind-body`,children:f.render({createRequested:t&&f.id===$.tokens,onCreateConsumed:r??(()=>void 0)})},f.id)]})}function yn(t,n){if(t===$.tokens)return e(G,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:n,children:[i(le,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`system.access.newToken`,`New token`)]})}function bn(){let[e,t]=o(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}c();var xn=[`oidcConnections`,`listConnections`],Sn=[`oidcConnections`,`connectionFormSchema`],Cn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},wn=/^[a-z0-9][a-z0-9-]{0,63}$/;function Tn(e){return e instanceof Error?e.message:String(e)}function En(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(R(e))return L;if(typeof e==`string`&&e.length>0)return e;I(e)}function Dn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function On({addonId:c}){let{t:f}=Y(),p=E(),g=l(),_=N(),v=Be({editKey:`oidcEdit`,newKey:`oidcNew`}),[y,b]=o(!1),[x,S]=o(null),[C,w]=o(``),[T,D]=o({...Cn}),O=t(null),k=s({queryKey:[...xn,c],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),A=s({queryKey:Sn,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),ee=k.data??[],j=Dn(A.data)?A.data:void 0,P=v.state,F=P.mode===`edit`?ee.find(e=>e.id===P.id)??null:null;a(()=>{if(v.state.mode===`edit`&&F!==null){let e=`edit:${F.id}`;if(O.current===e)return;O.current=e,S(null),w(F.id),D(F.formValues===void 0?{...Cn}:{...F.formValues});return}if(v.state.mode===`new`){if(O.current===`new`)return;O.current=`new`,S(null),w(``),D({...Cn})}},[F,v.state]);let I=r(async()=>{await g.invalidateQueries({queryKey:xn})},[g]),L=u({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>I()}),R=r(async e=>{await _({title:f(`system.oidcSettingsConnections.deleteOidcConnection`,`Delete OIDC connection?`),message:f(`system.oidcSettingsConnections.removeTheLoginButtonAnd`,`Remove “{{displayName}}” ({{id}}). The login button and IdP credentials for this id are dropped.`,{displayName:e.displayName,id:e.id}),confirmLabel:f(`common.delete`,`Delete`),cancelLabel:f(`common.cancel`,`Cancel`),variant:`danger`})&&(await L.mutateAsync(e.id),v.state.mode===`edit`&&v.state.id===e.id&&(v.close(),O.current=null))},[_,L,v,f]),te=r(async()=>{let e=T.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){S(`Display name is required.`);return}let n=v.state.mode===`new`,r=n?C.trim():F?.id??``;if(n&&!wn.test(r)){S(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){S(`That connection is no longer available.`);return}let i=En(T.clientSecret,n),a=T.icon,o=T.issuerUrl,s=T.clientId,c=T.redirectUri,l=T.scopes,u=T.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;b(!0),S(null);try{n&&await p.trpcClient.oidcConnections.createConnection.mutate({id:r,displayName:t}),await p.trpcClient.oidcConnections.updateConnection.mutate({id:r,displayName:t,icon:typeof a==`string`?a:`shield-check`,issuerUrl:typeof o==`string`?o:``,clientId:typeof s==`string`?s:``,...i===void 0?{}:{clientSecret:i},redirectUri:typeof c==`string`?c:``,scopes:typeof l==`string`?l:`openid profile email`,usernameClaim:d}),await I(),v.close(),O.current=null}catch(e){S(Tn(e))}finally{b(!1)}},[C,F?.id,v,T,I,p]),ne=n(()=>[{key:`id`,header:f(`system.oidcSettingsConnections.id`,`Id`),sortValue:e=>e.id,render:e=>i(`span`,{className:`font-mono text-xs text-foreground`,children:e.id})},{key:`name`,header:f(`system.oidcSettingsConnections.name`,`Name`),sortValue:e=>e.displayName,render:e=>i(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:f(`system.oidcSettingsConnections.issuer`,`Issuer`),sortValue:e=>e.issuerUrl,render:e=>i(`span`,{className:`truncate text-xs text-foreground-muted`,children:e.issuerUrl===``?`—`:e.issuerUrl})},{key:`status`,header:f(`system.oidcSettingsConnections.status`,`Status`),notSortableReason:`Badge`,render:e=>i(K,{variant:e.configured?`success`:`warning`,children:e.configured?f(`system.oidcSettingsConnections.configured`,`Configured`):f(`system.oidcSettingsConnections.notConfigured`,`Not configured`)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[i(G,{type:`button`,size:`sm`,variant:`secondary`,onClick:e=>{e.stopPropagation(),v.openEdit(t.id)},children:f(`common.edit`,`Edit`)}),i(G,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":f(`system.oidcSettingsConnections.delete`,`Delete {{displayName}}`,{displayName:t.displayName}),title:f(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),R(t)},children:i(h,{className:`h-3.5 w-3.5 text-danger`})})]})}],[v,R,f]),z=v.state.mode===`new`,B=z||F!==null,re=z?`new`:F===null?`closed`:`edit:${F.id}:${F.configured?`cfg`:`empty`}`,ie=`/addon/${c}/<id>/callback`;return e(`div`,{className:`flex min-h-0 flex-col gap-3`,"data-testid":`oidc-settings-connections`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[e(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.eachRowIsOneIdp`,`Each row is one IdP. Redirect URI:`),` `,i(`span`,{className:`font-mono text-xs`,children:ie})]}),e(G,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>v.openNew(),children:[i(m,{className:`h-3.5 w-3.5`}),f(`system.oidcSettingsConnections.addConnection`,`Add connection`)]})]}),k.isError?i(`p`,{className:`text-sm text-danger`,children:f(`system.oidcSettingsConnections.couldNotLoadConnections`,`Could not load connections.`)}):null,k.isPending?i(ve,{className:`h-32 w-full`}):i(we,{columns:ne,rows:ee,rowKey:e=>e.id,pageSize:25,emptyMessage:f(`system.oidcSettingsConnections.noOidcConnectionsYetAdd`,`No OIDC connections yet. Add one to register an IdP.`),onRowClick:e=>v.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),i(Xe,{open:B,onClose:()=>{v.close(),S(null),O.current=null},title:z?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:F?.displayName??`connection`}),icon:M,width:`xl`,testId:`oidc-connection-editor`,error:x,footer:i(G,{type:`button`,size:`sm`,disabled:y||z&&C.trim()===``,onClick:()=>void te(),children:y?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:B?e(d,{children:[z?e(`div`,{children:[i(De,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),i(Ve,{id:`oidc-connection-id`,value:C,onChange:e=>w(e.target.value),placeholder:`authentik`,autoComplete:`off`}),i(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:f(`system.oidcSettingsConnections.urlSlugAppearsInAddon`,`URL slug — appears in /addon/{{addonId}}/<id>/callback. Stable; renaming is not supported after save.`,{addonId:c})})]}):e(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.instanceId2`,`Instance id:`),` `,i(`span`,{className:`font-mono`,children:F?.id})]}),j===void 0?i(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):i($e,{schema:j,values:T,onChange:D,bare:!0},re)]}):null})]})}c();var kn=3e4,An=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],jn={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function Mn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:re,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:se,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Choose a stable instance id (slug). Set the IdP redirect URI to `https://<this-hub>/addon/auth-oidc/<id>/callback`.",`In Settings below, Add connection — enter the id, issuer, and credentials; Save.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:se,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:x,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:x,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:M,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Nn(){let{t:e}=Y(),t=H({capName:An[0].capName},{refetchInterval:kn}),r=H({capName:An[1].capName},{refetchInterval:kn}),a=ye(void 0,{refetchInterval:kn}),o=n(()=>$t(a.data??[]),[a.data]),s=n(()=>{let e=[],n=[t.data??[],r.data??[]];for(let[t,r]of An.entries())for(let i of n[t]??[])e.push({addonId:i.addonId,displayName:o.get(i.addonId)??i.addonId,isActive:i.isActive,capName:r.capName,stageBadge:r.stageBadge});return e},[t.data,r.data,o]),c=[{id:`authentication`,label:e(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:An[0].capName,label:e(jn.installLabelKey)},entries:s.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:M,...Qt(t.isActive),render:()=>i(Yt,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:i(K,{variant:`info`,className:Xt,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?i(On,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Mn(t.addonId).icon,content:i(Pn,{addonId:t.addonId})}]})}))}];return i(Zt,{embedded:!0,icon:M,title:e(jn.titleKey),subtitle:e(jn.subtitleKey),groups:c,isLoading:t.isLoading||r.isLoading,emptyTitle:e(jn.emptyTitleKey),emptyDescription:e(jn.emptyDescriptionKey)})}function Pn({addonId:t}){let{t:n}=Y(),r=Mn(t),a=r.icon;return e(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[e(`div`,{className:`flex items-start gap-2.5`,children:[i(a,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),i(`div`,{className:`text-xs text-foreground font-medium`,children:r.headline})]}),i(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:r.bullets.map((e,t)=>i(`li`,{children:e},t))}),r.setupSteps&&r.setupSteps.length>0&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[e(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[i(B,{className:`h-3 w-3`}),n(`system.authentication.setupSteps`,`Setup steps`)]}),i(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:r.setupSteps.map((e,t)=>i(`li`,{children:e},t))})]}),t===`local-auth`&&e(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[i(C,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),i(`span`,{children:i(gt,{i18nKey:`system.authentication.totpNote`,components:{access:i(ht,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:i(ht,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}function Fn({isPending:t,error:n,what:r,onRetry:a,children:o}){let{t:s}=Y();return t?e(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.queryBody.reading`,{what:r})]}):n===null?o:i(W,{title:s(`certificates.queryBody.couldNotRead`,`Could not read {{what}}`,{what:r}),message:n.message.length>0?n.message:s(`certificates.queryBody.requestFailed`,`Request failed`),onRetry:a})}function In(){let{t}=Y(),n=U.deviceCredentials.getDeviceCaStatus.useQuery({}),r=n.data;return i(X,{id:`device-ca`,title:t(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:M,description:t(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:i(Fn,{isPending:n.isPending,error:n.error,what:`the device CA`,onRetry:()=>void n.refetch(),children:r!==void 0&&e(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[e(q,{label:t(`certificates.deviceCaCard.state`,`State`),children:[r.state===`ready`&&i(K,{variant:`success`,children:t(`certificates.deviceCaCard.ready`,`Ready`)}),r.state===`absent`&&i(K,{variant:`default`,children:t(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),r.state===`unavailable`&&i(K,{variant:`danger`,children:t(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),r.state===`ready`&&e(d,{children:[i(q,{label:t(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:r.subject}),i(q,{label:t(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:r.fingerprintSha256}),i(q,{label:t(`certificates.deviceCaCard.validUntil`,`Valid until`),children:r.validTo})]}),r.state===`unavailable`&&i(q,{label:t(`certificates.deviceCaCard.reason`,`Reason`),children:i(`span`,{className:`text-danger`,children:r.reason})})]})})})}c();function Ln(){let{t}=Y(),n=U.useUtils(),r=U.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[a,s]=o(null),c=U.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{s(null),n.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>s(`Could not save: ${e.message}`)});return i(Fn,{isPending:r.isPending,error:r.error,what:`the enrollment setting`,onRetry:()=>void r.refetch(),children:r.data!==void 0&&e(q,{label:t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:i(ge,{checked:r.data.selfEnrollment===`allowed`,disabled:c.isPending,"aria-label":t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>c.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r.data.selfEnrollment===`allowed`?t(`certificates.deviceSettingsRow.allowedAUserSignedIn`,`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`):t(`certificates.deviceSettingsRow.disabledOnlyAnAdminCan`,`Disabled - only an admin can pair a device, with a QR code.`)}),a!==null&&i(`span`,{className:`block text-[11px] text-danger`,children:a})]})})}c();function Rn(e){let[t,n]=o(()=>Date.now());return a(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}c();var zn=80,Bn=208;function Vn({open:t,users:n,onClose:r,onPaired:a}){let{t:s}=Y(),c=U.deviceCredentials.startEnrollment.useMutation({onSuccess:a}),[l,u]=o(``),[d,f]=o(``),p=l===``?n[0]?.id??``:l,m=c.data,h=()=>{c.reset(),f(``),r()};return i(Xe,{open:t,onClose:h,title:s(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:x,width:`md`,testId:`pair-device-dialog`,error:c.isError?c.error.message:null,footer:m===void 0?e(G,{type:`button`,onClick:()=>{let e=d.trim();p===``||e===``||c.mutate({userId:p,deviceName:e})},disabled:c.isPending||p===``||d.trim()===``,children:[c.isPending&&i(D,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):i(G,{type:`button`,variant:`outline`,onClick:h,children:s(`certificates.pairDeviceDialog.done`,`Done`)}),children:m===void 0?e(`div`,{className:`space-y-3`,children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`certificates.pairDeviceDialog.createsAOneTimeCode`,`Creates a one-time code for a phone you hold. Scan it with the CamStack app on that phone; the phone then stays signed in as the chosen user until you revoke it.`)}),i(st,{label:s(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:i(Fe,{value:p,onChange:e=>u(e.target.value),options:n.map(e=>({value:e.id,label:e.username}))})}),i(st,{label:s(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:s(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:i(Ve,{value:d,maxLength:zn,onChange:e=>f(e.target.value),placeholder:s(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):i(Hn,{enrollUrl:m.enrollUrl,expiresAt:m.expiresAt,hubKnown:m.hubOrigin!==null,onRestart:()=>c.reset()})})}function Hn({enrollUrl:t,expiresAt:n,hubKnown:r,onRestart:a}){let{t:o}=Y(),s=zt(n,Rn(1e3));return i(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:e(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[i(`div`,{className:s.expired?`opacity-30`:void 0,children:i(qe,{value:t,size:Bn,alt:o(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),e(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`Open the CamStack app on the phone and scan this code. It works once.`)}),i(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:s.expired?o(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):o(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:s.label})}),e(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[i(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:t}),i(Ye,{value:t,srLabel:`Enrollment link`})]}),!r&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[i(F,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),i(`span`,{children:o(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),s.expired&&i(G,{type:`button`,variant:`outline`,size:`sm`,onClick:a,children:o(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}c();var Un={key:`access.nouns.device`};function Wn({pairOpen:t,onPairClose:r}){let{t:a}=Y(),s=N(),c=w(),l=U.useUtils(),u=U.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),d=Le(),[f,p]=o(null),[m,_]=o(null),v=()=>void l.deviceCredentials.listDeviceCredentials.invalidate(),b=e=>t=>{_(null),p(`${e} failed: ${t.message}`)},S=()=>{_(null),v()},C=U.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:b(`Revoke`)}),T=U.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&p(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),S()},onError:b(`Delete`)}),E=U.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:S,onError:b(`Rename`)}),D=Ct(Un,e=>C.mutateAsync({id:e}),v),O=D.busy||m!==null,k=n(()=>(u.data??[]).map(Rt),[u.data]),A=async e=>{await s({title:a(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:a(`certificates.devicesCard.sDeviceStopsSigningIn`,`{{ownerName}}'s device stops signing in at once and its open sessions end. To use it again it has to be paired anew. This cannot be undone.`,{ownerName:e.ownerName}),confirmLabel:a(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(p(null),_(e.id),C.mutate({id:e.id}))},ee=async e=>{await s({title:a(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:a(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`})&&(p(null),_(e.id),T.mutate({id:e.id}))},j=async e=>{let t=(await c({title:a(`certificates.devicesCard.renameDevice`,`Rename device`),label:a(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:a(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(p(null),_(e.id),E.mutate({id:e.id,deviceName:t}))},M={label:a(`certificates.devicesCard.revoke2`,`Revoke`),icon:y,isAvailable:Dt,onRun:e=>void A(e),busyId:C.isPending?m:null,disabled:O},P=[{label:a(`certificates.devicesCard.rename`,`Rename`),icon:g,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void j(e),busyId:E.isPending?m:null,disabled:O},{label:a(`common.delete`,`Delete`),icon:h,isAvailable:Pt,onRun:e=>void ee(e),busyId:T.isPending?m:null,disabled:O}];return e(X,{id:`devices`,title:a(`certificates.devicesCard.devices`,`Devices`),icon:x,description:a(`certificates.devicesCard.phonesThatStaySignedIn`,`Phones that stay signed in with a certificate instead of a login. Revoking one signs it out at once; it has to be paired again.`),notice:Ft(f,D.outcome),onDismissNotice:()=>{p(null),D.dismiss()},children:[i(Ln,{}),i(Et,{rows:k,label:a(`certificates.devicesCard.label`),isLoading:u.isPending,loadError:u.error===null?null:u.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:M,extraActions:P,bulk:{revoke:D,noun:Un,isSelectable:Dt}}),i(Vn,{open:t,users:d.data??[],onClose:r,onPaired:v})]})}var Gn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Kn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,qn={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function Jn(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Kn.exec(t);return e===null?Gn.test(t)?J.t(`helpers.pemFile.isCert`):J.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?J.t(`helpers.pemFile.encrypted`):null}return Gn.test(t)?e===`certificate`&&Kn.test(t)?J.t(`helpers.pemFile.certHasKey`):null:Kn.test(t)?J.t(`helpers.pemFile.isKey`):J.t(`helpers.pemFile.notCert`)}function Yn(e){return e.text()}c();function Xn({kind:n,label:r,value:a,onChange:s,rows:c=6}){let{t:l}=Y(),u=t(null),[d,f]=o(null),[p,m]=o(null),h=p??Jn(n,a),g=`pem-${n}`,_=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t!==void 0){f(t.name);try{let e=await Yn(t);m(null),s(e)}catch(e){m(`Could not read ${t.name}: ${e instanceof Error?e.message:String(e)}`)}}};return e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`label`,{htmlFor:g,className:`text-[11px] text-foreground-subtle`,children:r}),e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[d!==null&&i(`span`,{className:`truncate font-mono text-[10px] text-foreground-subtle`,"data-testid":`${g}-file-name`,children:d}),i(`input`,{ref:u,type:`file`,accept:qn[n],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),e(G,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>u.current?.click(),children:[i(ie,{className:`mr-1 h-3 w-3`}),l(`system.pemField.chooseFile`,`Choose file`)]})]})]}),i(`textarea`,{id:g,value:a,onChange:e=>{f(null),m(null),s(e.target.value)},rows:c,"aria-invalid":h!==null,className:`w-full rounded border border-border bg-surface px-2 py-1 font-mono text-[11px]`}),h!==null&&i(`p`,{className:`text-[11px] text-danger`,role:`alert`,children:h})]})}c();var Zn=30;function Qn(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<Zn*864e5}function $n(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function er(){let{t}=Y(),n=l(),r=nt(void 0,{refetchInterval:15e3}),a=ke({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=be({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),c=Ze({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),u=at({onSuccess:()=>{m(!1),g(``),v(``),b(``),n.invalidateQueries({queryKey:[[`localNetwork`]]})}}),d=r.data,[p,m]=o(!1),[h,g]=o(``),[_,v]=o(``),[y,b]=o(``),x=()=>{if(!d?.caCertPem)return;let e=new Blob([d.caCertPem],{type:`application/x-pem-file`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`camstack-ca.crt`,n.click(),URL.revokeObjectURL(t)},S=d?.mode===`uploaded`?`Uploaded`:d?.mode===`generated`?`Generated local CA`:`TLS disabled`;return i(Pe,{headingId:`local-access-certificate`,title:t(`system.localAccess.certificate`,`Certificate`),icon:T,children:e(`div`,{className:`${f} space-y-3`,children:[r.isError&&i(`p`,{className:`text-xs text-danger`,children:t(`system.localAccess.couldNotReadTlsStatus`,`Could not read TLS status.`)}),d?.reissueError&&i(W,{variant:`warning`,title:t(`system.localAccess.certificateReissue`,`Certificate reissue`),message:d.reissueError}),d?.restartRequired&&i(W,{variant:`warning`,title:t(`system.localAccess.restartRequired`,`Restart required`),message:t(`system.localAccess.theHttpsListenerStillServes`,`The HTTPS listener still serves the previous certificate. Restart the hub to apply it.`)}),d?.caMissing===!0&&i(W,{variant:`warning`,title:t(`system.localAccess.caMissingTitle`,`CA missing - devices cannot trust this hub`),message:t(`system.localAccess.caMissingBody`,"The uploaded certificate was not issued by a public CA and no CA was stored with it, so Download CA has nothing to hand out. Upload the certificate again together with its CA (for mkcert, the rootCA.pem in the folder `mkcert -CAROOT` prints).")}),d?.caReplacedAt!=null&&Qn(d.caReplacedAt)&&i(W,{variant:`warning`,title:t(`system.localAccess.caReplacedTitle`,`The local CA was replaced - re-install it on your devices`),message:t(`system.localAccess.caReplacedBody`,`The previous local CA had no name constraints: if its key ever leaked it could vouch for any website. The hub now uses a CA limited to private addresses and local names. Download it again and trust it on every phone and computer that used the old one (replaced {{when}}).`,{when:new Date(d.caReplacedAt).toLocaleString()})}),e(`dl`,{className:`grid grid-cols-1 gap-2 text-xs sm:grid-cols-2`,children:[e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.mode`,`Mode`)}),i(`dd`,{className:`font-medium`,children:S})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.validTo`,`Valid to`)}),i(`dd`,{className:`font-mono`,children:d?.validTo?new Date(d.validTo).toLocaleString():`—`})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.leafSha256`,`Leaf SHA-256`)}),i(`dd`,{className:`font-mono`,title:d?.leafFingerprintSha256??void 0,children:$n(d?.leafFingerprintSha256??null)})]}),d?.storedUpload!=null&&e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.storedUpload`,`Stored upload`)}),i(`dd`,{className:`font-medium`,children:t(`system.localAccess.storedUploadValue`,`valid to {{validTo}}, {{ca}}`,{validTo:new Date(d.storedUpload.validTo).toLocaleDateString(),ca:d.storedUpload.hasCa?t(`system.localAccess.storedUploadWithCa`,`with its CA`):t(`system.localAccess.storedUploadNoCa`,`no CA`)})})]}),e(`div`,{children:[i(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.caSha256`,`CA SHA-256`)}),i(`dd`,{className:`font-mono`,title:d?.caFingerprintSha256??void 0,children:d?.mode===`uploaded`&&d.caFingerprintSha256===null?i(`span`,{className:`font-sans text-foreground-subtle`,children:t(`system.localAccess.issuerNotIncludedInThe`,`Issuer not included in the upload (not the local CA)`)}):$n(d?.caFingerprintSha256??null)})]})]}),d&&d.sans.length>0&&i(`div`,{className:`flex flex-wrap gap-1`,children:d.sans.map(e=>i(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 font-mono text-[10px] text-foreground-subtle`,children:e},e))}),e(`div`,{className:`flex flex-wrap gap-2`,children:[i(We,{label:t(`system.localAccess.regenerate`,`Regenerate`),title:t(`system.localAccess.issueANewLeaf`,`Issue a new leaf?`),description:t(`system.localAccess.issuesANewLeafUnder`,`Issues a new leaf under the current local CA. Clients that trust the CA keep working. The HTTPS listener reloads.`),confirmLabel:t(`system.localAccess.regenerate`,`Regenerate`),disabled:d?.mode===`uploaded`||a.isPending,action:()=>a.mutateAsync({})}),i(G,{size:`sm`,variant:`outline`,onClick:()=>m(e=>!e),children:t(`system.localAccess.upload`,`Upload`)}),d?.caCertPem&&i(G,{size:`sm`,variant:`outline`,onClick:x,children:t(`system.localAccess.downloadCa`,`Download CA`)}),d?.mode===`uploaded`&&i(We,{label:t(`system.localAccess.revertToGenerated`,`Revert to generated`),title:t(`system.localAccess.revertTitle`,`Switch back to the generated certificate?`),description:t(`system.localAccess.keepsTheUploadedPair`,`Returns to the generated local CA. The uploaded certificate and its CA stay stored here; you can select them again.`),confirmLabel:t(`system.localAccess.revert`,`Revert`),disabled:s.isPending,action:()=>s.mutateAsync({})}),d?.mode===`generated`&&d.storedUpload!=null&&i(We,{label:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),title:t(`system.localAccess.useUploadedTitle`,`Serve the stored upload again?`),description:t(`system.localAccess.useUploadedDescription`,`The stored uploaded certificate replaces the generated one on the HTTPS listener. The generated certificate stays stored.`),confirmLabel:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),disabled:c.isPending,action:()=>c.mutateAsync(void 0)})]}),p&&e(`div`,{className:`space-y-2 border-t border-border pt-3`,children:[i(Xn,{kind:`certificate`,label:t(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:h,onChange:g}),i(Xn,{kind:`privateKey`,label:t(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:_,onChange:v}),i(Xn,{kind:`ca`,label:t(`system.localAccess.caPemRequired`,`CA (PEM) - required unless the certificate comes from a public CA`),value:y,onChange:b,rows:4}),i(G,{size:`sm`,disabled:!h.trim()||!_.trim()||Jn(`certificate`,h)!==null||Jn(`privateKey`,_)!==null||Jn(`ca`,y)!==null||u.isPending,onClick:()=>u.mutate({certPem:h,keyPem:_,...y.trim()?{caPem:y}:{}}),children:t(`system.localAccess.saveCertificate`,`Save certificate`)}),u.isError&&i(`p`,{className:`text-xs text-danger`,children:u.error instanceof Error?u.error.message:t(`system.localAccess.uploadFailed`,`Upload failed`)})]})]})})}var tr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function nr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function rr({https:t,mesh:n,now:r}){let{t:a}=Y(),o=nt().data?.caCertPem??``,s=()=>{if(o===``)return;let e=URL.createObjectURL(new Blob([o],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},c=n?.ca,l=c?.state===`ready`?Date.parse(c.validTo):null,u=n?.listener;return e(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[i(q,{label:a(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[nr(t)??`—`,o!==``&&e(G,{type:`button`,variant:`ghost`,size:`sm`,onClick:s,children:[i(v,{className:`h-3 w-3`,"aria-hidden":!0}),a(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),i(q,{label:a(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:c===void 0?`—`:c.state===`ready`?c.fingerprintSha256:i(`span`,{className:`text-danger`,children:a(`certificates.caStrip.unavailable`,{reason:c.reason})})}),c?.state===`ready`&&e(q,{label:a(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[c.validTo,l!==null&&!Number.isNaN(l)&&e(`span`,{className:`ml-2 text-[10px] ${tr[Ut(l,r)]}`,children:[`(`,kt(l,r),`)`]})]}),u!==void 0&&e(q,{label:a(`certificates.caStrip.nodeListener`,`Node listener`),children:[u.state===`open`&&i(K,{variant:`success`,children:a(`certificates.caStrip.open`,`Open`)}),u.state===`not-started`&&i(K,{variant:`default`,children:a(`certificates.caStrip.notStarted`,`Not started`)}),u.state===`closed`&&e(`span`,{className:`text-danger`,children:[a(`certificates.caStrip.closedSince`,{when:At(u.since)}),` `,u.reason]})]}),n!==void 0&&!n.registryAvailable&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[i(F,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),i(`span`,{children:a(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function ir(e,t){let n=new Set;for(let t of e)n.add(t.nodeId);for(let e of t?.nodes??[])n.add(e.nodeId);return[...n].map(n=>{let r=e.find(e=>e.nodeId===n)??null,i=t?.nodes.find(e=>e.nodeId===n)??null;return{nodeId:n,isHub:r?.isHub??n===`hub`,online:r?.online??i?.online??!1,https:r,mesh:i}}).toSorted((e,t)=>Number(t.isHub)-Number(e.isHub)||e.nodeId.localeCompare(t.nodeId))}function ar(e){return e.isHub?J.t(`helpers.nodesModel.hubReissued`):e.mesh===null?J.t(`helpers.nodesModel.noCertRecorded`):e.online?null:J.t(`helpers.certificateModel.nodeOffline`)}function or(e){return e.isHub||e.mesh===null?ar(e):null}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},cr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},lr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function ur(e){let t=e.https?.https;return t?.kind===`served`?Vt(t.status.validTo):null}function dr({ms:t,now:n}){return t===null?i(`span`,{className:`text-foreground-subtle`,children:`—`}):e(`div`,{children:[i(`div`,{children:At(t)}),i(`div`,{className:`text-[10px] ${sr[Ut(t,n)]}`,children:kt(t,n)})]})}function fr({row:t}){let{t:n}=Y(),r=t.https?.https;return r===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):r.kind===`served`?e(`div`,{title:r.status.leafFingerprintSha256??``,children:[i(K,{variant:`success`,className:`text-[10px]`,children:n(`certificates.nodesColumns.served`,`Served`)}),i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:lr[r.status.mode]}),i(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Bt(r.status.leafFingerprintSha256)}),r.status.sans.length>0&&i(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:r.status.sans.join(`, `),children:r.status.sans.join(`, `)})]}):e(`div`,{className:`max-w-[16rem]`,children:[i(K,{variant:r.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:r.kind===`unreadable`?n(`certificates.nodesColumns.unreadable`,`Unreadable`):n(`certificates.nodesColumns.notServed`,`Not served`)}),i(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:r.reason})]})}function pr({row:t}){let{t:n}=Y(),r=t.mesh?.current??null;if(r===null)return i(`span`,{className:`text-foreground-subtle`,children:n(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let a=t.mesh?.history.length??0;return e(`div`,{children:[i(`div`,{className:`font-mono text-[11px]`,title:r.serial,children:Lt(r.serial)}),i(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:r.fingerprintSha256,children:Bt(r.fingerprintSha256)}),e(`div`,{className:`text-[10px] text-foreground-subtle`,children:[cr[r.issuedVia],a>0?` · ${n(`certificates.nodesColumns.earlier`,{count:a})}`:``]})]})}function mr({row:e}){let{t}=Y(),n=e.mesh?.presentingCurrent??null;return n===null?i(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?i(K,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):i(K,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function hr(t){let n=t.icon;return e(G,{type:`button`,variant:`ghost`,size:`sm`,className:t.danger?`text-danger hover:bg-danger/10`:void 0,disabled:t.reason!==null||t.busy,title:t.reason??void 0,"aria-label":t.ariaLabel,onClick:t.onClick,children:[t.spinning?i(D,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):i(n,{className:`h-3 w-3`,"aria-hidden":!0}),t.label]})}function gr({reasons:t}){let{t:n}=Y();return e(et,{className:`inline-block`,children:[i(Ue,{children:i(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:n(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),i(Je,{children:i(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:t.map(e=>i(`li`,{children:e},e))})})]})}function _r({row:t,o:n}){let{t:r}=Y(),a=t.https===null?`No HTTPS inventory for this node.`:jt(t.https).reason,o=ar(t),s=or(t),c=e=>n.running?.nodeId===t.nodeId&&n.running.action===e,l=e=>!t.isHub||e===null,u=[a,o,s].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);return e(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[e(`div`,{className:`flex flex-col items-end gap-0.5`,children:[l(a)&&i(hr,{label:r(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:r(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:t.nodeId}),icon:p,reason:a,busy:n.busy,spinning:c(`renew-https`),danger:!1,onClick:()=>n.onRenewHttps(t)}),l(o)&&i(hr,{label:c(`renew-identity`)?r(`certificates.nodesColumns.renewing`,`Renewing…`):r(`certificates.nodesColumns.renewIdentity`,`Renew identity`),ariaLabel:r(`certificates.nodesColumns.renewTheClusterCertificateOf`,`Renew the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:p,reason:o,busy:n.busy,spinning:c(`renew-identity`),danger:!1,onClick:()=>n.onRenewIdentity(t)}),l(s)&&i(hr,{label:r(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:r(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:y,reason:s,busy:n.busy,spinning:c(`revoke-identity`),danger:!0,onClick:()=>n.onRevokeIdentity(t)})]}),t.isHub&&u.length>0&&i(gr,{reasons:u}),!t.isHub&&a!==null&&t.https!==null&&i(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${t.nodeId}`,children:a}),!t.isHub&&o!==null&&i(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${t.nodeId}`,children:o})]})}function vr(t){return[{key:`node`,header:J.t(`certificates.nodesColumns.node`,`Node`),sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:t=>e(`div`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`font-medium text-foreground`,children:t.nodeId}),t.nodeId===`hub`&&i(K,{variant:`info`,className:`text-[10px]`,children:J.t(`common.hubWord`)}),!t.online&&i(K,{variant:`default`,className:`text-[10px]`,children:J.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>i(fr,{row:e})},{key:`https-expires`,header:J.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>ur(e),render:e=>i(dr,{ms:ur(e),now:t.now})},{key:`identity`,header:J.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>i(pr,{row:e})},{key:`identity-expires`,header:J.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:e=>i(dr,{ms:e.mesh?.current?.notAfter??null,now:t.now})},{key:`presenting`,header:J.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>i(mr,{row:e})},{key:`actions`,header:J.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:e=>i(_r,{row:e,o:t})}]}c();function yr(){let{t}=Y(),r=N(),a=U.useUtils(),s=Rn(6e4),c=U.certificates.listHttpsCertificates.useQuery(),l=U.certificates.getMeshCertificates.useQuery(),[u,d]=o(null),[f,p]=o(null),[m,h]=o(null),g=()=>{h(null),a.certificates.listHttpsCertificates.invalidate(),a.certificates.getMeshCertificates.invalidate()},_=e=>(t,n)=>{h(null),d(`${n.nodeId}: ${e} - ${t.message}`)},v=U.certificates.renewHttpsOnNode.useMutation({onSuccess:(e,n)=>{p({tone:`success`,message:e.restartRequired?t(`certificates.nodesCard.newCertificateIssuedRestartThe`,`{{nodeId}}: new certificate issued. Restart the node to serve it.`,{nodeId:n.nodeId}):t(`certificates.nodesCard.newCertificateIssuedAndServed`,`{{nodeId}}: new certificate issued and served.`,{nodeId:n.nodeId})}),g()},onError:_(`renewal failed`)}),y=U.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(It(e)),g()},onError:_(`renewal could not start`)}),x=U.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}`}),g()},onError:_(`revoke failed`)}),S=v.isPending||y.isPending||x.isPending,C=(e,t)=>{d(null),p(null),h({nodeId:e,action:t})},w=async e=>{await r({title:t(`certificates.nodesCard.renewHttpsOn`,`Renew HTTPS on "{{nodeId}}"?`,{nodeId:e.nodeId}),message:e.isHub?t(`certificates.nodesCard.aNewCertificateIsIssued`,`A new certificate is issued from the local CA. Clients that trust the CA keep working.`):t(`certificates.nodesCard.theNodeMakesANew`,`The node makes a new key, the hub signs it and the node switches over without a restart. It keeps serving what it had if anything fails.`),confirmLabel:t(`certificates.nodesCard.renew`,`Renew`)})&&(C(e.nodeId,`renew-https`),v.mutate({nodeId:e.nodeId}))},T=e=>{C(e.nodeId,`renew-identity`),y.mutate({nodeId:e.nodeId})},E=async e=>{await r({title:t(`certificates.nodesCard.revokeTheIdentityOf`,`Revoke the identity of "{{nodeId}}"?`,{nodeId:e.nodeId}),message:t(`certificates.nodesCard.isDisconnectedAtOnceAnd`,`{{nodeId}} is disconnected at once and can no longer connect. To bring it back it must be paired again from System → Cluster → Agents. It stays in the node list until you forget it on the Cluster page. This cannot be undone.`,{nodeId:e.nodeId}),confirmLabel:t(`certificates.nodesCard.revokeAndDisconnect`,`Revoke and disconnect`),variant:`danger`})&&(C(e.nodeId,`revoke-identity`),x.mutate({nodeId:e.nodeId}))},D=vr({now:s,busy:S,running:m,onRenewHttps:e=>void w(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),O=n(()=>ir(c.data??[],l.data),[c.data,l.data]),k=l.data?.registryAvailable??!0;return i(X,{id:`nodes`,title:t(`certificates.nodesCard.nodes`,`Nodes`),icon:b,description:t(`certificates.nodesCard.eachNodeHoldsTwoCertificates`,`Each node holds two certificates: one it serves over HTTPS, one that proves its identity to the hub. Renewing replaces a certificate without a gap; revoking an identity cuts the node off until it re-joins.`),notice:Ft(u,f),onDismissNotice:()=>{d(null),p(null)},children:i(Fn,{isPending:c.isPending||l.isPending,error:c.error??l.error,what:`node certificates`,onRetry:()=>{c.refetch(),l.refetch()},children:e(`div`,{className:`space-y-3`,children:[i(rr,{https:c.data??[],mesh:l.data,now:s}),i(we,{columns:D,rows:O,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:me,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:k?t(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):t(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function br({pairOpen:t,onPairClose:n}){return e(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[i(Wn,{pairOpen:t,onPairClose:n}),i(In,{}),i(er,{}),i(yr,{})]})}function xr({userId:t,username:n,onClose:r}){let{t:a}=Y(),o=N(),s=U.useUtils(),c=xe({userId:t}),l=U.auth.listLoginMethods.useQuery(),u=Ke({onSuccess:()=>void s.userManagement.listExternalIdentities.invalidate()}),d=new Map((l.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=c.data??[],p=async(e,r)=>{await o({title:a(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:a(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:n,label:r}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&u.mutate({userId:t,provider:e.provider,subject:e.subject})};return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(k,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.externalIdentitiesModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),i(ze,{className:`space-y-3`,children:c.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),a(`common.loading`,`Loading…`)]}):f.length===0?i(`p`,{className:`text-xs text-foreground-subtle`,children:a(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`No linked accounts. Only the user can link one, from their own profile page.`)}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:f.map(t=>{let n=d.get(t.provider),r=n??t.provider;return e(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[e(`div`,{className:`flex-1 min-w-0`,children:[e(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&i(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:a(`users.externalIdentitiesModal.providerUnavailable`,`provider unavailable`)})]}),e(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[t.label??t.subject,` ·`,` `,new Date(t.linkedAt).toLocaleDateString()]})]}),e(`button`,{onClick:()=>void p(t,r),disabled:u.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[i(de,{className:`h-3 w-3`}),a(`common.remove`,`Remove`)]})]},`${t.provider}|${t.subject}`)})})}),i(Ge,{children:i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)})})]})})}function Sr({userId:t,username:n,onClose:r}){let{t:a}=Y(),o=l(),s=N(),c=je({userId:t}),u=c.data,f=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),p=Oe({onSuccess:()=>{f(),r()}}),m=c.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(x,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.totpModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),e(ze,{className:`space-y-4`,children:[m===`loading`&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),a(`users.totpModal.checkingStatus`,`Checking status…`)]}),m===`not_enrolled`&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[i(C,{className:`h-4 w-4 mt-0.5 shrink-0`}),e(`div`,{children:[i(`div`,{className:`font-medium text-foreground`,children:a(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),i(`p`,{className:`mt-0.5`,children:a(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),m===`enrolled`&&u&&e(d,{children:[e(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[i(S,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),e(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[i(`div`,{className:`font-medium`,children:a(`users.totpModal.2faIsActive`,`2FA is active`)}),i(`div`,{className:`text-foreground-subtle`,children:a(`common.enrolledOn`,{when:u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`})})]})]}),i(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`users.totpModal.removingHereClearsTheServer`,`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`)}),e(`div`,{className:`flex justify-end gap-2`,children:[i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)}),e(`button`,{onClick:async()=>{await s({title:a(`users.totpModal.remove2fa`,`Remove 2FA`),message:a(`users.totpModal.removeTwoFactorAuthenticationFor`,`Remove two-factor authentication for "{{username}}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,{username:n}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&p.mutate({userId:t})},disabled:p.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[p.isPending?i(D,{className:`h-3 w-3 animate-spin`}):i(O,{className:`h-3 w-3`}),a(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}c();function Cr({userId:t,username:n,onClose:r}){let{t:a}=Y(),{user:s,logout:c}=_t(),l=s?.id===t,u=N(),d=U.useUtils(),f=U.auth.listSessions.useQuery({userId:t}),[p,m]=o(null),h=U.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(l&&`userId`in t){c();return}d.auth.listSessions.invalidate()},onError:e=>m(`Sign out failed: ${e.message}`)}),g=async e=>{await u({title:a(`users.userSessionsModal.signOutThisSession`,`Sign out this session`),message:a(`users.userSessionsModal.onWillHaveToSign`,`"{{username}}" on {{label}} will have to sign in again.`,{username:n,label:Wt(e.client).label}),confirmLabel:a(`users.userSessionsModal.signOut`,`Sign out`),variant:`danger`})&&(m(null),h.mutate({id:e.id}))},_=async()=>{await u({title:a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),message:l?a(`users.userSessionsModal.everySessionOfYourOwn`,`Every session of your own account ends, this browser included: you will be signed out here too.`):a(`users.userSessionsModal.everySessionOfEndsAt`,`Every session of "{{username}}" ends at once; each device has to sign in again.`,{username:n}),confirmLabel:a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),variant:`danger`})&&(m(null),h.mutate({userId:t}))},v=h.isPending&&h.variables!==void 0&&`id`in h.variables?h.variables.id:null;return i(Ie,{open:!0,onOpenChange:e=>!e&&r(),children:e(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[i(He,{children:e(Me,{className:`flex items-center gap-2`,children:[i(ue,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.userSessionsModal.activeSessions`,`Active sessions`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.userSessionsModal.user`,`User:`),` `,i(`span`,{className:`font-mono`,children:n})]})]})]})}),e(ze,{className:`space-y-3`,children:[p!==null&&i(`div`,{className:`text-[11px] text-danger`,children:p}),i(Ht,{sessions:f.data??[],isLoading:f.isLoading,loadError:f.isError?f.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:v})]}),e(Ge,{className:`justify-between`,children:[e(`button`,{onClick:()=>void _(),disabled:h.isPending||(f.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[h.isPending&&v===null?i(D,{className:`h-3 w-3 animate-spin`}):i(ce,{className:`h-3 w-3`}),a(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),i(G,{onClick:r,variant:`secondary`,children:a(`common.close`,`Close`)})]})]})})}function wr({scopes:t,invalidReason:n}){let{t:r}=Y(),a=E(),o=s({queryKey:[`auth`,`previewScope`,t,!1],enabled:n===null,queryFn:()=>a.trpcClient.auth.previewScope.query({scopes:[...t],isAdmin:!1})}),{data:c}=V({projection:`slim`}),l=c?.length??null;if(n!==null)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,"data-testid":`role-preview`,children:[i(j,{className:`h-3 w-3 shrink-0`}),n]});if(o.isLoading)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,"data-testid":`role-preview`,children:[i(D,{className:`h-3 w-3 shrink-0 animate-spin`}),r(`users.rolePreview.resolving`)]});if(o.isError||!o.data)return i(`p`,{className:`text-[11px] text-danger`,"data-testid":`role-preview`,children:r(`users.rolePreview.couldNotResolve`)});let u=o.data.viewableDeviceCount,d=o.data.device.view.all?r(`users.rolePreview.everyDevice`,{count:u}):l===null?r(`users.rolePreview.devicesVisible`,{count:u}):r(`users.rolePreview.devicesVisibleOf`,{count:u,total:l});return e(`p`,{className:`flex items-center gap-1.5 text-[11px] ${u===0?`text-warning`:`text-foreground`}`,"data-testid":`role-preview`,children:[u===0?i(j,{className:`h-3 w-3 shrink-0`}):i(_,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u===0?r(`users.rolePreview.noDevice`):d]})}function Tr(e){let t=ne(e.scopes??[]);if(t===null)return{role:e.isAdmin?`admin`:`viewer`,mode:`except`,pickedIds:[],viewer:z,unconfigured:!e.isAdmin};let n=Mr(t);return{role:e.isAdmin?`admin`:`viewer`,mode:n.mode,pickedIds:n.pickedIds,viewer:Nr(n.mode,n.pickedIds,t.features),unconfigured:!1}}function Er(e,t){return{...e,role:t}}function Dr(e,t){return{...e,mode:t,viewer:Nr(t,e.pickedIds,e.viewer.features)}}function Or(e,t){let n=Pr(t);return{...e,pickedIds:n,viewer:Nr(e.mode,n,e.viewer.features)}}function kr(e,t,n){let r=e.viewer.features.filter(e=>e!==t),i=n?[...r,t]:r;return{...e,viewer:Nr(e.mode,e.pickedIds,i)}}function Ar(e){return e.role===`viewer`&&e.mode===`only`&&e.pickedIds.length===0?`no-allowed-device`:null}function jr(e){return Ar(e)===null?e.role===`admin`?{isAdmin:!0,scopes:[]}:{isAdmin:!1,scopes:[e.viewer]}:null}function Mr(e){if(e.allow===`*`)return{mode:`except`,pickedIds:e.block};let t=new Set(e.block);return{mode:`only`,pickedIds:e.allow.filter(e=>!t.has(e))}}function Nr(e,t,n){let r=Pr(t);return e===`except`?{type:`viewer`,allow:`*`,block:r,features:[...n]}:{type:`viewer`,allow:r,block:[],features:[...n]}}function Pr(e){return[...new Set(e)]}c();var Fr=`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`;function Ir(e,t){return e?`failed`:t===void 0?`pending`:`answered`}function Lr(e){let t=[];for(let n of e)n.parentDeviceId===null&&t.push({id:n.id,name:n.name,type:String(n.type),...n.location===null?{}:{location:n.location}});return t}function Rr({user:t,isSelf:r,onClose:a,onSubmit:s,submitting:c,error:l}){let{t:u}=Y(),[f,p]=o(n(()=>Tr(t),[t])),m=V({projection:`slim`}),h=m.data,g=Ir(m.isError,h),_=n(()=>Lr(h??[]),[h]),v=n(()=>({state:g,devices:g===`answered`?(h??[]).map(e=>({id:e.id,name:e.name})):void 0}),[g,h]),y=Ar(f),b=jr(f),x=y===`no-allowed-device`?u(`users.userAccessModal.pickAllowedDevice`):null,S=e=>{p(Er(f,e))},C=[{value:`except`,label:u(`users.userAccessModal.modeExcept`)},{value:`only`,label:u(`users.userAccessModal.modeOnly`)}];return i(Ie,{open:!0,onOpenChange:e=>!e&&a(),children:e(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[i(He,{children:i(Me,{children:u(`users.userAccessModal.title`,{name:t.username})})}),e(ze,{className:`space-y-4`,children:[f.unconfigured&&f.role===`viewer`&&i(W,{variant:`warning`,title:u(`users.userAccessModal.noAccessYet`),message:u(`users.userAccessModal.noAccessYetDetail`,{name:t.username})}),e(`section`,{className:`space-y-2`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.role`)}),e(`div`,{role:`radiogroup`,"aria-label":u(`users.userAccessModal.role`),className:`grid gap-1.5 sm:grid-cols-2`,children:[i(zr,{name:`admin`,checked:f.role===`admin`,label:u(`users.userAccessModal.admin`),description:u(`users.userAccessModal.adminDescription`),onPick:()=>S(`admin`)}),i(zr,{name:`viewer`,checked:f.role===`viewer`,disabled:r,label:u(`users.userAccessModal.viewer`),description:u(r?`users.userAccessModal.cannotDemoteSelf`:`users.userAccessModal.viewerDescription`),onPick:()=>S(`viewer`)})]})]}),f.role===`viewer`&&e(d,{children:[e(`section`,{className:`space-y-3`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.devices`)}),i(it,{label:u(`users.userAccessModal.whichDevices`),value:f.mode,options:C,onChange:e=>p(Dr(f,e))}),i(Se,{devices:_,listState:g,fleet:v,value:[...f.pickedIds],onChange:e=>p(Or(f,e)),emptyMeansAll:f.mode===`except`,noun:`device`,testId:`viewer-device-picker`}),i(wr,{scopes:b?.scopes??[],invalidReason:x})]}),e(`section`,{className:`space-y-2`,children:[i(`h3`,{className:Fr,children:u(`users.userAccessModal.features`)}),i(`div`,{className:`space-y-1`,children:te.map(t=>e(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md p-1.5 hover:bg-surface-hover`,children:[i(Te,{className:`mt-0.5`,checked:f.viewer.features.includes(t.id),onChange:e=>p(kr(f,t.id,e.target.checked))}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block text-[12px] font-medium text-foreground`,children:u(`users.viewerFeatures.${t.id}.label`,t.label)}),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:u(`users.viewerFeatures.${t.id}.description`,t.description)})]})]},t.id))})]})]}),l!==null&&i(W,{message:l})]}),e(Ge,{children:[i(G,{variant:`outline`,size:`sm`,onClick:a,children:u(`common.cancel`,`Cancel`)}),i(G,{size:`sm`,onClick:()=>b!==null&&s(b),disabled:c||b===null,children:c?i(D,{className:`h-3 w-3 animate-spin`}):u(`users.userAccessModal.saveAccess`)})]})]})})}function zr({name:t,checked:n,disabled:r=!1,label:a,description:o,onPick:s}){return e(`label`,{className:`flex items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-surface-hover`} ${r?`cursor-not-allowed opacity-60`:`cursor-pointer`}`,children:[i(`input`,{type:`radio`,name:`user-role`,value:t,checked:n,disabled:r,onChange:s,className:`mt-0.5`}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block text-[12px] font-medium text-foreground`,children:a}),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:o})]})]})}c();var Br=8;function Vr(){return{username:``,password:``,isAdmin:!1}}function Hr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Ur(e){return e instanceof Error?e.message:J.t(`admin.system.users.genericError`)}function Wr(){let{t}=Y(),n=l(),{user:r}=_t(),{state:s,openNew:c,openEdit:u,close:f}=Be(),[p,_]=o(null),[v,y]=o(null),[b,S]=o(!1),{data:C,isLoading:T,isError:E,error:O,refetch:ee}=Le(),j=N(),P=w(),F=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),I=_e(),L=Ae({onSuccess:F}),R=Ne({onSuccess:F}),te=ot({onSuccess:F}),ne=rt(),[z,B]=o(null),[re,ie]=o(!1),[oe,se]=o(null),[ce,le]=o(null),[de,fe]=o(null),[pe,me]=o(null),V=C??[],H=s.mode===`edit`?V.find(e=>e.id===s.id)??null:null,ge=()=>{_(null),y(null),S(!1),I.reset(),R.reset(),f()};a(()=>{if(s.mode===`closed`){_(null),y(null),S(!1);return}if(s.mode===`new`){_(e=>e!==null&&e.id===void 0?e:Vr());return}if(H===null){T||f();return}_(e=>e?.id===H.id?e:Hr(H))},[s,H,T,f]);let U=s.mode===`new`&&p!==null&&p.id===void 0||s.mode===`edit`&&p!==null&&H!==null;async function ve(e){await j({title:t(`admin.system.users.deleteUser`,`Delete user`),message:t(`admin.system.users.permanentlyDeleteUserThisCannot`,`Permanently delete user "{{username}}"? This cannot be undone — any active sessions will be revoked on next request.`,{username:e.username}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&(L.mutate({id:e.id}),s.mode===`edit`&&s.id===e.id&&ge())}async function ye(e){let n=await P({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.setANewPasswordFor`,`Set a new password for "{{username}}".`,{username:e.username}),label:t(`admin.system.users.newPassword`,`New password`),inputType:`password`,placeholder:t(`admin.system.users.atLeast8Characters`,`At least 8 characters`),confirmLabel:t(`admin.system.users.continue`,`Continue`),validate:e=>e.length<Br?J.t(`admin.system.users.passwordTooShort`,{min:Br}):null});n===null||n.length===0||await j({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.resetThePasswordForThey`,`Reset the password for "{{username}}"? They will need to use the new password on their next login.`,{username:e.username}),confirmLabel:t(`common.reset`,`Reset`)})&&te.mutate({id:e.id,newPassword:n})}function be(e){se(null),B(e)}async function xe(e,t){ie(!0),se(null);try{t.isAdmin!==e.isAdmin&&await R.mutateAsync({id:e.id,isAdmin:t.isAdmin}),await ne.mutateAsync({userId:e.id,scopes:[...t.scopes]}),B(null)}catch(e){se(Ur(e))}finally{ie(!1),F()}}async function Se(){if(p!==null){y(null);try{if(p.id===void 0){let e=p.username.trim();if(e===``||p.password.length<Br)return;await I.mutateAsync({username:e,password:p.password,isAdmin:p.isAdmin})}else await R.mutateAsync({id:p.id,isAdmin:p.isAdmin});F(),ge()}catch(e){y(Ur(e))}}}function Ce(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let Te=I.isPending||R.isPending,Ee=p!==null&&p.id===void 0&&p.username.trim()!==``&&p.password.length>=Br,De=p!==null&&p.id!==void 0,Oe=Te||(p?.id===void 0?!Ee:!De),ke=e=>L.isPending&&L.variables?.id===e.id||R.isPending&&R.variables?.id===e.id||te.isPending&&te.variables?.id===e.id,je=[{key:`username`,header:t(`admin.system.users.username`,`Username`),sortValue:e=>e.username,render:e=>i(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`scopes`,header:t(`admin.system.users.access`,`Access`),sortValue:e=>Gr(e),render:n=>i(`span`,{onClick:e=>e.stopPropagation(),children:e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>be(n),disabled:ke(n),title:t(`admin.system.users.configureAccess`,`Configure access`),"data-testid":`user-access-${n.id}`,children:[i(M,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),i(Kr,{user:n})]})})},{key:`createdAt`,header:t(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>i(`span`,{className:`text-foreground-subtle`,children:Ce(e.createdAt)})},{key:`actions`,header:t(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:n=>{let a=ke(n),o=n.id!==r?.id&&n.totpEnabled;return e(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(n.id),disabled:a,title:t(`admin.system.users.editUser`,`Edit user`),children:[i(g,{className:`h-3 w-3`}),t(`common.edit`,`Edit`)]}),o&&e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>le(n),disabled:a,title:t(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[i(x,{className:`h-3 w-3`}),t(`admin.system.users.remove2fa`,`Remove 2FA`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>fe(n),disabled:a,title:t(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[i(k,{className:`h-3 w-3`}),t(`admin.system.users.signInLinks`,`Sign-in links`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>me(n),disabled:a,title:t(`admin.system.users.activeSessions`,`Active sessions`),children:[i(ue,{className:`h-3 w-3`}),t(`admin.system.users.sessions`,`Sessions`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ye(n),disabled:a,title:t(`admin.system.users.resetPassword`,`Reset password`),children:[i(ae,{className:`h-3 w-3`}),t(`admin.system.users.resetPassword`,`Reset password`)]}),e(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ve(n),disabled:a,title:t(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[a?i(D,{className:`h-3 w-3 animate-spin`}):i(h,{className:`h-3 w-3`}),t(`common.delete`,`Delete`)]})]})}}];return e(bt,{embedded:!0,icon:A,title:t(`admin.system.users.users`,`Users`),subtitle:t(`admin.system.users.hubAccountsAdminFlagAccess`,`Hub accounts, admin flag, access scopes, sessions and sign-in links.`),actions:e(G,{size:`sm`,type:`button`,onClick:()=>{y(null),c()},children:[i(m,{className:`h-3.5 w-3.5`}),t(`admin.system.users.createUser`,`Create User`)]}),children:[E&&i(W,{title:t(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Ur(O),onRetry:()=>void ee()}),T&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`common.loading`,`Loading…`)]}),!T&&!E&&V.length===0&&i(he,{icon:A,title:t(`admin.system.users.noUsersYet`,`No users yet`),description:t(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!T&&!E&&V.length>0&&i(we,{columns:je,rows:V,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>u(e.id)}),i(Xe,{open:U,onClose:ge,title:p?.id===void 0?t(`admin.system.users.createUser`,`Create User`):t(`admin.system.users.edit`,`Edit {{value1}}`,{value1:p.username||`user`}),icon:A,error:v,testId:`user-form-dialog`,footer:i(G,{size:`sm`,type:`button`,disabled:Oe,onClick:()=>void Se(),children:Te?e(d,{children:[i(D,{className:`h-3.5 w-3.5 animate-spin`}),t(`admin.system.users.saving`,`Saving…`)]}):p?.id===void 0?t(`admin.system.users.create`,`Create`):t(`common.save`,`Save`)}),children:p!==null&&e(`div`,{className:`space-y-3`,children:[i(st,{label:t(`admin.system.users.username`,`Username`),required:p.id===void 0,children:i(Ve,{value:p.username,onChange:e=>_({...p,username:e.target.value}),placeholder:`john`,autoFocus:p.id===void 0,disabled:p.id!==void 0,"data-testid":`user-form-username`})}),p.id===void 0&&i(st,{label:t(`admin.system.users.password`,`Password`),required:!0,description:t(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Br)}),children:i(Re,{value:p.password,onValueChange:e=>_({...p,password:e}),shown:b,onToggleShown:()=>S(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),i(st,{label:t(`admin.system.users.admin`,`Admin`),description:t(`admin.system.users.unrestrictedAccessToEveryCapability`,`Unrestricted access to every capability and device.`),children:e(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(`input`,{type:`checkbox`,checked:p.isAdmin,onChange:e=>_({...p,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),i(`span`,{children:t(`admin.system.users.admin`,`Admin`)})]})}),p.id!==void 0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`admin.system.users.toChangeThePasswordUse`,`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`)})]})}),ce&&i(Sr,{userId:ce.id,username:ce.username,onClose:()=>le(null)}),de&&i(xr,{userId:de.id,username:de.username,onClose:()=>fe(null)}),pe&&i(Cr,{userId:pe.id,username:pe.username,onClose:()=>me(null)}),z&&i(Rr,{user:z,isSelf:z.id===r?.id,onClose:()=>B(null),onSubmit:e=>void xe(z,e),submitting:re,error:oe})]})}function Gr(e){let t=Tr(e);return t.role===`admin`?0:t.unconfigured?2:1}function Kr({user:t}){let{t:n}=Y(),r=Tr(t);if(r.role===`admin`)return i(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.admin`)});if(r.unconfigured)return i(`span`,{className:`font-medium text-warning`,children:n(`admin.system.users.noAccess`,`No access`)});let{allow:a,block:o,features:s}=r.viewer,c=a===`*`?n(`users.accessSummary.allDevices`):n(`users.accessSummary.devices`,{count:a.length});return e(`span`,{className:`text-foreground-subtle`,children:[i(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.viewer`)}),` ·`,` `,c,o.length>0&&e(d,{children:[` · `,n(`users.accessSummary.blocked`,{count:o.length})]}),s.length>0&&e(d,{children:[` · `,n(`users.accessSummary.features`,{count:s.length})]})]})}c();var qr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Jr=`certificates`;function Yr(t){return e(G,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:t,children:[i(x,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Xr(){let{t:e}=Y(),[t]=vt(),n=bn(),[r,a]=o(!1),s=qr[t.get(`tab`)??``];if(s!==void 0)return i(ft,{to:mt(`access`,{integration:s}),replace:!0});let c=ct(`/system/identity`,{t:e,isAdmin:!0})??{icon:ee,title:e(`system.identity`,`Identity & Access`)},l=t.get(`tab`)??`users`,u=t.get(`integration`),d=l===ut.access.tab?yn(u,n.requestCreate):l===`certificates`?Yr(()=>a(!0)):void 0;return i(yt,{icon:c.icon,title:c.title,defaultSection:`users`,sectionsLabel:`${c.title} sections`,actions:d,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:i(Wr,{})},{id:ut.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),ownedParams:pt.concat([Mt.token,Mt.scoped,Mt.admin]),content:i(vn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate})},{id:Jr,label:e(`systemPage.identity.certificates`,`Certificates`),content:i(br,{pairOpen:r,onPairClose:()=>a(!1)})},{id:ut.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:i(Nn,{}),ownedParams:pt}]})}export{Xr as IdentityPage};