@rubytech/create-maxy-code 0.1.352 → 0.1.354

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 (62) hide show
  1. package/package.json +1 -1
  2. package/payload/platform/lib/admin-access-password/__tests__/index.test.ts +96 -14
  3. package/payload/platform/lib/admin-access-password/dist/index.d.ts +20 -4
  4. package/payload/platform/lib/admin-access-password/dist/index.d.ts.map +1 -1
  5. package/payload/platform/lib/admin-access-password/dist/index.js +43 -4
  6. package/payload/platform/lib/admin-access-password/dist/index.js.map +1 -1
  7. package/payload/platform/lib/admin-access-password/src/index.ts +67 -4
  8. package/payload/platform/lib/admins-write/__tests__/index.test.ts +182 -0
  9. package/payload/platform/lib/admins-write/dist/index.d.ts +65 -11
  10. package/payload/platform/lib/admins-write/dist/index.d.ts.map +1 -1
  11. package/payload/platform/lib/admins-write/dist/index.js +93 -31
  12. package/payload/platform/lib/admins-write/dist/index.js.map +1 -1
  13. package/payload/platform/lib/admins-write/src/index.ts +133 -36
  14. package/payload/platform/package-lock.json +76 -1
  15. package/payload/platform/plugins/admin/PLUGIN.md +4 -0
  16. package/payload/platform/plugins/admin/mcp/dist/index.js +15 -3
  17. package/payload/platform/plugins/admin/mcp/dist/index.js.map +1 -1
  18. package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +16 -1
  19. package/payload/platform/plugins/cloudflare/skills/calendar-site/SKILL.md +2 -2
  20. package/payload/platform/plugins/cloudflare/skills/calendar-site/template/public/booking.css +41 -0
  21. package/payload/platform/plugins/cloudflare/skills/calendar-site/template/public/booking.js +236 -47
  22. package/payload/platform/plugins/cloudflare/skills/calendar-site/template/public/index.html +6 -0
  23. package/payload/platform/plugins/connector/mcp/dist/lib/call.d.ts +27 -9
  24. package/payload/platform/plugins/connector/mcp/dist/lib/call.d.ts.map +1 -1
  25. package/payload/platform/plugins/connector/mcp/dist/lib/call.js +102 -29
  26. package/payload/platform/plugins/connector/mcp/dist/lib/call.js.map +1 -1
  27. package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.d.ts +17 -6
  28. package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.d.ts.map +1 -1
  29. package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.js +28 -10
  30. package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.js.map +1 -1
  31. package/payload/platform/plugins/connector/mcp/package.json +13 -3
  32. package/payload/platform/plugins/docs/references/troubleshooting.md +15 -0
  33. package/payload/server/{chunk-QAKVFSEJ.js → chunk-7GNXBVGY.js} +38 -11
  34. package/payload/server/maxy-edge.js +1 -1
  35. package/payload/server/public/assets/{AdminLoginScreens-lt72mYrz.js → AdminLoginScreens-6WgO-Z3m.js} +1 -1
  36. package/payload/server/public/assets/{AdminShell-B-GeoG3j.js → AdminShell-GGnPXCOe.js} +1 -1
  37. package/payload/server/public/assets/{Checkbox-DoGMXVpF.js → Checkbox-D3XFVUMT.js} +1 -1
  38. package/payload/server/public/assets/OperatorConversations-CFWXdnjB.css +1 -0
  39. package/payload/server/public/assets/{OperatorConversations-CfG1EYyP.js → OperatorConversations-DeZ2wDEK.js} +1 -1
  40. package/payload/server/public/assets/{admin-DzLxv-nz.js → admin-B2yNhVvH.js} +1 -1
  41. package/payload/server/public/assets/{browser-Cyi6v8BS.js → browser-ByaQ0ItQ.js} +1 -1
  42. package/payload/server/public/assets/calendar-BjqCT8cW.js +1 -0
  43. package/payload/server/public/assets/chat-kl-Ips-o.js +1 -0
  44. package/payload/server/public/assets/{data-CrJZjlQ1.js → data-p9p-181v.js} +1 -1
  45. package/payload/server/public/assets/{graph-CutaO0w1.js → graph-BuunC8eP.js} +1 -1
  46. package/payload/server/public/assets/{graph-labels-CH0sWvcA.js → graph-labels-BF3Ak8q0.js} +1 -1
  47. package/payload/server/public/assets/{operator-MASl7IqX.js → operator-D7c8mN4J.js} +1 -1
  48. package/payload/server/public/assets/page-C6uMZdT1.js +32 -0
  49. package/payload/server/public/assets/{public-77Ubicd7.js → public-B9_UhjEa.js} +1 -1
  50. package/payload/server/public/browser.html +4 -4
  51. package/payload/server/public/calendar.html +4 -4
  52. package/payload/server/public/chat.html +5 -5
  53. package/payload/server/public/data.html +4 -4
  54. package/payload/server/public/graph.html +6 -6
  55. package/payload/server/public/index.html +6 -6
  56. package/payload/server/public/operator.html +7 -7
  57. package/payload/server/public/public.html +5 -5
  58. package/payload/server/server.js +1127 -1042
  59. package/payload/server/public/assets/OperatorConversations-C8G6Gfgu.css +0 -1
  60. package/payload/server/public/assets/calendar-CA3_Dm8j.js +0 -1
  61. package/payload/server/public/assets/chat-B9aNK1FG.js +0 -1
  62. package/payload/server/public/assets/page-CZy33qUH.js +0 -30
@@ -1,7 +1,42 @@
1
+ import { isIP } from "node:net";
2
+ import { Agent, fetch as undiciFetch } from "undici";
1
3
  import { redactHeaders, scrubSecret } from "./redact.js";
2
- import { guardTarget } from "./ssrf.js";
4
+ import { isPrivateIp, resolveTarget } from "./ssrf.js";
3
5
  const BODY_CAP = 262144; // 256 KiB
4
6
  const MAX_REDIRECTS = 5;
7
+ /** Tag carried by the fail-closed error a pinned lookup raises, so the connect-time refusal is distinguishable from a genuine network fault. */
8
+ const PIN_REFUSAL = "__connectorPinRefusal";
9
+ /**
10
+ * Build the DNS lookup an undici dispatcher uses to dial a connector. It returns the
11
+ * pre-validated addresses without consulting DNS — so no second, independent lookup
12
+ * happens at connect time — and re-validates each is public, failing closed. undici
13
+ * always calls it with `{ all: true }`; the single-result branch is kept for completeness.
14
+ */
15
+ export function pinnedLookup(addresses) {
16
+ return ((_hostname, options, cb) => {
17
+ const safe = addresses.filter((a) => !isPrivateIp(a));
18
+ if (safe.length === 0) {
19
+ cb(Object.assign(new Error("connector: pinned address failed public re-validation"), { [PIN_REFUSAL]: true }), "", 0);
20
+ return;
21
+ }
22
+ if (options?.all)
23
+ cb(null, safe.map((a) => ({ address: a, family: isIP(a) || 4 })));
24
+ else
25
+ cb(null, safe[0], isIP(safe[0]) || 4);
26
+ });
27
+ }
28
+ /** Dispatcher that dials only the validated addresses; TLS/SNI still use the hostname, so cert validation is unchanged. */
29
+ export function pinnedDispatcher(addresses) {
30
+ return new Agent({ connect: { lookup: pinnedLookup(addresses) } });
31
+ }
32
+ /** True when an error's cause chain carries the pinned-lookup fail-closed tag. */
33
+ function isPinRefusal(err) {
34
+ for (let cur = err; cur != null; cur = cur.cause) {
35
+ if (cur[PIN_REFUSAL] === true)
36
+ return true;
37
+ }
38
+ return false;
39
+ }
5
40
  /** Inject the credential per scheme. Returns the scheme label for the auth-applied log line. */
6
41
  function applyAuth(headers, rec, secret) {
7
42
  if (rec.authScheme === "bearer")
@@ -13,14 +48,16 @@ function applyAuth(headers, rec, secret) {
13
48
  return rec.authScheme;
14
49
  }
15
50
  /**
16
- * Make one authenticated, host-bound request to a registered connector. The guard runs
17
- * before the request and before every redirect hop; the credential is injected from the
18
- * caller-supplied secret and never logged. Returns status + redacted headers + capped body,
19
- * or a refusal when the guard rejects the target.
51
+ * Make one authenticated, host-bound request to a registered connector. The host is resolved
52
+ * and validated before the request and before every redirect hop, and the socket is pinned to
53
+ * the validated addresses so no second connect-time lookup can land on a rebind. The credential
54
+ * is injected from the caller-supplied secret and never logged. Returns status + redacted headers
55
+ * + capped body, or a refusal when resolution rejects the target.
20
56
  */
21
57
  export async function performCall(rec, secret, params, deps = {}) {
22
- const fetchImpl = deps.fetchImpl ?? fetch;
23
- const guard = deps.guard ?? guardTarget;
58
+ const fetchImpl = deps.fetchImpl ?? undiciFetch;
59
+ const resolve = deps.resolve ?? resolveTarget;
60
+ const makeDispatcher = deps.makeDispatcher ?? pinnedDispatcher;
24
61
  const log = deps.log ?? (() => { });
25
62
  const reqId = deps.reqId ?? "—";
26
63
  const url = new URL(params.path, rec.baseUrl);
@@ -32,11 +69,23 @@ export async function performCall(rec, secret, params, deps = {}) {
32
69
  for (const [k, v] of Object.entries(params.query))
33
70
  url.searchParams.set(k, v);
34
71
  log(`op=call reqId=${reqId} method=${params.method} host=${url.hostname} path=${url.pathname}`);
35
- const reqRefusal = await guard(url.hostname, rec.host, "request");
36
- if (reqRefusal) {
37
- log(`op=call-refused reqId=${reqId} reason=${reqRefusal} target=${url.hostname}`);
38
- return { ok: false, refused: reqRefusal };
72
+ const reqResolution = await resolve(url.hostname, rec.host, "request");
73
+ if (!reqResolution.ok) {
74
+ log(`op=call-refused reqId=${reqId} reason=${reqResolution.refused} target=${url.hostname}`);
75
+ return { ok: false, refused: reqResolution.refused };
39
76
  }
77
+ // Track every pinned dispatcher this call creates (initial + each redirect hop) so the
78
+ // finally can close them — an undici Agent holds a connection pool and timers and would
79
+ // otherwise leak in this long-lived process. A test seam returning undefined is untracked:
80
+ // that is the shared global dispatcher, which is never ours to close.
81
+ const createdDispatchers = [];
82
+ const pin = (addresses) => {
83
+ const d = makeDispatcher(addresses);
84
+ if (d)
85
+ createdDispatchers.push(d);
86
+ return d;
87
+ };
88
+ let dispatcher = pin(reqResolution.addresses);
40
89
  // Caller headers may not set the auth header or Host — those are ours to control.
41
90
  const headers = {};
42
91
  if (params.headers) {
@@ -60,25 +109,49 @@ export async function performCall(rec, secret, params, deps = {}) {
60
109
  const start = Date.now();
61
110
  let current = url;
62
111
  let hops = 0;
63
- let res;
64
- for (;;) {
65
- res = await fetchImpl(current.toString(), { method: params.method, headers, body: bodyStr, redirect: "manual" });
66
- const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
67
- if (!location || hops++ >= MAX_REDIRECTS)
68
- break;
69
- const next = new URL(location, current);
70
- const redirectRefusal = await guard(next.hostname, rec.host, "redirect");
71
- if (redirectRefusal) {
72
- log(`op=call-refused reqId=${reqId} reason=${redirectRefusal} target=${next.hostname}`);
73
- return { ok: false, refused: redirectRefusal };
112
+ try {
113
+ let res;
114
+ for (;;) {
115
+ res = await fetchImpl(current.toString(), {
116
+ method: params.method, headers, body: bodyStr, redirect: "manual",
117
+ // Omit when undefined so undici falls back to the global dispatcher (the test seam for
118
+ // a loopback stub); in production pin always returns the pinned dispatcher.
119
+ ...(dispatcher ? { dispatcher } : {}),
120
+ });
121
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
122
+ if (!location || hops++ >= MAX_REDIRECTS)
123
+ break;
124
+ const next = new URL(location, current);
125
+ const redirectResolution = await resolve(next.hostname, rec.host, "redirect");
126
+ if (!redirectResolution.ok) {
127
+ log(`op=call-refused reqId=${reqId} reason=${redirectResolution.refused} target=${next.hostname}`);
128
+ return { ok: false, refused: redirectResolution.refused };
129
+ }
130
+ dispatcher = pin(redirectResolution.addresses);
131
+ current = next;
74
132
  }
75
- current = next;
133
+ const raw = await res.text();
134
+ const truncated = raw.length > BODY_CAP;
135
+ // Scrub the credential from the body in case the upstream reflects it (debug/echo endpoints).
136
+ const body = scrubSecret(truncated ? raw.slice(0, BODY_CAP) : raw, secret);
137
+ log(`op=response reqId=${reqId} status=${res.status} bytes=${raw.length} ms=${Date.now() - start}`);
138
+ return { ok: true, status: res.status, headers: redactHeaders(res.headers, rec.headerName, secret), body, truncated };
139
+ }
140
+ catch (err) {
141
+ // A pinned lookup that fails its public re-validation at connect time surfaces here. The
142
+ // reason is the same as a resolve-time private address; the trigger is the pinned-lookup
143
+ // re-validation. Any other fetch error is a genuine fault, not a refusal — rethrow it.
144
+ if (isPinRefusal(err)) {
145
+ log(`op=call-refused reqId=${reqId} reason=private-ip target=${current.hostname}`);
146
+ return { ok: false, refused: "private-ip" };
147
+ }
148
+ throw err;
149
+ }
150
+ finally {
151
+ // The body is already buffered by now; close every dispatcher this call created. Fire-and-forget
152
+ // so socket teardown never delays the tool response.
153
+ for (const d of createdDispatchers)
154
+ void d.close().catch(() => { });
76
155
  }
77
- const raw = await res.text();
78
- const truncated = raw.length > BODY_CAP;
79
- // Scrub the credential from the body in case the upstream reflects it (debug/echo endpoints).
80
- const body = scrubSecret(truncated ? raw.slice(0, BODY_CAP) : raw, secret);
81
- log(`op=response reqId=${reqId} status=${res.status} bytes=${raw.length} ms=${Date.now() - start}`);
82
- return { ok: true, status: res.status, headers: redactHeaders(res.headers, rec.headerName, secret), body, truncated };
83
156
  }
84
157
  //# sourceMappingURL=call.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/lib/call.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAgB,MAAM,WAAW,CAAC;AAyBtD,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,UAAU;AACnC,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,gGAAgG;AAChG,SAAS,SAAS,CAAC,OAA+B,EAAE,GAAoB,EAAE,MAAc;IACtF,IAAI,GAAG,CAAC,UAAU,KAAK,QAAQ;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,EAAE,CAAC;SAC1E,IAAI,GAAG,CAAC,UAAU,KAAK,OAAO;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;;QAC7G,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAC,GAAG,MAAM,CAAC,CAAC,oDAAoD;IACrG,OAAO,GAAG,CAAC,UAAU,CAAC;AACxB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAoB,EACpB,MAAc,EACd,MAAkB,EAClB,OAAiB,EAAE;IAEnB,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC;IAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,WAAW,CAAC;IACxC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,GAAG,CAAC;IAEhC,MAAM,GAAG,GA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T,iGAAiG;QACjG,qDAAqD;QACrD,KAAK,MAAM,CAAC,IAAI,kBAAkB;YAAE,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACrE,CAAC;AACH,CAAC"}
@@ -7,12 +7,23 @@ export declare function isPrivateIp(ip: string): boolean;
7
7
  */
8
8
  export declare function hostResolvesPrivate(host: string): Promise<boolean>;
9
9
  export type Refusal = "host-mismatch" | "private-ip" | "redirect-escape";
10
+ export type Resolution = {
11
+ ok: true;
12
+ addresses: string[];
13
+ } | {
14
+ ok: false;
15
+ refused: Refusal;
16
+ };
10
17
  /**
11
- * Confirm a request/redirect target is the registered host and not a private address.
12
- * Returns a refusal reason, or null when the target is allowed. Hosts are normalised
13
- * (lowercased, brackets and a trailing FQDN dot stripped) before comparison. `kind`
14
- * distinguishes the mismatch label: an off-host initial request is "host-mismatch", an
15
- * off-host redirect is "redirect-escape".
18
+ * Resolve a request/redirect target to the validated public addresses the connection
19
+ * must pin to, or a refusal. The target must be the registered host (an off-host initial
20
+ * request is "host-mismatch", an off-host redirect is "redirect-escape"); the resolved set
21
+ * must be non-empty and every address public, else "private-ip". IP literals (incl.
22
+ * bracketed IPv6) skip DNS. Fails closed: a lookup error or empty result is a refusal.
23
+ *
24
+ * This is the single DNS lookup for a call. The caller pins the socket to the returned
25
+ * addresses so `fetch` performs no second, independent lookup — closing the window where
26
+ * a host could answer public here and private to the connect-time lookup.
16
27
  */
17
- export declare function guardTarget(targetHost: string, registeredHost: string, kind: "request" | "redirect"): Promise<Refusal | null>;
28
+ export declare function resolveTarget(targetHost: string, registeredHost: string, kind: "request" | "redirect"): Promise<Resolution>;
18
29
  //# sourceMappingURL=ssrf.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssrf.d.ts","sourceRoot":"","sources":["../../src/lib/ssrf.ts"],"names":[],"mappings":"AAwBA,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAqB/C;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAWxE;AAED,MAAM,MAAM,OAAO,GAAG,eAAe,GAAG,YAAY,GAAG,iBAAiB,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAsB,WAAW,CAC/B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,SAAS,GAAG,UAAU,GAC3B,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAMzB"}
1
+ {"version":3,"file":"ssrf.d.ts","sourceRoot":"","sources":["../../src/lib/ssrf.ts"],"names":[],"mappings":"AAwBA,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAqB/C;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAWxE;AAED,MAAM,MAAM,OAAO,GAAG,eAAe,GAAG,YAAY,GAAG,iBAAiB,CAAC;AAEzE,MAAM,MAAM,UAAU,GAClB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,EAAE,CAAA;CAAE,GACjC;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAEpC;;;;;;;;;;GAUG;AACH,wBAAsB,aAAa,CACjC,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,SAAS,GAAG,UAAU,GAC3B,OAAO,CAAC,UAAU,CAAC,CAmBrB"}
@@ -77,18 +77,36 @@ export async function hostResolvesPrivate(host) {
77
77
  }
78
78
  }
79
79
  /**
80
- * Confirm a request/redirect target is the registered host and not a private address.
81
- * Returns a refusal reason, or null when the target is allowed. Hosts are normalised
82
- * (lowercased, brackets and a trailing FQDN dot stripped) before comparison. `kind`
83
- * distinguishes the mismatch label: an off-host initial request is "host-mismatch", an
84
- * off-host redirect is "redirect-escape".
80
+ * Resolve a request/redirect target to the validated public addresses the connection
81
+ * must pin to, or a refusal. The target must be the registered host (an off-host initial
82
+ * request is "host-mismatch", an off-host redirect is "redirect-escape"); the resolved set
83
+ * must be non-empty and every address public, else "private-ip". IP literals (incl.
84
+ * bracketed IPv6) skip DNS. Fails closed: a lookup error or empty result is a refusal.
85
+ *
86
+ * This is the single DNS lookup for a call. The caller pins the socket to the returned
87
+ * addresses so `fetch` performs no second, independent lookup — closing the window where
88
+ * a host could answer public here and private to the connect-time lookup.
85
89
  */
86
- export async function guardTarget(targetHost, registeredHost, kind) {
90
+ export async function resolveTarget(targetHost, registeredHost, kind) {
87
91
  if (normalizeHost(targetHost) !== normalizeHost(registeredHost)) {
88
- return kind === "redirect" ? "redirect-escape" : "host-mismatch";
92
+ return { ok: false, refused: kind === "redirect" ? "redirect-escape" : "host-mismatch" };
89
93
  }
90
- if (await hostResolvesPrivate(targetHost))
91
- return "private-ip";
92
- return null;
94
+ const bare = normalizeHost(targetHost);
95
+ if (!bare)
96
+ return { ok: false, refused: "private-ip" }; // empty/malformed host is never a safe target
97
+ if (isIP(bare)) {
98
+ return isPrivateIp(bare) ? { ok: false, refused: "private-ip" } : { ok: true, addresses: [bare] };
99
+ }
100
+ let addrs;
101
+ try {
102
+ addrs = await lookup(bare, { all: true });
103
+ }
104
+ catch {
105
+ return { ok: false, refused: "private-ip" }; // DNS failure → fail closed
106
+ }
107
+ if (addrs.length === 0 || addrs.some((a) => isPrivateIp(a.address))) {
108
+ return { ok: false, refused: "private-ip" };
109
+ }
110
+ return { ok: true, addresses: addrs.map((a) => a.address) };
93
111
  }
94
112
  //# sourceMappingURL=ssrf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssrf.js","sourceRoot":"","sources":["../../src/lib/ssrf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AA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,CAAC;QACpE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC;IAC9C,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;AAC9D,CAAC"}
@@ -4,7 +4,17 @@
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
- "scripts": { "build": "tsc", "start": "node dist/index.js" },
8
- "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", "zod": "^3.24.0" },
9
- "devDependencies": { "typescript": "^5.7.0", "@types/node": "^22.0.0" }
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "start": "node dist/index.js"
10
+ },
11
+ "dependencies": {
12
+ "@modelcontextprotocol/sdk": "^1.12.1",
13
+ "undici": "^6.27.0",
14
+ "zod": "^3.24.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^22.0.0",
18
+ "typescript": "^5.7.0"
19
+ }
10
20
  }
@@ -64,6 +64,21 @@ grep -E "adminuser-self-heal|graph-write-gate.*reject" <server.log>
64
64
 
65
65
  The `subReason=admin-user-no-accountid` path should be impossible on any install whose admin server has booted at least once after the boot self-heal shipped — if it fires, the diagnostic recipe is the cross-check above, not "rerun the heal."
66
66
 
67
+ ## An admin can no longer log in, or a credential changed and you don't know who/when
68
+
69
+ **Symptom:** An admin's remote password or PIN stopped working, or an admin row vanished from `users.json` while `account.json` still lists them — with no obvious cause in `server.log`.
70
+
71
+ **Diagnose:** every credential-store write is recorded in a dedicated append-only log, separate from `server.log`:
72
+
73
+ ```
74
+ grep -E '\[users-audit\]|\[users-reconcile\]' ~/.<brand>/logs/users-audit.log ~/.<brand>/logs/server.log
75
+ ```
76
+
77
+ - `[users-audit] action=<…> actor=<id8> [session=<id8>] field=<…> rowsBefore=<…> rowsAfter=<…> ts=<…>` — one line per write. Filter by `actor=` or `session=` to attribute a single mutation; a credential change with an agent behind it carries `session=` even when that session's transcript is gone. A `users.json` mtime change with **no** `[users-audit]` line in the same window means an out-of-band write (something edited the file directly, outside every audited path).
78
+ - `[users-reconcile] op=ok admins=<n>` — emitted at boot and hourly; the stores agree. Absence of any `op=ok`/`op=divergence` line across an interval is itself the failure signal (the tick stopped).
79
+ - `[users-reconcile] op=divergence accountOnly=<id8,…> usersOnly=<id8,…>` — the stores disagree. `accountOnly` is the incident shape: an admin is in `account.json` with no `users.json` row (they will fail every login). Cross-check the most recent `[users-audit] rowsAfter` against the divergence to see whether an audited delete caused it or an out-of-band write did. `usersOnly` is a `users.json` row no account references.
80
+ - `[users-reconcile] op=error detail=…` — the reconcile itself could not read a store; the divergence state is unknown until the next clean tick.
81
+
67
82
  ## Fresh install opens to "Set your remote password" on the LAN URL
68
83
 
69
84
  **Symptom:** On a brand-new device, the LAN URL printed by `create-maxy` (e.g. `http://maxy.local:19200`) opens to a remote-password setup page instead of admin onboarding. This was an earlier regression and should not occur on any install built.
@@ -2702,6 +2702,7 @@ var PLATFORM_ROOT = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..
2702
2702
  var USERS_FILE = resolve(MAXY_DIR, "users.json");
2703
2703
  var LID_MAP_FILE = resolve(MAXY_DIR, "whatsapp-lid-map.json");
2704
2704
  var LOG_DIR = resolve(MAXY_DIR, "logs");
2705
+ var USERS_AUDIT_LOG = resolve(LOG_DIR, "users-audit.log");
2705
2706
  var BIN_DIR = resolve(MAXY_DIR, "bin");
2706
2707
  var REMOTE_PASSWORD_FILE = resolve(MAXY_DIR, ".remote-password");
2707
2708
  var REMOTE_SESSION_SECRET_FILE = resolve(MAXY_DIR, "credentials", "remote-session-secret");
@@ -2758,11 +2759,32 @@ function websockifyLog(event, fields = {}) {
2758
2759
 
2759
2760
  // ../lib/admin-access-password/src/index.ts
2760
2761
  import { scrypt, randomBytes, timingSafeEqual } from "crypto";
2761
- import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync, renameSync, unlinkSync } from "fs";
2762
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync, renameSync, unlinkSync, appendFileSync as appendFileSync2, mkdirSync as mkdirSync2 } from "fs";
2763
+ import { dirname } from "path";
2762
2764
  var SCRYPT_N = 16384;
2763
2765
  var SCRYPT_R = 8;
2764
2766
  var SCRYPT_P = 1;
2765
2767
  var SCRYPT_KEYLEN = 64;
2768
+ function id8(value) {
2769
+ return value.slice(0, 8);
2770
+ }
2771
+ function rowIds(users) {
2772
+ return users.map((u) => id8(u.userId)).join(",");
2773
+ }
2774
+ function appendUsersAuditLine(audit, fields) {
2775
+ const sess = audit.session ? ` session=${id8(audit.session)}` : "";
2776
+ const actor = audit.actor.includes("-") ? id8(audit.actor) : audit.actor;
2777
+ const line = `[users-audit] action=${fields.action} actor=${actor}${sess} field=${fields.field} rowsBefore=${fields.rowsBefore} rowsAfter=${fields.rowsAfter} ts=${(/* @__PURE__ */ new Date()).toISOString()}
2778
+ `;
2779
+ try {
2780
+ mkdirSync2(dirname(audit.logFile), { recursive: true, mode: 448 });
2781
+ appendFileSync2(audit.logFile, line, { mode: 384 });
2782
+ } catch (err) {
2783
+ console.error(
2784
+ `[users-audit] op=write-failed logFile=${audit.logFile} error=${err instanceof Error ? err.message : String(err)}`
2785
+ );
2786
+ }
2787
+ }
2766
2788
  function scryptAsync(password, salt) {
2767
2789
  return new Promise((resolve7, reject) => {
2768
2790
  scrypt(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }, (err, key) => {
@@ -2803,12 +2825,14 @@ function writeUsersAtomic(usersFile, users) {
2803
2825
  writeFileSync(tmp, JSON.stringify(users, null, 2) + "\n", { mode: 384 });
2804
2826
  renameSync(tmp, usersFile);
2805
2827
  }
2806
- async function setAccessPassword(userId, password, usersFile) {
2828
+ async function setAccessPassword(userId, password, usersFile, audit) {
2807
2829
  const users = readUsers(usersFile);
2808
2830
  const idx = users.findIndex((u) => u.userId === userId);
2809
2831
  if (idx === -1) throw new Error(`no users.json record for userId=${userId}`);
2832
+ const rows = rowIds(users);
2810
2833
  users[idx] = { ...users[idx], accessHash: await hashAccessPassword(password) };
2811
2834
  writeUsersAtomic(usersFile, users);
2835
+ appendUsersAuditLine(audit, { action: "set-access", field: "accessHash", rowsBefore: rows, rowsAfter: rows });
2812
2836
  }
2813
2837
  async function verifyAccessPassword(password, usersFile) {
2814
2838
  let users;
@@ -2857,7 +2881,7 @@ function accessStoreUnreadable(usersFile) {
2857
2881
  return true;
2858
2882
  }
2859
2883
  }
2860
- function migrateLegacyRemotePassword(usersFile, legacyFile, ownerUserId) {
2884
+ function migrateLegacyRemotePassword(usersFile, legacyFile, ownerUserId, audit) {
2861
2885
  if (!existsSync2(legacyFile)) return "noop-no-legacy";
2862
2886
  const legacy = readFileSync2(legacyFile, "utf-8").trim();
2863
2887
  const users = readUsers(usersFile);
@@ -2872,9 +2896,11 @@ function migrateLegacyRemotePassword(usersFile, legacyFile, ownerUserId) {
2872
2896
  unlinkSync(legacyFile);
2873
2897
  return "noop-no-legacy";
2874
2898
  }
2899
+ const rows = rowIds(users);
2875
2900
  users[idx] = { ...users[idx], accessHash: legacy };
2876
2901
  writeUsersAtomic(usersFile, users);
2877
2902
  unlinkSync(legacyFile);
2903
+ appendUsersAuditLine(audit, { action: "migrate", field: "accessHash", rowsBefore: rows, rowsAfter: rows });
2878
2904
  return "migrated";
2879
2905
  }
2880
2906
  function readLegacyRemoteHash(legacyFile) {
@@ -2898,8 +2924,8 @@ function isPasswordValid(password) {
2898
2924
 
2899
2925
  // app/lib/remote-auth.ts
2900
2926
  import { scrypt as scrypt2, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2, createHmac } from "crypto";
2901
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2902
- import { dirname } from "path";
2927
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync3 } from "fs";
2928
+ import { dirname as dirname2 } from "path";
2903
2929
  var SCRYPT_N2 = 16384;
2904
2930
  var SCRYPT_R2 = 8;
2905
2931
  var SCRYPT_P2 = 1;
@@ -2953,7 +2979,7 @@ function getSecret() {
2953
2979
  }
2954
2980
  const fresh = randomBytes2(SECRET_BYTES).toString("hex");
2955
2981
  try {
2956
- mkdirSync2(dirname(REMOTE_SESSION_SECRET_FILE), { recursive: true, mode: 448 });
2982
+ mkdirSync3(dirname2(REMOTE_SESSION_SECRET_FILE), { recursive: true, mode: 448 });
2957
2983
  writeFileSync2(REMOTE_SESSION_SECRET_FILE, fresh, { mode: 384, flag: "wx" });
2958
2984
  } catch {
2959
2985
  }
@@ -3612,8 +3638,8 @@ function classifyHost(host, operatorDomains2, isPublicHost) {
3612
3638
  import { watchFile } from "fs";
3613
3639
 
3614
3640
  // app/lib/operator-domains.ts
3615
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
3616
- import { dirname as dirname2, resolve as resolve3 } from "path";
3641
+ import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
3642
+ import { dirname as dirname3, resolve as resolve3 } from "path";
3617
3643
  var OPERATOR_DOMAINS_PATH = resolve3(MAXY_DIR, "operator-domains.json");
3618
3644
  function loadOperatorDomains() {
3619
3645
  if (!existsSync3(OPERATOR_DOMAINS_PATH)) return /* @__PURE__ */ new Set();
@@ -4371,11 +4397,11 @@ async function ensureConversation(accountId, agentType, cacheKey2, visitorId, ag
4371
4397
  console.error(`[session] conversation attributed: sessionId=${id.slice(0, 8)}\u2026 userId=${userId ?? "none"} ${agentType}/${accountId.slice(0, 8)}\u2026 sublabel=${conversationSublabel}`);
4372
4398
  if (wantsHandledByEdge) {
4373
4399
  const handled = result.records[0]?.get("handledBy");
4374
- const id8 = id.slice(0, 8);
4400
+ const id82 = id.slice(0, 8);
4375
4401
  if (handled === true) {
4376
- console.error(`[agent-graph] handled-by-write sessionId=${id8} slug=${handlerSlug}`);
4402
+ console.error(`[agent-graph] handled-by-write sessionId=${id82} slug=${handlerSlug}`);
4377
4403
  } else {
4378
- console.error(`[agent-graph] handled-by-skip reason=no-agent-node sessionId=${id8} slug=${handlerSlug}`);
4404
+ console.error(`[agent-graph] handled-by-skip reason=no-agent-node sessionId=${id82} slug=${handlerSlug}`);
4379
4405
  }
4380
4406
  }
4381
4407
  }
@@ -5741,6 +5767,7 @@ export {
5741
5767
  USERS_FILE,
5742
5768
  LID_MAP_FILE,
5743
5769
  LOG_DIR,
5770
+ USERS_AUDIT_LOG,
5744
5771
  BIN_DIR,
5745
5772
  REMOTE_PASSWORD_FILE,
5746
5773
  INSTALL_OWNER_FILE,
@@ -16,7 +16,7 @@ import {
16
16
  sanitizeClientCorrId,
17
17
  vncLog,
18
18
  websockifyLog
19
- } from "./chunk-QAKVFSEJ.js";
19
+ } from "./chunk-7GNXBVGY.js";
20
20
  import "./chunk-PFF6I7KP.js";
21
21
 
22
22
  // server/edge.ts
@@ -1 +1 @@
1
- import{o as e}from"./chunk-CAM3fms7.js";import{A as t,C as n,U as r,b as i,x as a,z as o}from"./OperatorConversations-CfG1EYyP.js";import{i as s}from"./admin-types-DJoj6VJv.js";import{_ as c,u as l}from"./AdminShell-B-GeoG3j.js";import{t as u}from"./Checkbox-DoGMXVpF.js";var d=`admin-landing-redirected`,f=`/graph`;function p(e){return e.variant===`operator`?!1:e.appState===`chat`&&!e.alreadyRedirected}var m=e(r(),1);function h(e=`admin`){let[t,n]=(0,m.useState)(`loading`),[r,i]=(0,m.useState)(``),[a,l]=(0,m.useState)(``),[u,h]=(0,m.useState)(``),[g,_]=(0,m.useState)(!1),[v,y]=(0,m.useState)(!1),[b,x]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),[O,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(void 0),[M,N]=(0,m.useState)(null),[P,F]=(0,m.useState)(void 0),[I,L]=(0,m.useState)(null),[ee,R]=(0,m.useState)(null),[z,B]=(0,m.useState)([]),[V,H]=(0,m.useState)(!1),[U,W]=(0,m.useState)(void 0),G=(0,m.useRef)(void 0),[K,q]=(0,m.useState)(!1);(0,m.useEffect)(()=>{typeof window>`u`||fetch(`/api/remote-auth/status`).then(e=>e.ok?e.json():null).then(e=>{e?.configured&&q(!0)}).catch(()=>{})},[]);let J=(0,m.useRef)(null),Y=(0,m.useRef)(null);(0,m.useEffect)(()=>{async function e(){let e=null;try{e=sessionStorage.getItem(`maxy-admin-session-key`)}catch{}if(!e)return!1;try{let t=await fetch(`/api/admin/session?session_key=${encodeURIComponent(e)}`);if(t.status===401){try{sessionStorage.removeItem(`maxy-admin-session-key`)}catch{}return!1}if(!t.ok)return!1;let r=await t.json();D(r.session_key),R(r.sessionId??null),j(r.businessName),N(r.role??null),F(r.userName===void 0?null:r.userName),L(r.avatar??null);let i=s(r.thinkingView);return G.current=i,W(i),n(`chat`),!0}catch(e){return console.error(`[admin] session restore failed:`,e),!1}}async function t(r=2){try{let i=await fetch(`/api/health`);if(!i.ok){if(r>0)return await new Promise(e=>setTimeout(e,1500)),t(r-1);console.error(`[admin] health check returned ${i.status} after retries`),n(`set-pin`);return}let a=await i.json();if(!a.pin_configured){n(`set-pin`);return}if(!a.claude_authenticated){n(`connect-claude`);return}if(await e())return;n(`enter-pin`)}catch(e){if(r>0)return await new Promise(e=>setTimeout(e,1500)),t(r-1);console.error(`[admin] health check failed:`,e),n(`set-pin`)}}t()},[]),(0,m.useEffect)(()=>{t===`chat`&&fetch(`/api/admin/claude-info`).then(e=>{if(e.ok)return e.json()}).then(e=>{e&&k(e)}).catch(()=>{})},[t]),(0,m.useEffect)(()=>{if(typeof window>`u`)return;let n=!1;try{n=sessionStorage.getItem(d)===`1`}catch{}if(p({appState:t,alreadyRedirected:n,variant:e})){try{sessionStorage.setItem(d,`1`)}catch{}console.info(`[admin-ui] landing-redirect target=${f}`),window.location.replace(f)}},[t,e]);let X=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(t!==`chat`)return;let e=setInterval(async()=>{try{let e=await fetch(`/api/health`);if(e.ok){let t=await e.json();if(t.auth_status===`dead`||t.auth_status===`missing`){n(`connect-claude`);return}}}catch{}if(E)try{let e=await fetch(`/api/admin/session?session_key=${encodeURIComponent(E)}`);if(e.status!==401)return;let t=(await e.clone().json().catch(()=>null))?.code??`unknown-401`;if(t===`remote-auth-required`){o(`heartbeat`,`/api/admin/session`);return}console.warn(`[admin-auth] outcome=heartbeat-detected-expiry code=${t}`),X.current?.()}catch{}},300*1e3);return()=>clearInterval(e)},[t,E]),(0,m.useEffect)(()=>{t===`connect-claude`&&fetch(`/api/health`).then(e=>e.ok?e.json():null).then(e=>{e?.claude_authenticated&&n(`enter-pin`)}).catch(()=>{})},[t]);async function Z(e,t){y(!0);try{let r=await fetch(`/api/admin/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:e,...t?{accountId:t}:{}})});if(!r.ok){h((await r.json().catch(()=>({}))).error||`Invalid PIN`);return}let a=await r.json();if(a.accounts&&!a.session_key){console.log(`[admin] account picker shown: userId=${a.userId} accountCount=${a.accounts.length}`),B(a.accounts),n(`account-picker`);return}D(a.session_key),R(a.sessionId??null),j(a.businessName),N(a.role??null),F(a.userName===void 0?null:a.userName),L(a.avatar??null);let o=s(a.thinkingView);if(G.current=o,W(o),t)try{sessionStorage.setItem(`maxy-account-id`,t)}catch{}try{sessionStorage.setItem(`maxy-admin-session-key`,a.session_key)}catch{}i(``),n(`chat`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1),H(!1)}}let Q=(0,m.useCallback)(async e=>{if(e.preventDefault(),v)return;h(``);let t=a.trim();if(!t){h(`Please enter your name.`);return}if(r.length<4){h(`PIN must be at least 4 characters.`);return}let o=r;y(!0);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:o,name:t})});if(!e.ok){let t=await e.json().catch(()=>({}));if(e.status===409){console.log(`[admin] PIN already configured — re-checking health`);try{let e=await fetch(`/api/health`);if(e.ok){let r=await e.json();r.pin_configured&&r.claude_authenticated?n(`enter-pin`):r.pin_configured?n(`connect-claude`):h(t.error||`Failed to set PIN.`)}else n(`enter-pin`)}catch{n(`enter-pin`)}return}h(t.error||`Failed to set PIN.`);return}let r=await fetch(`/api/health`);if((r.ok?await r.json():null)?.claude_authenticated){await Z(o);return}i(``),n(`connect-claude`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1)}},[r,v,a]),te=(0,m.useCallback)(async e=>{e.preventDefault(),h(``),await Z(r)},[r]),ne=(0,m.useCallback)(async()=>{T(!0);try{if(!await c())return console.warn(`[admin-ui] claude-disconnect not verified — credentials may persist; staying put`),!1;D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}return n(`connect-claude`),!0}finally{T(!1)}},[]),$=(0,m.useCallback)(()=>{D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}i(``),h(``),n(`enter-pin`)},[]);return(0,m.useEffect)(()=>{X.current=$},[$]),{appState:t,setAppState:n,pin:r,setPin:i,operatorName:a,setOperatorName:l,pinError:u,setPinError:h,showPin:g,setShowPin:_,pinLoading:v,authPolling:b,setAuthPolling:x,authLoading:S,setAuthLoading:C,disconnecting:w,cacheKey:E,setCacheKey:D,claudeInfo:O,setClaudeInfo:k,businessName:A,role:M,userName:P,userAvatar:I,sessionId:ee,setSessionId:R,accounts:z,accountPickerLoading:V,expandAll:U,setExpandAll:W,expandAllDefaultRef:G,remoteAuthEnabled:K,pinInputRef:J,setPinFormRef:Y,handleSetPin:Q,handleLogin:te,handleAccountSelect:(0,m.useCallback)(async e=>{H(!0),h(``),await Z(r,e)},[r]),handleDisconnect:ne,handleLogout:$,handleChangePin:(0,m.useCallback)(async()=>{if(!r){h(`Enter your current PIN first.`);return}y(!0),h(``);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({currentPin:r})});if(!e.ok){h((await e.json().catch(()=>({error:`Incorrect PIN.`}))).error||`Incorrect PIN.`);return}i(``),h(``),n(`set-pin`)}catch(e){console.error(`[admin-auth] change pin failed:`,e),h(e instanceof Error?e.message:String(e))}finally{y(!1)}},[r])}}var g=n();function _({inputRef:e,value:t,onChange:n,onComplete:r,showPin:i,autoFocus:a}){let o=(0,m.useRef)([]);function s(e,r){r.key===`Backspace`?(r.preventDefault(),t[e]?n(t.slice(0,e)+t.slice(e+1)):e>0&&(n(t.slice(0,e-1)+t.slice(e)),o.current[e-1]?.focus())):r.key===`ArrowLeft`&&e>0?o.current[e-1]?.focus():r.key===`ArrowRight`&&e<5?o.current[e+1]?.focus():r.key===`Enter`&&(r.preventDefault(),r.currentTarget.form?.requestSubmit())}function c(e,i){let a=i.nativeEvent.data;if(!a||!/^\d$/.test(a))return;let s=t.split(``);for(s[e]=a;s.length<e;)s.push(``);let c=s.join(``).replace(/\D/g,``).slice(0,6);n(c),c.length===6?r?.(c):e<5&&o.current[e+1]?.focus()}function l(e){e.preventDefault();let t=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);t&&(n(t),t.length===6?r?.(t):o.current[t.length]?.focus())}return(0,g.jsx)(`div`,{className:`pin-field`,children:Array.from({length:6}).map((n,r)=>(0,g.jsx)(`input`,{ref:t=>{o.current[r]=t,r===0&&e&&(e.current=t)},type:`text`,inputMode:`numeric`,className:`pin-box${t[r]?` pin-box-filled`:``}`,value:t[r]?i?t[r]:`•`:``,onKeyDown:e=>s(r,e),onInput:e=>c(r,e),onPaste:l,onFocus:e=>e.target.select(),autoFocus:a&&r===0,autoComplete:`off`,maxLength:1,"aria-label":`PIN digit ${r+1}`},r))})}function v(e){let{pin:t,setPin:n,showPin:r,setShowPin:o,pinLoading:s,pinError:c,pinInputRef:d,setPinFormRef:f,onSubmit:p,operatorName:m,setOperatorName:h}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Welcome to `,i.productName]}),(0,g.jsxs)(`p`,{className:`connect-subtitle`,children:[`Tell `,i.productName,` who you are, then choose a PIN.`]}),(0,g.jsxs)(`form`,{ref:f,onSubmit:p,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(`input`,{type:`text`,className:`connect-name-input`,placeholder:`Your full name`,value:m,onChange:e=>h(e.target.value),autoComplete:`name`,autoFocus:!0,required:!0,"aria-label":`Your full name`}),(0,g.jsx)(`div`,{style:{width:38,flexShrink:0},"aria-hidden":`true`})]}),(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t||!m.trim(),loading:s,"aria-label":`Set PIN`,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsx)(u,{checked:r,onChange:()=>o(e=>!e),label:`Show PIN`})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})})}function y(e){let{pin:t,setPin:n,showPin:r,setShowPin:o,pinLoading:s,pinError:c,pinInputRef:d,onSubmit:f,onChangePin:p,remoteAuthEnabled:m,onSignOutRemote:h}=e;return(0,g.jsxs)(`div`,{className:`connect-page`,children:[m&&h&&(0,g.jsx)(`button`,{type:`button`,className:`connect-signout`,onClick:h,children:`Sign out`}),(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:i.productName}),(0,g.jsxs)(`form`,{onSubmit:f,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r,autoFocus:!0}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t,loading:s,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsxs)(`div`,{className:`pin-options`,children:[(0,g.jsx)(u,{checked:r,onChange:()=>o(e=>!e),label:`Show PIN`}),(0,g.jsx)(l,{type:`button`,variant:`ghost`,onClick:p,children:`Change PIN`})]})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})]})}function b(e){let{accounts:n,loading:r,error:o,onSelect:s}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:i.productName}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Select an account`}),(0,g.jsx)(`div`,{className:`account-picker-list`,children:n.map(e=>(0,g.jsxs)(`button`,{className:`account-picker-card`,onClick:()=>s(e.accountId),disabled:r,type:`button`,children:[(0,g.jsx)(`span`,{className:`account-picker-name`,children:e.businessName||e.accountId}),(0,g.jsx)(`span`,{className:`account-picker-role`,children:e.role}),r&&(0,g.jsx)(t,{className:`account-picker-spinner`,size:16})]},e.accountId))}),o&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:o})]})})}function x(e){let{authPolling:t,setAuthPolling:n,authLoading:r,setAuthLoading:o,pinError:s,setPinError:c,setAppState:u}=e,[d,f]=(0,m.useState)(!1),[p,h]=(0,m.useState)(!1);async function _(){h(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`launch-browser`})})).json();e.launched?f(!0):e.error&&c(e.error)}catch(e){console.error(`[admin] browser launch error:`,e),c(`Could not launch browser.`)}h(!1)}async function v(){o(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`})).json();if(e.started){n(!0),f(!0),o(!1);for(let e=0;e<120;e++)if(await new Promise(e=>setTimeout(e,2e3)),(await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`wait`})})).json()).authenticated){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),u(`enter-pin`);return}c(`Timed out waiting for sign-in. Try again.`),n(!1)}else e.error&&c(e.error)}catch(e){console.error(`[admin] auth flow error:`,e),c(`Could not start auth flow.`)}o(!1)}async function y(){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),n(!1),c(``)}return t||d?(0,g.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100dvh`,overflow:`auto`},children:[(0,g.jsxs)(`header`,{className:`chat-header`,style:{paddingBottom:`12px`,flexShrink:0,position:`relative`,maxWidth:`680px`,width:`100%`,margin:`0 auto`,padding:`24px 20px 12px`},children:[t?(0,g.jsx)(`button`,{onClick:y,style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Cancel`,children:`✕`}):(0,g.jsx)(`button`,{onClick:()=>f(!1),style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Close browser`,children:`✕`}),(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`chat-logo`}),(0,g.jsx)(`h1`,{className:`chat-tagline`,children:`Connect Claude`}),(0,g.jsx)(`p`,{className:`chat-intro`,children:t?`Sign in and authorize in the browser below.`:`Open your email or prepare your accounts, then sign in.`}),!t&&(0,g.jsx)(`div`,{style:{marginTop:`12px`},children:(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`})})]}),(0,g.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,gap:`10px`,padding:`0 0 16px`},children:(0,g.jsx)(`iframe`,{src:`/vnc-viewer.html`,style:{flex:1,width:`100%`,minHeight:0,border:`none`,background:`#111`,display:`block`},title:`Claude Sign-in`})}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,style:{textAlign:`center`,padding:`0 20px 16px`},children:s})]}):(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsxs)(`div`,{className:`connect-logos`,children:[(0,g.jsx)(`div`,{className:`connect-logo-wrap`,children:(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`connect-logo`})}),(0,g.jsx)(`svg`,{className:`connect-arrow`,viewBox:`0 0 48 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,g.jsx)(`path`,{d:`M0 12h44m0 0l-8-8m8 8l-8 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,g.jsxs)(`div`,{className:`connect-logo-wrap`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`span`,{className:`connect-logo-label`,children:i.productName})]})]}),(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Connect Claude to power `,i.productName]}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Sign in with your Anthropic account to get started.`}),(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`}),(0,g.jsx)(`p`,{style:{marginTop:`6px`,fontSize:`11px`,color:`#999`,maxWidth:`300px`,textAlign:`center`,lineHeight:`1.4`},children:`First time? You may need to sign into your email and Anthropic account in the browser before connecting.`}),(0,g.jsx)(`button`,{onClick:_,disabled:p,style:{marginTop:`12px`,background:`none`,border:`none`,color:`var(--color-primary, #666)`,fontSize:`13px`,cursor:`pointer`,textDecoration:`underline`,textUnderlineOffset:`3px`},children:p?`Launching…`:`Open browser first`}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:s})]})})}function S({auth:e}){return e.appState===`loading`?(0,g.jsx)(`div`,{className:`connect-page`}):e.appState===`set-pin`?(0,g.jsx)(v,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,setPinFormRef:e.setPinFormRef,onSubmit:e.handleSetPin,operatorName:e.operatorName,setOperatorName:e.setOperatorName}):e.appState===`connect-claude`?(0,g.jsx)(x,{authPolling:e.authPolling,setAuthPolling:e.setAuthPolling,authLoading:e.authLoading,setAuthLoading:e.setAuthLoading,pinError:e.pinError,setPinError:e.setPinError,setAppState:e.setAppState}):e.appState===`enter-pin`?(0,g.jsx)(y,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,onSubmit:e.handleLogin,onChangePin:e.handleChangePin,remoteAuthEnabled:e.remoteAuthEnabled,onSignOutRemote:()=>{console.info(`[admin-ui] remote-auth sign-out → /__remote-auth/logout`),window.location.href=`/__remote-auth/logout`}}):e.appState===`account-picker`?(0,g.jsx)(b,{accounts:e.accounts,loading:e.accountPickerLoading,error:e.pinError,onSelect:e.handleAccountSelect}):null}export{h as n,S as t};
1
+ import{o as e}from"./chunk-CAM3fms7.js";import{A as t,C as n,U as r,b as i,x as a,z as o}from"./OperatorConversations-DeZ2wDEK.js";import{i as s}from"./admin-types-DJoj6VJv.js";import{_ as c,u as l}from"./AdminShell-GGnPXCOe.js";import{t as u}from"./Checkbox-D3XFVUMT.js";var d=`admin-landing-redirected`,f=`/graph`;function p(e){return e.variant===`operator`?!1:e.appState===`chat`&&!e.alreadyRedirected}var m=e(r(),1);function h(e=`admin`){let[t,n]=(0,m.useState)(`loading`),[r,i]=(0,m.useState)(``),[a,l]=(0,m.useState)(``),[u,h]=(0,m.useState)(``),[g,_]=(0,m.useState)(!1),[v,y]=(0,m.useState)(!1),[b,x]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),[O,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(void 0),[M,N]=(0,m.useState)(null),[P,F]=(0,m.useState)(void 0),[I,L]=(0,m.useState)(null),[ee,R]=(0,m.useState)(null),[z,B]=(0,m.useState)([]),[V,H]=(0,m.useState)(!1),[U,W]=(0,m.useState)(void 0),G=(0,m.useRef)(void 0),[K,q]=(0,m.useState)(!1);(0,m.useEffect)(()=>{typeof window>`u`||fetch(`/api/remote-auth/status`).then(e=>e.ok?e.json():null).then(e=>{e?.configured&&q(!0)}).catch(()=>{})},[]);let J=(0,m.useRef)(null),Y=(0,m.useRef)(null);(0,m.useEffect)(()=>{async function e(){let e=null;try{e=sessionStorage.getItem(`maxy-admin-session-key`)}catch{}if(!e)return!1;try{let t=await fetch(`/api/admin/session?session_key=${encodeURIComponent(e)}`);if(t.status===401){try{sessionStorage.removeItem(`maxy-admin-session-key`)}catch{}return!1}if(!t.ok)return!1;let r=await t.json();D(r.session_key),R(r.sessionId??null),j(r.businessName),N(r.role??null),F(r.userName===void 0?null:r.userName),L(r.avatar??null);let i=s(r.thinkingView);return G.current=i,W(i),n(`chat`),!0}catch(e){return console.error(`[admin] session restore failed:`,e),!1}}async function t(r=2){try{let i=await fetch(`/api/health`);if(!i.ok){if(r>0)return await new Promise(e=>setTimeout(e,1500)),t(r-1);console.error(`[admin] health check returned ${i.status} after retries`),n(`set-pin`);return}let a=await i.json();if(!a.pin_configured){n(`set-pin`);return}if(!a.claude_authenticated){n(`connect-claude`);return}if(await e())return;n(`enter-pin`)}catch(e){if(r>0)return await new Promise(e=>setTimeout(e,1500)),t(r-1);console.error(`[admin] health check failed:`,e),n(`set-pin`)}}t()},[]),(0,m.useEffect)(()=>{t===`chat`&&fetch(`/api/admin/claude-info`).then(e=>{if(e.ok)return e.json()}).then(e=>{e&&k(e)}).catch(()=>{})},[t]),(0,m.useEffect)(()=>{if(typeof window>`u`)return;let n=!1;try{n=sessionStorage.getItem(d)===`1`}catch{}if(p({appState:t,alreadyRedirected:n,variant:e})){try{sessionStorage.setItem(d,`1`)}catch{}console.info(`[admin-ui] landing-redirect target=${f}`),window.location.replace(f)}},[t,e]);let X=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(t!==`chat`)return;let e=setInterval(async()=>{try{let e=await fetch(`/api/health`);if(e.ok){let t=await e.json();if(t.auth_status===`dead`||t.auth_status===`missing`){n(`connect-claude`);return}}}catch{}if(E)try{let e=await fetch(`/api/admin/session?session_key=${encodeURIComponent(E)}`);if(e.status!==401)return;let t=(await e.clone().json().catch(()=>null))?.code??`unknown-401`;if(t===`remote-auth-required`){o(`heartbeat`,`/api/admin/session`);return}console.warn(`[admin-auth] outcome=heartbeat-detected-expiry code=${t}`),X.current?.()}catch{}},300*1e3);return()=>clearInterval(e)},[t,E]),(0,m.useEffect)(()=>{t===`connect-claude`&&fetch(`/api/health`).then(e=>e.ok?e.json():null).then(e=>{e?.claude_authenticated&&n(`enter-pin`)}).catch(()=>{})},[t]);async function Z(e,t){y(!0);try{let r=await fetch(`/api/admin/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:e,...t?{accountId:t}:{}})});if(!r.ok){h((await r.json().catch(()=>({}))).error||`Invalid PIN`);return}let a=await r.json();if(a.accounts&&!a.session_key){console.log(`[admin] account picker shown: userId=${a.userId} accountCount=${a.accounts.length}`),B(a.accounts),n(`account-picker`);return}D(a.session_key),R(a.sessionId??null),j(a.businessName),N(a.role??null),F(a.userName===void 0?null:a.userName),L(a.avatar??null);let o=s(a.thinkingView);if(G.current=o,W(o),t)try{sessionStorage.setItem(`maxy-account-id`,t)}catch{}try{sessionStorage.setItem(`maxy-admin-session-key`,a.session_key)}catch{}i(``),n(`chat`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1),H(!1)}}let Q=(0,m.useCallback)(async e=>{if(e.preventDefault(),v)return;h(``);let t=a.trim();if(!t){h(`Please enter your name.`);return}if(r.length<4){h(`PIN must be at least 4 characters.`);return}let o=r;y(!0);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:o,name:t})});if(!e.ok){let t=await e.json().catch(()=>({}));if(e.status===409){console.log(`[admin] PIN already configured — re-checking health`);try{let e=await fetch(`/api/health`);if(e.ok){let r=await e.json();r.pin_configured&&r.claude_authenticated?n(`enter-pin`):r.pin_configured?n(`connect-claude`):h(t.error||`Failed to set PIN.`)}else n(`enter-pin`)}catch{n(`enter-pin`)}return}h(t.error||`Failed to set PIN.`);return}let r=await fetch(`/api/health`);if((r.ok?await r.json():null)?.claude_authenticated){await Z(o);return}i(``),n(`connect-claude`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1)}},[r,v,a]),te=(0,m.useCallback)(async e=>{e.preventDefault(),h(``),await Z(r)},[r]),ne=(0,m.useCallback)(async()=>{T(!0);try{if(!await c())return console.warn(`[admin-ui] claude-disconnect not verified — credentials may persist; staying put`),!1;D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}return n(`connect-claude`),!0}finally{T(!1)}},[]),$=(0,m.useCallback)(()=>{D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}i(``),h(``),n(`enter-pin`)},[]);return(0,m.useEffect)(()=>{X.current=$},[$]),{appState:t,setAppState:n,pin:r,setPin:i,operatorName:a,setOperatorName:l,pinError:u,setPinError:h,showPin:g,setShowPin:_,pinLoading:v,authPolling:b,setAuthPolling:x,authLoading:S,setAuthLoading:C,disconnecting:w,cacheKey:E,setCacheKey:D,claudeInfo:O,setClaudeInfo:k,businessName:A,role:M,userName:P,userAvatar:I,sessionId:ee,setSessionId:R,accounts:z,accountPickerLoading:V,expandAll:U,setExpandAll:W,expandAllDefaultRef:G,remoteAuthEnabled:K,pinInputRef:J,setPinFormRef:Y,handleSetPin:Q,handleLogin:te,handleAccountSelect:(0,m.useCallback)(async e=>{H(!0),h(``),await Z(r,e)},[r]),handleDisconnect:ne,handleLogout:$,handleChangePin:(0,m.useCallback)(async()=>{if(!r){h(`Enter your current PIN first.`);return}y(!0),h(``);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({currentPin:r})});if(!e.ok){h((await e.json().catch(()=>({error:`Incorrect PIN.`}))).error||`Incorrect PIN.`);return}i(``),h(``),n(`set-pin`)}catch(e){console.error(`[admin-auth] change pin failed:`,e),h(e instanceof Error?e.message:String(e))}finally{y(!1)}},[r])}}var g=n();function _({inputRef:e,value:t,onChange:n,onComplete:r,showPin:i,autoFocus:a}){let o=(0,m.useRef)([]);function s(e,r){r.key===`Backspace`?(r.preventDefault(),t[e]?n(t.slice(0,e)+t.slice(e+1)):e>0&&(n(t.slice(0,e-1)+t.slice(e)),o.current[e-1]?.focus())):r.key===`ArrowLeft`&&e>0?o.current[e-1]?.focus():r.key===`ArrowRight`&&e<5?o.current[e+1]?.focus():r.key===`Enter`&&(r.preventDefault(),r.currentTarget.form?.requestSubmit())}function c(e,i){let a=i.nativeEvent.data;if(!a||!/^\d$/.test(a))return;let s=t.split(``);for(s[e]=a;s.length<e;)s.push(``);let c=s.join(``).replace(/\D/g,``).slice(0,6);n(c),c.length===6?r?.(c):e<5&&o.current[e+1]?.focus()}function l(e){e.preventDefault();let t=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);t&&(n(t),t.length===6?r?.(t):o.current[t.length]?.focus())}return(0,g.jsx)(`div`,{className:`pin-field`,children:Array.from({length:6}).map((n,r)=>(0,g.jsx)(`input`,{ref:t=>{o.current[r]=t,r===0&&e&&(e.current=t)},type:`text`,inputMode:`numeric`,className:`pin-box${t[r]?` pin-box-filled`:``}`,value:t[r]?i?t[r]:`•`:``,onKeyDown:e=>s(r,e),onInput:e=>c(r,e),onPaste:l,onFocus:e=>e.target.select(),autoFocus:a&&r===0,autoComplete:`off`,maxLength:1,"aria-label":`PIN digit ${r+1}`},r))})}function v(e){let{pin:t,setPin:n,showPin:r,setShowPin:o,pinLoading:s,pinError:c,pinInputRef:d,setPinFormRef:f,onSubmit:p,operatorName:m,setOperatorName:h}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Welcome to `,i.productName]}),(0,g.jsxs)(`p`,{className:`connect-subtitle`,children:[`Tell `,i.productName,` who you are, then choose a PIN.`]}),(0,g.jsxs)(`form`,{ref:f,onSubmit:p,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(`input`,{type:`text`,className:`connect-name-input`,placeholder:`Your full name`,value:m,onChange:e=>h(e.target.value),autoComplete:`name`,autoFocus:!0,required:!0,"aria-label":`Your full name`}),(0,g.jsx)(`div`,{style:{width:38,flexShrink:0},"aria-hidden":`true`})]}),(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t||!m.trim(),loading:s,"aria-label":`Set PIN`,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsx)(u,{checked:r,onChange:()=>o(e=>!e),label:`Show PIN`})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})})}function y(e){let{pin:t,setPin:n,showPin:r,setShowPin:o,pinLoading:s,pinError:c,pinInputRef:d,onSubmit:f,onChangePin:p,remoteAuthEnabled:m,onSignOutRemote:h}=e;return(0,g.jsxs)(`div`,{className:`connect-page`,children:[m&&h&&(0,g.jsx)(`button`,{type:`button`,className:`connect-signout`,onClick:h,children:`Sign out`}),(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:i.productName}),(0,g.jsxs)(`form`,{onSubmit:f,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r,autoFocus:!0}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t,loading:s,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsxs)(`div`,{className:`pin-options`,children:[(0,g.jsx)(u,{checked:r,onChange:()=>o(e=>!e),label:`Show PIN`}),(0,g.jsx)(l,{type:`button`,variant:`ghost`,onClick:p,children:`Change PIN`})]})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})]})}function b(e){let{accounts:n,loading:r,error:o,onSelect:s}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:i.productName}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Select an account`}),(0,g.jsx)(`div`,{className:`account-picker-list`,children:n.map(e=>(0,g.jsxs)(`button`,{className:`account-picker-card`,onClick:()=>s(e.accountId),disabled:r,type:`button`,children:[(0,g.jsx)(`span`,{className:`account-picker-name`,children:e.businessName||e.accountId}),(0,g.jsx)(`span`,{className:`account-picker-role`,children:e.role}),r&&(0,g.jsx)(t,{className:`account-picker-spinner`,size:16})]},e.accountId))}),o&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:o})]})})}function x(e){let{authPolling:t,setAuthPolling:n,authLoading:r,setAuthLoading:o,pinError:s,setPinError:c,setAppState:u}=e,[d,f]=(0,m.useState)(!1),[p,h]=(0,m.useState)(!1);async function _(){h(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`launch-browser`})})).json();e.launched?f(!0):e.error&&c(e.error)}catch(e){console.error(`[admin] browser launch error:`,e),c(`Could not launch browser.`)}h(!1)}async function v(){o(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`})).json();if(e.started){n(!0),f(!0),o(!1);for(let e=0;e<120;e++)if(await new Promise(e=>setTimeout(e,2e3)),(await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`wait`})})).json()).authenticated){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),u(`enter-pin`);return}c(`Timed out waiting for sign-in. Try again.`),n(!1)}else e.error&&c(e.error)}catch(e){console.error(`[admin] auth flow error:`,e),c(`Could not start auth flow.`)}o(!1)}async function y(){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),n(!1),c(``)}return t||d?(0,g.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100dvh`,overflow:`auto`},children:[(0,g.jsxs)(`header`,{className:`chat-header`,style:{paddingBottom:`12px`,flexShrink:0,position:`relative`,maxWidth:`680px`,width:`100%`,margin:`0 auto`,padding:`24px 20px 12px`},children:[t?(0,g.jsx)(`button`,{onClick:y,style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Cancel`,children:`✕`}):(0,g.jsx)(`button`,{onClick:()=>f(!1),style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Close browser`,children:`✕`}),(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`chat-logo`}),(0,g.jsx)(`h1`,{className:`chat-tagline`,children:`Connect Claude`}),(0,g.jsx)(`p`,{className:`chat-intro`,children:t?`Sign in and authorize in the browser below.`:`Open your email or prepare your accounts, then sign in.`}),!t&&(0,g.jsx)(`div`,{style:{marginTop:`12px`},children:(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`})})]}),(0,g.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,gap:`10px`,padding:`0 0 16px`},children:(0,g.jsx)(`iframe`,{src:`/vnc-viewer.html`,style:{flex:1,width:`100%`,minHeight:0,border:`none`,background:`#111`,display:`block`},title:`Claude Sign-in`})}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,style:{textAlign:`center`,padding:`0 20px 16px`},children:s})]}):(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsxs)(`div`,{className:`connect-logos`,children:[(0,g.jsx)(`div`,{className:`connect-logo-wrap`,children:(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`connect-logo`})}),(0,g.jsx)(`svg`,{className:`connect-arrow`,viewBox:`0 0 48 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,g.jsx)(`path`,{d:`M0 12h44m0 0l-8-8m8 8l-8 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,g.jsxs)(`div`,{className:`connect-logo-wrap`,children:[(0,g.jsx)(`img`,{src:a,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`span`,{className:`connect-logo-label`,children:i.productName})]})]}),(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Connect Claude to power `,i.productName]}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Sign in with your Anthropic account to get started.`}),(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`}),(0,g.jsx)(`p`,{style:{marginTop:`6px`,fontSize:`11px`,color:`#999`,maxWidth:`300px`,textAlign:`center`,lineHeight:`1.4`},children:`First time? You may need to sign into your email and Anthropic account in the browser before connecting.`}),(0,g.jsx)(`button`,{onClick:_,disabled:p,style:{marginTop:`12px`,background:`none`,border:`none`,color:`var(--color-primary, #666)`,fontSize:`13px`,cursor:`pointer`,textDecoration:`underline`,textUnderlineOffset:`3px`},children:p?`Launching…`:`Open browser first`}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:s})]})})}function S({auth:e}){return e.appState===`loading`?(0,g.jsx)(`div`,{className:`connect-page`}):e.appState===`set-pin`?(0,g.jsx)(v,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,setPinFormRef:e.setPinFormRef,onSubmit:e.handleSetPin,operatorName:e.operatorName,setOperatorName:e.setOperatorName}):e.appState===`connect-claude`?(0,g.jsx)(x,{authPolling:e.authPolling,setAuthPolling:e.setAuthPolling,authLoading:e.authLoading,setAuthLoading:e.setAuthLoading,pinError:e.pinError,setPinError:e.setPinError,setAppState:e.setAppState}):e.appState===`enter-pin`?(0,g.jsx)(y,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,onSubmit:e.handleLogin,onChangePin:e.handleChangePin,remoteAuthEnabled:e.remoteAuthEnabled,onSignOutRemote:()=>{console.info(`[admin-ui] remote-auth sign-out → /__remote-auth/logout`),window.location.href=`/__remote-auth/logout`}}):e.appState===`account-picker`?(0,g.jsx)(b,{accounts:e.accounts,loading:e.accountPickerLoading,error:e.pinError,onSelect:e.handleAccountSelect}):null}export{h as n,S as t};