@agentconnect.md/setup 2.18.0-rc.8 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,8 +5,12 @@ import path$1, { resolve } from "node:path";
5
5
  import { loadEnvFile } from "node:process";
6
6
  import { createHash, createPrivateKey, randomBytes, subtle } from "node:crypto";
7
7
  import { isDeepStrictEqual } from "node:util";
8
+ import { request as request$1 } from "node:http";
9
+ import { request as request$2 } from "node:https";
10
+ import { lookup } from "node:dns";
8
11
  import { fileURLToPath } from "node:url";
9
12
  import { gzipSync } from "node:zlib";
13
+ import { isIP } from "node:net";
10
14
  import { readFile } from "node:fs/promises";
11
15
  // \0rolldown/runtime.js
12
16
  var __create = Object.create;
@@ -35641,6 +35645,8 @@ function constantCatch(value) {
35641
35645
  }
35642
35646
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js
35643
35647
  var _a$1;
35648
+ /** A special constant with type `never` */
35649
+ const NEVER = /*@__PURE__*/ Object.freeze({ status: "aborted" });
35644
35650
  const _zodDesc = {
35645
35651
  value: void 0,
35646
35652
  enumerable: false
@@ -46925,7 +46931,7 @@ function googleCloudProjectUrl(projectId) {
46925
46931
  return `https://cloudresourcemanager.googleapis.com/v1/projects/${encodeURIComponent(projectId)}`;
46926
46932
  }
46927
46933
  /** Give up on a silent endpoint rather than hold the save request open. */
46928
- const PROBE_TIMEOUT_MS$3 = 5e3;
46934
+ const PROBE_TIMEOUT_MS$4 = 5e3;
46929
46935
  /** Bound provider text echoed into an operator-facing message. */
46930
46936
  const MAX_PROVIDER_DETAIL = 300;
46931
46937
  /** Connectivity failures are retryable; every other failure is the credential's or the project's. */
@@ -47026,7 +47032,7 @@ async function probeGoogleChatCredential(key, fetchImpl, now = () => /* @__PURE_
47026
47032
  authorization: `Bearer ${minted.accessToken}`,
47027
47033
  accept: "application/json"
47028
47034
  },
47029
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$3)
47035
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$4)
47030
47036
  });
47031
47037
  } catch {
47032
47038
  return unreachable("the Google Chat API");
@@ -47062,7 +47068,7 @@ async function resolveProjectNumber(key, fetchImpl, now = () => /* @__PURE__ */
47062
47068
  authorization: `Bearer ${minted.accessToken}`,
47063
47069
  accept: "application/json"
47064
47070
  },
47065
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$3)
47071
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$4)
47066
47072
  });
47067
47073
  } catch {
47068
47074
  return unreachable("the Cloud Resource Manager API");
@@ -47159,7 +47165,7 @@ async function mintAccessToken(key, scope, fetchImpl, now) {
47159
47165
  grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
47160
47166
  assertion
47161
47167
  }).toString(),
47162
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$3)
47168
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$4)
47163
47169
  });
47164
47170
  } catch {
47165
47171
  return unreachable("Google's token endpoint");
@@ -63458,6 +63464,152 @@ function normalizeGiteaBaseUrl(raw) {
63458
63464
  const GITEA_MINIMUM_VERSION = "1.23";
63459
63465
  /** Forgejo's oldest maintained line, its current LTS (§3); it versions independently of Gitea. */
63460
63466
  const FORGEJO_MINIMUM_VERSION = "15.0";
63467
+ // ../control-plane/dist/net/private-address.js
63468
+ /**
63469
+ * One definition of "this literal address can never be reached from the public
63470
+ * internet", shared by the SSRF fast-fail on user-supplied upstream URLs
63471
+ * (`orchestrator/mcpProvider.ts`) and the public-ingress gate on http-transport
63472
+ * bots (`http/relay-ingress.ts`). Pure — literals only, no DNS.
63473
+ */
63474
+ /** This-host, link-local, cloud metadata (AWS/GCP/Azure/Alibaba/Oracle), benchmark, and multicast/reserved IPv4. */
63475
+ function linkLocalOrUnspecifiedV4(ip) {
63476
+ const o = ip.split(".").map(Number);
63477
+ if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
63478
+ const [a, b, c, d] = o;
63479
+ if (a === 0 || a === 169 && b === 254) return true;
63480
+ if (a === 100 && b === 100 && c === 100 && d === 200) return true;
63481
+ if (a === 192 && b === 0 && c === 0) return true;
63482
+ if (a === 198 && (b === 18 || b === 19)) return true;
63483
+ if (a >= 224) return true;
63484
+ return false;
63485
+ }
63486
+ function parseIpv4Tail$1(part) {
63487
+ const octets = part.split(".");
63488
+ if (octets.length !== 4 || octets.some((o) => !/^\d+$/.test(o))) return null;
63489
+ const nums = octets.map(Number);
63490
+ if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
63491
+ const [a, b, c, d] = nums;
63492
+ return [(a << 8 | b) & 65535, (c << 8 | d) & 65535];
63493
+ }
63494
+ function expandIpv6Side$1(raw, allowTrailingV4) {
63495
+ if (!raw) return [];
63496
+ const parts = raw.split(":");
63497
+ const out = [];
63498
+ for (let i = 0; i < parts.length; i++) {
63499
+ const part = parts[i];
63500
+ if (!part) return null;
63501
+ if (allowTrailingV4 && i === parts.length - 1 && part.includes(".")) {
63502
+ const pair = parseIpv4Tail$1(part);
63503
+ if (!pair) return null;
63504
+ out.push(pair[0], pair[1]);
63505
+ continue;
63506
+ }
63507
+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
63508
+ out.push(parseInt(part, 16));
63509
+ }
63510
+ return out;
63511
+ }
63512
+ /** Expand an IPv6 literal into 8 16-bit hextets (handles brackets, zone IDs, `::`, and embedded dotted IPv4). */
63513
+ function parseIpv6Hextets$1(ip) {
63514
+ const clean = ip.trim().toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
63515
+ if (!clean) return null;
63516
+ const compressed = clean.split("::");
63517
+ if (compressed.length > 2) return null;
63518
+ if (compressed.length === 1) {
63519
+ const hextets = expandIpv6Side$1(compressed[0], true);
63520
+ return hextets && hextets.length === 8 ? hextets : null;
63521
+ }
63522
+ const left = expandIpv6Side$1(compressed[0], false);
63523
+ const right = expandIpv6Side$1(compressed[1], true);
63524
+ if (!left || !right || left.length + right.length >= 8) return null;
63525
+ return [
63526
+ ...left,
63527
+ ...new Array(8 - left.length - right.length).fill(0),
63528
+ ...right
63529
+ ];
63530
+ }
63531
+ /** Extract embedded IPv4 from `::ffff:0:0/96`, `::ffff:0:0:0/96`, NAT64 `64:ff9b::/96` & `64:ff9b:1::/48`, or `::/96`. */
63532
+ function embeddedV4FromHextets$1(h) {
63533
+ const toV4 = (hi, lo) => `${hi >> 8 & 255}.${hi & 255}.${lo >> 8 & 255}.${lo & 255}`;
63534
+ const zero0to4 = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
63535
+ if (zero0to4 && h[5] === 65535) return toV4(h[6], h[7]);
63536
+ if (h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 65535 && h[5] === 0) return toV4(h[6], h[7]);
63537
+ if (zero0to4 && h[5] === 0 && (h[6] !== 0 || (h[7] ?? 0) > 1)) return toV4(h[6], h[7]);
63538
+ if (h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0) return toV4(h[6], h[7]);
63539
+ if (h[0] === 100 && h[1] === 65435 && h[2] === 1) return toV4(h[6], h[7]);
63540
+ return null;
63541
+ }
63542
+ /** Unspecified (`::`), link-local (`fe80::/10`), multicast (`ff00::/8`), AWS IPv6 IMDS (`fd00:ec2::254`), and embedded IPv4 equivalents. */
63543
+ function linkLocalOrUnspecifiedV6(ip) {
63544
+ const h = parseIpv6Hextets$1(ip);
63545
+ if (!h) return false;
63546
+ if (h.every((x) => x === 0)) return true;
63547
+ if ((h[0] & 65472) === 65152) return true;
63548
+ if ((h[0] & 65280) === 65280) return true;
63549
+ if (h[0] === 64768 && h[1] === 3778 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0 && h[6] === 0 && h[7] === 596) return true;
63550
+ const v4 = embeddedV4FromHextets$1(h);
63551
+ return v4 ? linkLocalOrUnspecifiedV4(v4) : false;
63552
+ }
63553
+ // ../control-plane/dist/net/guarded-fetch.js
63554
+ function normalizeLiteralIp(ip) {
63555
+ return ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
63556
+ }
63557
+ /** True only for link-local (`169.254.0.0/16`, `fe80::/10`) and unspecified (`0.0.0.0/8`, `::`) addresses; allows private/loopback self-hosted hosts. */
63558
+ function isLinkLocalOrUnspecifiedAddress(ip) {
63559
+ const addr = normalizeLiteralIp(ip);
63560
+ if (isIP(addr) === 4) return linkLocalOrUnspecifiedV4(addr);
63561
+ if (isIP(addr) === 6) return linkLocalOrUnspecifiedV6(addr);
63562
+ return false;
63563
+ }
63564
+ // ../control-plane/dist/platforms/mattermost/server-url.js
63565
+ /**
63566
+ * Normalize and SSRF-guard a self-hosted Mattermost base URL.
63567
+ * Allows http/https, private/loopback/intranet hosts, and subpaths (stripping trailing slashes);
63568
+ * rejects non-http(s) schemes, embedded userinfo, query strings, fragments, link-local ranges, and unspecified addresses.
63569
+ */
63570
+ function normalizeMattermostServerUrl(raw) {
63571
+ const trimmed = raw.trim();
63572
+ if (!trimmed || /[\s\u0000-\u001f\u007f]/.test(trimmed)) return {
63573
+ ok: false,
63574
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
63575
+ };
63576
+ if (trimmed.includes("?") || trimmed.includes("#")) return {
63577
+ ok: false,
63578
+ reason: "The Mattermost server URL must not include a query string or fragment."
63579
+ };
63580
+ let url;
63581
+ try {
63582
+ url = new URL(trimmed);
63583
+ } catch {
63584
+ return {
63585
+ ok: false,
63586
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
63587
+ };
63588
+ }
63589
+ if (url.protocol !== "http:" && url.protocol !== "https:") return {
63590
+ ok: false,
63591
+ reason: "Mattermost server URL must use http:// or https://."
63592
+ };
63593
+ const authority = trimmed.slice(url.protocol.length + 2).split("/")[0] ?? "";
63594
+ if (url.username || url.password || authority.includes("@")) return {
63595
+ ok: false,
63596
+ reason: "The Mattermost server URL must not include a username or password."
63597
+ };
63598
+ if (!url.hostname) return {
63599
+ ok: false,
63600
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
63601
+ };
63602
+ const host = url.hostname.replace(/^\[|\]$/g, "");
63603
+ if (isIP(host) !== 0 && isLinkLocalOrUnspecifiedAddress(host)) return {
63604
+ ok: false,
63605
+ reason: "This Mattermost server address is not allowed."
63606
+ };
63607
+ const path = url.pathname.replace(/\/+$/, "");
63608
+ return {
63609
+ ok: true,
63610
+ serverUrl: `${url.origin}${path}`
63611
+ };
63612
+ }
63461
63613
  const HttpUrlSchema = string().url().superRefine((value, ctx) => {
63462
63614
  const url = new URL(value);
63463
63615
  if (url.protocol !== "http:" && url.protocol !== "https:") ctx.addIssue({
@@ -63517,6 +63669,20 @@ const LogtoSlackConnectorSchema = preprocess(withoutDerivedConnectorId, strictOb
63517
63669
  appId: string().trim().min(1),
63518
63670
  clientId: string().trim().min(1)
63519
63671
  }));
63672
+ const LogtoMattermostConnectorSchema = strictObject({
63673
+ serverUrl: string().trim().min(1).transform((value, ctx) => {
63674
+ const normalized = normalizeMattermostServerUrl(value);
63675
+ if (!normalized.ok) {
63676
+ ctx.addIssue({
63677
+ code: "custom",
63678
+ message: normalized.reason
63679
+ });
63680
+ return NEVER;
63681
+ }
63682
+ return normalized.serverUrl;
63683
+ }),
63684
+ clientId: string().trim().min(1)
63685
+ });
63520
63686
  const SsoDomainSchema = string().trim().toLowerCase().regex(/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/, "must be an email domain");
63521
63687
  /** The deployment's one SSO connector. Logto mints its id at creation; the IdP details arrive later. */
63522
63688
  const LogtoSsoConnectorSchema = strictObject({
@@ -63638,6 +63804,8 @@ const DeploymentConfigValuesV1Schema = strictObject({
63638
63804
  azureadConnector: strictObject({ clientId: string().trim().min(1) }).nullable().optional(),
63639
63805
  /** Deployment Slack App identity reused for Slack social sign-in. */
63640
63806
  slackConnector: LogtoSlackConnectorSchema.nullable().optional(),
63807
+ /** Self-hosted Mattermost OAuth 2.0 application for Mattermost social sign-in. Its secret stays write-only. */
63808
+ mattermostConnector: LogtoMattermostConnectorSchema.nullable().optional(),
63641
63809
  /** SSO (OIDC or SAML) connector. */
63642
63810
  ssoConnector: LogtoSsoConnectorSchema.nullable().optional()
63643
63811
  }).nullable(),
@@ -63749,6 +63917,7 @@ const DEPLOYMENT_SECRET_KEYS = [
63749
63917
  "logto.telegramConnectorClientSecret",
63750
63918
  "logto.discordConnectorClientSecret",
63751
63919
  "logto.azureadConnectorClientSecret",
63920
+ "logto.mattermostConnectorClientSecret",
63752
63921
  "logto.ssoConnectorClientSecret",
63753
63922
  "msTeams.blueprintClientSecret"
63754
63923
  ];
@@ -63845,6 +64014,14 @@ function deploymentSecretsRequiringRefresh(previous, next) {
63845
64014
  const nextSsoOidc = next.logto?.ssoConnector?.oidc;
63846
64015
  const previousSsoOidc = previous?.logto?.ssoConnector?.oidc;
63847
64016
  const logtoSsoClientChanged = nextSsoOidc && (previousSsoOidc?.issuer !== nextSsoOidc.issuer || previousSsoOidc?.clientId !== nextSsoOidc.clientId);
64017
+ const nextMattermostConnector = next.logto?.mattermostConnector;
64018
+ const previousMattermostConnector = previous?.logto?.mattermostConnector;
64019
+ const normalizedMattermostUrl = (raw) => {
64020
+ if (!raw) return void 0;
64021
+ const parsed = normalizeMattermostServerUrl(raw);
64022
+ return parsed.ok ? parsed.serverUrl : raw;
64023
+ };
64024
+ const logtoMattermostConnectorChanged = nextMattermostConnector && (previousMattermostConnector?.clientId !== nextMattermostConnector.clientId || normalizedMattermostUrl(previousMattermostConnector?.serverUrl) !== normalizedMattermostUrl(nextMattermostConnector.serverUrl));
63848
64025
  const emailAccountChanged = next.email && previous?.email?.accountId !== next.email.accountId;
63849
64026
  const msTeamsBlueprintChanged = next.msTeams?.agentBots && previous?.msTeams?.agentBots?.blueprintId !== next.msTeams.agentBots.blueprintId;
63850
64027
  return [
@@ -63862,6 +64039,7 @@ function deploymentSecretsRequiringRefresh(previous, next) {
63862
64039
  ...logtoIdentityChanged ? ["logto.managementAppSecret"] : [],
63863
64040
  ...logtoGithubConnectorChanged ? ["logto.githubConnectorClientSecret"] : [],
63864
64041
  ...logtoGoogleConnectorChanged ? ["logto.googleConnectorClientSecret"] : [],
64042
+ ...logtoMattermostConnectorChanged ? ["logto.mattermostConnectorClientSecret"] : [],
63865
64043
  ...logtoSsoClientChanged ? ["logto.ssoConnectorClientSecret"] : [],
63866
64044
  ...[
63867
64045
  "telegram",
@@ -63889,6 +64067,7 @@ function requiredSecrets(values) {
63889
64067
  ...values.logto ? ["logto.managementAppSecret"] : [],
63890
64068
  ...values.logto?.githubConnector ? ["logto.githubConnectorClientSecret"] : [],
63891
64069
  ...values.logto?.googleConnector ? ["logto.googleConnectorClientSecret"] : [],
64070
+ ...values.logto?.mattermostConnector ? ["logto.mattermostConnectorClientSecret"] : [],
63892
64071
  ...values.logto?.ssoConnector?.oidc ? ["logto.ssoConnectorClientSecret"] : [],
63893
64072
  ...[
63894
64073
  "telegram",
@@ -64585,6 +64764,7 @@ const LOGTO_GITHUB_CONNECTOR_ID = "agentconnect-github";
64585
64764
  const LOGTO_GITLAB_CONNECTOR_ID = "agentconnect-gitlab";
64586
64765
  const LOGTO_GOOGLE_CONNECTOR_ID = "agentconnect-google";
64587
64766
  const LOGTO_SLACK_CONNECTOR_ID = "agentconnect-slack";
64767
+ const LOGTO_MATTERMOST_CONNECTOR_ID = "agentconnect-mattermost";
64588
64768
  const LOGTO_LOGIN_APPS = {
64589
64769
  telegram: {
64590
64770
  name: "Telegram",
@@ -65915,10 +66095,10 @@ function toTimestamp(apiTimeInMs, expirationInSeconds) {
65915
66095
  return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
65916
66096
  }
65917
66097
  async function createDeviceCode(options) {
65918
- const request$5 = options.request || request;
66098
+ const request$7 = options.request || request;
65919
66099
  const parameters = { client_id: options.clientId };
65920
66100
  if ("scopes" in options && Array.isArray(options.scopes)) parameters.scope = options.scopes.join(" ");
65921
- return oauthRequest(request$5, "POST /login/device/code", parameters);
66101
+ return oauthRequest(request$7, "POST /login/device/code", parameters);
65922
66102
  }
65923
66103
  async function exchangeDeviceCode(options) {
65924
66104
  const response = await oauthRequest(options.request || request, "POST /login/oauth/access_token", {
@@ -66102,15 +66282,15 @@ async function hook$3(state, request, route, parameters) {
66102
66282
  var VERSION$3 = "0.0.0-development";
66103
66283
  function createOAuthDeviceAuth(options) {
66104
66284
  const requestWithDefaults = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-oauth-device.js/${VERSION$3} ${getUserAgent()}` } });
66105
- const { request: request$3 = requestWithDefaults, ...otherOptions } = options;
66285
+ const { request: request$5 = requestWithDefaults, ...otherOptions } = options;
66106
66286
  const state = options.clientType === "github-app" ? {
66107
66287
  ...otherOptions,
66108
66288
  clientType: "github-app",
66109
- request: request$3
66289
+ request: request$5
66110
66290
  } : {
66111
66291
  ...otherOptions,
66112
66292
  clientType: "oauth-app",
66113
- request: request$3,
66293
+ request: request$5,
66114
66294
  scopes: options.scopes || []
66115
66295
  };
66116
66296
  if (!options.clientId) throw new Error("[@octokit/auth-oauth-device] \"clientId\" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)");
@@ -66250,14 +66430,14 @@ async function hook$2(state, request, route, parameters = {}) {
66250
66430
  endpoint.headers.authorization = "token " + token;
66251
66431
  return request(endpoint);
66252
66432
  }
66253
- function createOAuthUserAuth({ clientId, clientSecret, clientType = "oauth-app", request: request$2 = request.defaults({ headers: { "user-agent": `octokit-auth-oauth-app.js/${VERSION$2} ${getUserAgent()}` } }), onTokenCreated, ...strategyOptions }) {
66433
+ function createOAuthUserAuth({ clientId, clientSecret, clientType = "oauth-app", request: request$4 = request.defaults({ headers: { "user-agent": `octokit-auth-oauth-app.js/${VERSION$2} ${getUserAgent()}` } }), onTokenCreated, ...strategyOptions }) {
66254
66434
  const state = Object.assign({
66255
66435
  clientType,
66256
66436
  clientId,
66257
66437
  clientSecret,
66258
66438
  onTokenCreated,
66259
66439
  strategyOptions,
66260
- request: request$2
66440
+ request: request$4
66261
66441
  });
66262
66442
  return Object.assign(auth$2.bind(null, state), { hook: hook$2.bind(null, state) });
66263
66443
  }
@@ -66834,9 +67014,9 @@ function createAppAuth(options) {
66834
67014
  if ("installationId" in options && !options.installationId) throw new Error("[@octokit/auth-app] installationId is set to a falsy value");
66835
67015
  const log = options.log || {};
66836
67016
  if (typeof log.warn !== "function") log.warn = console.warn.bind(console);
66837
- const request$1 = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-app.js/${VERSION} ${getUserAgent()}` } });
67017
+ const request$3 = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-app.js/${VERSION} ${getUserAgent()}` } });
66838
67018
  const state = Object.assign({
66839
- request: request$1,
67019
+ request: request$3,
66840
67020
  cache: getCache()
66841
67021
  }, options, options.installationId ? { installationId: Number(options.installationId) } : {}, {
66842
67022
  log,
@@ -66844,7 +67024,7 @@ function createAppAuth(options) {
66844
67024
  clientType: "github-app",
66845
67025
  clientId: options.clientId || "",
66846
67026
  clientSecret: options.clientSecret || "",
66847
- request: request$1
67027
+ request: request$3
66848
67028
  })
66849
67029
  });
66850
67030
  return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) });
@@ -67299,9 +67479,9 @@ function gitlabConfiguredUrls(config, baseUrl = GITLAB_DEFAULT_BASE_URL) {
67299
67479
  * be this process guessing about someone else's network.
67300
67480
  */
67301
67481
  /** Give up on a silent instance rather than hold the save request open. */
67302
- const PROBE_TIMEOUT_MS$2 = 5e3;
67482
+ const PROBE_TIMEOUT_MS$3 = 5e3;
67303
67483
  /** Node's TLS verification failures, as they surface through `fetch`'s cause chain. */
67304
- const TLS_FAILURE_CODES$1 = /* @__PURE__ */ new Set([
67484
+ const TLS_FAILURE_CODES$2 = /* @__PURE__ */ new Set([
67305
67485
  "CERT_HAS_EXPIRED",
67306
67486
  "CERT_NOT_YET_VALID",
67307
67487
  "CERT_REVOKED",
@@ -67333,10 +67513,10 @@ async function probeGitlabInstance(rawBaseUrl, fetchImpl) {
67333
67513
  response = await fetchImpl(`${baseUrl}/api/v4/version`, {
67334
67514
  method: "GET",
67335
67515
  headers: { accept: "application/json" },
67336
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$2)
67516
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$3)
67337
67517
  });
67338
67518
  } catch (error) {
67339
- if (isTlsFailure$1(error)) return {
67519
+ if (isTlsFailure$2(error)) return {
67340
67520
  status: "tls_untrusted",
67341
67521
  baseUrl,
67342
67522
  message: `the certificate at ${baseUrl} was not trusted by this process; the Control Plane needs the instance authority bundle`
@@ -67367,10 +67547,10 @@ async function isJsonObjectBody(response) {
67367
67547
  }
67368
67548
  }
67369
67549
  /** `fetch` reports a TLS failure through nested causes, so walk a bounded chain. */
67370
- function isTlsFailure$1(error) {
67550
+ function isTlsFailure$2(error) {
67371
67551
  for (let cursor = error, depth = 0; cursor !== void 0 && cursor !== null && depth < 5; depth++) {
67372
67552
  const candidate = cursor;
67373
- if (typeof candidate.code === "string" && TLS_FAILURE_CODES$1.has(candidate.code)) return true;
67553
+ if (typeof candidate.code === "string" && TLS_FAILURE_CODES$2.has(candidate.code)) return true;
67374
67554
  cursor = candidate.cause;
67375
67555
  }
67376
67556
  return false;
@@ -67438,9 +67618,9 @@ function parseGiteaVersion(raw) {
67438
67618
  * Control Plane, and refusing would be this process guessing about someone else's network.
67439
67619
  */
67440
67620
  /** Give up on a silent instance rather than hold the save request open. */
67441
- const PROBE_TIMEOUT_MS$1 = 5e3;
67621
+ const PROBE_TIMEOUT_MS$2 = 5e3;
67442
67622
  /** Node's TLS verification failures, as they surface through `fetch`'s cause chain. */
67443
- const TLS_FAILURE_CODES = /* @__PURE__ */ new Set([
67623
+ const TLS_FAILURE_CODES$1 = /* @__PURE__ */ new Set([
67444
67624
  "CERT_HAS_EXPIRED",
67445
67625
  "CERT_NOT_YET_VALID",
67446
67626
  "CERT_REVOKED",
@@ -67472,10 +67652,10 @@ async function probeGiteaInstance(rawBaseUrl, fetchImpl) {
67472
67652
  response = await fetchImpl(`${baseUrl}/api/v1/version`, {
67473
67653
  method: "GET",
67474
67654
  headers: { accept: "application/json" },
67475
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$1)
67655
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS$2)
67476
67656
  });
67477
67657
  } catch (error) {
67478
- if (isTlsFailure(error)) return {
67658
+ if (isTlsFailure$1(error)) return {
67479
67659
  status: "tls_untrusted",
67480
67660
  baseUrl,
67481
67661
  message: `the certificate at ${baseUrl} was not trusted by this process; the Control Plane needs the instance authority bundle`
@@ -67518,14 +67698,392 @@ async function readVersionBody(response) {
67518
67698
  }
67519
67699
  }
67520
67700
  /** `fetch` reports a TLS failure through nested causes, so walk a bounded chain. */
67521
- function isTlsFailure(error) {
67701
+ function isTlsFailure$1(error) {
67522
67702
  for (let cursor = error, depth = 0; cursor !== void 0 && cursor !== null && depth < 5; depth++) {
67523
67703
  const candidate = cursor;
67524
- if (typeof candidate.code === "string" && TLS_FAILURE_CODES.has(candidate.code)) return true;
67704
+ if (typeof candidate.code === "string" && TLS_FAILURE_CODES$1.has(candidate.code)) return true;
67525
67705
  cursor = candidate.cause;
67526
67706
  }
67527
67707
  return false;
67528
67708
  }
67709
+ // src/mattermost-probe.ts
67710
+ /**
67711
+ * Unauthenticated Mattermost instance floor probe for Setup Server (`#4340`).
67712
+ *
67713
+ * When validating a self-hosted Mattermost Server URL before or after saving
67714
+ * `logto.mattermostConnector`, issue `GET <serverUrl>/api/v4/system/ping` with
67715
+ * no credentials and `redirect: 'manual'`. A healthy Mattermost API root answers
67716
+ * `200` with its ping JSON (`{ status: "OK", ... }`), or `401`/`403` with a JSON
67717
+ * error body if an upstream gateway protects the endpoint — proving DNS, TLS
67718
+ * trust, and subpath shape.
67719
+ *
67720
+ * ONLY the URL shape blocks saving (`invalid_url`). The Setup Server, Control
67721
+ * Plane, and Logto may run in different network zones, so `unreachable`,
67722
+ * `tls_untrusted`, and `not_a_mattermost_api_root` surface as diagnostics rather
67723
+ * than blocking saves.
67724
+ */
67725
+ /** Give up on a silent instance rather than hold diagnostic requests open. */
67726
+ const PROBE_TIMEOUT_MS$1 = 5e3;
67727
+ /** Cap ping JSON response size so a hostile endpoint cannot OOM Setup Server. */
67728
+ const MAX_PROBE_BYTES = 65536;
67729
+ var ProbeBlockedError = class extends Error {
67730
+ constructor() {
67731
+ super("ssrf: blocked address");
67732
+ }
67733
+ };
67734
+ var ProbeSizeError = class extends Error {
67735
+ constructor() {
67736
+ super("probe: response too large");
67737
+ }
67738
+ };
67739
+ /** Node's TLS verification failures, as they surface through `fetch`/`https`'s cause chain. */
67740
+ const TLS_FAILURE_CODES = /* @__PURE__ */ new Set([
67741
+ "CERT_HAS_EXPIRED",
67742
+ "CERT_NOT_YET_VALID",
67743
+ "CERT_REVOKED",
67744
+ "CERT_UNTRUSTED",
67745
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
67746
+ "ERR_TLS_CERT_ALTNAME_INVALID",
67747
+ "HOSTNAME_MISMATCH",
67748
+ "SELF_SIGNED_CERT_IN_CHAIN",
67749
+ "UNABLE_TO_GET_ISSUER_CERT",
67750
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
67751
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
67752
+ ]);
67753
+ /** Whether a probe verdict must stop the save (URL shape or blocked destination only). */
67754
+ function probeMattermostBlocksSave(probe) {
67755
+ return probe.status === "invalid_url";
67756
+ }
67757
+ function makePinnedLookup(resolve) {
67758
+ return (hostname, options, callback) => {
67759
+ resolve(hostname, { all: true }, (err, addresses) => {
67760
+ if (err) return callback(err, "", 0);
67761
+ if (!addresses || addresses.length === 0) return callback(/* @__PURE__ */ new Error("probe: unresolved host"), "", 0);
67762
+ if (addresses.some((a) => isLinkLocalOrUnspecifiedIp(a.address))) return callback(new ProbeBlockedError(), "", 0);
67763
+ if (options?.all) return callback(null, addresses);
67764
+ const pick = addresses[0];
67765
+ return callback(null, pick.address, pick.family);
67766
+ });
67767
+ };
67768
+ }
67769
+ async function resolveAndValidateHost(hostname, resolve) {
67770
+ if (isIP(hostname) !== 0) return isLinkLocalOrUnspecifiedIp(hostname) ? "blocked" : "ok";
67771
+ return await new Promise((resolvePromise) => {
67772
+ resolve(hostname, { all: true }, (err, addresses) => {
67773
+ if (err || !addresses || addresses.length === 0) {
67774
+ resolvePromise("unreachable");
67775
+ return;
67776
+ }
67777
+ resolvePromise(addresses.some((a) => isLinkLocalOrUnspecifiedIp(a.address)) ? "blocked" : "ok");
67778
+ });
67779
+ });
67780
+ }
67781
+ async function nodePinnedProbeGet(pingUrl, lookupImpl, timeoutMs = PROBE_TIMEOUT_MS$1) {
67782
+ const target = new URL(pingUrl);
67783
+ const reqFn = target.protocol === "https:" ? request$2 : request$1;
67784
+ const lookup = makePinnedLookup(lookupImpl);
67785
+ return await new Promise((resolve, reject) => {
67786
+ let settled = false;
67787
+ let responseStarted = false;
67788
+ let ended = false;
67789
+ const controller = new AbortController();
67790
+ const timerBox = {};
67791
+ const finish = (err, value) => {
67792
+ if (settled) return;
67793
+ settled = true;
67794
+ clearTimeout(timerBox.id);
67795
+ if (err !== null && err !== void 0) reject(err);
67796
+ else resolve(value);
67797
+ };
67798
+ const req = reqFn(target, {
67799
+ method: "GET",
67800
+ headers: { accept: "application/json" },
67801
+ lookup,
67802
+ signal: controller.signal,
67803
+ ...target.protocol === "https:" ? { servername: target.hostname } : {}
67804
+ }, (res) => {
67805
+ responseStarted = true;
67806
+ const chunks = [];
67807
+ let size = 0;
67808
+ res.on("data", (chunk) => {
67809
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
67810
+ size += buf.byteLength;
67811
+ if (size > MAX_PROBE_BYTES) {
67812
+ const sizeErr = new ProbeSizeError();
67813
+ res.destroy(sizeErr);
67814
+ req.destroy(sizeErr);
67815
+ finish(sizeErr);
67816
+ return;
67817
+ }
67818
+ chunks.push(buf);
67819
+ });
67820
+ res.on("end", () => {
67821
+ ended = true;
67822
+ let body;
67823
+ try {
67824
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
67825
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) body = parsed;
67826
+ } catch {
67827
+ body = void 0;
67828
+ }
67829
+ finish(null, {
67830
+ status: res.statusCode ?? 0,
67831
+ body
67832
+ });
67833
+ });
67834
+ res.on("close", () => {
67835
+ if (!ended) finish(/* @__PURE__ */ new Error("probe: response stream closed prematurely"));
67836
+ });
67837
+ res.on("error", (err) => finish(err));
67838
+ });
67839
+ timerBox.id = setTimeout(() => {
67840
+ const timeoutErr = /* @__PURE__ */ new Error("Timed out");
67841
+ controller.abort(timeoutErr);
67842
+ req.destroy(timeoutErr);
67843
+ finish(timeoutErr);
67844
+ }, timeoutMs);
67845
+ timerBox.id.unref?.();
67846
+ req.on("close", () => {
67847
+ if (!responseStarted) finish(/* @__PURE__ */ new Error("probe: request closed prematurely"));
67848
+ });
67849
+ req.on("error", (err) => finish(err));
67850
+ req.end();
67851
+ });
67852
+ }
67853
+ async function probeMattermostInstance(rawServerUrl, fetchImpl, lookupImpl, opts = {}) {
67854
+ const normalized = normalizeMattermostProbeUrl(rawServerUrl);
67855
+ if (!normalized.ok) return {
67856
+ status: "invalid_url",
67857
+ message: normalized.reason
67858
+ };
67859
+ const { serverUrl } = normalized;
67860
+ const host = new URL(serverUrl).hostname.replace(/^\[|\]$/g, "");
67861
+ const timeoutMs = opts.timeoutMs ?? PROBE_TIMEOUT_MS$1;
67862
+ let status;
67863
+ let body;
67864
+ try {
67865
+ if (fetchImpl && fetchImpl !== globalThis.fetch) {
67866
+ if (lookupImpl) {
67867
+ const verdict = await resolveAndValidateHost(host, lookupImpl);
67868
+ if (verdict === "blocked") return {
67869
+ status: "invalid_url",
67870
+ message: "This Mattermost server address is not allowed."
67871
+ };
67872
+ if (verdict === "unreachable") return {
67873
+ status: "unreachable",
67874
+ serverUrl,
67875
+ message: `${serverUrl} could not be reached from the Setup Server; check intranet connectivity or save anyway if the Control Plane and Logto can reach it`
67876
+ };
67877
+ }
67878
+ const response = await fetchImpl(`${serverUrl}/api/v4/system/ping`, {
67879
+ method: "GET",
67880
+ headers: { accept: "application/json" },
67881
+ redirect: "manual",
67882
+ signal: AbortSignal.timeout(timeoutMs)
67883
+ });
67884
+ status = response.status;
67885
+ body = await readJsonObject(response);
67886
+ } else {
67887
+ const result = await nodePinnedProbeGet(`${serverUrl}/api/v4/system/ping`, lookupImpl ?? lookup, timeoutMs);
67888
+ status = result.status;
67889
+ body = result.body;
67890
+ }
67891
+ } catch (error) {
67892
+ if (error instanceof ProbeBlockedError) return {
67893
+ status: "invalid_url",
67894
+ message: "This Mattermost server address is not allowed."
67895
+ };
67896
+ if (error instanceof ProbeSizeError) return {
67897
+ status: "not_a_mattermost_api_root",
67898
+ serverUrl,
67899
+ message: `${serverUrl}/api/v4/system/ping returned a response larger than ${MAX_PROBE_BYTES} bytes`
67900
+ };
67901
+ if (isTlsFailure(error)) return {
67902
+ status: "tls_untrusted",
67903
+ serverUrl,
67904
+ message: `the certificate at ${serverUrl} was not trusted by this process; mount your internal CA bundle and set NODE_EXTRA_CA_CERTS on Setup Server, Control Plane, and Logto`
67905
+ };
67906
+ return {
67907
+ status: "unreachable",
67908
+ serverUrl,
67909
+ message: `${serverUrl} could not be reached from the Setup Server; check intranet connectivity or save anyway if the Control Plane and Logto can reach it`
67910
+ };
67911
+ }
67912
+ if (status === 200) {
67913
+ if (body !== void 0 && (!("status" in body) || typeof body.status !== "string" || body.status.toUpperCase() === "OK")) return {
67914
+ status: "ok",
67915
+ serverUrl,
67916
+ message: `${serverUrl} answered as a Mattermost API root`
67917
+ };
67918
+ } else if ((status === 401 || status === 403) && body !== void 0) return {
67919
+ status: "ok",
67920
+ serverUrl,
67921
+ message: `${serverUrl} answered as a Mattermost API root`
67922
+ };
67923
+ return {
67924
+ status: "not_a_mattermost_api_root",
67925
+ serverUrl,
67926
+ message: `${serverUrl}/api/v4/system/ping answered ${status} rather than a Mattermost API root; check the server URL and any path prefix`
67927
+ };
67928
+ }
67929
+ function normalizeMattermostProbeUrl(rawServerUrl) {
67930
+ const trimmed = rawServerUrl.trim();
67931
+ if (!trimmed || /[\s\u0000-\u001f\u007f]/.test(trimmed)) return {
67932
+ ok: false,
67933
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
67934
+ };
67935
+ if (trimmed.includes("?") || trimmed.includes("#")) return {
67936
+ ok: false,
67937
+ reason: "The Mattermost server URL must not include a query string or fragment."
67938
+ };
67939
+ let url;
67940
+ try {
67941
+ url = new URL(trimmed);
67942
+ } catch {
67943
+ return {
67944
+ ok: false,
67945
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
67946
+ };
67947
+ }
67948
+ if (url.protocol !== "http:" && url.protocol !== "https:") return {
67949
+ ok: false,
67950
+ reason: "Mattermost server URL must use http:// or https://."
67951
+ };
67952
+ const authority = trimmed.slice(url.protocol.length + 2).split("/")[0] ?? "";
67953
+ if (url.username || url.password || authority.includes("@")) return {
67954
+ ok: false,
67955
+ reason: "The Mattermost server URL must not include a username or password."
67956
+ };
67957
+ if (!url.hostname) return {
67958
+ ok: false,
67959
+ reason: "Enter a valid Mattermost server URL (for example, https://mattermost.example.com)."
67960
+ };
67961
+ const host = url.hostname.replace(/^\[|\]$/g, "");
67962
+ if (isIP(host) !== 0 && isLinkLocalOrUnspecifiedIp(host)) return {
67963
+ ok: false,
67964
+ reason: "This Mattermost server address is not allowed."
67965
+ };
67966
+ const path = url.pathname.replace(/\/+$/, "");
67967
+ return {
67968
+ ok: true,
67969
+ serverUrl: `${url.origin}${path}`
67970
+ };
67971
+ }
67972
+ function isLinkLocalOrUnspecifiedV4(ip) {
67973
+ const octets = ip.split(".").map(Number);
67974
+ if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
67975
+ const [a, b, c, d] = octets;
67976
+ if (a === 0 || a === 169 && b === 254) return true;
67977
+ if (a === 100 && b === 100 && c === 100 && d === 200) return true;
67978
+ if (a === 192 && b === 0 && c === 0) return true;
67979
+ if (a === 198 && (b === 18 || b === 19)) return true;
67980
+ if (a >= 224) return true;
67981
+ return false;
67982
+ }
67983
+ function parseIpv4Tail(part) {
67984
+ const octets = part.split(".");
67985
+ if (octets.length !== 4 || octets.some((o) => !/^\d+$/.test(o))) return null;
67986
+ const nums = octets.map(Number);
67987
+ if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
67988
+ const [a, b, c, d] = nums;
67989
+ return [(a << 8 | b) & 65535, (c << 8 | d) & 65535];
67990
+ }
67991
+ function expandIpv6Side(raw, allowTrailingV4) {
67992
+ if (!raw) return [];
67993
+ const parts = raw.split(":");
67994
+ const out = [];
67995
+ for (let i = 0; i < parts.length; i++) {
67996
+ const part = parts[i];
67997
+ if (!part) return null;
67998
+ if (allowTrailingV4 && i === parts.length - 1 && part.includes(".")) {
67999
+ const pair = parseIpv4Tail(part);
68000
+ if (!pair) return null;
68001
+ out.push(pair[0], pair[1]);
68002
+ continue;
68003
+ }
68004
+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
68005
+ out.push(parseInt(part, 16));
68006
+ }
68007
+ return out;
68008
+ }
68009
+ function parseIpv6Hextets(ip) {
68010
+ const compressed = ip.split("::");
68011
+ if (compressed.length > 2) return null;
68012
+ if (compressed.length === 1) {
68013
+ const hextets = expandIpv6Side(compressed[0], true);
68014
+ return hextets && hextets.length === 8 ? hextets : null;
68015
+ }
68016
+ const left = expandIpv6Side(compressed[0], false);
68017
+ const right = expandIpv6Side(compressed[1], true);
68018
+ if (!left || !right || left.length + right.length >= 8) return null;
68019
+ return [
68020
+ ...left,
68021
+ ...new Array(8 - left.length - right.length).fill(0),
68022
+ ...right
68023
+ ];
68024
+ }
68025
+ function embeddedV4FromHextets(h) {
68026
+ const toV4 = (hi, lo) => `${hi >> 8 & 255}.${hi & 255}.${lo >> 8 & 255}.${lo & 255}`;
68027
+ const zero0to4 = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
68028
+ if (zero0to4 && h[5] === 65535) return toV4(h[6], h[7]);
68029
+ if (h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 65535 && h[5] === 0) return toV4(h[6], h[7]);
68030
+ if (zero0to4 && h[5] === 0 && (h[6] !== 0 || (h[7] ?? 0) > 1)) return toV4(h[6], h[7]);
68031
+ if (h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0) return toV4(h[6], h[7]);
68032
+ if (h[0] === 100 && h[1] === 65435 && h[2] === 1) return toV4(h[6], h[7]);
68033
+ return null;
68034
+ }
68035
+ function isLinkLocalOrUnspecifiedIp(ip) {
68036
+ const normalized = (ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "").trim();
68037
+ if (isIP(normalized) === 4) return isLinkLocalOrUnspecifiedV4(normalized);
68038
+ const h = parseIpv6Hextets(normalized);
68039
+ if (!h) return false;
68040
+ if (h.every((x) => x === 0)) return true;
68041
+ if ((h[0] & 65472) === 65152) return true;
68042
+ if ((h[0] & 65280) === 65280) return true;
68043
+ if (h[0] === 64768 && h[1] === 3778 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0 && h[6] === 0 && h[7] === 596) return true;
68044
+ const v4 = embeddedV4FromHextets(h);
68045
+ return v4 ? isLinkLocalOrUnspecifiedV4(v4) : false;
68046
+ }
68047
+ async function readJsonObject(response) {
68048
+ const reader = response.body?.getReader();
68049
+ let raw;
68050
+ if (reader) {
68051
+ const chunks = [];
68052
+ let size = 0;
68053
+ try {
68054
+ for (;;) {
68055
+ const { done, value } = await reader.read();
68056
+ if (done) break;
68057
+ size += value.byteLength;
68058
+ if (size > MAX_PROBE_BYTES) {
68059
+ await reader.cancel().catch(() => {});
68060
+ throw new ProbeSizeError();
68061
+ }
68062
+ chunks.push(Buffer.from(value));
68063
+ }
68064
+ } finally {
68065
+ reader.releaseLock();
68066
+ }
68067
+ raw = Buffer.concat(chunks).toString("utf8");
68068
+ } else {
68069
+ raw = await response.text();
68070
+ if (Buffer.byteLength(raw) > MAX_PROBE_BYTES) throw new ProbeSizeError();
68071
+ }
68072
+ try {
68073
+ const body = JSON.parse(raw);
68074
+ return typeof body === "object" && body !== null && !Array.isArray(body) ? body : void 0;
68075
+ } catch {
68076
+ return;
68077
+ }
68078
+ }
68079
+ /** `fetch` reports TLS failures through nested `cause` (or `AggregateError.errors`), so walk a bounded tree. */
68080
+ function isTlsFailure(error, depth = 0) {
68081
+ if (error === void 0 || error === null || depth >= 5) return false;
68082
+ const candidate = error;
68083
+ if (typeof candidate.code === "string" && TLS_FAILURE_CODES.has(candidate.code)) return true;
68084
+ if (Array.isArray(candidate.errors) && candidate.errors.some((item) => isTlsFailure(item, depth + 1))) return true;
68085
+ return isTlsFailure(candidate.cause, depth + 1);
68086
+ }
67529
68087
  // src/linear-app.ts
67530
68088
  /** The public `/v1` OAuth callback the deployment app must list (linear-integration.md §7.1). */
67531
68089
  const LINEAR_OAUTH_CALLBACK_PATH = "/v1/integrations/linear/oauth/callback";
@@ -68549,16 +69107,16 @@ const ssoForm = (prefix) => String.raw`
68549
69107
  </div>`;
68550
69108
  const SETUP_HTML = String.raw(_templateObject || (_templateObject = _taggedTemplateLiteral([
68551
69109
  "<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>AgentConnect deployment settings</title>\n <style>\n :root { color-scheme: light dark; font: 15px/1.5 system-ui, sans-serif; }\n body { max-width: 1280px; margin: 48px auto; padding: 0 20px 60px; }\n h1 { margin-bottom: 4px; } h2 { margin-top: 32px; } h3 { margin: 0 0 8px; }\n .muted { color: #777; } .row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }\n button, .button { padding: 8px 13px; cursor: pointer; }\n .button { border: 1px solid #8888; border-radius: 4px; color: inherit; text-decoration: none; display: inline-block; }\n input, select { width: min(520px, 100%); padding: 7px; box-sizing: border-box; }\n input[type=\"checkbox\"] { width: auto; padding: 0; }\n .field { display: grid; gap: 4px; margin: 10px 0; }\n .provider-stack { display: grid; gap: 16px; }\n .panel { border: 1px solid #8886; border-radius: 8px; padding: 16px; }\n .section-head, .provider-head { display: flex; justify-content: space-between; gap: 16px; align-items: start; }\n .section-head h2, .provider-head h3 { margin: 0; }\n .provider-head p { margin: 4px 0 0; }\n .badge { flex: none; border: 1px solid #8886; border-radius: 999px; padding: 3px 9px; font-size: 13px; }\n .badge.pass { color: #198754; border-color: #19875466; background: #19875412; }\n .badge.warn { color: #a66b00; border-color: #d99b1366; background: #d99b1315; }\n .badge.fail { color: #c33; border-color: #c333; background: #c3331111; }\n .credentials { display: grid; grid-template-columns: minmax(160px, 220px) minmax(0, 1fr); gap: 7px 16px; margin: 16px 0; }\n .credentials dt { color: #777; }\n .credentials dd { margin: 0; overflow-wrap: anywhere; }\n .credentials code { user-select: all; }\n .redacted { font-family: ui-monospace, monospace; letter-spacing: .08em; }\n .secret-line, .value-line { display: flex; gap: 10px; align-items: center; min-height: 30px; }\n .edit-secret { padding: 2px 8px; font-size: 13px; }\n .secret-editor { display: flex; gap: 8px; flex-wrap: wrap; width: 100%; }\n .secret-editor input { width: min(420px, 100%); }\n .edit-configuration { padding: 2px 8px; font-size: 13px; }\n .startup-owned { color: #777; font-size: 13px; }\n .danger { color: #c33; border-color: #c336; }\n .subsection { margin-top: 16px; padding-top: 14px; border-top: 1px solid #8883; }\n textarea { width: min(720px, 100%); min-height: 100px; padding: 7px; box-sizing: border-box; }\n .uris { margin: 8px 0; padding-left: 20px; } .uris code { user-select: all; }\n .notice { border-left: 4px solid #d99b13; padding: 8px 12px; background: #d99b1315; }\n .diff-title { display: block; margin-bottom: 8px; }\n .config-diff { display: grid; gap: 1px; border: 1px solid #8884; border-radius: 6px; overflow: hidden; background: #8884; }\n .diff-row { display: grid; grid-template-columns: minmax(140px, .8fr) minmax(0, 1.2fr) minmax(0, 1.2fr); background: Canvas; }\n .diff-row > * { min-width: 0; padding: 7px 9px; overflow-wrap: anywhere; white-space: pre-wrap; }\n .diff-head { font-size: 12px; font-weight: 600; color: #777; }\n .diff-field { font-weight: 600; }\n .diff-value { font-family: ui-monospace, monospace; font-size: 13px; }\n pre { padding: 12px; border-radius: 6px; background: #8881; overflow-x: auto; user-select: all; }\n #message { white-space: pre-wrap; padding: 10px 0; min-height: 1.5em; }\n .error { color: #c33; } .ok { color: #198754; } .warn { color: #a66b00; }\n code { overflow-wrap: anywhere; }\n .setup-layout { display: grid; grid-template-columns: 190px minmax(0, 1fr); gap: 32px; align-items: start; }\n .setup-nav { position: sticky; top: 24px; display: grid; gap: 3px; padding: 10px; border: 1px solid #8886; border-radius: 8px; background: Canvas; }\n .setup-nav a { padding: 7px 9px; border-radius: 5px; color: inherit; text-decoration: none; white-space: nowrap; }\n .setup-nav a:hover { background: #8882; }\n .setup-section { scroll-margin-top: 24px; }\n details.environment { margin: 0 0 24px; } details.environment summary { cursor: pointer; font-weight: 600; }\n @media (max-width: 760px) {\n body { margin-top: 24px; }\n .setup-layout { grid-template-columns: 1fr; gap: 18px; }\n .setup-nav { position: static; display: flex; overflow-x: auto; }\n .credentials { grid-template-columns: 1fr; gap: 2px; }\n .credentials dd { margin-bottom: 8px; }\n .diff-row { grid-template-columns: 1fr; }\n .diff-head { display: none; }\n .diff-value::before { display: block; margin-bottom: 2px; color: #777; font: 11px/1.4 system-ui, sans-serif; }\n .diff-current::before { content: 'Current'; }\n .diff-expected::before { content: 'Expected'; }\n }\n [hidden] { display: none !important; }\n </style>\n</head>\n<body>\n <section id=\"access\">\n <h1>AgentConnect Setup</h1>\n <p id=\"access-message\" class=\"muted\" aria-live=\"polite\">Checking Logto sign-in…</p>\n <div class=\"row\">\n <button id=\"login\" hidden>Sign in with Logto</button>\n <a id=\"open-logto\" class=\"button\" href=\"http://localhost:3002\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n <button id=\"show-bootstrap\" hidden>Continue setup</button>\n </div>\n\n <section id=\"bootstrap\" hidden>\n <h2>Set up sign-in</h2>\n <p id=\"bootstrap-progress\" class=\"muted\">Step 1 of 2</p>\n <div id=\"bootstrap-logto-step\" class=\"panel\">\n <h3>Connect Logto</h3>\n <p class=\"muted\">Enter the one-time Logto Management API credential. It is sealed in the deployment database and verified before continuing.</p>\n <label class=\"field\">Logto M2M App ID<input id=\"logto-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Logto M2M App Secret<input id=\"logto-app-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-management-api-resource\" type=\"url\" autocomplete=\"off\"></label>\n <p class=\"muted\">Logto Cloud uses <code>https://&lt;tenant-id&gt;.logto.app/api</code>. Keep <code>https://default.logto.app/api</code> for Logto OSS.</p>\n <button id=\"bootstrap-logto-submit\">Save Logto and continue</button>\n </div>\n <div id=\"bootstrap-provider-step\" hidden>\n <h3>Choose a sign-in provider</h3>\n <p class=\"muted\">Logto Management API access is ready. Configure one provider to enable sign-in.</p>\n <label class=\"field\">Sign-in provider\n <select id=\"bootstrap-provider\"><option value=\"google\">Google (works on localhost)</option><option value=\"github\">GitHub integration App</option><option id=\"bootstrap-slack-option\" value=\"slack\">Slack integration App</option><option value=\"sso\">Single sign-on (OIDC or SAML)</option></select>\n </label>\n <div id=\"bootstrap-google\" class=\"panel\">\n <h3>Google OAuth client</h3>\n <p class=\"muted\">Create a Web application client in Google Auth Platform, then paste its credentials here.</p>\n <p>Authorized JavaScript origin:</p><ul id=\"bootstrap-google-origins\" class=\"uris\"></ul>\n <p>Authorized redirect URIs:</p><ul id=\"bootstrap-google-redirects\" class=\"uris\"></ul>\n <a class=\"button\" href=\"https://console.cloud.google.com/auth/clients\" target=\"_blank\" rel=\"noopener\">Open Google settings</a>\n <label class=\"field\">Client ID<input id=\"bootstrap-google-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client Secret<input id=\"bootstrap-google-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n <button id=\"bootstrap-google-submit\">Save Google OAuth and configure Logto</button>\n </div>\n <div id=\"bootstrap-github\" class=\"panel\" hidden>\n <h3>GitHub integration App</h3>\n <p id=\"bootstrap-github-note\" class=\"muted\">This creates one complete App for both GitHub sign-in and repository integration.</p>\n <label class=\"field\">Owner\n <select id=\"bootstrap-github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"bootstrap-github-org-field\" class=\"field\" hidden>Organization login<input id=\"bootstrap-github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"bootstrap-github-name\" value=\"AgentConnect\"></label>\n <button id=\"bootstrap-github-submit\">Create GitHub App and configure Logto</button>\n </div>\n <div id=\"bootstrap-slack\" class=\"panel\" hidden>\n <h3>Slack integration App</h3>\n <p id=\"bootstrap-slack-note\" class=\"muted\">Creates one complete Slack App for workspace installation and a separate Sign in with Slack OIDC flow.</p>\n <p>Logto redirect URI:</p><ul id=\"bootstrap-slack-redirects\" class=\"uris\"></ul>\n <label class=\"field\">App name<input id=\"bootstrap-slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"bootstrap-slack-token\" type=\"password\" autocomplete=\"new-password\"></label>\n <button id=\"bootstrap-slack-submit\">Create Slack App and configure Logto</button>\n </div>\n <div id=\"bootstrap-sso\" class=\"panel\" hidden>\n <h3>Single sign-on</h3>\n <p class=\"muted\">Sign in through the organization's identity provider. Logto creates the connector first, so its URLs can be registered with the identity provider.</p>\n ",
68552
- "\n </div>\n <button id=\"bootstrap-back\">Back to Logto credentials</button>\n </div>\n </section>\n </section>\n\n <main id=\"setup\" hidden>\n <div class=\"setup-layout\">\n <nav class=\"setup-nav\" aria-label=\"Deployment settings\">\n <a href=\"#startup-section\">Startup</a>\n <a href=\"#logto-section\">Logto</a>\n <a href=\"#sso-section\">Single sign-on</a>\n <a href=\"#github-section\">GitHub</a>\n <a href=\"#gitlab-section\">GitLab</a>\n <a href=\"#gitea-section\">Gitea</a>\n <a href=\"#slack-section\">Slack</a>\n <a href=\"#linear-section\">Linear</a>\n <a href=\"#google-section\">Google</a>\n <a href=\"#telegram-section\">Telegram</a>\n <a href=\"#discord-section\">Discord</a>\n <a href=\"#azuread-section\">Microsoft</a>\n <a href=\"#googlechat-section\">Google Chat</a>\n <a href=\"#email-section\">Email</a>\n <a href=\"#feishu-section\">Feishu</a>\n <a href=\"#lark-section\">Lark</a>\n <a href=\"#options-section\">Options</a>\n </nav>\n <div class=\"setup-content\">\n <h1>AgentConnect deployment settings</h1>\n <p class=\"muted\">Saved settings take effect after the stack is restarted.</p>\n <div class=\"row\">\n <button id=\"logout\">Log out</button>\n </div>\n <div id=\"message\" aria-live=\"polite\"></div>\n\n <section id=\"editor\" hidden>\n <details id=\"startup-section\" class=\"environment setup-section\" open>\n <summary>Startup environment</summary>\n <p class=\"notice\">Public service URLs come from <code>.env</code>. Provider callbacks below are derived from these values.</p>\n <pre id=\"startup-environment\"></pre>\n </details>\n\n <section id=\"logto-section\" class=\"setup-section\" aria-labelledby=\"logto-heading\">\n <div class=\"section-head\">\n <div><h2 id=\"logto-heading\">Logto</h2><p class=\"muted\">Authentication and administrator access.</p></div>\n <span id=\"logto-match\" class=\"badge\">Not checked</span>\n </div>\n <div class=\"panel\">\n <dl class=\"credentials\">\n <dt>Management endpoint</dt><dd class=\"value-line\"><code id=\"logto-management-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>Management App ID</dt><dd class=\"value-line\"><code id=\"logto-management-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management API resource</dt><dd class=\"value-line\"><code id=\"logto-management-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management App secret</dt><dd class=\"secret-line\"><span id=\"logto-management-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.managementAppSecret\" data-secret-display=\"logto-management-secret-display\">Edit</button></dd>\n <dt>Sign-in endpoint</dt><dd class=\"value-line\"><code id=\"logto-browser-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>SPA App ID</dt><dd class=\"value-line\"><code id=\"logto-browser-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Browser API resource</dt><dd class=\"value-line\"><code id=\"logto-browser-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n </dl>\n <div id=\"logto-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Logto configuration</h3>\n <label class=\"field\">Management App ID<input id=\"logto-edit-management-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-edit-management-resource\" autocomplete=\"off\"></label>\n <label class=\"field\">New Management App secret<input id=\"logto-edit-management-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when management identity changes\"></label>\n <label class=\"field\">SPA App ID<input id=\"logto-edit-browser-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Browser API resource<input id=\"logto-edit-browser-resource\" autocomplete=\"off\" placeholder=\"Optional\"></label>\n <div class=\"row\"><button id=\"save-logto-configuration\">Save configuration</button><button id=\"cancel-logto-configuration\">Cancel</button></div>\n </div>\n <p id=\"logto-status\" class=\"muted\">Checking redirects and sign-in settings…</p>\n <div id=\"logto-drift\" class=\"notice\" hidden></div>\n <div class=\"row\">\n <button id=\"check-logto\">Check match</button>\n <button id=\"reconcile-logto\">Apply expected settings</button>\n <a id=\"logto-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n </div>\n </div>\n </section>\n\n <h2>Providers</h2>\n <div class=\"provider-stack\">\n <section id=\"github-section\" class=\"panel setup-section\" aria-labelledby=\"github-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"github-heading\">GitHub</h3><p class=\"muted\">Repository integration and optional Logto sign-in.</p></div>\n <span id=\"github-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"github-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>App slug</dt><dd class=\"value-line\"><code id=\"github-app-slug\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"github-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Webhook delivery</dt><dd class=\"value-line\"><code id=\"github-webhook-enabled\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"github-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.clientSecret\" data-secret-display=\"github-client-secret-display\">Edit</button></dd>\n <dt>Private key</dt><dd class=\"secret-line\"><span id=\"github-private-key-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.privateKeyB64\" data-secret-display=\"github-private-key-display\">Edit</button></dd>\n <dt>Webhook secret</dt><dd class=\"secret-line\"><span id=\"github-webhook-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.webhookSecret\" data-secret-display=\"github-webhook-secret-display\">Edit</button></dd>\n <dt>Logto connector secret</dt><dd class=\"secret-line\"><span id=\"github-logto-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.githubConnectorClientSecret\" data-secret-display=\"github-logto-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"github-status\" class=\"muted\"></p>\n <div id=\"github-drift\" class=\"notice\" hidden></div>\n <div id=\"github-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit GitHub App identity</h3>\n <label class=\"field\">App ID<input id=\"github-edit-app-id\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n <label class=\"field\">App slug<input id=\"github-edit-slug\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"github-edit-client-id\" autocomplete=\"off\"></label>\n <label><input id=\"github-edit-webhook-enabled\" type=\"checkbox\"> Enable Relay webhook delivery</label>\n <label class=\"field\">New client secret<input id=\"github-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when App or Client ID changes\"></label>\n <label class=\"field\">New private key (base64)<textarea id=\"github-edit-private-key\" autocomplete=\"off\" placeholder=\"Required when App ID changes\"></textarea></label>\n <label class=\"field\">New webhook secret<input id=\"github-edit-webhook-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when an active webhook App ID changes\"></label>\n <label id=\"github-edit-logto-secret-field\" class=\"field\" hidden>New Logto connector client secret<input id=\"github-edit-logto-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when this App is also used for sign-in\"></label>\n <div class=\"row\"><button id=\"save-github-configuration\">Save configuration</button><button id=\"cancel-github-configuration\">Cancel</button></div>\n </div>\n <div id=\"github-create-controls\" class=\"subsection\">\n <label class=\"field\">Owner\n <select id=\"github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"github-org-field\" class=\"field\" hidden>Organization login<input id=\"github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"github-name\" value=\"AgentConnect\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-github\">Create GitHub App</button>\n <button id=\"connect-github-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-github\" hidden>Check match</button>\n <button id=\"clear-github\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"github-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open GitHub settings</a>\n </div>\n </section>\n\n <section id=\"gitlab-section\" class=\"panel setup-section\" aria-labelledby=\"gitlab-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitlab-heading\">GitLab</h3><p class=\"muted\">OAuth application used to administer projects on this deployment's GitLab instance.</p></div>\n <span id=\"gitlab-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitlab-instance\">https://gitlab.com</code></dd>\n <dt>Application ID</dt><dd class=\"value-line\"><code id=\"gitlab-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"gitlab\">Edit</button></dd>\n <dt>Secret</dt><dd class=\"secret-line\"><span id=\"gitlab-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"gitlab.clientSecret\" data-secret-display=\"gitlab-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"gitlab-status\" class=\"muted\"></p>\n <p id=\"gitlab-probe\" class=\"muted\" hidden></p>\n <div id=\"gitlab-drift\" class=\"notice\" hidden></div>\n <p>Redirect URI:</p><ul id=\"gitlab-callbacks\" class=\"uris\"></ul>\n <p>Scopes:</p><ul id=\"gitlab-scopes\" class=\"uris\"></ul>\n <p class=\"muted\">GitLab does not expose OAuth application creation through an API. In User settings &rarr; Applications, or a group's Settings &rarr; Applications, add an application whose redirect URI is exactly the value above, keep Confidential selected, grant the scopes above, then save the generated Application ID and Secret here. GitLab shows the secret only once.</p>\n <p class=\"muted\">Use your own user applications unless you are an instance administrator registering one application for everyone; an instance-wide application lives in the Admin area instead.</p>\n <p class=\"muted\">Creating each agent's bot account later needs authority this page cannot verify — no GitLab API reports it: either connect an instance administrator (whose API token cannot act as one while Admin Mode is enabled), or, on Premium and Ultimate, turn on Admin &rarr; Settings &rarr; General &rarr; Account and limit &rarr; &ldquo;Allow top-level group Owners to create service accounts&rdquo;.</p>\n <div class=\"row\"><a id=\"gitlab-applications\" class=\"button\" href=\"https://gitlab.com/-/user_settings/applications\" target=\"_blank\" rel=\"noopener\">Open GitLab applications</a><a id=\"gitlab-admin-applications\" class=\"button\" href=\"https://gitlab.com/admin/applications\" target=\"_blank\" rel=\"noopener\">Open admin applications</a></div>\n <div id=\"gitlab-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitlab-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitlab.com\"></label>\n <label class=\"field\">Application ID<input id=\"gitlab-id\" autocomplete=\"off\"></label>\n <label id=\"gitlab-initial-secret-field\" class=\"field\">Secret<input id=\"gitlab-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Application ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitlab\">Save GitLab application</button><button id=\"cancel-gitlab-configuration\" hidden>Cancel</button><button id=\"clear-gitlab\" class=\"danger\" hidden>Clear configuration</button></div>\n <div class=\"subsection\">\n <h4>GitLab sign-in</h4>\n <p>Add these redirect URIs and the openid, profile and email scopes to the same confidential OAuth application.</p>\n <ul id=\"gitlab-login-redirects\" class=\"uris\"></ul>\n <p id=\"gitlab-login-status\" class=\"muted\"></p>\n <div class=\"row\"><button id=\"connect-gitlab-login\">Use for Logto sign-in</button><button id=\"disconnect-gitlab-login\" hidden>Disable GitLab sign-in</button><button id=\"check-gitlab-login\" hidden>Check Logto</button></div>\n </div>\n </section>\n\n <section id=\"gitea-section\" class=\"panel setup-section\" aria-labelledby=\"gitea-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitea-heading\">Gitea</h3><p class=\"muted\">The Gitea instance this deployment addresses. Gitea registers no application, so the address is the whole setting.</p></div>\n <span id=\"gitea-match\" class=\"badge\">Default</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitea-instance\">https://gitea.com</code><button class=\"edit-configuration\" data-provider=\"gitea\">Edit</button></dd>\n </dl>\n <p id=\"gitea-status\" class=\"muted\"></p>\n <p id=\"gitea-probe\" class=\"muted\" hidden></p>\n <p class=\"muted\">Each organization connects Gitea by pasting the personal access token of a bot user it created, in the console — nothing about that identity is a deployment setting. Gitea 1.23 or later, or Forgejo 15 or later, is required, and the address is checked against that floor when it is saved.</p>\n <p class=\"muted\">Leave the field empty for gitea.com. A self-hosted instance under a path prefix keeps the prefix. A Forgejo instance, Codeberg included, is entered the same way.</p>\n <div id=\"gitea-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitea-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitea.com\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitea\">Save Gitea instance</button><button id=\"cancel-gitea-configuration\" hidden>Cancel</button><button id=\"clear-gitea\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"slack-section\" class=\"panel setup-section\" aria-labelledby=\"slack-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"slack-heading\">Slack</h3><p class=\"muted\">One App for workspace integration and Logto sign-in.</p></div>\n <span id=\"slack-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"slack-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"slack-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"slack-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.clientSecret\" data-secret-display=\"slack-client-secret-display\">Edit</button></dd>\n <dt>Signing secret</dt><dd class=\"secret-line\"><span id=\"slack-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.signingSecret\" data-secret-display=\"slack-signing-secret-display\">Edit</button></dd>\n <dt>Logto sign-in</dt><dd id=\"slack-logto-status\">Not configured</dd>\n </dl>\n <p id=\"slack-status\" class=\"muted\"></p>\n <div id=\"slack-drift\" class=\"notice\" hidden></div>\n <div id=\"slack-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Slack App identity</h3>\n <label class=\"field\">App ID<input id=\"slack-edit-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"slack-edit-client-id\" autocomplete=\"off\"></label>\n <label class=\"field\">New client secret<input id=\"slack-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <label class=\"field\">New signing secret<input id=\"slack-edit-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <div class=\"row\"><button id=\"save-slack-configuration\">Save configuration</button><button id=\"cancel-slack-configuration\">Cancel</button></div>\n </div>\n <div class=\"subsection\">\n <label id=\"slack-name-field\" class=\"field\">App name<input id=\"slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"slack-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Used only for create, check or update\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-slack\">Create Slack App</button>\n <button id=\"connect-slack-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-slack\" hidden>Check match</button>\n <button id=\"reconcile-slack\" hidden>Apply update</button>\n <button id=\"clear-slack\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"slack-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Slack settings</a>\n </div>\n </section>\n\n <section id=\"linear-section\" class=\"panel setup-section\" aria-labelledby=\"linear-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"linear-heading\">Linear</h3><p class=\"muted\">One OAuth application for the whole deployment. Every workspace connects through it.</p></div>\n <span id=\"linear-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"linear-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"linear\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"linear-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.clientSecret\" data-secret-display=\"linear-client-secret-display\">Edit</button></dd>\n <dt>Webhook signing secret</dt><dd class=\"secret-line\"><span id=\"linear-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.signingSecret\" data-secret-display=\"linear-signing-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"linear-status\" class=\"muted\"></p>\n <div id=\"linear-drift\" class=\"notice\" hidden></div>\n <p>Callback URL:</p><ul id=\"linear-callbacks\" class=\"uris\"></ul>\n <p>Webhook URL:</p><ul id=\"linear-webhooks\" class=\"uris\"></ul>\n <p class=\"muted\">Linear does not expose OAuth application creation through an API. In Settings &rarr; API &rarr; OAuth applications, create one application under the product's own name and icon, add the callback URL above, then save its Client ID, Client secret, and webhook signing secret here.</p>\n <p class=\"muted\">On the same application, enable webhooks, point them at the webhook URL above, and check the <strong>Agent session events</strong> category.</p>\n <p class=\"muted\">Until that category is enabled, agent sessions are disabled for the whole application: delegating an issue only sets the delegate badge and no session is created. Enabling it later raises a new scope, so every already-connected workspace must reconnect before webhooks arrive.</p>\n <div class=\"row\"><a id=\"linear-applications\" class=\"button\" href=\"https://linear.app/settings/api/applications\" target=\"_blank\" rel=\"noopener\">Open Linear OAuth applications</a></div>\n <div id=\"linear-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"linear-id\" autocomplete=\"off\"></label>\n <div id=\"linear-initial-secret-fields\">\n <label class=\"field\">Client secret<input id=\"linear-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n <label class=\"field\">Webhook signing secret<input id=\"linear-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n </div>\n </div>\n <div class=\"row\"><button id=\"save-linear\">Save Linear application</button><button id=\"cancel-linear-configuration\" hidden>Cancel</button><button id=\"clear-linear\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"sso-section\" class=\"panel setup-section\" aria-labelledby=\"sso-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"sso-heading\">Single sign-on</h3><p class=\"muted\">OIDC or SAML identity provider for console sign-in.</p></div>\n <span id=\"sso-match\" class=\"badge\">Not configured</span>\n </div>\n ",
69110
+ "\n </div>\n <button id=\"bootstrap-back\">Back to Logto credentials</button>\n </div>\n </section>\n </section>\n\n <main id=\"setup\" hidden>\n <div class=\"setup-layout\">\n <nav class=\"setup-nav\" aria-label=\"Deployment settings\">\n <a href=\"#startup-section\">Startup</a>\n <a href=\"#logto-section\">Logto</a>\n <a href=\"#sso-section\">Single sign-on</a>\n <a href=\"#github-section\">GitHub</a>\n <a href=\"#gitlab-section\">GitLab</a>\n <a href=\"#gitea-section\">Gitea</a>\n <a href=\"#slack-section\">Slack</a>\n <a href=\"#linear-section\">Linear</a>\n <a href=\"#google-section\">Google</a>\n <a href=\"#telegram-section\">Telegram</a>\n <a href=\"#discord-section\">Discord</a>\n <a href=\"#azuread-section\">Microsoft</a>\n <a href=\"#googlechat-section\">Google Chat</a>\n <a href=\"#email-section\">Email</a>\n <a href=\"#feishu-section\">Feishu</a>\n <a href=\"#lark-section\">Lark</a>\n <a href=\"#mattermost-section\">Mattermost</a>\n <a href=\"#options-section\">Options</a>\n </nav>\n <div class=\"setup-content\">\n <h1>AgentConnect deployment settings</h1>\n <p class=\"muted\">Saved settings take effect after the stack is restarted.</p>\n <div class=\"row\">\n <button id=\"logout\">Log out</button>\n </div>\n <div id=\"message\" aria-live=\"polite\"></div>\n\n <section id=\"editor\" hidden>\n <details id=\"startup-section\" class=\"environment setup-section\" open>\n <summary>Startup environment</summary>\n <p class=\"notice\">Public service URLs come from <code>.env</code>. Provider callbacks below are derived from these values.</p>\n <pre id=\"startup-environment\"></pre>\n </details>\n\n <section id=\"logto-section\" class=\"setup-section\" aria-labelledby=\"logto-heading\">\n <div class=\"section-head\">\n <div><h2 id=\"logto-heading\">Logto</h2><p class=\"muted\">Authentication and administrator access.</p></div>\n <span id=\"logto-match\" class=\"badge\">Not checked</span>\n </div>\n <div class=\"panel\">\n <dl class=\"credentials\">\n <dt>Management endpoint</dt><dd class=\"value-line\"><code id=\"logto-management-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>Management App ID</dt><dd class=\"value-line\"><code id=\"logto-management-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management API resource</dt><dd class=\"value-line\"><code id=\"logto-management-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management App secret</dt><dd class=\"secret-line\"><span id=\"logto-management-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.managementAppSecret\" data-secret-display=\"logto-management-secret-display\">Edit</button></dd>\n <dt>Sign-in endpoint</dt><dd class=\"value-line\"><code id=\"logto-browser-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>SPA App ID</dt><dd class=\"value-line\"><code id=\"logto-browser-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Browser API resource</dt><dd class=\"value-line\"><code id=\"logto-browser-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n </dl>\n <div id=\"logto-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Logto configuration</h3>\n <label class=\"field\">Management App ID<input id=\"logto-edit-management-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-edit-management-resource\" autocomplete=\"off\"></label>\n <label class=\"field\">New Management App secret<input id=\"logto-edit-management-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when management identity changes\"></label>\n <label class=\"field\">SPA App ID<input id=\"logto-edit-browser-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Browser API resource<input id=\"logto-edit-browser-resource\" autocomplete=\"off\" placeholder=\"Optional\"></label>\n <div class=\"row\"><button id=\"save-logto-configuration\">Save configuration</button><button id=\"cancel-logto-configuration\">Cancel</button></div>\n </div>\n <p id=\"logto-status\" class=\"muted\">Checking redirects and sign-in settings…</p>\n <div id=\"logto-drift\" class=\"notice\" hidden></div>\n <div class=\"row\">\n <button id=\"check-logto\">Check match</button>\n <button id=\"reconcile-logto\">Apply expected settings</button>\n <a id=\"logto-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n </div>\n </div>\n </section>\n\n <h2>Providers</h2>\n <div class=\"provider-stack\">\n <section id=\"github-section\" class=\"panel setup-section\" aria-labelledby=\"github-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"github-heading\">GitHub</h3><p class=\"muted\">Repository integration and optional Logto sign-in.</p></div>\n <span id=\"github-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"github-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>App slug</dt><dd class=\"value-line\"><code id=\"github-app-slug\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"github-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Webhook delivery</dt><dd class=\"value-line\"><code id=\"github-webhook-enabled\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"github-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.clientSecret\" data-secret-display=\"github-client-secret-display\">Edit</button></dd>\n <dt>Private key</dt><dd class=\"secret-line\"><span id=\"github-private-key-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.privateKeyB64\" data-secret-display=\"github-private-key-display\">Edit</button></dd>\n <dt>Webhook secret</dt><dd class=\"secret-line\"><span id=\"github-webhook-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.webhookSecret\" data-secret-display=\"github-webhook-secret-display\">Edit</button></dd>\n <dt>Logto connector secret</dt><dd class=\"secret-line\"><span id=\"github-logto-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.githubConnectorClientSecret\" data-secret-display=\"github-logto-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"github-status\" class=\"muted\"></p>\n <div id=\"github-drift\" class=\"notice\" hidden></div>\n <div id=\"github-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit GitHub App identity</h3>\n <label class=\"field\">App ID<input id=\"github-edit-app-id\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n <label class=\"field\">App slug<input id=\"github-edit-slug\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"github-edit-client-id\" autocomplete=\"off\"></label>\n <label><input id=\"github-edit-webhook-enabled\" type=\"checkbox\"> Enable Relay webhook delivery</label>\n <label class=\"field\">New client secret<input id=\"github-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when App or Client ID changes\"></label>\n <label class=\"field\">New private key (base64)<textarea id=\"github-edit-private-key\" autocomplete=\"off\" placeholder=\"Required when App ID changes\"></textarea></label>\n <label class=\"field\">New webhook secret<input id=\"github-edit-webhook-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when an active webhook App ID changes\"></label>\n <label id=\"github-edit-logto-secret-field\" class=\"field\" hidden>New Logto connector client secret<input id=\"github-edit-logto-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when this App is also used for sign-in\"></label>\n <div class=\"row\"><button id=\"save-github-configuration\">Save configuration</button><button id=\"cancel-github-configuration\">Cancel</button></div>\n </div>\n <div id=\"github-create-controls\" class=\"subsection\">\n <label class=\"field\">Owner\n <select id=\"github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"github-org-field\" class=\"field\" hidden>Organization login<input id=\"github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"github-name\" value=\"AgentConnect\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-github\">Create GitHub App</button>\n <button id=\"connect-github-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-github\" hidden>Check match</button>\n <button id=\"clear-github\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"github-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open GitHub settings</a>\n </div>\n </section>\n\n <section id=\"gitlab-section\" class=\"panel setup-section\" aria-labelledby=\"gitlab-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitlab-heading\">GitLab</h3><p class=\"muted\">OAuth application used to administer projects on this deployment's GitLab instance.</p></div>\n <span id=\"gitlab-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitlab-instance\">https://gitlab.com</code></dd>\n <dt>Application ID</dt><dd class=\"value-line\"><code id=\"gitlab-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"gitlab\">Edit</button></dd>\n <dt>Secret</dt><dd class=\"secret-line\"><span id=\"gitlab-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"gitlab.clientSecret\" data-secret-display=\"gitlab-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"gitlab-status\" class=\"muted\"></p>\n <p id=\"gitlab-probe\" class=\"muted\" hidden></p>\n <div id=\"gitlab-drift\" class=\"notice\" hidden></div>\n <p>Redirect URI:</p><ul id=\"gitlab-callbacks\" class=\"uris\"></ul>\n <p>Scopes:</p><ul id=\"gitlab-scopes\" class=\"uris\"></ul>\n <p class=\"muted\">GitLab does not expose OAuth application creation through an API. In User settings &rarr; Applications, or a group's Settings &rarr; Applications, add an application whose redirect URI is exactly the value above, keep Confidential selected, grant the scopes above, then save the generated Application ID and Secret here. GitLab shows the secret only once.</p>\n <p class=\"muted\">Use your own user applications unless you are an instance administrator registering one application for everyone; an instance-wide application lives in the Admin area instead.</p>\n <p class=\"muted\">Creating each agent's bot account later needs authority this page cannot verify — no GitLab API reports it: either connect an instance administrator (whose API token cannot act as one while Admin Mode is enabled), or, on Premium and Ultimate, turn on Admin &rarr; Settings &rarr; General &rarr; Account and limit &rarr; &ldquo;Allow top-level group Owners to create service accounts&rdquo;.</p>\n <div class=\"row\"><a id=\"gitlab-applications\" class=\"button\" href=\"https://gitlab.com/-/user_settings/applications\" target=\"_blank\" rel=\"noopener\">Open GitLab applications</a><a id=\"gitlab-admin-applications\" class=\"button\" href=\"https://gitlab.com/admin/applications\" target=\"_blank\" rel=\"noopener\">Open admin applications</a></div>\n <div id=\"gitlab-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitlab-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitlab.com\"></label>\n <label class=\"field\">Application ID<input id=\"gitlab-id\" autocomplete=\"off\"></label>\n <label id=\"gitlab-initial-secret-field\" class=\"field\">Secret<input id=\"gitlab-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Application ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitlab\">Save GitLab application</button><button id=\"cancel-gitlab-configuration\" hidden>Cancel</button><button id=\"clear-gitlab\" class=\"danger\" hidden>Clear configuration</button></div>\n <div class=\"subsection\">\n <h4>GitLab sign-in</h4>\n <p>Add these redirect URIs and the openid, profile and email scopes to the same confidential OAuth application.</p>\n <ul id=\"gitlab-login-redirects\" class=\"uris\"></ul>\n <p id=\"gitlab-login-status\" class=\"muted\"></p>\n <div class=\"row\"><button id=\"connect-gitlab-login\">Use for Logto sign-in</button><button id=\"disconnect-gitlab-login\" hidden>Disable GitLab sign-in</button><button id=\"check-gitlab-login\" hidden>Check Logto</button></div>\n </div>\n </section>\n\n <section id=\"gitea-section\" class=\"panel setup-section\" aria-labelledby=\"gitea-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitea-heading\">Gitea</h3><p class=\"muted\">The Gitea instance this deployment addresses. Gitea registers no application, so the address is the whole setting.</p></div>\n <span id=\"gitea-match\" class=\"badge\">Default</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitea-instance\">https://gitea.com</code><button class=\"edit-configuration\" data-provider=\"gitea\">Edit</button></dd>\n </dl>\n <p id=\"gitea-status\" class=\"muted\"></p>\n <p id=\"gitea-probe\" class=\"muted\" hidden></p>\n <p class=\"muted\">Each organization connects Gitea by pasting the personal access token of a bot user it created, in the console — nothing about that identity is a deployment setting. Gitea 1.23 or later, or Forgejo 15 or later, is required, and the address is checked against that floor when it is saved.</p>\n <p class=\"muted\">Leave the field empty for gitea.com. A self-hosted instance under a path prefix keeps the prefix. A Forgejo instance, Codeberg included, is entered the same way.</p>\n <div id=\"gitea-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitea-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitea.com\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitea\">Save Gitea instance</button><button id=\"cancel-gitea-configuration\" hidden>Cancel</button><button id=\"clear-gitea\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"slack-section\" class=\"panel setup-section\" aria-labelledby=\"slack-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"slack-heading\">Slack</h3><p class=\"muted\">One App for workspace integration and Logto sign-in.</p></div>\n <span id=\"slack-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"slack-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"slack-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"slack-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.clientSecret\" data-secret-display=\"slack-client-secret-display\">Edit</button></dd>\n <dt>Signing secret</dt><dd class=\"secret-line\"><span id=\"slack-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.signingSecret\" data-secret-display=\"slack-signing-secret-display\">Edit</button></dd>\n <dt>Logto sign-in</dt><dd id=\"slack-logto-status\">Not configured</dd>\n </dl>\n <p id=\"slack-status\" class=\"muted\"></p>\n <div id=\"slack-drift\" class=\"notice\" hidden></div>\n <div id=\"slack-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Slack App identity</h3>\n <label class=\"field\">App ID<input id=\"slack-edit-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"slack-edit-client-id\" autocomplete=\"off\"></label>\n <label class=\"field\">New client secret<input id=\"slack-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <label class=\"field\">New signing secret<input id=\"slack-edit-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <div class=\"row\"><button id=\"save-slack-configuration\">Save configuration</button><button id=\"cancel-slack-configuration\">Cancel</button></div>\n </div>\n <div class=\"subsection\">\n <label id=\"slack-name-field\" class=\"field\">App name<input id=\"slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"slack-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Used only for create, check or update\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-slack\">Create Slack App</button>\n <button id=\"connect-slack-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-slack\" hidden>Check match</button>\n <button id=\"reconcile-slack\" hidden>Apply update</button>\n <button id=\"clear-slack\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"slack-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Slack settings</a>\n </div>\n </section>\n\n <section id=\"linear-section\" class=\"panel setup-section\" aria-labelledby=\"linear-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"linear-heading\">Linear</h3><p class=\"muted\">One OAuth application for the whole deployment. Every workspace connects through it.</p></div>\n <span id=\"linear-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"linear-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"linear\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"linear-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.clientSecret\" data-secret-display=\"linear-client-secret-display\">Edit</button></dd>\n <dt>Webhook signing secret</dt><dd class=\"secret-line\"><span id=\"linear-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.signingSecret\" data-secret-display=\"linear-signing-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"linear-status\" class=\"muted\"></p>\n <div id=\"linear-drift\" class=\"notice\" hidden></div>\n <p>Callback URL:</p><ul id=\"linear-callbacks\" class=\"uris\"></ul>\n <p>Webhook URL:</p><ul id=\"linear-webhooks\" class=\"uris\"></ul>\n <p class=\"muted\">Linear does not expose OAuth application creation through an API. In Settings &rarr; API &rarr; OAuth applications, create one application under the product's own name and icon, add the callback URL above, then save its Client ID, Client secret, and webhook signing secret here.</p>\n <p class=\"muted\">On the same application, enable webhooks, point them at the webhook URL above, and check the <strong>Agent session events</strong> category.</p>\n <p class=\"muted\">Until that category is enabled, agent sessions are disabled for the whole application: delegating an issue only sets the delegate badge and no session is created. Enabling it later raises a new scope, so every already-connected workspace must reconnect before webhooks arrive.</p>\n <div class=\"row\"><a id=\"linear-applications\" class=\"button\" href=\"https://linear.app/settings/api/applications\" target=\"_blank\" rel=\"noopener\">Open Linear OAuth applications</a></div>\n <div id=\"linear-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"linear-id\" autocomplete=\"off\"></label>\n <div id=\"linear-initial-secret-fields\">\n <label class=\"field\">Client secret<input id=\"linear-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n <label class=\"field\">Webhook signing secret<input id=\"linear-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n </div>\n </div>\n <div class=\"row\"><button id=\"save-linear\">Save Linear application</button><button id=\"cancel-linear-configuration\" hidden>Cancel</button><button id=\"clear-linear\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"sso-section\" class=\"panel setup-section\" aria-labelledby=\"sso-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"sso-heading\">Single sign-on</h3><p class=\"muted\">OIDC or SAML identity provider for console sign-in.</p></div>\n <span id=\"sso-match\" class=\"badge\">Not configured</span>\n </div>\n ",
68553
69111
  "\n <div class=\"row\"><button id=\"sso-remove\" class=\"danger\" hidden>Remove SSO sign-in</button></div>\n </section>\n\n <section id=\"google-section\" class=\"panel setup-section\" aria-labelledby=\"google-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"google-heading\">Google</h3><p class=\"muted\">OAuth client used by the Logto Google connector.</p></div>\n <span id=\"google-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"google-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"google\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"google-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.googleConnectorClientSecret\" data-secret-display=\"google-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"google-status\" class=\"muted\"></p>\n <div id=\"google-drift\" class=\"notice\" hidden></div>\n <p>Authorized JavaScript origin:</p><ul id=\"google-origins\" class=\"uris\"></ul>\n <p>Authorized redirect URIs:</p><ul id=\"google-redirects\" class=\"uris\"></ul>\n <p class=\"muted\">Google does not expose OAuth client redirect settings through an API. Copy these required values into Google Auth Platform; Setup can verify only the Logto connector.</p>\n <div class=\"row\"><a class=\"button\" href=\"https://console.cloud.google.com/auth/clients\" target=\"_blank\" rel=\"noopener\">Open Google settings</a></div>\n <div id=\"google-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"google-id\" autocomplete=\"off\"></label>\n <label id=\"google-initial-secret-field\" class=\"field\">Client secret<input id=\"google-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when Client ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-google\">Save Google client</button><button id=\"cancel-google-configuration\" hidden>Cancel</button><button id=\"check-google\" hidden>Check match</button><button id=\"clear-google\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n ",
68554
- "\n\n <section id=\"googlechat-section\" class=\"panel setup-section\" aria-labelledby=\"googlechat-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"googlechat-heading\">Google Chat</h3><p class=\"muted\">One Chat app for the deployment. Each Google Workspace organization connects itself from Google Chat.</p></div>\n <span id=\"googlechat-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Project ID</dt><dd class=\"value-line\"><code id=\"googlechat-project-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Project number</dt><dd class=\"value-line\"><code id=\"googlechat-project-number\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Service-account key</dt><dd class=\"value-line\"><span id=\"googlechat-key-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n </dl>\n <p id=\"googlechat-status\" class=\"muted\"></p>\n <div id=\"googlechat-drift\" class=\"notice\" hidden></div>\n <p>HTTP endpoint URL:</p><ul id=\"googlechat-callbacks\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>Use a Google Workspace account that may create a Cloud project and service-account keys. An organization policy can block key creation.</li>\n <li>Create a Google Cloud project for this app and enable the Google Chat API in it.</li>\n <li>On the Chat API Configuration page, build the app as a Google Workspace add-on, the default for a new app (convert an existing app first). Under Connection settings choose HTTP endpoint URL, use one URL for all triggers, and enter the URL above. Allow 1:1 messages and joining spaces, and choose who can use the app.</li>\n <li>Under Commands, add a slash command named /help with the description \"Show how to use this app\" and command ID 1; any free ID works, since AgentConnect matches the name.</li>\n <li>In the same project, create a service account and a JSON key for it, grant it the Browser role on the project, and enable the Cloud Resource Manager API; AgentConnect reads the project number with that key.</li>\n <li>Save the project ID and key here. The project number is optional: it is on the project's settings page and in the add-on's service account email, service-PROJECT_NUMBER@gcp-sa-gsuiteaddons.iam.gserviceaccount.com. When entered, it must match the number read from the key's project.</li>\n <li>Configure Google sign-in above, then add the app in Google Chat and send it a message. Each Google Workspace organization connects itself from Google Chat by signing in to the console with Google; publish the app on the Google Workspace Marketplace to reach other organizations.</li>\n </ol>\n <div class=\"row\"><a id=\"googlechat-configuration\" class=\"button\" href=\"https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat\" target=\"_blank\" rel=\"noopener\">Open Chat API configuration</a></div>\n <div id=\"googlechat-config-controls\" class=\"subsection\">\n <h3 id=\"googlechat-edit-heading\" hidden>Edit Google Chat App identity</h3>\n <label class=\"field\">Project ID<input id=\"googlechat-project-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">Project number (optional)<input id=\"googlechat-project-number-input\" inputmode=\"numeric\" autocomplete=\"off\" placeholder=\"Read from the key's project\"></label>\n <label class=\"field\">Service-account key JSON<input id=\"googlechat-key\" type=\"password\" autocomplete=\"off\" placeholder=\"Required when the project ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-googlechat\">Save Google Chat app</button><button id=\"cancel-googlechat-configuration\" hidden>Cancel</button><button id=\"clear-googlechat\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"email-section\" class=\"panel setup-section\" aria-labelledby=\"email-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"email-heading\">Email</h3><p class=\"muted\">One mail domain for the deployment. Each agent gets an address on it, received and sent through Cloudflare Email Service.</p></div>\n <span id=\"email-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Mail domain</dt><dd class=\"value-line\"><code id=\"email-mail-domain\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Cloudflare account ID</dt><dd class=\"value-line\"><code id=\"email-account-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>API token</dt><dd class=\"value-line\"><span id=\"email-token-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Ingress secret</dt><dd class=\"value-line\"><span id=\"email-ingress-display\" class=\"muted\">Not configured</span></dd>\n <dt>Daily send limit</dt><dd class=\"value-line\"><code id=\"email-send-limit\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n </dl>\n <p id=\"email-status\" class=\"muted\"></p>\n <div id=\"email-drift\" class=\"notice\" hidden></div>\n <div id=\"email-ingress-once\" class=\"notice\" hidden>\n <p>Ingress secret, shown once. Set it as the Worker's secret now:</p>\n <pre id=\"email-ingress-secret\"></pre>\n <div class=\"row\"><button id=\"copy-email-ingress\">Copy</button><button id=\"dismiss-email-ingress\">Dismiss</button></div>\n </div>\n <p>Inbound URL for the ingress Worker:</p><ul id=\"email-inbound\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>In Cloudflare, onboard a zone used for nothing else as the mail domain, for Email Routing and for Email Sending. A domain that already receives mail elsewhere cannot be used.</li>\n <li>Create an API token with the Email Sending: Edit permission for that account, then save the domain, the account ID and the token here. Setup checks the token with one read of the account's Email Sending suppression list and sends nothing.</li>\n <li>Deploy the ingress Worker with the inbound URL above and the ingress secret shown after the first save, and point the zone's catch-all routing rule at it.</li>\n <li>The daily send limit is the most mail the whole deployment sends in a day. Left empty, only the limits for each address and each organization apply.</li>\n </ol>\n <div class=\"row\"><a id=\"email-dashboard\" class=\"button\" href=\"https://dash.cloudflare.com/\" target=\"_blank\" rel=\"noopener\">Open Cloudflare</a></div>\n <div id=\"email-config-controls\" class=\"subsection\">\n <h3 id=\"email-edit-heading\" hidden>Edit Email configuration</h3>\n <label class=\"field\">Mail domain<input id=\"email-mail-domain-input\" autocomplete=\"off\" placeholder=\"mail.example.com\"></label>\n <label class=\"field\">Cloudflare account ID<input id=\"email-account-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">API token<input id=\"email-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the account ID changes\"></label>\n <label class=\"field\">Daily send limit (optional)<input id=\"email-send-limit-input\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n </div>\n <div class=\"row\"><button id=\"save-email\">Save Email</button><button id=\"cancel-email-configuration\" hidden>Cancel</button><button id=\"rotate-email-ingress\" hidden>Replace ingress secret</button><span id=\"email-rotate-confirm\" hidden>Replace? Mail is refused until the Worker has the new one. <button id=\"confirm-rotate-email-ingress\" class=\"danger\">Replace</button><button id=\"cancel-rotate-email-ingress\">Cancel</button></span><button id=\"clear-email\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n\n <section id=\"feishu-section\" class=\"panel setup-section\" aria-labelledby=\"feishu-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"feishu-heading\">Feishu</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Feishu, OAuth callbacks, and published App setup.</p></div>\n <span id=\"feishu-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"feishu-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"feishu\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"feishu-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"feishu.loginAppSecret\" data-secret-display=\"feishu-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"feishu-login-status\" class=\"muted\"></p>\n <div id=\"feishu-drift\" class=\"notice\" hidden></div>\n <div id=\"feishu-config-controls\" class=\"subsection\">\n <label id=\"feishu-create-name-field\" class=\"field\">New App name<input id=\"feishu-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"feishu-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"feishu-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-feishu-login-app\">Create Feishu App</button>\n <button id=\"save-feishu-login-app\">Save existing App</button>\n <button id=\"cancel-feishu-configuration\" hidden>Cancel</button>\n <button id=\"check-feishu-login-app\" hidden>Check setup</button>\n <button id=\"clear-feishu\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"feishu-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Feishu settings</a>\n </div>\n </section>\n\n <section id=\"lark-section\" class=\"panel setup-section\" aria-labelledby=\"lark-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"lark-heading\">Lark</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Lark, OAuth callbacks, and published App setup.</p></div>\n <span id=\"lark-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"lark-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"lark\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"lark-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"lark.loginAppSecret\" data-secret-display=\"lark-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"lark-login-status\" class=\"muted\"></p>\n <div id=\"lark-drift\" class=\"notice\" hidden></div>\n <div id=\"lark-config-controls\" class=\"subsection\">\n <label id=\"lark-create-name-field\" class=\"field\">New App name<input id=\"lark-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"lark-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"lark-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-lark-login-app\">Create Lark App</button>\n <button id=\"save-lark-login-app\">Save existing App</button>\n <button id=\"cancel-lark-configuration\" hidden>Cancel</button>\n <button id=\"check-lark-login-app\" hidden>Check setup</button>\n <button id=\"clear-lark\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"lark-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Lark settings</a>\n </div>\n </section>\n </div>\n\n <section id=\"options-section\" class=\"setup-section\">\n <h2>Deployment options</h2>\n <div class=\"panel\">\n <label class=\"field\"><span><input id=\"preset-agents-enabled\" type=\"checkbox\"> Enable preset Agents</span></label>\n <label class=\"field\">Max organizations created per non-ADMIN user<input id=\"max-orgs-per-non-admin-user\" type=\"number\" min=\"0\" step=\"1\" value=\"1\"></label>\n <label class=\"field\"><span><input id=\"organization-sso\" type=\"checkbox\"> Let organizations set up their own SSO</span></label>\n <div class=\"row\"><button id=\"save-options\">Save options</button></div>\n </div>\n </section>\n </section>\n </div>\n </div>\n </main>\n\n <script>\n const api = '/api/v1';\n const tokenKey = 'agentconnect.setup.token';\n const verifierKey = 'agentconnect.setup.pkce';\n const stateKey = 'agentconnect.setup.state';\n let currentRevision = 0;\n let currentStatus = null;\n let bootstrapInfo = null;\n const el = (id) => document.getElementById(id);\n const message = (text, error = false) => {\n const target = el('setup').hidden ? el('access-message') : el('message');\n target.textContent = text;\n target.className = error ? 'error' : 'ok';\n };\n const bearer = () => {\n const token = sessionStorage.getItem(tokenKey);\n return token ? { authorization: 'Bearer ' + token } : {};\n };\n const json = async (response) => {\n const body = await response.json().catch(() => ({}));\n if (!response.ok) throw Object.assign(new Error(body.message || ('HTTP ' + response.status)), { status: response.status, code: body.code });\n return body;\n };\n const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');\n const random = () => base64url(crypto.getRandomValues(new Uint8Array(32)));\n const configured = (byKey, key) => Boolean(byKey.get(key) && byKey.get(key).configured);\n const loginApps = ",
68555
- ";\n\n function showIdentityEditors(provider, show) {\n for (const button of document.querySelectorAll('.edit-configuration[data-provider=\"' + provider + '\"]')) {\n button.hidden = !show;\n }\n }\n\n function text(id, value) {\n el(id).textContent = value === null || value === undefined || value === '' ? 'Not configured' : String(value);\n }\n\n function secretText(id, byKey, key, editable) {\n const stored = configured(byKey, key);\n const display = el(id);\n const button = document.querySelector('[data-secret-display=\"' + id + '\"]');\n const row = display.closest('.secret-line');\n const editor = row && row.querySelector('.secret-editor');\n if (editor) editor.remove();\n display.hidden = false;\n display.textContent = stored ? '***' : 'Not configured';\n display.className = stored ? 'redacted' : 'muted';\n button.hidden = !editable;\n button.textContent = stored ? 'Edit' : 'Set';\n }\n\n function match(id, state, label) {\n const target = el(id);\n target.textContent = label;\n target.className = 'badge' + (state ? ' ' + state : '');\n }\n\n async function authConfig() { return json(await fetch(api + '/auth-config')); }\n\n async function signIn() {\n const config = await authConfig();\n if (config.mode !== 'oidc') throw new Error('Save an OIDC configuration first');\n const verifier = random();\n const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));\n const state = random();\n sessionStorage.setItem(verifierKey, verifier);\n sessionStorage.setItem(stateKey, state);\n const url = new URL(config.authorizationEndpoint);\n url.searchParams.set('client_id', config.appId);\n url.searchParams.set('redirect_uri', config.redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', 'openid profile email roles');\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n if (config.resource) url.searchParams.set('resource', config.resource);\n if (config.ssoConnectorId) url.searchParams.set('direct_sign_in', 'sso:' + config.ssoConnectorId);\n location.assign(url);\n }\n\n async function finishSignIn() {\n const url = new URL(location.href);\n const code = url.searchParams.get('code');\n if (!code) return;\n const state = url.searchParams.get('state');\n if (!state || state !== sessionStorage.getItem(stateKey)) throw new Error('OIDC state mismatch');\n const verifier = sessionStorage.getItem(verifierKey);\n if (!verifier) throw new Error('PKCE verifier is missing; start sign-in again');\n const config = await authConfig();\n const body = new URLSearchParams({\n grant_type: 'authorization_code', code, client_id: config.appId,\n redirect_uri: config.redirectUri, code_verifier: verifier\n });\n if (config.resource) body.set('resource', config.resource);\n const tokens = await json(await fetch(config.tokenEndpoint, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body\n }));\n if (typeof tokens.id_token !== 'string') throw new Error('Logto did not return an ID token');\n sessionStorage.setItem(tokenKey, tokens.id_token);\n sessionStorage.removeItem(verifierKey);\n sessionStorage.removeItem(stateKey);\n history.replaceState({}, '', '/');\n }\n\n function renderUriList(id, values) {\n el(id).replaceChildren(...(values || []).map((value) => {\n const item = document.createElement('li');\n const code = document.createElement('code'); code.textContent = value;\n item.append(code); return item;\n }));\n }\n\n function updateBootstrapProvider() {\n const provider = el('bootstrap-provider').value;\n el('bootstrap-google').hidden = provider !== 'google';\n el('bootstrap-github').hidden = provider !== 'github';\n el('bootstrap-slack').hidden = provider !== 'slack';\n el('bootstrap-sso').hidden = provider !== 'sso';\n }\n\n // The SSO connector each form shows: the saved one in settings, the one just created during first-run setup.\n const ssoState = {};\n\n function ssoUrls(connector) {\n const base = ((bootstrapInfo && bootstrapInfo.logtoEndpoint) || '').replace(//+$/, '');\n const id = encodeURIComponent(connector.connectorId);\n return connector.protocol === 'oidc'\n ? ['Redirect URI: ' + base + '/callback/' + id]\n : ['ACS URL: ' + base + '/api/authn/single-sign-on/saml/' + id, 'SP entity ID: ' + base + '/enterprise-sso/' + id];\n }\n\n function renderSso(prefix, connector) {\n ssoState[prefix] = connector || undefined;\n if (connector) {\n el(prefix + '-protocol').value = connector.protocol;\n el(prefix + '-name').value = connector.name;\n el(prefix + '-domains').value = (connector.domains || []).join(', ');\n el(prefix + '-member-source').value = connector.memberSource || 'domain';\n renderMemberOrganizations(prefix, connector.memberOrganization || '');\n renderUriList(prefix + '-urls', ssoUrls(connector));\n const oidc = connector.oidc || {};\n el(prefix + '-issuer').value = oidc.issuer || '';\n el(prefix + '-client-id').value = oidc.clientId || '';\n el(prefix + '-scope').value = oidc.scope || '';\n el(prefix + '-trust-email').checked = connector.oidc ? oidc.trustUnverifiedEmail : true;\n const saml = connector.saml || {};\n el(prefix + '-metadata-url').value = saml.metadataUrl || '';\n el(prefix + '-metadata').value = saml.metadata || '';\n el(prefix + '-email-attribute').value = (saml.attributeMapping && saml.attributeMapping.email) || '';\n }\n updateSsoProtocol(prefix);\n }\n\n // The organizations new members may join; the empty value is the deployment's only one, and a saved id that is gone stays visible.\n let ssoOrganizations = [];\n function renderMemberOrganizations(prefix, selected) {\n const select = el(prefix + '-member-organization');\n select.replaceChildren();\n const option = (value, label) => {\n const item = document.createElement('option');\n item.value = value;\n item.textContent = label;\n select.append(item);\n };\n option('', 'The only organization');\n for (const org of ssoOrganizations) option(org.id, (org.name || org.slug) + ' (' + org.slug + ')');\n if (selected && !ssoOrganizations.some((org) => org.id === selected)) option(selected, 'Missing organization (' + selected + ')');\n select.value = selected;\n updateMemberOrganization(prefix);\n }\n\n function updateMemberOrganization(prefix) {\n el(prefix + '-member-organization').disabled = el(prefix + '-member-source').value === 'invite';\n }\n\n function updateSsoProtocol(prefix) {\n const connector = ssoState[prefix];\n const protocol = el(prefix + '-protocol').value;\n const current = Boolean(connector && connector.protocol === protocol);\n el(prefix + '-oidc').hidden = protocol !== 'oidc';\n el(prefix + '-saml').hidden = protocol !== 'saml';\n // Another protocol is another connector, so its details wait until it is created.\n el(prefix + '-details').hidden = !current;\n el(prefix + '-create').hidden = current;\n }\n\n async function createSso(prefix) {\n const name = el(prefix + '-name').value;\n const result = await json(await fetch(api + '/create/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ protocol: el(prefix + '-protocol').value, name })\n }));\n renderSso(prefix, { connectorId: result.connectorId, protocol: result.protocol, name, domains: [], memberSource: 'domain', oidc: null, saml: null });\n message('SSO connector created. Register its URLs with the identity provider, then enter the provider details.');\n }\n\n async function saveSso(prefix) {\n const protocol = el(prefix + '-protocol').value;\n const secret = el(prefix + '-client-secret').value;\n const metadataUrl = el(prefix + '-metadata-url').value.trim();\n const metadata = el(prefix + '-metadata').value.trim();\n const emailAttribute = el(prefix + '-email-attribute').value.trim();\n const connector = {\n name: el(prefix + '-name').value,\n domains: el(prefix + '-domains').value.split(',').map((domain) => domain.trim()).filter(Boolean),\n memberSource: el(prefix + '-member-source').value,\n memberOrganization: el(prefix + '-member-organization').value || null,\n ...(protocol === 'oidc'\n ? { oidc: {\n issuer: el(prefix + '-issuer').value.trim(),\n clientId: el(prefix + '-client-id').value.trim(),\n ...(secret ? { clientSecret: secret } : {}),\n scope: el(prefix + '-scope').value.trim(),\n trustUnverifiedEmail: el(prefix + '-trust-email').checked\n } }\n : { saml: {\n ...(metadataUrl ? { metadataUrl } : {}),\n ...(metadata ? { metadata } : {}),\n ...(emailAttribute ? { attributeMapping: { email: emailAttribute } } : {})\n } })\n };\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector })\n }));\n el(prefix + '-client-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n }\n\n async function removeSso() {\n if (!window.confirm('Remove SSO sign-in and delete its Logto connector? People who signed in through it lose that sign-in; their accounts stay.')) return;\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector: null })\n }));\n await reconcileLogto();\n await load();\n }\n\n function showBootstrapStep(step) {\n const logto = step === 'logto';\n el('bootstrap-logto-step').hidden = !logto;\n el('bootstrap-provider-step').hidden = logto;\n el('bootstrap-progress').textContent = logto ? 'Step 1 of 2' : 'Step 2 of 2';\n }\n\n function updateOwner(prefix) {\n el(prefix + '-org-field').hidden = el(prefix + '-owner').value !== 'organization';\n }\n\n function ownership(prefix) {\n if (el(prefix + '-owner').value === 'personal') return { owner: 'personal', organization: null };\n const organization = el(prefix + '-org').value.trim();\n if (!organization) throw new Error('Enter the GitHub organization login');\n return { owner: 'organization', organization };\n }\n\n function formatDiffValue(value) {\n if (value === null || value === undefined || value === '') return 'Not configured';\n if (Array.isArray(value)) return value.length ? value.map(formatDiffValue).join('\n') : '[]';\n if (typeof value === 'object') {\n return Object.entries(value).map(([key, item]) => key + ': ' + (Array.isArray(item) ? item.join(', ') : formatDiffValue(item))).join('\n');\n }\n return String(value);\n }\n\n function showDiff(id, rows, label = 'Update required') {\n const box = el(id);\n box.hidden = rows.length === 0;\n box.replaceChildren();\n if (rows.length === 0) return;\n const title = document.createElement('strong');\n title.className = 'diff-title';\n title.textContent = label;\n const grid = document.createElement('div');\n grid.className = 'config-diff';\n const head = document.createElement('div');\n head.className = 'diff-row diff-head';\n for (const text of ['Field', 'Current', 'Expected']) {\n const cell = document.createElement('span'); cell.textContent = text; head.append(cell);\n }\n grid.append(head);\n for (const item of rows) {\n const row = document.createElement('div'); row.className = 'diff-row';\n const field = document.createElement('span'); field.className = 'diff-field'; field.textContent = item.field;\n const current = document.createElement('span'); current.className = 'diff-value diff-current'; current.textContent = formatDiffValue(item.current);\n const expected = document.createElement('span'); expected.className = 'diff-value diff-expected'; expected.textContent = formatDiffValue(item.expected);\n row.append(field, current, expected); grid.append(row);\n }\n box.append(title, grid);\n }\n\n function renderStartupEnvironment() {\n const services = bootstrapInfo.services;\n const environment = [\n ['AGENTCONNECT_PUBLIC_CP_URL', services.controlPlane],\n ['AGENTCONNECT_PUBLIC_RELAY_URL', services.relay],\n ['AGENTCONNECT_PUBLIC_WEB_URL', services.web],\n ['LOGTO_ENDPOINT', bootstrapInfo.logtoEndpoint],\n ['LOGTO_MGMT_ENDPOINT', bootstrapInfo.logtoManagementEndpoint]\n ];\n el('startup-environment').textContent = environment\n .filter(([, value]) => value)\n .map(([key, value]) => key + '=' + value)\n .join('\n');\n }\n\n function renderApps(status) {\n currentStatus = status;\n const byKey = new Map((status.secrets || []).map((item) => [item.key, item]));\n const values = status.values;\n const expected = status.providerExpectations || { github: null, gitlab: null, slack: null, linear: null, googleChat: null, google: { origins: [], redirects: [] } };\n renderStartupEnvironment();\n\n const logto = values.logto;\n text('logto-management-endpoint', logto && bootstrapInfo.logtoManagementEndpoint);\n text('logto-management-id', logto && logto.managementAppId);\n text('logto-management-resource', logto && logto.managementResource);\n secretText('logto-management-secret-display', byKey, 'logto.managementAppSecret', Boolean(logto));\n const sso = logto && logto.ssoConnector;\n ssoOrganizations = status.organizations || [];\n renderSso('sso', sso);\n el('sso-remove').hidden = !sso;\n match('sso-match', !sso ? '' : sso.oidc || sso.saml ? 'pass' : 'warn', !sso ? 'Not configured' : sso.oidc || sso.saml ? 'Configured' : 'Needs identity provider');\n text('logto-browser-endpoint', logto && logto.browser && bootstrapInfo.logtoEndpoint);\n text('logto-browser-id', values.auth.mode === 'oidc' ? values.auth.browserClient.appId : null);\n text('logto-browser-resource', logto && logto.browser && logto.browser.apiResource);\n el('logto-edit-controls').hidden = true;\n showIdentityEditors('logto', Boolean(logto && logto.browser && values.auth.mode === 'oidc'));\n match(\n 'logto-match',\n logto && configured(byKey, 'logto.managementAppSecret') ? '' : 'warn',\n logto && configured(byKey, 'logto.managementAppSecret') ? 'Ready to check' : 'Not configured'\n );\n\n el('preset-agents-enabled').checked = values.features.presetAgentsEnabled;\n el('max-orgs-per-non-admin-user').value = String(values.features.maxOrgsPerNonAdminUser);\n el('organization-sso').checked = values.features.organizationSso === true;\n\n const github = values.github;\n const webhookStored = byKey.get('github.webhookSecret') && byKey.get('github.webhookSecret').configured;\n const webhookInactive = github && github.webhookEnabled === false;\n text('github-app-id', github && github.appId);\n text('github-app-slug', github && github.slug);\n text('github-client-id', github && github.clientId);\n text('github-webhook-enabled', github && (github.webhookEnabled === false ? 'Disabled' : 'Enabled'));\n el('github-edit-controls').hidden = true;\n showIdentityEditors('github', Boolean(github));\n secretText('github-client-secret-display', byKey, 'github.clientSecret', Boolean(github));\n secretText('github-private-key-display', byKey, 'github.privateKeyB64', Boolean(github));\n secretText('github-webhook-secret-display', byKey, 'github.webhookSecret', Boolean(github));\n secretText('github-logto-secret-display', byKey, 'logto.githubConnectorClientSecret', Boolean(values.logto && values.logto.githubConnector));\n el('github-status').textContent = github\n ? github.slug + ' is configured. Webhook secret: ' + (webhookStored ? 'stored' : webhookInactive ? 'not required yet' : 'missing') + '.' +\n (webhookInactive ? ' Relay webhook delivery is disabled.' : '')\n : 'Creates the complete App used for repository installation, webhooks, and optional GitHub sign-in.';\n const githubDrift = github\n ? expected.github\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'Valid Web, API, and ingress URLs' }]\n : [];\n match('github-match', !github ? '' : githubDrift.length ? 'warn' : '', !github ? 'Not configured' : githubDrift.length ? 'Expected URLs changed' : 'Ready to check');\n el('github-create-controls').hidden = Boolean(github);\n el('create-github').hidden = Boolean(github);\n el('clear-github').hidden = !github;\n el('connect-github-login').hidden = !github || !values.logto || Boolean(values.logto.githubConnector);\n el('check-github').hidden = !github;\n if (github) showDiff('github-drift', githubDrift, 'Expected URLs changed since App creation');\n else el('github-drift').hidden = true;\n\n const gitlab = values.gitlab;\n const gitlabSecret = configured(byKey, 'gitlab.clientSecret');\n const expectedGitlab = expected.gitlab;\n renderUriList('gitlab-callbacks', expectedGitlab ? [expectedGitlab.callbackUrl] : []);\n renderUriList('gitlab-scopes', expectedGitlab ? expectedGitlab.scopes : []);\n text('gitlab-client-id', gitlab && gitlab.clientId);\n secretText('gitlab-client-secret-display', byKey, 'gitlab.clientSecret', Boolean(gitlab));\n showIdentityEditors('gitlab', Boolean(gitlab));\n el('gitlab-id').value = gitlab ? gitlab.clientId : '';\n text('gitlab-instance', (gitlab && gitlab.baseUrl) || 'https://gitlab.com');\n // Host-aware application links (§24.1): composed by the server against the\n // configured base, so a path-prefixed install keeps its prefix here too.\n if (expectedGitlab) {\n el('gitlab-applications').href = expectedGitlab.applicationsUrl;\n el('gitlab-admin-applications').href = expectedGitlab.adminApplicationsUrl;\n }\n el('gitlab-base-url').value = (gitlab && gitlab.baseUrl) || '';\n el('gitlab-status').textContent = gitlab\n ? gitlab.clientId + ' is configured.'\n : expectedGitlab\n ? 'Register the OAuth application on the configured GitLab instance, then save its Application ID and Secret here.'\n : 'Publishing the redirect URI needs an HTTPS API public URL.';\n showDiff('gitlab-drift', gitlab && !expectedGitlab\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS API URL' }]\n : []);\n match('gitlab-match', gitlab && gitlabSecret ? 'warn' : '', !gitlab ? 'Not configured' : !gitlabSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('gitlab-initial-secret-field').hidden = Boolean(gitlab) && gitlabSecret;\n el('gitlab-config-controls').hidden = Boolean(gitlab);\n el('save-gitlab').hidden = Boolean(gitlab);\n el('cancel-gitlab-configuration').hidden = true;\n el('clear-gitlab').hidden = !gitlab;\n const gitlabLogin = values.logto?.browser?.socialProviders.includes('gitlab');\n renderUriList('gitlab-login-redirects', expected.gitlabSignIn?.redirects || []);\n el('gitlab-login-status').textContent = gitlabLogin ? 'GitLab sign-in is configured. Use Check Logto to verify it.' : 'GitLab sign-in is not enabled.';\n el('connect-gitlab-login').hidden = Boolean(gitlabLogin);\n el('connect-gitlab-login').disabled = !gitlab || !gitlabSecret || !values.logto?.browser;\n el('disconnect-gitlab-login').hidden = !gitlabLogin;\n el('check-gitlab-login').hidden = !gitlabLogin;\n\n const gitea = values.gitea;\n text('gitea-instance', (gitea && gitea.baseUrl) || 'https://gitea.com');\n el('gitea-base-url').value = (gitea && gitea.baseUrl) || '';\n showIdentityEditors('gitea', Boolean(gitea));\n el('gitea-status').textContent = gitea\n ? ((gitea.baseUrl || 'https://gitea.com') + ' is configured.')\n : 'Organizations can connect gitea.com without saving anything. Save an address only for a self-hosted instance.';\n match('gitea-match', gitea ? 'warn' : '', gitea ? \"Can't verify automatically\" : 'Default');\n el('gitea-config-controls').hidden = Boolean(gitea);\n el('save-gitea').hidden = Boolean(gitea);\n el('cancel-gitea-configuration').hidden = true;\n el('clear-gitea').hidden = !gitea;\n\n const slack = values.slack;\n text('slack-app-id', slack && slack.appId);\n text('slack-client-id', slack && slack.clientId);\n el('slack-edit-controls').hidden = true;\n showIdentityEditors('slack', Boolean(slack));\n secretText('slack-client-secret-display', byKey, 'slack.clientSecret', Boolean(slack));\n secretText('slack-signing-secret-display', byKey, 'slack.signingSecret', Boolean(slack));\n el('slack-logto-status').textContent = values.logto && values.logto.slackConnector\n ? 'Enabled; reuses the Slack client secret above.'\n : 'Not enabled.';\n el('slack-status').textContent = slack ? slack.appId + ' is configured.' : 'Creates the default AgentConnect integration manifest.';\n const slackDrift = slack\n ? expected.slack\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS Web, API, and ingress URLs' }]\n : [];\n match('slack-match', !slack ? '' : slackDrift.length ? 'warn' : '', !slack ? 'Not configured' : slackDrift.length ? 'Update required' : 'Ready to check');\n el('slack-name-field').hidden = Boolean(slack);\n el('create-slack').hidden = Boolean(slack);\n el('connect-slack-login').hidden = !slack || !values.logto || Boolean(values.logto.slackConnector) || !bootstrapInfo?.slackAvailable;\n el('clear-slack').hidden = !slack;\n el('check-slack').hidden = !slack;\n el('reconcile-slack').hidden = !slack;\n el('slack-settings').hidden = !slack;\n if (slack) {\n el('slack-settings').href = 'https://api.slack.com/apps/' + encodeURIComponent(slack.appId);\n showDiff('slack-drift', slackDrift);\n } else el('slack-drift').hidden = true;\n\n const googleChat = values.googleChat;\n const googleChatKey = configured(byKey, 'googleChat.serviceAccountKey');\n const expectedGoogleChat = expected.googleChat;\n renderUriList('googlechat-callbacks', expectedGoogleChat ? [expectedGoogleChat.callbackUrl] : []);\n text('googlechat-project-id', googleChat && googleChat.projectId);\n text('googlechat-project-number', googleChat && googleChat.projectNumber);\n el('googlechat-key-display').textContent = googleChatKey ? '***' : 'Not configured';\n el('googlechat-key-display').className = googleChatKey ? 'redacted' : 'muted';\n showIdentityEditors('googlechat', Boolean(googleChat));\n el('googlechat-project-id-input').value = googleChat ? googleChat.projectId : '';\n el('googlechat-project-number-input').value = googleChat ? googleChat.projectNumber : '';\n el('googlechat-key').value = '';\n if (expectedGoogleChat) el('googlechat-configuration').href = expectedGoogleChat.configurationUrl;\n el('googlechat-status').textContent = googleChat\n ? googleChat.projectId + ' is configured.'\n : expectedGoogleChat\n ? 'Configure the Chat app in Google Cloud Console, then save its project and service-account key here.'\n : 'Publishing the HTTP endpoint URL needs an HTTPS ingress public URL.';\n showDiff('googlechat-drift', googleChat && !expectedGoogleChat\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n match('googlechat-match', googleChat && googleChatKey ? 'pass' : googleChat ? 'warn' : '', !googleChat ? 'Not configured' : !googleChatKey ? 'Missing key' : 'Checked on save');\n el('googlechat-edit-heading').hidden = true;\n el('googlechat-config-controls').hidden = Boolean(googleChat);\n el('save-googlechat').hidden = Boolean(googleChat);\n el('cancel-googlechat-configuration').hidden = true;\n el('clear-googlechat').hidden = !googleChat;\n\n const email = values.email;\n const emailToken = configured(byKey, 'email.apiToken');\n const emailIngress = configured(byKey, 'email.ingressSecret');\n const expectedEmail = expected.email;\n renderUriList('email-inbound', expectedEmail ? [expectedEmail.inboundUrl] : []);\n text('email-mail-domain', email && email.mailDomain);\n text('email-account-id', email && email.accountId);\n text('email-send-limit', email && (email.dailySendLimit ? email.dailySendLimit : 'No deployment-wide limit'));\n for (const [id, stored] of [['email-token-display', emailToken], ['email-ingress-display', emailIngress]]) {\n el(id).textContent = stored ? '***' : 'Not configured';\n el(id).className = stored ? 'redacted' : 'muted';\n }\n showIdentityEditors('email', Boolean(email));\n el('email-mail-domain-input').value = email ? email.mailDomain : '';\n el('email-account-id-input').value = email ? email.accountId : '';\n el('email-send-limit-input').value = email && email.dailySendLimit ? String(email.dailySendLimit) : '';\n el('email-token').value = '';\n if (expectedEmail) el('email-dashboard').href = expectedEmail.dashboardUrl;\n el('email-status').textContent = email\n ? 'Agents get addresses on ' + email.mailDomain + '.'\n : expectedEmail\n ? 'Onboard the mail domain in Cloudflare, then save it with the account ID and an API token here.'\n : 'Publishing the inbound URL needs an HTTPS ingress public URL.';\n showDiff('email-drift', email && !expectedEmail\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n const emailReady = email && emailToken && emailIngress;\n match('email-match', emailReady ? 'pass' : email ? 'warn' : '', !email ? 'Not configured' : !emailReady ? 'Missing secret' : 'Checked on save');\n el('email-edit-heading').hidden = true;\n el('email-config-controls').hidden = Boolean(email);\n el('save-email').hidden = Boolean(email);\n el('cancel-email-configuration').hidden = true;\n // A status render never touches the secret box or a pending Replace: they belong to the operator's own clicks.\n if (!email) el('email-rotate-confirm').hidden = true;\n el('rotate-email-ingress').hidden = !email || !el('email-rotate-confirm').hidden;\n el('clear-email').hidden = !email;\n\n\n const linear = values.linear;\n const linearSecrets = configured(byKey, 'linear.clientSecret') && configured(byKey, 'linear.signingSecret');\n const expectedLinear = expected.linear;\n renderUriList('linear-callbacks', expectedLinear ? [expectedLinear.callbackUrl] : []);\n renderUriList('linear-webhooks', expectedLinear ? [expectedLinear.webhookUrl] : []);\n text('linear-client-id', linear && linear.clientId);\n secretText('linear-client-secret-display', byKey, 'linear.clientSecret', Boolean(linear));\n secretText('linear-signing-secret-display', byKey, 'linear.signingSecret', Boolean(linear));\n showIdentityEditors('linear', Boolean(linear));\n el('linear-id').value = linear ? linear.clientId : '';\n if (expectedLinear) el('linear-applications').href = expectedLinear.applicationsUrl;\n el('linear-status').textContent = linear\n ? linear.clientId + ' is configured.'\n : expectedLinear\n ? 'Register the OAuth application in Linear, then save its Client ID and both secrets here.'\n : 'Publishing the callback and webhook URLs needs HTTPS API and ingress public URLs.';\n showDiff('linear-drift', linear && !expectedLinear\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS API and ingress URLs' }]\n : []);\n match('linear-match', linear && linearSecrets ? 'warn' : '', !linear ? 'Not configured' : !linearSecrets ? 'Missing secret' : \"Can't verify automatically\");\n el('linear-initial-secret-fields').hidden = Boolean(linear) && linearSecrets;\n el('linear-config-controls').hidden = Boolean(linear);\n el('save-linear').hidden = Boolean(linear);\n el('cancel-linear-configuration').hidden = true;\n el('clear-linear').hidden = !linear;\n\n const google = values.logto && values.logto.googleConnector;\n const googleSecret = configured(byKey, 'logto.googleConnectorClientSecret');\n const expectedGoogle = expected.google;\n renderUriList('google-origins', expectedGoogle.origins);\n renderUriList('google-redirects', expectedGoogle.redirects);\n text('google-client-id', google && google.clientId);\n secretText('google-client-secret-display', byKey, 'logto.googleConnectorClientSecret', Boolean(google));\n showIdentityEditors('google', Boolean(google));\n el('google-id').value = google ? google.clientId : '';\n el('google-status').textContent = google ? 'Google OAuth client is configured.' : 'Create a Web application OAuth client manually, then save it here.';\n showDiff('google-drift', []);\n match('google-match', google && googleSecret ? 'warn' : '', !google ? 'Not configured' : !googleSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('google-initial-secret-field').hidden = googleSecret;\n el('save-google').textContent = google ? 'Confirm callback settings' : 'Save Google client';\n el('google-config-controls').hidden = Boolean(google);\n el('save-google').hidden = Boolean(google);\n el('cancel-google-configuration').hidden = true;\n el('check-google').hidden = !google || !googleSecret;\n el('clear-google').hidden = !google;\n\n for (const [provider, app] of Object.entries(loginApps)) {\n const saved = values.logto && values.logto[provider + 'Connector'];\n const secretKey = 'logto.' + provider + 'ConnectorClientSecret';\n const hasSecret = configured(byKey, secretKey);\n renderUriList(provider + '-redirects', expected[provider].redirects);\n text(provider + '-client-id', saved && saved.clientId);\n secretText(provider + '-client-secret-display', byKey, secretKey, Boolean(saved));\n showIdentityEditors(provider, Boolean(saved));\n el(provider + '-id').value = saved ? saved.clientId : '';\n el(provider + '-status').hidden = !saved;\n el(provider + '-status').textContent = saved ? app.name + ' login application is saved.' : '';\n showDiff(provider + '-drift', []);\n match(provider + '-match', saved ? 'warn' : '', !saved ? 'Not configured' : !hasSecret ? 'Missing secret' : 'Not checked');\n el(provider + '-initial-secret-field').hidden = hasSecret;\n el(provider + '-config-controls').hidden = Boolean(saved);\n el('save-' + provider).hidden = Boolean(saved);\n el('save-' + provider).disabled = !values.logto || !values.logto.browser;\n el('cancel-' + provider + '-configuration').hidden = true;\n el('check-' + provider).hidden = !saved || !hasSecret;\n el('clear-' + provider).hidden = !saved;\n }\n const expectedTeams = expected.msTeams;\n text('azuread-teams-tenant-id', values.msTeams && values.msTeams.tenantId);\n el('azuread-teams-tenant-input').value = values.msTeams ? values.msTeams.tenantId : '';\n renderUriList('azuread-teams-endpoint', expectedTeams ? [expectedTeams.messagingEndpoint] : []);\n renderUriList('azuread-teams-redirects', expectedTeams ? [expectedTeams.connectRedirectUri] : []);\n // Agent bots sit beside the Teams app: the group shows once it is configured, and its form until a blueprint is saved.\n const agentBots = values.msTeams && values.msTeams.agentBots;\n const blueprintSecret = configured(byKey, 'msTeams.blueprintClientSecret');\n el('azuread-agent-bots').hidden = !values.msTeams;\n text('azuread-agent-bots-blueprint', agentBots && agentBots.blueprintId);\n el('azuread-agent-bots-secret').textContent = blueprintSecret ? '***' : 'Not configured';\n el('azuread-agent-bots-secret').className = blueprintSecret ? 'redacted' : 'muted';\n text('azuread-agent-bots-subscription', agentBots && agentBots.subscriptionId);\n text('azuread-agent-bots-group', agentBots && agentBots.resourceGroup);\n el('azuread-agent-bots-controls').hidden = Boolean(agentBots);\n el('clear-azuread-agent-bots').hidden = !agentBots;\n renderUriList('azuread-azure-devops-redirects', expected.azureDevOps ? [expected.azureDevOps.connectRedirectUri] : []);\n\n const feishuSecret = byKey.get('feishu.loginAppSecret');\n const larkSecret = byKey.get('lark.loginAppSecret');\n el('feishu-login-id').value = values.feishu ? values.feishu.loginAppId : '';\n el('lark-login-id').value = values.lark ? values.lark.loginAppId : '';\n text('feishu-app-id', values.feishu && values.feishu.loginAppId);\n text('lark-app-id', values.lark && values.lark.loginAppId);\n showIdentityEditors('feishu', Boolean(values.feishu));\n showIdentityEditors('lark', Boolean(values.lark));\n secretText('feishu-app-secret-display', byKey, 'feishu.loginAppSecret', Boolean(values.feishu));\n secretText('lark-app-secret-display', byKey, 'lark.loginAppSecret', Boolean(values.lark));\n el('feishu-login-status').textContent = values.feishu && feishuSecret && feishuSecret.configured\n ? values.feishu.loginAppId + ' is configured.'\n : 'No Feishu tenant App is configured.';\n el('lark-login-status').textContent = values.lark && larkSecret && larkSecret.configured\n ? values.lark.loginAppId + ' is configured.'\n : 'No Lark tenant App is configured.';\n match('feishu-match', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? '' : '', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? 'Ready to check' : 'Not configured');\n match('lark-match', values.lark && configured(byKey, 'lark.loginAppSecret') ? '' : '', values.lark && configured(byKey, 'lark.loginAppSecret') ? 'Ready to check' : 'Not configured');\n showDiff('feishu-drift', []);\n showDiff('lark-drift', []);\n el('feishu-config-controls').hidden = Boolean(values.feishu);\n el('lark-config-controls').hidden = Boolean(values.lark);\n el('feishu-create-name-field').hidden = Boolean(values.feishu);\n el('lark-create-name-field').hidden = Boolean(values.lark);\n el('create-feishu-login-app').hidden = Boolean(values.feishu);\n el('create-lark-login-app').hidden = Boolean(values.lark);\n el('save-feishu-login-app').hidden = Boolean(values.feishu);\n el('save-lark-login-app').hidden = Boolean(values.lark);\n el('cancel-feishu-configuration').hidden = true;\n el('cancel-lark-configuration').hidden = true;\n el('clear-feishu').hidden = !values.feishu;\n el('clear-lark').hidden = !values.lark;\n el('check-feishu-login-app').hidden = !values.feishu || !configured(byKey, 'feishu.loginAppSecret');\n el('check-lark-login-app').hidden = !values.lark || !configured(byKey, 'lark.loginAppSecret');\n el('feishu-settings').hidden = !values.feishu;\n el('lark-settings').hidden = !values.lark;\n if (values.feishu) el('feishu-settings').href = 'https://open.feishu.cn/app/' + encodeURIComponent(values.feishu.loginAppId);\n if (values.lark) el('lark-settings').href = 'https://open.larksuite.com/app/' + encodeURIComponent(values.lark.loginAppId);\n }\n\n function requiredInput(id, label) {\n const value = el(id).value.trim();\n if (!value) throw new Error('Enter ' + label);\n return value;\n }\n\n function githubConnectorUsesDeployment(values) {\n const github = values.github;\n const connector = values.logto && values.logto.githubConnector;\n return Boolean(\n github && connector &&\n connector.appId === github.appId &&\n connector.slug === github.slug &&\n connector.clientId === github.clientId\n );\n }\n\n function beginConfigurationEdit(provider) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const values = currentStatus.values;\n if (provider === 'logto') {\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') return;\n el('logto-edit-management-id').value = logto.managementAppId;\n el('logto-edit-management-resource').value = logto.managementResource;\n el('logto-edit-management-secret').value = '';\n el('logto-edit-browser-id').value = values.auth.browserClient.appId;\n el('logto-edit-browser-resource').value = logto.browser.apiResource || '';\n el('logto-edit-controls').hidden = false;\n el('logto-edit-management-id').focus();\n } else if (provider === 'github') {\n const github = values.github;\n if (!github) return;\n el('github-edit-app-id').value = String(github.appId);\n el('github-edit-slug').value = github.slug;\n el('github-edit-client-id').value = github.clientId || '';\n el('github-edit-webhook-enabled').checked = github.webhookEnabled !== false;\n for (const id of ['github-edit-client-secret', 'github-edit-private-key', 'github-edit-webhook-secret', 'github-edit-logto-secret']) el(id).value = '';\n el('github-edit-logto-secret-field').hidden = !githubConnectorUsesDeployment(values);\n el('github-edit-controls').hidden = false;\n el('clear-github').hidden = true;\n el('github-edit-app-id').focus();\n } else if (provider === 'slack') {\n const slack = values.slack;\n if (!slack) return;\n el('slack-edit-app-id').value = slack.appId;\n el('slack-edit-client-id').value = slack.clientId;\n el('slack-edit-client-secret').value = '';\n el('slack-edit-signing-secret').value = '';\n el('slack-edit-controls').hidden = false;\n el('clear-slack').hidden = true;\n el('slack-edit-app-id').focus();\n } else if (provider === 'gitea') {\n if (!values.gitea) return;\n el('gitea-base-url').value = values.gitea.baseUrl || '';\n el('gitea-config-controls').hidden = false;\n el('save-gitea').hidden = false;\n el('cancel-gitea-configuration').hidden = false;\n el('clear-gitea').hidden = true;\n el('gitea-base-url').focus();\n } else if (provider === 'gitlab') {\n if (!values.gitlab) return;\n el('gitlab-id').value = values.gitlab.clientId;\n el('gitlab-secret').value = '';\n el('gitlab-config-controls').hidden = false;\n el('gitlab-initial-secret-field').hidden = false;\n el('save-gitlab').hidden = false;\n el('cancel-gitlab-configuration').hidden = false;\n el('clear-gitlab').hidden = true;\n el('gitlab-id').focus();\n } else if (provider === 'googlechat') {\n if (!values.googleChat) return;\n el('googlechat-project-id-input').value = values.googleChat.projectId;\n el('googlechat-project-number-input').value = values.googleChat.projectNumber;\n el('googlechat-key').value = '';\n el('googlechat-edit-heading').hidden = false;\n el('googlechat-config-controls').hidden = false;\n el('save-googlechat').hidden = false;\n el('cancel-googlechat-configuration').hidden = false;\n el('clear-googlechat').hidden = true;\n el('googlechat-project-id-input').focus();\n } else if (provider === 'email') {\n if (!values.email) return;\n el('email-mail-domain-input').value = values.email.mailDomain;\n el('email-account-id-input').value = values.email.accountId;\n el('email-send-limit-input').value = values.email.dailySendLimit ? String(values.email.dailySendLimit) : '';\n el('email-token').value = '';\n el('email-edit-heading').hidden = false;\n el('email-config-controls').hidden = false;\n el('save-email').hidden = false;\n el('cancel-email-configuration').hidden = false;\n el('rotate-email-ingress').hidden = true;\n el('email-rotate-confirm').hidden = true;\n el('clear-email').hidden = true;\n el('email-mail-domain-input').focus();\n } else if (provider === 'linear') {\n if (!values.linear) return;\n el('linear-id').value = values.linear.clientId;\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n el('linear-config-controls').hidden = false;\n el('linear-initial-secret-fields').hidden = false;\n el('save-linear').hidden = false;\n el('cancel-linear-configuration').hidden = false;\n el('clear-linear').hidden = true;\n el('linear-id').focus();\n } else if (provider === 'google') {\n const google = values.logto && values.logto.googleConnector;\n if (!google) return;\n el('google-id').value = google.clientId;\n el('google-secret').value = '';\n el('google-config-controls').hidden = false;\n el('google-initial-secret-field').hidden = false;\n el('save-google').hidden = false;\n el('save-google').textContent = 'Save Google client';\n el('cancel-google-configuration').hidden = false;\n el('clear-google').hidden = true;\n el('google-id').focus();\n } else if (Object.hasOwn(loginApps, provider)) {\n el(provider + '-secret').value = '';\n el(provider + '-config-controls').hidden = false;\n el(provider + '-initial-secret-field').hidden = false;\n el('save-' + provider).hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-id').focus();\n } else if (provider === 'feishu' || provider === 'lark') {\n el(provider + '-config-controls').hidden = false;\n el(provider + '-create-name-field').hidden = true;\n el('create-' + provider + '-login-app').hidden = true;\n el('save-' + provider + '-login-app').hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-login-secret').value = '';\n el(provider + '-login-id').focus();\n }\n showIdentityEditors(provider, false);\n }\n\n function cancelConfigurationEdit() {\n if (currentStatus) renderApps(currentStatus);\n }\n\n async function replaceConfiguration(values, secrets, successMessage) {\n const response = await json(await fetch(api + '/deployment-config', {\n method: 'PUT',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values, ...(secrets ? { secrets } : {}) })\n }));\n await load();\n message(successMessage || 'Configuration saved. Restart AgentConnect to apply it.');\n return response;\n }\n\n async function saveLogtoConfiguration() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') throw new Error('Logto is not configured');\n const managementAppId = requiredInput('logto-edit-management-id', 'the Management App ID');\n const managementResource = requiredInput('logto-edit-management-resource', 'the Management API resource');\n const browserAppId = requiredInput('logto-edit-browser-id', 'the SPA App ID');\n const browserResource = el('logto-edit-browser-resource').value.trim() || null;\n const managementIdentityChanged = managementAppId !== logto.managementAppId;\n const managementSecret = el('logto-edit-management-secret').value;\n if (managementIdentityChanged && !managementSecret) throw new Error('Enter the new Management App secret');\n const browser = { ...logto.browser, apiResource: browserResource };\n const auth = {\n ...values.auth,\n audience: browserResource || browserAppId,\n browserClient: { appId: browserAppId, apiResource: browserResource }\n };\n await replaceConfiguration(\n {\n ...values,\n auth,\n logto: { ...logto, managementAppId, managementResource, browser }\n },\n managementSecret ? { 'logto.managementAppSecret': managementSecret } : undefined,\n 'Logto configuration saved. Sign in again if the SPA identity changed, then restart AgentConnect.'\n );\n }\n\n async function saveGithubConfiguration() {\n if (!currentStatus || !currentStatus.values.github) throw new Error('GitHub is not configured');\n const values = currentStatus.values;\n const previous = values.github;\n const appId = Number(requiredInput('github-edit-app-id', 'the GitHub App ID'));\n if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error('GitHub App ID must be a positive integer');\n const slug = requiredInput('github-edit-slug', 'the GitHub App slug');\n const clientId = requiredInput('github-edit-client-id', 'the GitHub Client ID');\n const appChanged = appId !== previous.appId;\n const clientChanged = clientId !== previous.clientId;\n const webhookEnabled = el('github-edit-webhook-enabled').checked;\n const webhookEnabling = webhookEnabled && previous.webhookEnabled === false;\n const connectorReused = githubConnectorUsesDeployment(values);\n const clientSecret = el('github-edit-client-secret').value;\n const privateKey = el('github-edit-private-key').value.trim();\n const webhookSecret = el('github-edit-webhook-secret').value;\n const connectorSecret = el('github-edit-logto-secret').value;\n const webhookSecretStored = currentStatus.secrets.some((secret) => secret.key === 'github.webhookSecret' && secret.configured);\n if ((appChanged || clientChanged) && !clientSecret) throw new Error('Enter the new GitHub client secret');\n if (appChanged && !privateKey) throw new Error('Enter the new GitHub private key as base64');\n if (webhookEnabled && ((appChanged && !webhookSecret) || (webhookEnabling && !webhookSecret && !webhookSecretStored))) throw new Error('Enter the new GitHub webhook secret');\n if (connectorReused && (appChanged || clientChanged) && !connectorSecret) throw new Error('Enter the new Logto connector client secret');\n const secrets = {};\n if (clientSecret) secrets['github.clientSecret'] = clientSecret;\n if (privateKey) secrets['github.privateKeyB64'] = privateKey;\n if (webhookSecret) secrets['github.webhookSecret'] = webhookSecret;\n if (connectorSecret) secrets['logto.githubConnectorClientSecret'] = connectorSecret;\n const nextLogto = connectorReused && values.logto\n ? { ...values.logto, githubConnector: { ...values.logto.githubConnector, appId, slug, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n github: { ...previous, appId, slug, clientId, webhookEnabled },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'GitHub App identity saved. Restart AgentConnect to apply it.'\n );\n if (connectorSecret) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function saveSlackConfiguration() {\n if (!currentStatus || !currentStatus.values.slack) throw new Error('Slack is not configured');\n const values = currentStatus.values;\n const previous = values.slack;\n const appId = requiredInput('slack-edit-app-id', 'the Slack App ID');\n const clientId = requiredInput('slack-edit-client-id', 'the Slack Client ID');\n const changed = appId !== previous.appId || clientId !== previous.clientId;\n const clientSecret = el('slack-edit-client-secret').value;\n const signingSecret = el('slack-edit-signing-secret').value;\n if (changed && (!clientSecret || !signingSecret)) throw new Error('Enter both the new Slack client secret and signing secret');\n const secrets = {};\n if (clientSecret) secrets['slack.clientSecret'] = clientSecret;\n if (signingSecret) secrets['slack.signingSecret'] = signingSecret;\n const nextLogto = values.logto && values.logto.slackConnector\n ? { ...values.logto, slackConnector: { ...values.logto.slackConnector, appId, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n slack: { ...previous, appId, clientId },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'Slack App identity saved. Restart AgentConnect to apply it.'\n );\n if (clientSecret && nextLogto && nextLogto.slackConnector) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function clearProvider(provider) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const label = provider === 'github' ? 'GitHub' : provider === 'gitlab' ? 'GitLab' : provider === 'gitea' ? 'Gitea' : provider === 'slack' ? 'Slack' : provider === 'googlechat' ? 'Google Chat' : provider === 'email' ? 'Email' : provider === 'linear' ? 'Linear' : provider === 'google' ? 'Google' : provider === 'feishu' ? 'Feishu' : 'Lark';\n if (!window.confirm('Clear the saved ' + label + ' configuration and secrets?')) return;\n const values = currentStatus.values;\n let next = values;\n let secrets = {};\n if (provider === 'github') {\n const connectorReused = githubConnectorUsesDeployment(values);\n const logto = connectorReused && values.logto\n ? {\n ...values.logto,\n githubConnector: null\n }\n : values.logto;\n next = { ...values, github: null, ...(logto ? { logto } : {}) };\n secrets = {\n 'github.clientSecret': null,\n 'github.privateKeyB64': null,\n 'github.webhookSecret': null,\n ...(connectorReused ? { 'logto.githubConnectorClientSecret': null } : {})\n };\n } else if (provider === 'gitea') {\n // Gitea holds no deployment secret, so clearing the address clears the whole entry.\n next = { ...values, gitea: null };\n } else if (provider === 'gitlab') {\n await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: null })\n }));\n showGitlabProbe(null);\n await load();\n message('GitLab configuration cleared. Its setup controls are available again.');\n return;\n } else if (provider === 'slack') {\n const logto = values.logto\n ? {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'slack') }\n : values.logto.browser,\n slackConnector: null\n }\n : values.logto;\n next = { ...values, slack: null, ...(logto ? { logto } : {}) };\n secrets = { 'slack.clientSecret': null, 'slack.signingSecret': null };\n } else if (provider === 'googlechat') {\n next = { ...values, googleChat: null };\n secrets = { 'googleChat.serviceAccountKey': null };\n } else if (provider === 'email') {\n next = { ...values, email: null };\n secrets = { 'email.apiToken': null, 'email.ingressSecret': null };\n } else if (provider === 'linear') {\n next = { ...values, linear: null };\n secrets = { 'linear.clientSecret': null, 'linear.signingSecret': null };\n } else if (provider === 'google') {\n if (!values.logto) return;\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'google') }\n : values.logto.browser,\n googleConnector: null\n }\n };\n secrets = { 'logto.googleConnectorClientSecret': null };\n } else if (provider === 'feishu' || provider === 'lark') {\n next = { ...values, [provider]: null };\n secrets = { [provider + '.loginAppSecret']: null };\n }\n await replaceConfiguration(next, secrets, label + ' configuration cleared. Its setup controls are available again.');\n if (provider === 'gitea') el('gitea-probe').hidden = true;\n if (provider === 'email') showEmailIngressSecret('');\n }\n\n async function startGithub(prefix) {\n const result = await json(await fetch(api + '/create/github/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n purpose: 'deployment',\n name: el(prefix + '-name').value,\n ownership: ownership(prefix),\n connectLogto: prefix === 'bootstrap-github'\n })\n }));\n const form = document.createElement('form');\n form.method = 'post'; form.action = result.action;\n const manifest = document.createElement('input');\n manifest.type = 'hidden'; manifest.name = 'manifest'; manifest.value = JSON.stringify(result.manifest);\n form.append(manifest); document.body.append(form);\n message('Opening GitHub to review the complete integration App.');\n form.submit();\n }\n\n async function loadBootstrapInfo() {\n bootstrapInfo = await json(await fetch(api + '/bootstrap-info'));\n el('open-logto').href = bootstrapInfo.logtoAdminEndpoint;\n el('logto-settings').href = bootstrapInfo.logtoAdminEndpoint;\n if (!el('logto-app-id').value && bootstrapInfo.logtoManagementAppId) {\n el('logto-app-id').value = bootstrapInfo.logtoManagementAppId;\n }\n renderUriList('bootstrap-google-origins', bootstrapInfo.google.javascriptOrigins);\n renderUriList('bootstrap-google-redirects', bootstrapInfo.google.redirectUris);\n renderUriList('bootstrap-slack-redirects', [bootstrapInfo.slackLoginRedirectUrl]);\n el('logto-management-api-resource').value = bootstrapInfo.logtoManagementResource;\n el('bootstrap-github-submit').disabled = !bootstrapInfo.githubAvailable;\n if (!bootstrapInfo.githubAvailable) {\n el('bootstrap-github-note').textContent = 'GitHub App creation needs valid saved Web, API, and ingress URLs.';\n } else if (!bootstrapInfo.githubWebhookActive) {\n el('bootstrap-github-note').textContent = 'Creates the complete GitHub App now without submitting the localhost webhook URL. Add it after saving reachable HTTPS ingress.';\n } else {\n el('bootstrap-github-note').textContent = 'This creates one complete App for both GitHub sign-in and repository integration.';\n }\n el('bootstrap-slack-option').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-submit').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-note').textContent = bootstrapInfo.slackAvailable\n ? 'Creates one complete Slack App. Sign-in uses a separate openid profile email flow from workspace installation.'\n : 'Slack sign-in needs all public service URLs to use HTTPS. Use Google locally or expose the stack through trusted HTTPS endpoints.';\n if (!bootstrapInfo.slackAvailable && el('bootstrap-provider').value === 'slack') {\n el('bootstrap-provider').value = 'google';\n updateBootstrapProvider();\n }\n return bootstrapInfo;\n }\n\n async function logtoBootstrapFinding() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n for (const id of ['logto.client_credentials', 'logto.roles_read']) {\n const finding = report.findings.find((candidate) => candidate.id === id);\n if (!finding || finding.status !== 'pass') {\n return finding || { status: 'fail', message: 'Logto Management API permissions could not be verified.' };\n }\n }\n return { status: 'pass', message: 'Logto Management API access is ready.' };\n }\n\n async function showBootstrap() {\n el('bootstrap').hidden = false;\n el('show-bootstrap').hidden = true;\n const info = bootstrapInfo || await loadBootstrapInfo();\n if (!info.logtoConfigured) {\n showBootstrapStep('logto');\n return;\n }\n const finding = await logtoBootstrapFinding();\n if (finding && finding.status === 'pass') {\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n return;\n }\n showBootstrapStep('logto');\n message(finding?.message || 'Logto Management API credentials could not be verified.', true);\n }\n\n async function bootstrapLogto() {\n await json(await fetch(api + '/bootstrap/logto', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n managementAppId: el('logto-app-id').value,\n managementAppSecret: el('logto-app-secret').value,\n managementResource: el('logto-management-api-resource').value\n })\n }));\n el('logto-app-secret').value = '';\n await loadBootstrapInfo();\n const finding = await logtoBootstrapFinding();\n if (!finding || finding.status !== 'pass') {\n throw new Error(finding?.message || 'Logto Management API credentials could not be verified.');\n }\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n }\n\n async function bootstrapGoogle() {\n const secret = el('bootstrap-google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ clientId: el('bootstrap-google-id').value, clientSecret: secret })\n }));\n el('bootstrap-google-secret').value = '';\n await reconcileLogto(true);\n await load();\n }\n\n async function bootstrapGithub() {\n if (!bootstrapInfo || !bootstrapInfo.githubAvailable) throw new Error('GitHub App creation needs valid saved Web, API, and ingress URLs.');\n await startGithub('bootstrap-github');\n }\n\n async function bootstrapSlack() {\n if (!bootstrapInfo || !bootstrapInfo.slackAvailable) throw new Error('Slack sign-in requires all public service URLs to use HTTPS.');\n await createSlack('bootstrap-slack', true);\n await reconcileLogto();\n await load();\n }\n\n async function createSlack(prefix = 'slack', connectLogto = false) {\n const result = await json(await fetch(api + '/create/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n name: el(prefix + '-name').value,\n configToken: el(prefix + '-token').value,\n connectLogto\n })\n }));\n el(prefix + '-token').value = '';\n if (!connectLogto) await load();\n message('Slack App ' + result.app.id + ' was created with the default integration manifest. Restart AgentConnect to apply it.');\n }\n\n async function checkGithub() {\n const result = await json(await fetch(api + '/check/github', { headers: bearer() }));\n el('github-settings').href = result.settingsUrl;\n el('github-settings').hidden = false;\n const label = result.missing.length ? 'Update required' : \"Can't verify automatically\";\n showDiff('github-drift', result.diff || [], label);\n match('github-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : label);\n message(result.status === 'pass' ? 'GitHub App matches the expected integration manifest.' : result.missing.length ? 'GitHub App settings need an update.' : \"GitHub can't expose callback, setup, or webhook-active settings through its API; check them in GitHub.\", result.status === 'fail');\n }\n\n async function connectGithubLogin() {\n await json(await fetch(api + '/configure/github-login', { method: 'POST', headers: bearer() }));\n await reconcileLogto();\n await load();\n message('The deployment GitHub App is now also used for Logto sign-in. Update its displayed callback URLs.');\n }\n\n async function connectSlackLogin() {\n if (!currentStatus || !currentStatus.values.slack || !currentStatus.values.logto) {\n throw new Error('Save the Slack App and Logto configuration first');\n }\n const values = currentStatus.values;\n const slack = values.slack;\n const logto = values.logto;\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...logto,\n browser: logto.browser\n ? { ...logto.browser, socialProviders: [...new Set([...logto.browser.socialProviders, 'slack'])] }\n : logto.browser,\n slackConnector: {\n appId: slack.appId,\n clientId: slack.clientId\n }\n }\n },\n undefined,\n 'Slack App is ready to connect to Logto.'\n );\n await reconcileLogto();\n await load();\n message('The deployment Slack App is now also used for Logto sign-in.');\n }\n\n async function checkSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/check/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(result.status === 'pass' ? 'Slack App matches the default integration manifest.' : 'Slack App settings need an update.', result.status !== 'pass');\n }\n\n async function reconcileSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/reconcile/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(\n result.status !== 'pass'\n ? 'Slack App was updated but some settings still differ.'\n : result.applied.length === 0\n ? 'Slack App already matches the default integration manifest.'\n : result.permissionsUpdated\n ? 'Slack App updated. Reinstall it in each workspace to grant the added scopes.'\n : 'Slack App updated.',\n result.status !== 'pass'\n );\n }\n\n async function checkGoogle() {\n const report = await checkLogto();\n const connector = report.findings.find((finding) => finding.id === 'logto.connectors');\n const google = currentStatus && currentStatus.values.logto && currentStatus.values.logto.googleConnector;\n const connectorDiff = connector && connector.diff\n ? connector.diff.filter((item) => item.field.toLowerCase().startsWith('google'))\n : [];\n const passed = Boolean(google && connector && connectorDiff.length === 0);\n showDiff('google-drift', connectorDiff);\n match('google-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Update required');\n message(\n passed\n ? \"The Logto Google connector matches. Google OAuth redirect settings can't be verified automatically.\"\n : 'The Logto Google connector needs an update.',\n !passed\n );\n }\n\n async function checkRegionalLoginApp(region) {\n const result = await json(await fetch(api + '/check/regional-login-app/' + region, { headers: bearer() }));\n const label = region === 'feishu' ? 'Feishu' : 'Lark';\n showDiff(region + '-drift', result.diff || []);\n match(region + '-match', result.status === 'pass' ? 'pass' : result.status === 'fail' ? 'fail' : 'warn', result.status === 'pass' ? 'Matches' : result.status === 'fail' ? 'Update required' : 'Could not check');\n el(region + '-login-status').textContent = result.message;\n el(region + '-login-status').className = result.status === 'pass' ? 'ok' : result.status === 'fail' ? 'warn' : 'muted';\n message(result.message || (label + ' credential check completed.'), result.status === 'fail');\n }\n\n async function saveGitlab() {\n const clientSecret = el('gitlab-secret').value;\n const baseUrl = el('gitlab-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('gitlab-id', 'the GitLab Application ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(baseUrl ? { baseUrl } : {})\n }\n })\n }));\n el('gitlab-secret').value = '';\n if (currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) await reconcileLogto(Boolean(clientSecret));\n await load();\n showGitlabProbe(saved.probe);\n message('GitLab OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n // Only the URL shape blocks the save, so every other verdict is a line to read.\n function showGitlabProbe(probe) {\n const line = el('gitlab-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function configureGitlabLogin(enabled) {\n await json(await fetch(api + '/configure/gitlab-login', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ enabled })\n }));\n try { await reconcileLogto(enabled); } finally { await load(); }\n message('GitLab sign-in ' + (enabled ? 'configured' : 'disabled') + '. Restart AgentConnect to apply it.');\n }\n\n async function saveGitea() {\n const baseUrl = el('gitea-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitea', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ instance: { ...(baseUrl ? { baseUrl } : {}) } })\n }));\n await load();\n // Shape and the version floor already blocked the save, so any verdict here is a line to read.\n const line = el('gitea-probe');\n line.hidden = !saved.probe;\n line.textContent = saved.probe ? saved.probe.message : '';\n message('Gitea instance saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogleChat() {\n const projectNumber = el('googlechat-project-number-input').value.trim();\n const application = {\n projectId: requiredInput('googlechat-project-id-input', 'the Google Cloud project ID'),\n ...(projectNumber ? { projectNumber } : {})\n };\n const serviceAccountKey = el('googlechat-key').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/google-chat', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: { ...application, ...(serviceAccountKey ? { serviceAccountKey } : {}) } })\n }));\n } finally {\n // The key never stays in the page once it has been submitted, whatever the outcome.\n el('googlechat-key').value = '';\n }\n await load();\n message('Google Chat app saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n }\n\n async function saveEmail(rotateIngressSecret) {\n const stored = currentStatus && currentStatus.values.email;\n const limit = rotateIngressSecret\n ? (stored && stored.dailySendLimit ? String(stored.dailySendLimit) : '')\n : el('email-send-limit-input').value.trim();\n if (limit && !/^[1-9][0-9]*$/.test(limit)) throw new Error('Enter the daily send limit as a whole number, or leave it empty.');\n const apiToken = rotateIngressSecret ? '' : el('email-token').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/email', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n email: {\n mailDomain: rotateIngressSecret ? stored.mailDomain : requiredInput('email-mail-domain-input', 'the mail domain'),\n accountId: rotateIngressSecret ? stored.accountId : requiredInput('email-account-id-input', 'the Cloudflare account ID'),\n dailySendLimit: limit ? Number(limit) : null,\n ...(apiToken ? { apiToken } : {}),\n ...(rotateIngressSecret ? { rotateIngressSecret: true } : {})\n }\n })\n }));\n } finally {\n // The token never stays in the page once it has been submitted, whatever the outcome.\n el('email-token').value = '';\n }\n // The response alone fills the secret box, so no render that follows can take it away.\n showEmailIngressSecret(saved.ingressSecret);\n message('Email saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n await refreshDeploymentConfig();\n }\n\n function showEmailIngressSecret(secret) {\n el('email-ingress-secret').textContent = secret || '';\n el('email-ingress-once').hidden = !secret;\n }\n\n async function copyEmailIngressSecret() {\n await navigator.clipboard.writeText(el('email-ingress-secret').textContent);\n message('Ingress secret copied.');\n }\n\n function confirmEmailIngressRotation(open) {\n el('email-rotate-confirm').hidden = !open;\n el('rotate-email-ingress').hidden = open;\n if (open) el('cancel-rotate-email-ingress').focus();\n }\n\n async function saveLinear() {\n const clientSecret = el('linear-client-secret').value;\n const signingSecret = el('linear-signing-secret').value;\n await json(await fetch(api + '/configure/linear', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('linear-id', 'the Linear Client ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(signingSecret ? { signingSecret } : {})\n }\n })\n }));\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n await load();\n message('Linear OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogle() {\n const secret = el('google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n clientId: el('google-id').value,\n ...(secret ? { clientSecret: secret } : {})\n })\n }));\n el('google-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n message('Google OAuth client and Logto connector are configured. Restart AgentConnect to apply the saved settings.');\n }\n\n // Agent bots (teams-integration.md §8.6.3): 'create' makes the blueprint through Graph, 'save' takes one entered by hand, 'clear' turns them off.\n async function saveAgentBots(mode) {\n if (mode === 'clear' && !window.confirm('Clear the saved blueprint and its secret? Agents that already have a bot of their own stop answering in Teams.')) return;\n const azure = mode === 'clear' ? {} : {\n subscriptionId: requiredInput('azuread-agent-bots-subscription-input', 'the Azure subscription ID'),\n resourceGroup: requiredInput('azuread-agent-bots-group-input', 'the resource group')\n };\n let saved;\n try {\n if (mode === 'create') {\n const operator = requiredInput('azuread-agent-bots-operator-input', 'your Microsoft Entra user');\n saved = await json(await fetch(api + '/configure/msteams-agent-bots/blueprint', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ operator, ...azure })\n }));\n } else {\n const clientSecret = el('azuread-agent-bots-secret-input').value;\n const agentBots = mode === 'clear' ? null : {\n blueprintId: requiredInput('azuread-agent-bots-blueprint-input', 'the blueprint ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...azure\n };\n saved = await json(await fetch(api + '/configure/msteams-agent-bots', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ agentBots })\n }));\n }\n } finally {\n // The secret never stays in the page once it has been submitted, whatever the outcome.\n el('azuread-agent-bots-secret-input').value = '';\n }\n await load();\n if (mode === 'clear') return message('Agent bots cleared. Restart AgentConnect to apply the saved settings.');\n const settling = mode === 'create' && saved.check !== 'ok';\n message('Blueprint ' + saved.blueprintId + ' saved.' + (settling ? ' Its new secret was not accepted yet; give Microsoft a minute before you restart.' : '') + ' Restart AgentConnect to apply the saved settings.' + (mode === 'create' ? ' You may now remove the three Graph permissions from the application.' : ''));\n }\n\n async function saveLoginApp(provider, clear = false) {\n const app = loginApps[provider];\n if (clear && !window.confirm('Clear the saved ' + app.name + ' login application and secret?')) return;\n const clientSecret = el(provider + '-secret').value;\n const application = clear ? null : {\n clientId: requiredInput(provider + '-id', 'the ' + app.name + ' Client ID'),\n ...(clientSecret ? { clientSecret } : {})\n };\n // Microsoft's home tenant also makes the app the deployment's Teams app; empty turns that off.\n const teams = provider === 'azuread' && !clear ? { teamsTenantId: el('azuread-teams-tenant-input').value.trim() || null } : {};\n try {\n await json(await fetch(api + '/configure/login-app/' + provider, {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application, ...teams })\n }));\n } finally {\n el(provider + '-secret').value = '';\n }\n try {\n await reconcileLogto(Boolean(clientSecret) && !clear);\n } finally {\n await load();\n }\n message(app.name + (clear ? ' sign-in configuration cleared.' : ' login application and Logto connector configured.') + ' Restart AgentConnect to apply the saved settings.');\n }\n\n function renderLoginAppChecks(report) {\n const connectors = report.findings.find((finding) => finding.id === 'logto.connectors');\n if (currentStatus?.values.logto?.browser?.socialProviders.includes('gitlab')) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('gitlab')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n el('gitlab-login-status').textContent = passed\n ? 'GitLab connector matches. Confirm the redirect URLs and OpenID scopes in GitLab.'\n : 'GitLab sign-in could not be verified. Review the Logto check above.';\n }\n for (const [provider, app] of Object.entries(loginApps)) {\n if (!currentStatus?.values.logto?.[provider + 'Connector']) continue;\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith(provider)) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff(provider + '-drift', diff);\n match(provider + '-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el(provider + '-status').textContent = passed\n ? app.name + ' connector matches. Confirm the redirect URLs in the provider settings.'\n : app.name + ' connector could not be verified. Review the Logto check above.';\n }\n }\n\n function regionalLoginApp(prefix) {\n const appId = el(prefix + '-login-id').value.trim();\n const appSecret = el(prefix + '-login-secret').value;\n return appId ? { appId, ...(appSecret ? { appSecret } : {}) } : null;\n }\n\n async function saveRegionalLoginApp(region) {\n const app = regionalLoginApp(region);\n if (!app) throw new Error('Enter the ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App ID');\n await json(await fetch(api + '/configure/regional-login-app', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, app })\n }));\n el(region + '-login-secret').value = '';\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' tenant App is saved. Restart AgentConnect services to apply it.');\n }\n\n async function createRegionalLoginApp(region) {\n const popup = window.open('about:blank', '_blank');\n try {\n const started = await json(await fetch(api + '/create/regional-login-app/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, name: el(region + '-create-name').value })\n }));\n if (popup) popup.location.replace(started.authorizationUrl);\n else window.open(started.authorizationUrl, '_blank', 'noopener');\n message('Approve the new ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App in the opened page. This page will finish saving it automatically.');\n while (true) {\n const result = await json(await fetch(api + '/create/regional-login-app/' + encodeURIComponent(started.id), { headers: bearer() }));\n if (result.status === 'completed') {\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' App ' + result.appId + ' was created and saved. Restart AgentConnect services to apply it.');\n return;\n }\n if (result.status === 'failed') throw new Error('Regional App creation ' + result.reason + '. Start it again.');\n await new Promise((resolve) => setTimeout(resolve, Math.max(500, Math.min(result.retryAfterMs || 2000, 5000))));\n }\n } catch (error) {\n if (popup) popup.close();\n throw error;\n }\n }\n\n async function reconcileLogto(refreshConnectorSecrets) {\n return json(await fetch(api + '/reconcile/logto', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ refreshConnectorSecrets: Boolean(refreshConnectorSecrets) })\n }));\n }\n\n async function refreshDeploymentConfig() {\n const status = await json(await fetch(api + '/deployment-config', { headers: bearer() }));\n el('access').hidden = true;\n el('setup').hidden = false;\n el('editor').hidden = false;\n currentRevision = status.revision;\n renderApps(status);\n return status;\n }\n\n async function checkLogto() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n await refreshDeploymentConfig();\n const failures = report.findings.filter((finding) => finding.status !== 'pass');\n el('logto-status').textContent = failures.length === 0\n ? 'SPA redirects, connectors, and social-only sign-in match.'\n : failures.map((finding) => finding.message).join(' ');\n el('logto-status').className = failures.length === 0 ? 'ok' : 'warn';\n match('logto-match', failures.length === 0 ? 'pass' : 'warn', failures.length === 0 ? 'Matches' : 'Update required');\n showDiff(\n 'logto-drift',\n failures.flatMap((finding) => finding.diff && finding.diff.length\n ? finding.diff\n : [{ field: finding.id.replace(/^logto./, '').replaceAll('_', ' '), current: finding.message, expected: 'Matches expected configuration' }])\n );\n el('logto-settings').hidden = failures.length === 0;\n renderLoginAppChecks(report);\n return report;\n }\n\n function githubNotice(value) {\n if (value === 'deployment-created') return 'GitHub integration App created. Its private key and webhook secret are stored.';\n if (value === 'deployment-login-created') return 'GitHub integration App created and connected to Logto sign-in.';\n if (value === 'cancelled') return 'GitHub App creation was cancelled.';\n if (value === 'expired') return 'GitHub App creation expired. Start it again.';\n if (value === 'invalid-callback') return 'GitHub returned an invalid App creation callback.';\n if (value === 'conversion-failed') return 'GitHub may have created the App, but did not return complete credentials. Delete the orphaned App and retry.';\n if (value === 'save-failed') return 'GitHub created the App, but its credentials could not be saved. Delete the orphaned App and retry.';\n return '';\n }\n\n async function load() {\n let publicAuth = await authConfig();\n const currentUrl = new URL(location.href);\n const githubResult = currentUrl.searchParams.get('github');\n const notice = githubNotice(githubResult);\n if (githubResult === 'deployment-login-created' && publicAuth.mode === 'none') {\n await reconcileLogto();\n publicAuth = await authConfig();\n }\n if (githubResult) history.replaceState({}, '', '/');\n const hasToken = Boolean(sessionStorage.getItem(tokenKey));\n el('access').hidden = false;\n el('setup').hidden = true;\n el('login').hidden = true;\n el('open-logto').hidden = true;\n el('show-bootstrap').hidden = true;\n el('editor').hidden = true;\n el('bootstrap').hidden = true;\n if (publicAuth.logtoAdminEndpoint) {\n el('open-logto').href = publicAuth.logtoAdminEndpoint;\n el('logto-settings').href = publicAuth.logtoAdminEndpoint;\n }\n if (publicAuth.mode === 'none') {\n sessionStorage.removeItem(tokenKey);\n await loadBootstrapInfo();\n el('open-logto').hidden = false;\n el('show-bootstrap').hidden = false;\n message(notice || 'Logto sign-in is not configured. Set up the initial Logto administrator first.');\n return;\n }\n if (publicAuth.mode === 'unavailable') {\n el('open-logto').hidden = false;\n message(publicAuth.message || 'Logto sign-in is unavailable. Open Logto Console to review its settings.', true);\n return;\n }\n if (!hasToken) {\n el('login').hidden = false;\n message(notice || 'Sign in with Logto to continue.');\n return;\n }\n if (publicAuth.claimAvailable) {\n try {\n await json(await fetch(api + '/bootstrap/claim', { method: 'POST', headers: bearer() }));\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('This first user is now an ADMIN. Sign in again to refresh the role claim.');\n return;\n } catch (error) {\n if (error.status !== 401 && error.status !== 403) throw error;\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with Logto to continue.', true);\n return;\n }\n }\n try {\n await loadBootstrapInfo();\n await refreshDeploymentConfig();\n message(notice);\n checkLogto().catch((error) => {\n el('logto-status').textContent = error.message;\n el('logto-status').className = 'warn';\n el('logto-settings').hidden = false;\n });\n } catch (error) {\n if (error.status === 401 || error.status === 403) {\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with a Logto ADMIN account.', true);\n }\n else throw error;\n }\n }\n\n async function saveSecretReplacement(key, value) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n if (!value) throw new Error('Enter the replacement secret');\n const refreshLogto =\n (key === 'gitlab.clientSecret' && currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) ||\n (key === 'logto.githubConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.githubConnector) ||\n (key === 'logto.googleConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.googleConnector) ||\n Object.keys(loginApps).some((provider) => key === 'logto.' + provider + 'ConnectorClientSecret' && currentStatus.values.logto?.[provider + 'Connector']) ||\n (key === 'slack.clientSecret' && currentStatus.values.logto && currentStatus.values.logto.slackConnector);\n await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values: currentStatus.values, secrets: { [key]: value } })\n }));\n try {\n if (refreshLogto) await reconcileLogto(true);\n } finally {\n await load();\n }\n if (refreshLogto) {\n message('Secret replaced and applied to the Logto connector. Restart AgentConnect to apply deployment changes.');\n } else {\n message('Secret replaced. Restart AgentConnect to apply it.');\n }\n }\n\n function editSecret(button) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const row = button.closest('.secret-line');\n const display = el(button.dataset.secretDisplay);\n if (!row || !display || row.querySelector('.secret-editor')) return;\n const editor = document.createElement('span'); editor.className = 'secret-editor';\n const input = document.createElement('input');\n input.type = 'password'; input.autocomplete = 'new-password'; input.placeholder = 'Enter replacement secret';\n const save = document.createElement('button'); save.textContent = 'Save';\n const cancel = document.createElement('button'); cancel.textContent = 'Cancel';\n const close = () => { editor.remove(); display.hidden = false; button.hidden = false; };\n save.onclick = async () => {\n save.disabled = true;\n try { await saveSecretReplacement(button.dataset.secretKey, input.value); }\n catch (error) { save.disabled = false; message(error.message, true); }\n };\n cancel.onclick = close;\n input.onkeydown = (event) => { if (event.key === 'Enter') save.click(); if (event.key === 'Escape') close(); };\n display.hidden = true; button.hidden = true;\n editor.append(input, save, cancel); row.append(editor); input.focus();\n }\n\n async function saveOptions() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = {\n ...currentStatus.values,\n features: {\n presetAgentsEnabled: el('preset-agents-enabled').checked,\n maxOrgsPerNonAdminUser: Number(el('max-orgs-per-non-admin-user').value),\n organizationSso: el('organization-sso').checked\n }\n };\n const saved = await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values })\n }));\n try {\n if (currentStatus.values.auth.mode === 'oidc') await reconcileLogto();\n } catch (error) {\n await load();\n throw new Error('Saved deployment options, but Logto was not updated: ' + error.message);\n }\n message('Saved deployment options. Restart AgentConnect to apply them.');\n await load();\n }\n\n el('login').onclick = () => signIn().catch((error) => message(error.message, true));\n el('show-bootstrap').onclick = () => showBootstrap().catch((error) => message(error.message, true));\n el('bootstrap-provider').onchange = updateBootstrapProvider;\n el('bootstrap-github-owner').onchange = () => updateOwner('bootstrap-github');\n el('github-owner').onchange = () => updateOwner('github');\n el('bootstrap-logto-submit').onclick = () => bootstrapLogto().catch((error) => message(error.message, true));\n el('bootstrap-back').onclick = () => showBootstrapStep('logto');\n el('bootstrap-google-submit').onclick = () => bootstrapGoogle().catch((error) => message(error.message, true));\n for (const prefix of ['bootstrap-sso', 'sso']) {\n el(prefix + '-protocol').onchange = () => updateSsoProtocol(prefix);\n el(prefix + '-member-source').onchange = () => updateMemberOrganization(prefix);\n el(prefix + '-create').onclick = () => createSso(prefix).catch((error) => message(error.message, true));\n el(prefix + '-submit').onclick = () => saveSso(prefix).catch((error) => message(error.message, true));\n }\n el('sso-remove').onclick = () => removeSso().catch((error) => message(error.message, true));\n el('bootstrap-github-submit').onclick = () => bootstrapGithub().catch((error) => message(error.message, true));\n el('bootstrap-slack-submit').onclick = () => bootstrapSlack().catch((error) => message(error.message, true));\n el('create-github').onclick = () => startGithub('github').catch((error) => message(error.message, true));\n el('save-logto-configuration').onclick = () => saveLogtoConfiguration().catch((error) => message(error.message, true));\n el('cancel-logto-configuration').onclick = cancelConfigurationEdit;\n el('save-github-configuration').onclick = () => saveGithubConfiguration().catch((error) => message(error.message, true));\n el('cancel-github-configuration').onclick = cancelConfigurationEdit;\n el('clear-github').onclick = () => clearProvider('github').catch((error) => message(error.message, true));\n el('connect-github-login').onclick = () => connectGithubLogin().catch((error) => message(error.message, true));\n el('connect-gitlab-login').onclick = () => configureGitlabLogin(true).catch((error) => message(error.message, true));\n el('disconnect-gitlab-login').onclick = () => configureGitlabLogin(false).catch((error) => message(error.message, true));\n el('check-gitlab-login').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-github').onclick = () => checkGithub().catch((error) => message(error.message, true));\n el('create-slack').onclick = () => createSlack('slack').catch((error) => message(error.message, true));\n el('connect-slack-login').onclick = () => connectSlackLogin().catch((error) => message(error.message, true));\n el('save-slack-configuration').onclick = () => saveSlackConfiguration().catch((error) => message(error.message, true));\n el('cancel-slack-configuration').onclick = cancelConfigurationEdit;\n el('clear-slack').onclick = () => clearProvider('slack').catch((error) => message(error.message, true));\n el('check-slack').onclick = () => checkSlack().catch((error) => message(error.message, true));\n el('reconcile-slack').onclick = () => reconcileSlack().catch((error) => message(error.message, true));\n el('save-gitea').onclick = () => saveGitea().catch((error) => message(error.message, true));\n el('cancel-gitea-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitea').onclick = () => clearProvider('gitea').catch((error) => message(error.message, true));\n el('save-gitlab').onclick = () => saveGitlab().catch((error) => message(error.message, true));\n el('cancel-gitlab-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitlab').onclick = () => clearProvider('gitlab').catch((error) => message(error.message, true));\n el('save-googlechat').onclick = () => saveGoogleChat().catch((error) => message(error.message, true));\n for (const [id, mode] of [['create-azuread-agent-bots-blueprint', 'create'], ['save-azuread-agent-bots', 'save'], ['clear-azuread-agent-bots', 'clear']]) {\n el(id).onclick = () => saveAgentBots(mode).catch((error) => message(error.message, true));\n }\n el('cancel-googlechat-configuration').onclick = cancelConfigurationEdit;\n el('clear-googlechat').onclick = () => clearProvider('googlechat').catch((error) => message(error.message, true));\n el('save-email').onclick = () => saveEmail(false).catch((error) => message(error.message, true));\n el('rotate-email-ingress').onclick = () => confirmEmailIngressRotation(true);\n el('cancel-rotate-email-ingress').onclick = () => confirmEmailIngressRotation(false);\n el('confirm-rotate-email-ingress').onclick = () => {\n confirmEmailIngressRotation(false);\n saveEmail(true).catch((error) => message(error.message, true));\n };\n el('copy-email-ingress').onclick = () => copyEmailIngressSecret().catch(() => message('Copy failed. Select the secret and copy it.', true));\n el('dismiss-email-ingress').onclick = () => showEmailIngressSecret('');\n el('cancel-email-configuration').onclick = cancelConfigurationEdit;\n el('clear-email').onclick = () => clearProvider('email').catch((error) => message(error.message, true));\n el('save-linear').onclick = () => saveLinear().catch((error) => message(error.message, true));\n el('cancel-linear-configuration').onclick = cancelConfigurationEdit;\n el('clear-linear').onclick = () => clearProvider('linear').catch((error) => message(error.message, true));\n el('save-google').onclick = () => saveGoogle().catch((error) => message(error.message, true));\n el('cancel-google-configuration').onclick = cancelConfigurationEdit;\n el('clear-google').onclick = () => clearProvider('google').catch((error) => message(error.message, true));\n el('check-google').onclick = () => checkGoogle().catch((error) => message(error.message, true));\n for (const provider of Object.keys(loginApps)) {\n el('save-' + provider).onclick = () => saveLoginApp(provider).catch((error) => message(error.message, true));\n el('cancel-' + provider + '-configuration').onclick = cancelConfigurationEdit;\n el('clear-' + provider).onclick = () => saveLoginApp(provider, true).catch((error) => message(error.message, true));\n el('check-' + provider).onclick = () => checkLogto().catch((error) => message(error.message, true));\n }\n el('create-feishu-login-app').onclick = () => createRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('save-feishu-login-app').onclick = () => saveRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('cancel-feishu-configuration').onclick = cancelConfigurationEdit;\n el('clear-feishu').onclick = () => clearProvider('feishu').catch((error) => message(error.message, true));\n el('check-feishu-login-app').onclick = () => checkRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('create-lark-login-app').onclick = () => createRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('save-lark-login-app').onclick = () => saveRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('cancel-lark-configuration').onclick = cancelConfigurationEdit;\n el('clear-lark').onclick = () => clearProvider('lark').catch((error) => message(error.message, true));\n el('check-lark-login-app').onclick = () => checkRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('check-logto').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('reconcile-logto').onclick = () => reconcileLogto().then(load).catch((error) => message(error.message, true));\n el('logout').onclick = () => { sessionStorage.removeItem(tokenKey); load().catch((error) => message(error.message, true)); };\n el('save-options').onclick = () => saveOptions().catch((error) => message(error.message, true));\n for (const button of document.querySelectorAll('.edit-secret')) button.onclick = () => editSecret(button);\n for (const button of document.querySelectorAll('.edit-configuration')) button.onclick = () => beginConfigurationEdit(button.dataset.provider);\n updateBootstrapProvider();\n finishSignIn().then(load).catch((error) => message(error.message, true));\n <\/script>\n</body>\n</html>"
69112
+ "\n\n <section id=\"googlechat-section\" class=\"panel setup-section\" aria-labelledby=\"googlechat-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"googlechat-heading\">Google Chat</h3><p class=\"muted\">One Chat app for the deployment. Each Google Workspace organization connects itself from Google Chat.</p></div>\n <span id=\"googlechat-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Project ID</dt><dd class=\"value-line\"><code id=\"googlechat-project-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Project number</dt><dd class=\"value-line\"><code id=\"googlechat-project-number\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Service-account key</dt><dd class=\"value-line\"><span id=\"googlechat-key-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n </dl>\n <p id=\"googlechat-status\" class=\"muted\"></p>\n <div id=\"googlechat-drift\" class=\"notice\" hidden></div>\n <p>HTTP endpoint URL:</p><ul id=\"googlechat-callbacks\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>Use a Google Workspace account that may create a Cloud project and service-account keys. An organization policy can block key creation.</li>\n <li>Create a Google Cloud project for this app and enable the Google Chat API in it.</li>\n <li>On the Chat API Configuration page, build the app as a Google Workspace add-on, the default for a new app (convert an existing app first). Under Connection settings choose HTTP endpoint URL, use one URL for all triggers, and enter the URL above. Allow 1:1 messages and joining spaces, and choose who can use the app.</li>\n <li>Under Commands, add a slash command named /help with the description \"Show how to use this app\" and command ID 1; any free ID works, since AgentConnect matches the name.</li>\n <li>In the same project, create a service account and a JSON key for it, grant it the Browser role on the project, and enable the Cloud Resource Manager API; AgentConnect reads the project number with that key.</li>\n <li>Save the project ID and key here. The project number is optional: it is on the project's settings page and in the add-on's service account email, service-PROJECT_NUMBER@gcp-sa-gsuiteaddons.iam.gserviceaccount.com. When entered, it must match the number read from the key's project.</li>\n <li>Configure Google sign-in above, then add the app in Google Chat and send it a message. Each Google Workspace organization connects itself from Google Chat by signing in to the console with Google; publish the app on the Google Workspace Marketplace to reach other organizations.</li>\n </ol>\n <div class=\"row\"><a id=\"googlechat-configuration\" class=\"button\" href=\"https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat\" target=\"_blank\" rel=\"noopener\">Open Chat API configuration</a></div>\n <div id=\"googlechat-config-controls\" class=\"subsection\">\n <h3 id=\"googlechat-edit-heading\" hidden>Edit Google Chat App identity</h3>\n <label class=\"field\">Project ID<input id=\"googlechat-project-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">Project number (optional)<input id=\"googlechat-project-number-input\" inputmode=\"numeric\" autocomplete=\"off\" placeholder=\"Read from the key's project\"></label>\n <label class=\"field\">Service-account key JSON<input id=\"googlechat-key\" type=\"password\" autocomplete=\"off\" placeholder=\"Required when the project ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-googlechat\">Save Google Chat app</button><button id=\"cancel-googlechat-configuration\" hidden>Cancel</button><button id=\"clear-googlechat\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"email-section\" class=\"panel setup-section\" aria-labelledby=\"email-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"email-heading\">Email</h3><p class=\"muted\">One mail domain for the deployment. Each agent gets an address on it, received and sent through Cloudflare Email Service.</p></div>\n <span id=\"email-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Mail domain</dt><dd class=\"value-line\"><code id=\"email-mail-domain\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Cloudflare account ID</dt><dd class=\"value-line\"><code id=\"email-account-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>API token</dt><dd class=\"value-line\"><span id=\"email-token-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Ingress secret</dt><dd class=\"value-line\"><span id=\"email-ingress-display\" class=\"muted\">Not configured</span></dd>\n <dt>Daily send limit</dt><dd class=\"value-line\"><code id=\"email-send-limit\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n </dl>\n <p id=\"email-status\" class=\"muted\"></p>\n <div id=\"email-drift\" class=\"notice\" hidden></div>\n <div id=\"email-ingress-once\" class=\"notice\" hidden>\n <p>Ingress secret, shown once. Set it as the Worker's secret now:</p>\n <pre id=\"email-ingress-secret\"></pre>\n <div class=\"row\"><button id=\"copy-email-ingress\">Copy</button><button id=\"dismiss-email-ingress\">Dismiss</button></div>\n </div>\n <p>Inbound URL for the ingress Worker:</p><ul id=\"email-inbound\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>In Cloudflare, onboard a zone used for nothing else as the mail domain, for Email Routing and for Email Sending. A domain that already receives mail elsewhere cannot be used.</li>\n <li>Create an API token with the Email Sending: Edit permission for that account, then save the domain, the account ID and the token here. Setup checks the token with one read of the account's Email Sending suppression list and sends nothing.</li>\n <li>Deploy the ingress Worker with the inbound URL above and the ingress secret shown after the first save, and point the zone's catch-all routing rule at it.</li>\n <li>The daily send limit is the most mail the whole deployment sends in a day. Left empty, only the limits for each address and each organization apply.</li>\n </ol>\n <div class=\"row\"><a id=\"email-dashboard\" class=\"button\" href=\"https://dash.cloudflare.com/\" target=\"_blank\" rel=\"noopener\">Open Cloudflare</a></div>\n <div id=\"email-config-controls\" class=\"subsection\">\n <h3 id=\"email-edit-heading\" hidden>Edit Email configuration</h3>\n <label class=\"field\">Mail domain<input id=\"email-mail-domain-input\" autocomplete=\"off\" placeholder=\"mail.example.com\"></label>\n <label class=\"field\">Cloudflare account ID<input id=\"email-account-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">API token<input id=\"email-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the account ID changes\"></label>\n <label class=\"field\">Daily send limit (optional)<input id=\"email-send-limit-input\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n </div>\n <div class=\"row\"><button id=\"save-email\">Save Email</button><button id=\"cancel-email-configuration\" hidden>Cancel</button><button id=\"rotate-email-ingress\" hidden>Replace ingress secret</button><span id=\"email-rotate-confirm\" hidden>Replace? Mail is refused until the Worker has the new one. <button id=\"confirm-rotate-email-ingress\" class=\"danger\">Replace</button><button id=\"cancel-rotate-email-ingress\">Cancel</button></span><button id=\"clear-email\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n\n <section id=\"feishu-section\" class=\"panel setup-section\" aria-labelledby=\"feishu-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"feishu-heading\">Feishu</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Feishu, OAuth callbacks, and published App setup.</p></div>\n <span id=\"feishu-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"feishu-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"feishu\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"feishu-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"feishu.loginAppSecret\" data-secret-display=\"feishu-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"feishu-login-status\" class=\"muted\"></p>\n <div id=\"feishu-drift\" class=\"notice\" hidden></div>\n <div id=\"feishu-config-controls\" class=\"subsection\">\n <label id=\"feishu-create-name-field\" class=\"field\">New App name<input id=\"feishu-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"feishu-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"feishu-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-feishu-login-app\">Create Feishu App</button>\n <button id=\"save-feishu-login-app\">Save existing App</button>\n <button id=\"cancel-feishu-configuration\" hidden>Cancel</button>\n <button id=\"check-feishu-login-app\" hidden>Check setup</button>\n <button id=\"clear-feishu\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"feishu-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Feishu settings</a>\n </div>\n </section>\n\n <section id=\"lark-section\" class=\"panel setup-section\" aria-labelledby=\"lark-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"lark-heading\">Lark</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Lark, OAuth callbacks, and published App setup.</p></div>\n <span id=\"lark-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"lark-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"lark\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"lark-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"lark.loginAppSecret\" data-secret-display=\"lark-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"lark-login-status\" class=\"muted\"></p>\n <div id=\"lark-drift\" class=\"notice\" hidden></div>\n <div id=\"lark-config-controls\" class=\"subsection\">\n <label id=\"lark-create-name-field\" class=\"field\">New App name<input id=\"lark-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"lark-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"lark-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-lark-login-app\">Create Lark App</button>\n <button id=\"save-lark-login-app\">Save existing App</button>\n <button id=\"cancel-lark-configuration\" hidden>Cancel</button>\n <button id=\"check-lark-login-app\" hidden>Check setup</button>\n <button id=\"clear-lark\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"lark-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Lark settings</a>\n </div>\n </section>\n\n <section id=\"mattermost-section\" class=\"panel setup-section\" aria-labelledby=\"mattermost-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"mattermost-heading\">Mattermost</h3><p class=\"muted\">Self-hosted OAuth 2.0 application used by the Logto Mattermost sign-in connector and conversation access checks.</p></div>\n <span id=\"mattermost-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Server URL</dt><dd class=\"value-line\"><code id=\"mattermost-server-url\">Not configured</code><button class=\"edit-configuration\" data-provider=\"mattermost\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"mattermost-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"mattermost\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"mattermost-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.mattermostConnectorClientSecret\" data-secret-display=\"mattermost-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"mattermost-status\" class=\"muted\"></p>\n <div id=\"mattermost-probe\" class=\"notice\" hidden></div>\n <div id=\"mattermost-drift\" class=\"notice\" hidden></div>\n <p>Redirect URIs:</p><ul id=\"mattermost-redirects\" class=\"uris\"></ul>\n <p class=\"muted\">Create an OAuth 2.0 application in Mattermost (System Console &rarr; Integrations &rarr; OAuth 2.0 Applications) with trusted client enabled and the redirect URIs above.</p>\n <div id=\"mattermost-config-controls\" class=\"subsection\">\n <label class=\"field\">Server URL<input id=\"mattermost-server-url-input\" autocomplete=\"off\" placeholder=\"https://mattermost.example.com\"></label>\n <label class=\"field\">Client ID<input id=\"mattermost-id\" autocomplete=\"off\"></label>\n <label id=\"mattermost-initial-secret-field\" class=\"field\">Client secret<input id=\"mattermost-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when Server URL or Client ID changes\"></label>\n </div>\n <div class=\"row\">\n <button id=\"probe-mattermost\">Check Server URL</button>\n <button id=\"save-mattermost\">Save and configure sign-in</button>\n <button id=\"cancel-mattermost-configuration\" hidden>Cancel</button>\n <button id=\"check-mattermost\" hidden>Check Logto</button>\n <button id=\"clear-mattermost\" class=\"danger\" hidden>Clear configuration</button>\n </div>\n </section>\n </div>\n\n <section id=\"options-section\" class=\"setup-section\">\n <h2>Deployment options</h2>\n <div class=\"panel\">\n <label class=\"field\"><span><input id=\"preset-agents-enabled\" type=\"checkbox\"> Enable preset Agents</span></label>\n <label class=\"field\">Max organizations created per non-ADMIN user<input id=\"max-orgs-per-non-admin-user\" type=\"number\" min=\"0\" step=\"1\" value=\"1\"></label>\n <label class=\"field\"><span><input id=\"organization-sso\" type=\"checkbox\"> Let organizations set up their own SSO</span></label>\n <div class=\"row\"><button id=\"save-options\">Save options</button></div>\n </div>\n </section>\n </section>\n </div>\n </div>\n </main>\n\n <script>\n const api = '/api/v1';\n const tokenKey = 'agentconnect.setup.token';\n const verifierKey = 'agentconnect.setup.pkce';\n const stateKey = 'agentconnect.setup.state';\n let currentRevision = 0;\n let currentStatus = null;\n let bootstrapInfo = null;\n const el = (id) => document.getElementById(id);\n const message = (text, error = false) => {\n const target = el('setup').hidden ? el('access-message') : el('message');\n target.textContent = text;\n target.className = error ? 'error' : 'ok';\n };\n const bearer = () => {\n const token = sessionStorage.getItem(tokenKey);\n return token ? { authorization: 'Bearer ' + token } : {};\n };\n const json = async (response) => {\n const body = await response.json().catch(() => ({}));\n if (!response.ok) throw Object.assign(new Error(body.message || ('HTTP ' + response.status)), { status: response.status, code: body.code });\n return body;\n };\n const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');\n const random = () => base64url(crypto.getRandomValues(new Uint8Array(32)));\n const configured = (byKey, key) => Boolean(byKey.get(key) && byKey.get(key).configured);\n const loginApps = ",
69113
+ ";\n\n function showIdentityEditors(provider, show) {\n for (const button of document.querySelectorAll('.edit-configuration[data-provider=\"' + provider + '\"]')) {\n button.hidden = !show;\n }\n }\n\n function text(id, value) {\n el(id).textContent = value === null || value === undefined || value === '' ? 'Not configured' : String(value);\n }\n\n function secretText(id, byKey, key, editable) {\n const stored = configured(byKey, key);\n const display = el(id);\n const button = document.querySelector('[data-secret-display=\"' + id + '\"]');\n const row = display.closest('.secret-line');\n const editor = row && row.querySelector('.secret-editor');\n if (editor) editor.remove();\n display.hidden = false;\n display.textContent = stored ? '***' : 'Not configured';\n display.className = stored ? 'redacted' : 'muted';\n button.hidden = !editable;\n button.textContent = stored ? 'Edit' : 'Set';\n }\n\n function match(id, state, label) {\n const target = el(id);\n target.textContent = label;\n target.className = 'badge' + (state ? ' ' + state : '');\n }\n\n async function authConfig() { return json(await fetch(api + '/auth-config')); }\n\n async function signIn() {\n const config = await authConfig();\n if (config.mode !== 'oidc') throw new Error('Save an OIDC configuration first');\n const verifier = random();\n const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));\n const state = random();\n sessionStorage.setItem(verifierKey, verifier);\n sessionStorage.setItem(stateKey, state);\n const url = new URL(config.authorizationEndpoint);\n url.searchParams.set('client_id', config.appId);\n url.searchParams.set('redirect_uri', config.redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', 'openid profile email roles');\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n if (config.resource) url.searchParams.set('resource', config.resource);\n if (config.ssoConnectorId) url.searchParams.set('direct_sign_in', 'sso:' + config.ssoConnectorId);\n location.assign(url);\n }\n\n async function finishSignIn() {\n const url = new URL(location.href);\n const code = url.searchParams.get('code');\n if (!code) return;\n const state = url.searchParams.get('state');\n if (!state || state !== sessionStorage.getItem(stateKey)) throw new Error('OIDC state mismatch');\n const verifier = sessionStorage.getItem(verifierKey);\n if (!verifier) throw new Error('PKCE verifier is missing; start sign-in again');\n const config = await authConfig();\n const body = new URLSearchParams({\n grant_type: 'authorization_code', code, client_id: config.appId,\n redirect_uri: config.redirectUri, code_verifier: verifier\n });\n if (config.resource) body.set('resource', config.resource);\n const tokens = await json(await fetch(config.tokenEndpoint, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body\n }));\n if (typeof tokens.id_token !== 'string') throw new Error('Logto did not return an ID token');\n sessionStorage.setItem(tokenKey, tokens.id_token);\n sessionStorage.removeItem(verifierKey);\n sessionStorage.removeItem(stateKey);\n history.replaceState({}, '', '/');\n }\n\n function renderUriList(id, values) {\n el(id).replaceChildren(...(values || []).map((value) => {\n const item = document.createElement('li');\n const code = document.createElement('code'); code.textContent = value;\n item.append(code); return item;\n }));\n }\n\n function updateBootstrapProvider() {\n const provider = el('bootstrap-provider').value;\n el('bootstrap-google').hidden = provider !== 'google';\n el('bootstrap-github').hidden = provider !== 'github';\n el('bootstrap-slack').hidden = provider !== 'slack';\n el('bootstrap-sso').hidden = provider !== 'sso';\n }\n\n // The SSO connector each form shows: the saved one in settings, the one just created during first-run setup.\n const ssoState = {};\n\n function ssoUrls(connector) {\n const base = ((bootstrapInfo && bootstrapInfo.logtoEndpoint) || '').replace(//+$/, '');\n const id = encodeURIComponent(connector.connectorId);\n return connector.protocol === 'oidc'\n ? ['Redirect URI: ' + base + '/callback/' + id]\n : ['ACS URL: ' + base + '/api/authn/single-sign-on/saml/' + id, 'SP entity ID: ' + base + '/enterprise-sso/' + id];\n }\n\n function renderSso(prefix, connector) {\n ssoState[prefix] = connector || undefined;\n if (connector) {\n el(prefix + '-protocol').value = connector.protocol;\n el(prefix + '-name').value = connector.name;\n el(prefix + '-domains').value = (connector.domains || []).join(', ');\n el(prefix + '-member-source').value = connector.memberSource || 'domain';\n renderMemberOrganizations(prefix, connector.memberOrganization || '');\n renderUriList(prefix + '-urls', ssoUrls(connector));\n const oidc = connector.oidc || {};\n el(prefix + '-issuer').value = oidc.issuer || '';\n el(prefix + '-client-id').value = oidc.clientId || '';\n el(prefix + '-scope').value = oidc.scope || '';\n el(prefix + '-trust-email').checked = connector.oidc ? oidc.trustUnverifiedEmail : true;\n const saml = connector.saml || {};\n el(prefix + '-metadata-url').value = saml.metadataUrl || '';\n el(prefix + '-metadata').value = saml.metadata || '';\n el(prefix + '-email-attribute').value = (saml.attributeMapping && saml.attributeMapping.email) || '';\n }\n updateSsoProtocol(prefix);\n }\n\n // The organizations new members may join; the empty value is the deployment's only one, and a saved id that is gone stays visible.\n let ssoOrganizations = [];\n function renderMemberOrganizations(prefix, selected) {\n const select = el(prefix + '-member-organization');\n select.replaceChildren();\n const option = (value, label) => {\n const item = document.createElement('option');\n item.value = value;\n item.textContent = label;\n select.append(item);\n };\n option('', 'The only organization');\n for (const org of ssoOrganizations) option(org.id, (org.name || org.slug) + ' (' + org.slug + ')');\n if (selected && !ssoOrganizations.some((org) => org.id === selected)) option(selected, 'Missing organization (' + selected + ')');\n select.value = selected;\n updateMemberOrganization(prefix);\n }\n\n function updateMemberOrganization(prefix) {\n el(prefix + '-member-organization').disabled = el(prefix + '-member-source').value === 'invite';\n }\n\n function updateSsoProtocol(prefix) {\n const connector = ssoState[prefix];\n const protocol = el(prefix + '-protocol').value;\n const current = Boolean(connector && connector.protocol === protocol);\n el(prefix + '-oidc').hidden = protocol !== 'oidc';\n el(prefix + '-saml').hidden = protocol !== 'saml';\n // Another protocol is another connector, so its details wait until it is created.\n el(prefix + '-details').hidden = !current;\n el(prefix + '-create').hidden = current;\n }\n\n async function createSso(prefix) {\n const name = el(prefix + '-name').value;\n const result = await json(await fetch(api + '/create/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ protocol: el(prefix + '-protocol').value, name })\n }));\n renderSso(prefix, { connectorId: result.connectorId, protocol: result.protocol, name, domains: [], memberSource: 'domain', oidc: null, saml: null });\n message('SSO connector created. Register its URLs with the identity provider, then enter the provider details.');\n }\n\n async function saveSso(prefix) {\n const protocol = el(prefix + '-protocol').value;\n const secret = el(prefix + '-client-secret').value;\n const metadataUrl = el(prefix + '-metadata-url').value.trim();\n const metadata = el(prefix + '-metadata').value.trim();\n const emailAttribute = el(prefix + '-email-attribute').value.trim();\n const connector = {\n name: el(prefix + '-name').value,\n domains: el(prefix + '-domains').value.split(',').map((domain) => domain.trim()).filter(Boolean),\n memberSource: el(prefix + '-member-source').value,\n memberOrganization: el(prefix + '-member-organization').value || null,\n ...(protocol === 'oidc'\n ? { oidc: {\n issuer: el(prefix + '-issuer').value.trim(),\n clientId: el(prefix + '-client-id').value.trim(),\n ...(secret ? { clientSecret: secret } : {}),\n scope: el(prefix + '-scope').value.trim(),\n trustUnverifiedEmail: el(prefix + '-trust-email').checked\n } }\n : { saml: {\n ...(metadataUrl ? { metadataUrl } : {}),\n ...(metadata ? { metadata } : {}),\n ...(emailAttribute ? { attributeMapping: { email: emailAttribute } } : {})\n } })\n };\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector })\n }));\n el(prefix + '-client-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n }\n\n async function removeSso() {\n if (!window.confirm('Remove SSO sign-in and delete its Logto connector? People who signed in through it lose that sign-in; their accounts stay.')) return;\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector: null })\n }));\n await reconcileLogto();\n await load();\n }\n\n function showBootstrapStep(step) {\n const logto = step === 'logto';\n el('bootstrap-logto-step').hidden = !logto;\n el('bootstrap-provider-step').hidden = logto;\n el('bootstrap-progress').textContent = logto ? 'Step 1 of 2' : 'Step 2 of 2';\n }\n\n function updateOwner(prefix) {\n el(prefix + '-org-field').hidden = el(prefix + '-owner').value !== 'organization';\n }\n\n function ownership(prefix) {\n if (el(prefix + '-owner').value === 'personal') return { owner: 'personal', organization: null };\n const organization = el(prefix + '-org').value.trim();\n if (!organization) throw new Error('Enter the GitHub organization login');\n return { owner: 'organization', organization };\n }\n\n function formatDiffValue(value) {\n if (value === null || value === undefined || value === '') return 'Not configured';\n if (Array.isArray(value)) return value.length ? value.map(formatDiffValue).join('\n') : '[]';\n if (typeof value === 'object') {\n return Object.entries(value).map(([key, item]) => key + ': ' + (Array.isArray(item) ? item.join(', ') : formatDiffValue(item))).join('\n');\n }\n return String(value);\n }\n\n function showDiff(id, rows, label = 'Update required') {\n const box = el(id);\n box.hidden = rows.length === 0;\n box.replaceChildren();\n if (rows.length === 0) return;\n const title = document.createElement('strong');\n title.className = 'diff-title';\n title.textContent = label;\n const grid = document.createElement('div');\n grid.className = 'config-diff';\n const head = document.createElement('div');\n head.className = 'diff-row diff-head';\n for (const text of ['Field', 'Current', 'Expected']) {\n const cell = document.createElement('span'); cell.textContent = text; head.append(cell);\n }\n grid.append(head);\n for (const item of rows) {\n const row = document.createElement('div'); row.className = 'diff-row';\n const field = document.createElement('span'); field.className = 'diff-field'; field.textContent = item.field;\n const current = document.createElement('span'); current.className = 'diff-value diff-current'; current.textContent = formatDiffValue(item.current);\n const expected = document.createElement('span'); expected.className = 'diff-value diff-expected'; expected.textContent = formatDiffValue(item.expected);\n row.append(field, current, expected); grid.append(row);\n }\n box.append(title, grid);\n }\n\n function renderStartupEnvironment() {\n const services = bootstrapInfo.services;\n const environment = [\n ['AGENTCONNECT_PUBLIC_CP_URL', services.controlPlane],\n ['AGENTCONNECT_PUBLIC_RELAY_URL', services.relay],\n ['AGENTCONNECT_PUBLIC_WEB_URL', services.web],\n ['LOGTO_ENDPOINT', bootstrapInfo.logtoEndpoint],\n ['LOGTO_MGMT_ENDPOINT', bootstrapInfo.logtoManagementEndpoint]\n ];\n el('startup-environment').textContent = environment\n .filter(([, value]) => value)\n .map(([key, value]) => key + '=' + value)\n .join('\n');\n }\n\n function renderApps(status) {\n currentStatus = status;\n const byKey = new Map((status.secrets || []).map((item) => [item.key, item]));\n const values = status.values;\n const expected = status.providerExpectations || { github: null, gitlab: null, slack: null, linear: null, googleChat: null, google: { origins: [], redirects: [] } };\n renderStartupEnvironment();\n\n const logto = values.logto;\n text('logto-management-endpoint', logto && bootstrapInfo.logtoManagementEndpoint);\n text('logto-management-id', logto && logto.managementAppId);\n text('logto-management-resource', logto && logto.managementResource);\n secretText('logto-management-secret-display', byKey, 'logto.managementAppSecret', Boolean(logto));\n const sso = logto && logto.ssoConnector;\n ssoOrganizations = status.organizations || [];\n renderSso('sso', sso);\n el('sso-remove').hidden = !sso;\n match('sso-match', !sso ? '' : sso.oidc || sso.saml ? 'pass' : 'warn', !sso ? 'Not configured' : sso.oidc || sso.saml ? 'Configured' : 'Needs identity provider');\n text('logto-browser-endpoint', logto && logto.browser && bootstrapInfo.logtoEndpoint);\n text('logto-browser-id', values.auth.mode === 'oidc' ? values.auth.browserClient.appId : null);\n text('logto-browser-resource', logto && logto.browser && logto.browser.apiResource);\n el('logto-edit-controls').hidden = true;\n showIdentityEditors('logto', Boolean(logto && logto.browser && values.auth.mode === 'oidc'));\n match(\n 'logto-match',\n logto && configured(byKey, 'logto.managementAppSecret') ? '' : 'warn',\n logto && configured(byKey, 'logto.managementAppSecret') ? 'Ready to check' : 'Not configured'\n );\n\n el('preset-agents-enabled').checked = values.features.presetAgentsEnabled;\n el('max-orgs-per-non-admin-user').value = String(values.features.maxOrgsPerNonAdminUser);\n el('organization-sso').checked = values.features.organizationSso === true;\n\n const github = values.github;\n const webhookStored = byKey.get('github.webhookSecret') && byKey.get('github.webhookSecret').configured;\n const webhookInactive = github && github.webhookEnabled === false;\n text('github-app-id', github && github.appId);\n text('github-app-slug', github && github.slug);\n text('github-client-id', github && github.clientId);\n text('github-webhook-enabled', github && (github.webhookEnabled === false ? 'Disabled' : 'Enabled'));\n el('github-edit-controls').hidden = true;\n showIdentityEditors('github', Boolean(github));\n secretText('github-client-secret-display', byKey, 'github.clientSecret', Boolean(github));\n secretText('github-private-key-display', byKey, 'github.privateKeyB64', Boolean(github));\n secretText('github-webhook-secret-display', byKey, 'github.webhookSecret', Boolean(github));\n secretText('github-logto-secret-display', byKey, 'logto.githubConnectorClientSecret', Boolean(values.logto && values.logto.githubConnector));\n el('github-status').textContent = github\n ? github.slug + ' is configured. Webhook secret: ' + (webhookStored ? 'stored' : webhookInactive ? 'not required yet' : 'missing') + '.' +\n (webhookInactive ? ' Relay webhook delivery is disabled.' : '')\n : 'Creates the complete App used for repository installation, webhooks, and optional GitHub sign-in.';\n const githubDrift = github\n ? expected.github\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'Valid Web, API, and ingress URLs' }]\n : [];\n match('github-match', !github ? '' : githubDrift.length ? 'warn' : '', !github ? 'Not configured' : githubDrift.length ? 'Expected URLs changed' : 'Ready to check');\n el('github-create-controls').hidden = Boolean(github);\n el('create-github').hidden = Boolean(github);\n el('clear-github').hidden = !github;\n el('connect-github-login').hidden = !github || !values.logto || Boolean(values.logto.githubConnector);\n el('check-github').hidden = !github;\n if (github) showDiff('github-drift', githubDrift, 'Expected URLs changed since App creation');\n else el('github-drift').hidden = true;\n\n const gitlab = values.gitlab;\n const gitlabSecret = configured(byKey, 'gitlab.clientSecret');\n const expectedGitlab = expected.gitlab;\n renderUriList('gitlab-callbacks', expectedGitlab ? [expectedGitlab.callbackUrl] : []);\n renderUriList('gitlab-scopes', expectedGitlab ? expectedGitlab.scopes : []);\n text('gitlab-client-id', gitlab && gitlab.clientId);\n secretText('gitlab-client-secret-display', byKey, 'gitlab.clientSecret', Boolean(gitlab));\n showIdentityEditors('gitlab', Boolean(gitlab));\n el('gitlab-id').value = gitlab ? gitlab.clientId : '';\n text('gitlab-instance', (gitlab && gitlab.baseUrl) || 'https://gitlab.com');\n // Host-aware application links (§24.1): composed by the server against the\n // configured base, so a path-prefixed install keeps its prefix here too.\n if (expectedGitlab) {\n el('gitlab-applications').href = expectedGitlab.applicationsUrl;\n el('gitlab-admin-applications').href = expectedGitlab.adminApplicationsUrl;\n }\n el('gitlab-base-url').value = (gitlab && gitlab.baseUrl) || '';\n el('gitlab-status').textContent = gitlab\n ? gitlab.clientId + ' is configured.'\n : expectedGitlab\n ? 'Register the OAuth application on the configured GitLab instance, then save its Application ID and Secret here.'\n : 'Publishing the redirect URI needs an HTTPS API public URL.';\n showDiff('gitlab-drift', gitlab && !expectedGitlab\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS API URL' }]\n : []);\n match('gitlab-match', gitlab && gitlabSecret ? 'warn' : '', !gitlab ? 'Not configured' : !gitlabSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('gitlab-initial-secret-field').hidden = Boolean(gitlab) && gitlabSecret;\n el('gitlab-config-controls').hidden = Boolean(gitlab);\n el('save-gitlab').hidden = Boolean(gitlab);\n el('cancel-gitlab-configuration').hidden = true;\n el('clear-gitlab').hidden = !gitlab;\n const gitlabLogin = values.logto?.browser?.socialProviders.includes('gitlab');\n renderUriList('gitlab-login-redirects', expected.gitlabSignIn?.redirects || []);\n el('gitlab-login-status').textContent = gitlabLogin ? 'GitLab sign-in is configured. Use Check Logto to verify it.' : 'GitLab sign-in is not enabled.';\n el('connect-gitlab-login').hidden = Boolean(gitlabLogin);\n el('connect-gitlab-login').disabled = !gitlab || !gitlabSecret || !values.logto?.browser;\n el('disconnect-gitlab-login').hidden = !gitlabLogin;\n el('check-gitlab-login').hidden = !gitlabLogin;\n\n const gitea = values.gitea;\n text('gitea-instance', (gitea && gitea.baseUrl) || 'https://gitea.com');\n el('gitea-base-url').value = (gitea && gitea.baseUrl) || '';\n showIdentityEditors('gitea', Boolean(gitea));\n el('gitea-status').textContent = gitea\n ? ((gitea.baseUrl || 'https://gitea.com') + ' is configured.')\n : 'Organizations can connect gitea.com without saving anything. Save an address only for a self-hosted instance.';\n match('gitea-match', gitea ? 'warn' : '', gitea ? \"Can't verify automatically\" : 'Default');\n el('gitea-config-controls').hidden = Boolean(gitea);\n el('save-gitea').hidden = Boolean(gitea);\n el('cancel-gitea-configuration').hidden = true;\n el('clear-gitea').hidden = !gitea;\n\n const slack = values.slack;\n text('slack-app-id', slack && slack.appId);\n text('slack-client-id', slack && slack.clientId);\n el('slack-edit-controls').hidden = true;\n showIdentityEditors('slack', Boolean(slack));\n secretText('slack-client-secret-display', byKey, 'slack.clientSecret', Boolean(slack));\n secretText('slack-signing-secret-display', byKey, 'slack.signingSecret', Boolean(slack));\n el('slack-logto-status').textContent = values.logto && values.logto.slackConnector\n ? 'Enabled; reuses the Slack client secret above.'\n : 'Not enabled.';\n el('slack-status').textContent = slack ? slack.appId + ' is configured.' : 'Creates the default AgentConnect integration manifest.';\n const slackDrift = slack\n ? expected.slack\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS Web, API, and ingress URLs' }]\n : [];\n match('slack-match', !slack ? '' : slackDrift.length ? 'warn' : '', !slack ? 'Not configured' : slackDrift.length ? 'Update required' : 'Ready to check');\n el('slack-name-field').hidden = Boolean(slack);\n el('create-slack').hidden = Boolean(slack);\n el('connect-slack-login').hidden = !slack || !values.logto || Boolean(values.logto.slackConnector) || !bootstrapInfo?.slackAvailable;\n el('clear-slack').hidden = !slack;\n el('check-slack').hidden = !slack;\n el('reconcile-slack').hidden = !slack;\n el('slack-settings').hidden = !slack;\n if (slack) {\n el('slack-settings').href = 'https://api.slack.com/apps/' + encodeURIComponent(slack.appId);\n showDiff('slack-drift', slackDrift);\n } else el('slack-drift').hidden = true;\n\n const googleChat = values.googleChat;\n const googleChatKey = configured(byKey, 'googleChat.serviceAccountKey');\n const expectedGoogleChat = expected.googleChat;\n renderUriList('googlechat-callbacks', expectedGoogleChat ? [expectedGoogleChat.callbackUrl] : []);\n text('googlechat-project-id', googleChat && googleChat.projectId);\n text('googlechat-project-number', googleChat && googleChat.projectNumber);\n el('googlechat-key-display').textContent = googleChatKey ? '***' : 'Not configured';\n el('googlechat-key-display').className = googleChatKey ? 'redacted' : 'muted';\n showIdentityEditors('googlechat', Boolean(googleChat));\n el('googlechat-project-id-input').value = googleChat ? googleChat.projectId : '';\n el('googlechat-project-number-input').value = googleChat ? googleChat.projectNumber : '';\n el('googlechat-key').value = '';\n if (expectedGoogleChat) el('googlechat-configuration').href = expectedGoogleChat.configurationUrl;\n el('googlechat-status').textContent = googleChat\n ? googleChat.projectId + ' is configured.'\n : expectedGoogleChat\n ? 'Configure the Chat app in Google Cloud Console, then save its project and service-account key here.'\n : 'Publishing the HTTP endpoint URL needs an HTTPS ingress public URL.';\n showDiff('googlechat-drift', googleChat && !expectedGoogleChat\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n match('googlechat-match', googleChat && googleChatKey ? 'pass' : googleChat ? 'warn' : '', !googleChat ? 'Not configured' : !googleChatKey ? 'Missing key' : 'Checked on save');\n el('googlechat-edit-heading').hidden = true;\n el('googlechat-config-controls').hidden = Boolean(googleChat);\n el('save-googlechat').hidden = Boolean(googleChat);\n el('cancel-googlechat-configuration').hidden = true;\n el('clear-googlechat').hidden = !googleChat;\n\n const email = values.email;\n const emailToken = configured(byKey, 'email.apiToken');\n const emailIngress = configured(byKey, 'email.ingressSecret');\n const expectedEmail = expected.email;\n renderUriList('email-inbound', expectedEmail ? [expectedEmail.inboundUrl] : []);\n text('email-mail-domain', email && email.mailDomain);\n text('email-account-id', email && email.accountId);\n text('email-send-limit', email && (email.dailySendLimit ? email.dailySendLimit : 'No deployment-wide limit'));\n for (const [id, stored] of [['email-token-display', emailToken], ['email-ingress-display', emailIngress]]) {\n el(id).textContent = stored ? '***' : 'Not configured';\n el(id).className = stored ? 'redacted' : 'muted';\n }\n showIdentityEditors('email', Boolean(email));\n el('email-mail-domain-input').value = email ? email.mailDomain : '';\n el('email-account-id-input').value = email ? email.accountId : '';\n el('email-send-limit-input').value = email && email.dailySendLimit ? String(email.dailySendLimit) : '';\n el('email-token').value = '';\n if (expectedEmail) el('email-dashboard').href = expectedEmail.dashboardUrl;\n el('email-status').textContent = email\n ? 'Agents get addresses on ' + email.mailDomain + '.'\n : expectedEmail\n ? 'Onboard the mail domain in Cloudflare, then save it with the account ID and an API token here.'\n : 'Publishing the inbound URL needs an HTTPS ingress public URL.';\n showDiff('email-drift', email && !expectedEmail\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n const emailReady = email && emailToken && emailIngress;\n match('email-match', emailReady ? 'pass' : email ? 'warn' : '', !email ? 'Not configured' : !emailReady ? 'Missing secret' : 'Checked on save');\n el('email-edit-heading').hidden = true;\n el('email-config-controls').hidden = Boolean(email);\n el('save-email').hidden = Boolean(email);\n el('cancel-email-configuration').hidden = true;\n // A status render never touches the secret box or a pending Replace: they belong to the operator's own clicks.\n if (!email) el('email-rotate-confirm').hidden = true;\n el('rotate-email-ingress').hidden = !email || !el('email-rotate-confirm').hidden;\n el('clear-email').hidden = !email;\n\n\n const linear = values.linear;\n const linearSecrets = configured(byKey, 'linear.clientSecret') && configured(byKey, 'linear.signingSecret');\n const expectedLinear = expected.linear;\n renderUriList('linear-callbacks', expectedLinear ? [expectedLinear.callbackUrl] : []);\n renderUriList('linear-webhooks', expectedLinear ? [expectedLinear.webhookUrl] : []);\n text('linear-client-id', linear && linear.clientId);\n secretText('linear-client-secret-display', byKey, 'linear.clientSecret', Boolean(linear));\n secretText('linear-signing-secret-display', byKey, 'linear.signingSecret', Boolean(linear));\n showIdentityEditors('linear', Boolean(linear));\n el('linear-id').value = linear ? linear.clientId : '';\n if (expectedLinear) el('linear-applications').href = expectedLinear.applicationsUrl;\n el('linear-status').textContent = linear\n ? linear.clientId + ' is configured.'\n : expectedLinear\n ? 'Register the OAuth application in Linear, then save its Client ID and both secrets here.'\n : 'Publishing the callback and webhook URLs needs HTTPS API and ingress public URLs.';\n showDiff('linear-drift', linear && !expectedLinear\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS API and ingress URLs' }]\n : []);\n match('linear-match', linear && linearSecrets ? 'warn' : '', !linear ? 'Not configured' : !linearSecrets ? 'Missing secret' : \"Can't verify automatically\");\n el('linear-initial-secret-fields').hidden = Boolean(linear) && linearSecrets;\n el('linear-config-controls').hidden = Boolean(linear);\n el('save-linear').hidden = Boolean(linear);\n el('cancel-linear-configuration').hidden = true;\n el('clear-linear').hidden = !linear;\n\n const google = values.logto && values.logto.googleConnector;\n const googleSecret = configured(byKey, 'logto.googleConnectorClientSecret');\n const expectedGoogle = expected.google;\n renderUriList('google-origins', expectedGoogle.origins);\n renderUriList('google-redirects', expectedGoogle.redirects);\n text('google-client-id', google && google.clientId);\n secretText('google-client-secret-display', byKey, 'logto.googleConnectorClientSecret', Boolean(google));\n showIdentityEditors('google', Boolean(google));\n el('google-id').value = google ? google.clientId : '';\n el('google-status').textContent = google ? 'Google OAuth client is configured.' : 'Create a Web application OAuth client manually, then save it here.';\n showDiff('google-drift', []);\n match('google-match', google && googleSecret ? 'warn' : '', !google ? 'Not configured' : !googleSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('google-initial-secret-field').hidden = googleSecret;\n el('save-google').textContent = google ? 'Confirm callback settings' : 'Save Google client';\n el('google-config-controls').hidden = Boolean(google);\n el('save-google').hidden = Boolean(google);\n el('cancel-google-configuration').hidden = true;\n el('check-google').hidden = !google || !googleSecret;\n el('clear-google').hidden = !google;\n\n for (const [provider, app] of Object.entries(loginApps)) {\n const saved = values.logto && values.logto[provider + 'Connector'];\n const secretKey = 'logto.' + provider + 'ConnectorClientSecret';\n const hasSecret = configured(byKey, secretKey);\n renderUriList(provider + '-redirects', expected[provider].redirects);\n text(provider + '-client-id', saved && saved.clientId);\n secretText(provider + '-client-secret-display', byKey, secretKey, Boolean(saved));\n showIdentityEditors(provider, Boolean(saved));\n el(provider + '-id').value = saved ? saved.clientId : '';\n el(provider + '-status').hidden = !saved;\n el(provider + '-status').textContent = saved ? app.name + ' login application is saved.' : '';\n showDiff(provider + '-drift', []);\n match(provider + '-match', saved ? 'warn' : '', !saved ? 'Not configured' : !hasSecret ? 'Missing secret' : 'Not checked');\n el(provider + '-initial-secret-field').hidden = hasSecret;\n el(provider + '-config-controls').hidden = Boolean(saved);\n el('save-' + provider).hidden = Boolean(saved);\n el('save-' + provider).disabled = !values.logto || !values.logto.browser;\n el('cancel-' + provider + '-configuration').hidden = true;\n el('check-' + provider).hidden = !saved || !hasSecret;\n el('clear-' + provider).hidden = !saved;\n }\n const expectedTeams = expected.msTeams;\n text('azuread-teams-tenant-id', values.msTeams && values.msTeams.tenantId);\n el('azuread-teams-tenant-input').value = values.msTeams ? values.msTeams.tenantId : '';\n renderUriList('azuread-teams-endpoint', expectedTeams ? [expectedTeams.messagingEndpoint] : []);\n renderUriList('azuread-teams-redirects', expectedTeams ? [expectedTeams.connectRedirectUri] : []);\n // Agent bots sit beside the Teams app: the group shows once it is configured, and its form until a blueprint is saved.\n const agentBots = values.msTeams && values.msTeams.agentBots;\n const blueprintSecret = configured(byKey, 'msTeams.blueprintClientSecret');\n el('azuread-agent-bots').hidden = !values.msTeams;\n text('azuread-agent-bots-blueprint', agentBots && agentBots.blueprintId);\n el('azuread-agent-bots-secret').textContent = blueprintSecret ? '***' : 'Not configured';\n el('azuread-agent-bots-secret').className = blueprintSecret ? 'redacted' : 'muted';\n text('azuread-agent-bots-subscription', agentBots && agentBots.subscriptionId);\n text('azuread-agent-bots-group', agentBots && agentBots.resourceGroup);\n el('azuread-agent-bots-controls').hidden = Boolean(agentBots);\n el('clear-azuread-agent-bots').hidden = !agentBots;\n renderUriList('azuread-azure-devops-redirects', expected.azureDevOps ? [expected.azureDevOps.connectRedirectUri] : []);\n\n const feishuSecret = byKey.get('feishu.loginAppSecret');\n const larkSecret = byKey.get('lark.loginAppSecret');\n el('feishu-login-id').value = values.feishu ? values.feishu.loginAppId : '';\n el('lark-login-id').value = values.lark ? values.lark.loginAppId : '';\n text('feishu-app-id', values.feishu && values.feishu.loginAppId);\n text('lark-app-id', values.lark && values.lark.loginAppId);\n showIdentityEditors('feishu', Boolean(values.feishu));\n showIdentityEditors('lark', Boolean(values.lark));\n secretText('feishu-app-secret-display', byKey, 'feishu.loginAppSecret', Boolean(values.feishu));\n secretText('lark-app-secret-display', byKey, 'lark.loginAppSecret', Boolean(values.lark));\n el('feishu-login-status').textContent = values.feishu && feishuSecret && feishuSecret.configured\n ? values.feishu.loginAppId + ' is configured.'\n : 'No Feishu tenant App is configured.';\n el('lark-login-status').textContent = values.lark && larkSecret && larkSecret.configured\n ? values.lark.loginAppId + ' is configured.'\n : 'No Lark tenant App is configured.';\n match('feishu-match', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? '' : '', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? 'Ready to check' : 'Not configured');\n match('lark-match', values.lark && configured(byKey, 'lark.loginAppSecret') ? '' : '', values.lark && configured(byKey, 'lark.loginAppSecret') ? 'Ready to check' : 'Not configured');\n showDiff('feishu-drift', []);\n showDiff('lark-drift', []);\n el('feishu-config-controls').hidden = Boolean(values.feishu);\n el('lark-config-controls').hidden = Boolean(values.lark);\n el('feishu-create-name-field').hidden = Boolean(values.feishu);\n el('lark-create-name-field').hidden = Boolean(values.lark);\n el('create-feishu-login-app').hidden = Boolean(values.feishu);\n el('create-lark-login-app').hidden = Boolean(values.lark);\n el('save-feishu-login-app').hidden = Boolean(values.feishu);\n el('save-lark-login-app').hidden = Boolean(values.lark);\n el('cancel-feishu-configuration').hidden = true;\n el('cancel-lark-configuration').hidden = true;\n el('clear-feishu').hidden = !values.feishu;\n el('clear-lark').hidden = !values.lark;\n el('check-feishu-login-app').hidden = !values.feishu || !configured(byKey, 'feishu.loginAppSecret');\n el('check-lark-login-app').hidden = !values.lark || !configured(byKey, 'lark.loginAppSecret');\n el('feishu-settings').hidden = !values.feishu;\n el('lark-settings').hidden = !values.lark;\n if (values.feishu) el('feishu-settings').href = 'https://open.feishu.cn/app/' + encodeURIComponent(values.feishu.loginAppId);\n if (values.lark) el('lark-settings').href = 'https://open.larksuite.com/app/' + encodeURIComponent(values.lark.loginAppId);\n\n const mattermost = values.logto && values.logto.mattermostConnector;\n const mattermostSecret = configured(byKey, 'logto.mattermostConnectorClientSecret');\n const expectedMattermost = expected.mattermostSignIn;\n renderUriList('mattermost-redirects', expectedMattermost ? expectedMattermost.redirects : []);\n text('mattermost-server-url', mattermost && mattermost.serverUrl);\n text('mattermost-client-id', mattermost && mattermost.clientId);\n secretText('mattermost-client-secret-display', byKey, 'logto.mattermostConnectorClientSecret', Boolean(mattermost));\n showIdentityEditors('mattermost', Boolean(mattermost));\n el('mattermost-server-url-input').value = mattermost ? mattermost.serverUrl : '';\n el('mattermost-id').value = mattermost ? mattermost.clientId : '';\n el('mattermost-status').hidden = !mattermost;\n el('mattermost-status').textContent = mattermost ? 'Mattermost sign-in OAuth application is saved.' : '';\n showDiff('mattermost-drift', []);\n match('mattermost-match', mattermost ? 'warn' : '', !mattermost ? 'Not configured' : !mattermostSecret ? 'Missing secret' : 'Not checked');\n el('mattermost-initial-secret-field').hidden = Boolean(mattermost) && mattermostSecret;\n el('mattermost-config-controls').hidden = Boolean(mattermost);\n el('save-mattermost').hidden = Boolean(mattermost);\n el('save-mattermost').disabled = !values.logto || !values.logto.browser;\n el('cancel-mattermost-configuration').hidden = true;\n el('check-mattermost').hidden = !mattermost || !mattermostSecret;\n el('clear-mattermost').hidden = !mattermost;\n }\n\n function requiredInput(id, label) {\n const value = el(id).value.trim();\n if (!value) throw new Error('Enter ' + label);\n return value;\n }\n\n function githubConnectorUsesDeployment(values) {\n const github = values.github;\n const connector = values.logto && values.logto.githubConnector;\n return Boolean(\n github && connector &&\n connector.appId === github.appId &&\n connector.slug === github.slug &&\n connector.clientId === github.clientId\n );\n }\n\n function beginConfigurationEdit(provider) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const values = currentStatus.values;\n if (provider === 'logto') {\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') return;\n el('logto-edit-management-id').value = logto.managementAppId;\n el('logto-edit-management-resource').value = logto.managementResource;\n el('logto-edit-management-secret').value = '';\n el('logto-edit-browser-id').value = values.auth.browserClient.appId;\n el('logto-edit-browser-resource').value = logto.browser.apiResource || '';\n el('logto-edit-controls').hidden = false;\n el('logto-edit-management-id').focus();\n } else if (provider === 'github') {\n const github = values.github;\n if (!github) return;\n el('github-edit-app-id').value = String(github.appId);\n el('github-edit-slug').value = github.slug;\n el('github-edit-client-id').value = github.clientId || '';\n el('github-edit-webhook-enabled').checked = github.webhookEnabled !== false;\n for (const id of ['github-edit-client-secret', 'github-edit-private-key', 'github-edit-webhook-secret', 'github-edit-logto-secret']) el(id).value = '';\n el('github-edit-logto-secret-field').hidden = !githubConnectorUsesDeployment(values);\n el('github-edit-controls').hidden = false;\n el('clear-github').hidden = true;\n el('github-edit-app-id').focus();\n } else if (provider === 'slack') {\n const slack = values.slack;\n if (!slack) return;\n el('slack-edit-app-id').value = slack.appId;\n el('slack-edit-client-id').value = slack.clientId;\n el('slack-edit-client-secret').value = '';\n el('slack-edit-signing-secret').value = '';\n el('slack-edit-controls').hidden = false;\n el('clear-slack').hidden = true;\n el('slack-edit-app-id').focus();\n } else if (provider === 'gitea') {\n if (!values.gitea) return;\n el('gitea-base-url').value = values.gitea.baseUrl || '';\n el('gitea-config-controls').hidden = false;\n el('save-gitea').hidden = false;\n el('cancel-gitea-configuration').hidden = false;\n el('clear-gitea').hidden = true;\n el('gitea-base-url').focus();\n } else if (provider === 'gitlab') {\n if (!values.gitlab) return;\n el('gitlab-id').value = values.gitlab.clientId;\n el('gitlab-secret').value = '';\n el('gitlab-config-controls').hidden = false;\n el('gitlab-initial-secret-field').hidden = false;\n el('save-gitlab').hidden = false;\n el('cancel-gitlab-configuration').hidden = false;\n el('clear-gitlab').hidden = true;\n el('gitlab-id').focus();\n } else if (provider === 'googlechat') {\n if (!values.googleChat) return;\n el('googlechat-project-id-input').value = values.googleChat.projectId;\n el('googlechat-project-number-input').value = values.googleChat.projectNumber;\n el('googlechat-key').value = '';\n el('googlechat-edit-heading').hidden = false;\n el('googlechat-config-controls').hidden = false;\n el('save-googlechat').hidden = false;\n el('cancel-googlechat-configuration').hidden = false;\n el('clear-googlechat').hidden = true;\n el('googlechat-project-id-input').focus();\n } else if (provider === 'email') {\n if (!values.email) return;\n el('email-mail-domain-input').value = values.email.mailDomain;\n el('email-account-id-input').value = values.email.accountId;\n el('email-send-limit-input').value = values.email.dailySendLimit ? String(values.email.dailySendLimit) : '';\n el('email-token').value = '';\n el('email-edit-heading').hidden = false;\n el('email-config-controls').hidden = false;\n el('save-email').hidden = false;\n el('cancel-email-configuration').hidden = false;\n el('rotate-email-ingress').hidden = true;\n el('email-rotate-confirm').hidden = true;\n el('clear-email').hidden = true;\n el('email-mail-domain-input').focus();\n } else if (provider === 'linear') {\n if (!values.linear) return;\n el('linear-id').value = values.linear.clientId;\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n el('linear-config-controls').hidden = false;\n el('linear-initial-secret-fields').hidden = false;\n el('save-linear').hidden = false;\n el('cancel-linear-configuration').hidden = false;\n el('clear-linear').hidden = true;\n el('linear-id').focus();\n } else if (provider === 'google') {\n const google = values.logto && values.logto.googleConnector;\n if (!google) return;\n el('google-id').value = google.clientId;\n el('google-secret').value = '';\n el('google-config-controls').hidden = false;\n el('google-initial-secret-field').hidden = false;\n el('save-google').hidden = false;\n el('save-google').textContent = 'Save Google client';\n el('cancel-google-configuration').hidden = false;\n el('clear-google').hidden = true;\n el('google-id').focus();\n } else if (Object.hasOwn(loginApps, provider)) {\n el(provider + '-secret').value = '';\n el(provider + '-config-controls').hidden = false;\n el(provider + '-initial-secret-field').hidden = false;\n el('save-' + provider).hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-id').focus();\n } else if (provider === 'mattermost') {\n const mattermost = values.logto && values.logto.mattermostConnector;\n if (!mattermost) return;\n el('mattermost-server-url-input').value = mattermost.serverUrl;\n el('mattermost-id').value = mattermost.clientId;\n el('mattermost-secret').value = '';\n el('mattermost-config-controls').hidden = false;\n el('mattermost-initial-secret-field').hidden = false;\n el('save-mattermost').hidden = false;\n el('cancel-mattermost-configuration').hidden = false;\n el('clear-mattermost').hidden = true;\n el('mattermost-server-url-input').focus();\n } else if (provider === 'feishu' || provider === 'lark') {\n el(provider + '-config-controls').hidden = false;\n el(provider + '-create-name-field').hidden = true;\n el('create-' + provider + '-login-app').hidden = true;\n el('save-' + provider + '-login-app').hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-login-secret').value = '';\n el(provider + '-login-id').focus();\n }\n showIdentityEditors(provider, false);\n }\n\n function cancelConfigurationEdit() {\n if (currentStatus) renderApps(currentStatus);\n }\n\n async function replaceConfiguration(values, secrets, successMessage) {\n const response = await json(await fetch(api + '/deployment-config', {\n method: 'PUT',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values, ...(secrets ? { secrets } : {}) })\n }));\n await load();\n message(successMessage || 'Configuration saved. Restart AgentConnect to apply it.');\n return response;\n }\n\n async function saveLogtoConfiguration() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') throw new Error('Logto is not configured');\n const managementAppId = requiredInput('logto-edit-management-id', 'the Management App ID');\n const managementResource = requiredInput('logto-edit-management-resource', 'the Management API resource');\n const browserAppId = requiredInput('logto-edit-browser-id', 'the SPA App ID');\n const browserResource = el('logto-edit-browser-resource').value.trim() || null;\n const managementIdentityChanged = managementAppId !== logto.managementAppId;\n const managementSecret = el('logto-edit-management-secret').value;\n if (managementIdentityChanged && !managementSecret) throw new Error('Enter the new Management App secret');\n const browser = { ...logto.browser, apiResource: browserResource };\n const auth = {\n ...values.auth,\n audience: browserResource || browserAppId,\n browserClient: { appId: browserAppId, apiResource: browserResource }\n };\n await replaceConfiguration(\n {\n ...values,\n auth,\n logto: { ...logto, managementAppId, managementResource, browser }\n },\n managementSecret ? { 'logto.managementAppSecret': managementSecret } : undefined,\n 'Logto configuration saved. Sign in again if the SPA identity changed, then restart AgentConnect.'\n );\n }\n\n async function saveGithubConfiguration() {\n if (!currentStatus || !currentStatus.values.github) throw new Error('GitHub is not configured');\n const values = currentStatus.values;\n const previous = values.github;\n const appId = Number(requiredInput('github-edit-app-id', 'the GitHub App ID'));\n if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error('GitHub App ID must be a positive integer');\n const slug = requiredInput('github-edit-slug', 'the GitHub App slug');\n const clientId = requiredInput('github-edit-client-id', 'the GitHub Client ID');\n const appChanged = appId !== previous.appId;\n const clientChanged = clientId !== previous.clientId;\n const webhookEnabled = el('github-edit-webhook-enabled').checked;\n const webhookEnabling = webhookEnabled && previous.webhookEnabled === false;\n const connectorReused = githubConnectorUsesDeployment(values);\n const clientSecret = el('github-edit-client-secret').value;\n const privateKey = el('github-edit-private-key').value.trim();\n const webhookSecret = el('github-edit-webhook-secret').value;\n const connectorSecret = el('github-edit-logto-secret').value;\n const webhookSecretStored = currentStatus.secrets.some((secret) => secret.key === 'github.webhookSecret' && secret.configured);\n if ((appChanged || clientChanged) && !clientSecret) throw new Error('Enter the new GitHub client secret');\n if (appChanged && !privateKey) throw new Error('Enter the new GitHub private key as base64');\n if (webhookEnabled && ((appChanged && !webhookSecret) || (webhookEnabling && !webhookSecret && !webhookSecretStored))) throw new Error('Enter the new GitHub webhook secret');\n if (connectorReused && (appChanged || clientChanged) && !connectorSecret) throw new Error('Enter the new Logto connector client secret');\n const secrets = {};\n if (clientSecret) secrets['github.clientSecret'] = clientSecret;\n if (privateKey) secrets['github.privateKeyB64'] = privateKey;\n if (webhookSecret) secrets['github.webhookSecret'] = webhookSecret;\n if (connectorSecret) secrets['logto.githubConnectorClientSecret'] = connectorSecret;\n const nextLogto = connectorReused && values.logto\n ? { ...values.logto, githubConnector: { ...values.logto.githubConnector, appId, slug, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n github: { ...previous, appId, slug, clientId, webhookEnabled },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'GitHub App identity saved. Restart AgentConnect to apply it.'\n );\n if (connectorSecret) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function saveSlackConfiguration() {\n if (!currentStatus || !currentStatus.values.slack) throw new Error('Slack is not configured');\n const values = currentStatus.values;\n const previous = values.slack;\n const appId = requiredInput('slack-edit-app-id', 'the Slack App ID');\n const clientId = requiredInput('slack-edit-client-id', 'the Slack Client ID');\n const changed = appId !== previous.appId || clientId !== previous.clientId;\n const clientSecret = el('slack-edit-client-secret').value;\n const signingSecret = el('slack-edit-signing-secret').value;\n if (changed && (!clientSecret || !signingSecret)) throw new Error('Enter both the new Slack client secret and signing secret');\n const secrets = {};\n if (clientSecret) secrets['slack.clientSecret'] = clientSecret;\n if (signingSecret) secrets['slack.signingSecret'] = signingSecret;\n const nextLogto = values.logto && values.logto.slackConnector\n ? { ...values.logto, slackConnector: { ...values.logto.slackConnector, appId, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n slack: { ...previous, appId, clientId },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'Slack App identity saved. Restart AgentConnect to apply it.'\n );\n if (clientSecret && nextLogto && nextLogto.slackConnector) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function clearProvider(provider) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const label = provider === 'github' ? 'GitHub' : provider === 'gitlab' ? 'GitLab' : provider === 'gitea' ? 'Gitea' : provider === 'slack' ? 'Slack' : provider === 'googlechat' ? 'Google Chat' : provider === 'email' ? 'Email' : provider === 'linear' ? 'Linear' : provider === 'google' ? 'Google' : provider === 'mattermost' ? 'Mattermost' : provider === 'feishu' ? 'Feishu' : 'Lark';\n if (!window.confirm('Clear the saved ' + label + ' configuration and secrets?')) return;\n const values = currentStatus.values;\n let next = values;\n let secrets = {};\n if (provider === 'github') {\n const connectorReused = githubConnectorUsesDeployment(values);\n const logto = connectorReused && values.logto\n ? {\n ...values.logto,\n githubConnector: null\n }\n : values.logto;\n next = { ...values, github: null, ...(logto ? { logto } : {}) };\n secrets = {\n 'github.clientSecret': null,\n 'github.privateKeyB64': null,\n 'github.webhookSecret': null,\n ...(connectorReused ? { 'logto.githubConnectorClientSecret': null } : {})\n };\n } else if (provider === 'gitea') {\n // Gitea holds no deployment secret, so clearing the address clears the whole entry.\n next = { ...values, gitea: null };\n } else if (provider === 'gitlab') {\n await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: null })\n }));\n showGitlabProbe(null);\n await load();\n message('GitLab configuration cleared. Its setup controls are available again.');\n return;\n } else if (provider === 'slack') {\n const logto = values.logto\n ? {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'slack') }\n : values.logto.browser,\n slackConnector: null\n }\n : values.logto;\n next = { ...values, slack: null, ...(logto ? { logto } : {}) };\n secrets = { 'slack.clientSecret': null, 'slack.signingSecret': null };\n } else if (provider === 'googlechat') {\n next = { ...values, googleChat: null };\n secrets = { 'googleChat.serviceAccountKey': null };\n } else if (provider === 'email') {\n next = { ...values, email: null };\n secrets = { 'email.apiToken': null, 'email.ingressSecret': null };\n } else if (provider === 'linear') {\n next = { ...values, linear: null };\n secrets = { 'linear.clientSecret': null, 'linear.signingSecret': null };\n } else if (provider === 'google') {\n if (!values.logto) return;\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'google') }\n : values.logto.browser,\n googleConnector: null\n }\n };\n secrets = { 'logto.googleConnectorClientSecret': null };\n } else if (provider === 'mattermost') {\n if (!values.logto || !values.logto.browser) return;\n const socialProviders = values.logto.browser.socialProviders.filter((item) => item !== 'mattermost');\n if (socialProviders.length === 0 && (!values.logto.ssoConnector || (!values.logto.ssoConnector.oidc && !values.logto.ssoConnector.saml))) {\n throw new Error('Keep at least one sign-in provider configured');\n }\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: { ...values.logto.browser, socialProviders },\n mattermostConnector: null\n }\n };\n secrets = { 'logto.mattermostConnectorClientSecret': null };\n } else if (provider === 'feishu' || provider === 'lark') {\n next = { ...values, [provider]: null };\n secrets = { [provider + '.loginAppSecret']: null };\n }\n await replaceConfiguration(next, secrets, label + ' configuration cleared. Its setup controls are available again.');\n if (provider === 'mattermost') {\n try { await reconcileLogto(false); } finally { await load(); }\n showMattermostProbe(null);\n }\n if (provider === 'gitea') el('gitea-probe').hidden = true;\n if (provider === 'email') showEmailIngressSecret('');\n }\n\n async function startGithub(prefix) {\n const result = await json(await fetch(api + '/create/github/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n purpose: 'deployment',\n name: el(prefix + '-name').value,\n ownership: ownership(prefix),\n connectLogto: prefix === 'bootstrap-github'\n })\n }));\n const form = document.createElement('form');\n form.method = 'post'; form.action = result.action;\n const manifest = document.createElement('input');\n manifest.type = 'hidden'; manifest.name = 'manifest'; manifest.value = JSON.stringify(result.manifest);\n form.append(manifest); document.body.append(form);\n message('Opening GitHub to review the complete integration App.');\n form.submit();\n }\n\n async function loadBootstrapInfo() {\n bootstrapInfo = await json(await fetch(api + '/bootstrap-info'));\n el('open-logto').href = bootstrapInfo.logtoAdminEndpoint;\n el('logto-settings').href = bootstrapInfo.logtoAdminEndpoint;\n if (!el('logto-app-id').value && bootstrapInfo.logtoManagementAppId) {\n el('logto-app-id').value = bootstrapInfo.logtoManagementAppId;\n }\n renderUriList('bootstrap-google-origins', bootstrapInfo.google.javascriptOrigins);\n renderUriList('bootstrap-google-redirects', bootstrapInfo.google.redirectUris);\n renderUriList('bootstrap-slack-redirects', [bootstrapInfo.slackLoginRedirectUrl]);\n el('logto-management-api-resource').value = bootstrapInfo.logtoManagementResource;\n el('bootstrap-github-submit').disabled = !bootstrapInfo.githubAvailable;\n if (!bootstrapInfo.githubAvailable) {\n el('bootstrap-github-note').textContent = 'GitHub App creation needs valid saved Web, API, and ingress URLs.';\n } else if (!bootstrapInfo.githubWebhookActive) {\n el('bootstrap-github-note').textContent = 'Creates the complete GitHub App now without submitting the localhost webhook URL. Add it after saving reachable HTTPS ingress.';\n } else {\n el('bootstrap-github-note').textContent = 'This creates one complete App for both GitHub sign-in and repository integration.';\n }\n el('bootstrap-slack-option').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-submit').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-note').textContent = bootstrapInfo.slackAvailable\n ? 'Creates one complete Slack App. Sign-in uses a separate openid profile email flow from workspace installation.'\n : 'Slack sign-in needs all public service URLs to use HTTPS. Use Google locally or expose the stack through trusted HTTPS endpoints.';\n if (!bootstrapInfo.slackAvailable && el('bootstrap-provider').value === 'slack') {\n el('bootstrap-provider').value = 'google';\n updateBootstrapProvider();\n }\n return bootstrapInfo;\n }\n\n async function logtoBootstrapFinding() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n for (const id of ['logto.client_credentials', 'logto.roles_read']) {\n const finding = report.findings.find((candidate) => candidate.id === id);\n if (!finding || finding.status !== 'pass') {\n return finding || { status: 'fail', message: 'Logto Management API permissions could not be verified.' };\n }\n }\n return { status: 'pass', message: 'Logto Management API access is ready.' };\n }\n\n async function showBootstrap() {\n el('bootstrap').hidden = false;\n el('show-bootstrap').hidden = true;\n const info = bootstrapInfo || await loadBootstrapInfo();\n if (!info.logtoConfigured) {\n showBootstrapStep('logto');\n return;\n }\n const finding = await logtoBootstrapFinding();\n if (finding && finding.status === 'pass') {\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n return;\n }\n showBootstrapStep('logto');\n message(finding?.message || 'Logto Management API credentials could not be verified.', true);\n }\n\n async function bootstrapLogto() {\n await json(await fetch(api + '/bootstrap/logto', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n managementAppId: el('logto-app-id').value,\n managementAppSecret: el('logto-app-secret').value,\n managementResource: el('logto-management-api-resource').value\n })\n }));\n el('logto-app-secret').value = '';\n await loadBootstrapInfo();\n const finding = await logtoBootstrapFinding();\n if (!finding || finding.status !== 'pass') {\n throw new Error(finding?.message || 'Logto Management API credentials could not be verified.');\n }\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n }\n\n async function bootstrapGoogle() {\n const secret = el('bootstrap-google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ clientId: el('bootstrap-google-id').value, clientSecret: secret })\n }));\n el('bootstrap-google-secret').value = '';\n await reconcileLogto(true);\n await load();\n }\n\n async function bootstrapGithub() {\n if (!bootstrapInfo || !bootstrapInfo.githubAvailable) throw new Error('GitHub App creation needs valid saved Web, API, and ingress URLs.');\n await startGithub('bootstrap-github');\n }\n\n async function bootstrapSlack() {\n if (!bootstrapInfo || !bootstrapInfo.slackAvailable) throw new Error('Slack sign-in requires all public service URLs to use HTTPS.');\n await createSlack('bootstrap-slack', true);\n await reconcileLogto();\n await load();\n }\n\n async function createSlack(prefix = 'slack', connectLogto = false) {\n const result = await json(await fetch(api + '/create/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n name: el(prefix + '-name').value,\n configToken: el(prefix + '-token').value,\n connectLogto\n })\n }));\n el(prefix + '-token').value = '';\n if (!connectLogto) await load();\n message('Slack App ' + result.app.id + ' was created with the default integration manifest. Restart AgentConnect to apply it.');\n }\n\n async function checkGithub() {\n const result = await json(await fetch(api + '/check/github', { headers: bearer() }));\n el('github-settings').href = result.settingsUrl;\n el('github-settings').hidden = false;\n const label = result.missing.length ? 'Update required' : \"Can't verify automatically\";\n showDiff('github-drift', result.diff || [], label);\n match('github-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : label);\n message(result.status === 'pass' ? 'GitHub App matches the expected integration manifest.' : result.missing.length ? 'GitHub App settings need an update.' : \"GitHub can't expose callback, setup, or webhook-active settings through its API; check them in GitHub.\", result.status === 'fail');\n }\n\n async function connectGithubLogin() {\n await json(await fetch(api + '/configure/github-login', { method: 'POST', headers: bearer() }));\n await reconcileLogto();\n await load();\n message('The deployment GitHub App is now also used for Logto sign-in. Update its displayed callback URLs.');\n }\n\n async function connectSlackLogin() {\n if (!currentStatus || !currentStatus.values.slack || !currentStatus.values.logto) {\n throw new Error('Save the Slack App and Logto configuration first');\n }\n const values = currentStatus.values;\n const slack = values.slack;\n const logto = values.logto;\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...logto,\n browser: logto.browser\n ? { ...logto.browser, socialProviders: [...new Set([...logto.browser.socialProviders, 'slack'])] }\n : logto.browser,\n slackConnector: {\n appId: slack.appId,\n clientId: slack.clientId\n }\n }\n },\n undefined,\n 'Slack App is ready to connect to Logto.'\n );\n await reconcileLogto();\n await load();\n message('The deployment Slack App is now also used for Logto sign-in.');\n }\n\n async function checkSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/check/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(result.status === 'pass' ? 'Slack App matches the default integration manifest.' : 'Slack App settings need an update.', result.status !== 'pass');\n }\n\n async function reconcileSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/reconcile/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(\n result.status !== 'pass'\n ? 'Slack App was updated but some settings still differ.'\n : result.applied.length === 0\n ? 'Slack App already matches the default integration manifest.'\n : result.permissionsUpdated\n ? 'Slack App updated. Reinstall it in each workspace to grant the added scopes.'\n : 'Slack App updated.',\n result.status !== 'pass'\n );\n }\n\n async function checkGoogle() {\n const report = await checkLogto();\n const connector = report.findings.find((finding) => finding.id === 'logto.connectors');\n const google = currentStatus && currentStatus.values.logto && currentStatus.values.logto.googleConnector;\n const connectorDiff = connector && connector.diff\n ? connector.diff.filter((item) => item.field.toLowerCase().startsWith('google'))\n : [];\n const passed = Boolean(google && connector && connectorDiff.length === 0);\n showDiff('google-drift', connectorDiff);\n match('google-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Update required');\n message(\n passed\n ? \"The Logto Google connector matches. Google OAuth redirect settings can't be verified automatically.\"\n : 'The Logto Google connector needs an update.',\n !passed\n );\n }\n\n async function checkRegionalLoginApp(region) {\n const result = await json(await fetch(api + '/check/regional-login-app/' + region, { headers: bearer() }));\n const label = region === 'feishu' ? 'Feishu' : 'Lark';\n showDiff(region + '-drift', result.diff || []);\n match(region + '-match', result.status === 'pass' ? 'pass' : result.status === 'fail' ? 'fail' : 'warn', result.status === 'pass' ? 'Matches' : result.status === 'fail' ? 'Update required' : 'Could not check');\n el(region + '-login-status').textContent = result.message;\n el(region + '-login-status').className = result.status === 'pass' ? 'ok' : result.status === 'fail' ? 'warn' : 'muted';\n message(result.message || (label + ' credential check completed.'), result.status === 'fail');\n }\n\n async function saveGitlab() {\n const clientSecret = el('gitlab-secret').value;\n const baseUrl = el('gitlab-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('gitlab-id', 'the GitLab Application ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(baseUrl ? { baseUrl } : {})\n }\n })\n }));\n el('gitlab-secret').value = '';\n if (currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) await reconcileLogto(Boolean(clientSecret));\n await load();\n showGitlabProbe(saved.probe);\n message('GitLab OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n // Only the URL shape blocks the save, so every other verdict is a line to read.\n function showGitlabProbe(probe) {\n const line = el('gitlab-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function configureGitlabLogin(enabled) {\n await json(await fetch(api + '/configure/gitlab-login', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ enabled })\n }));\n try { await reconcileLogto(enabled); } finally { await load(); }\n message('GitLab sign-in ' + (enabled ? 'configured' : 'disabled') + '. Restart AgentConnect to apply it.');\n }\n\n async function saveGitea() {\n const baseUrl = el('gitea-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitea', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ instance: { ...(baseUrl ? { baseUrl } : {}) } })\n }));\n await load();\n // Shape and the version floor already blocked the save, so any verdict here is a line to read.\n const line = el('gitea-probe');\n line.hidden = !saved.probe;\n line.textContent = saved.probe ? saved.probe.message : '';\n message('Gitea instance saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogleChat() {\n const projectNumber = el('googlechat-project-number-input').value.trim();\n const application = {\n projectId: requiredInput('googlechat-project-id-input', 'the Google Cloud project ID'),\n ...(projectNumber ? { projectNumber } : {})\n };\n const serviceAccountKey = el('googlechat-key').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/google-chat', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: { ...application, ...(serviceAccountKey ? { serviceAccountKey } : {}) } })\n }));\n } finally {\n // The key never stays in the page once it has been submitted, whatever the outcome.\n el('googlechat-key').value = '';\n }\n await load();\n message('Google Chat app saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n }\n\n async function saveEmail(rotateIngressSecret) {\n const stored = currentStatus && currentStatus.values.email;\n const limit = rotateIngressSecret\n ? (stored && stored.dailySendLimit ? String(stored.dailySendLimit) : '')\n : el('email-send-limit-input').value.trim();\n if (limit && !/^[1-9][0-9]*$/.test(limit)) throw new Error('Enter the daily send limit as a whole number, or leave it empty.');\n const apiToken = rotateIngressSecret ? '' : el('email-token').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/email', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n email: {\n mailDomain: rotateIngressSecret ? stored.mailDomain : requiredInput('email-mail-domain-input', 'the mail domain'),\n accountId: rotateIngressSecret ? stored.accountId : requiredInput('email-account-id-input', 'the Cloudflare account ID'),\n dailySendLimit: limit ? Number(limit) : null,\n ...(apiToken ? { apiToken } : {}),\n ...(rotateIngressSecret ? { rotateIngressSecret: true } : {})\n }\n })\n }));\n } finally {\n // The token never stays in the page once it has been submitted, whatever the outcome.\n el('email-token').value = '';\n }\n // The response alone fills the secret box, so no render that follows can take it away.\n showEmailIngressSecret(saved.ingressSecret);\n message('Email saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n await refreshDeploymentConfig();\n }\n\n function showEmailIngressSecret(secret) {\n el('email-ingress-secret').textContent = secret || '';\n el('email-ingress-once').hidden = !secret;\n }\n\n async function copyEmailIngressSecret() {\n await navigator.clipboard.writeText(el('email-ingress-secret').textContent);\n message('Ingress secret copied.');\n }\n\n function confirmEmailIngressRotation(open) {\n el('email-rotate-confirm').hidden = !open;\n el('rotate-email-ingress').hidden = open;\n if (open) el('cancel-rotate-email-ingress').focus();\n }\n\n async function saveLinear() {\n const clientSecret = el('linear-client-secret').value;\n const signingSecret = el('linear-signing-secret').value;\n await json(await fetch(api + '/configure/linear', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('linear-id', 'the Linear Client ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(signingSecret ? { signingSecret } : {})\n }\n })\n }));\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n await load();\n message('Linear OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n function showMattermostProbe(probe) {\n const line = el('mattermost-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function probeMattermost() {\n const serverUrl = el('mattermost-server-url-input').value.trim();\n const probe = await json(await fetch(api + '/check/mattermost', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify(serverUrl ? { serverUrl } : {})\n }));\n showMattermostProbe(probe);\n message(probe.ok ? 'Mattermost instance reachable.' : probe.message, !probe.ok);\n return probe;\n }\n\n async function saveMattermost() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n if (!values.logto || !values.logto.browser) throw new Error('Save Logto configuration before Mattermost sign-in');\n const serverUrl = requiredInput('mattermost-server-url-input', 'the Mattermost server URL').replace(//+$/, '');\n const clientId = requiredInput('mattermost-id', 'the Mattermost Client ID');\n const clientSecret = el('mattermost-secret').value;\n const probe = await json(await fetch(api + '/check/mattermost', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ serverUrl })\n }));\n showMattermostProbe(probe);\n if (probe.blocksSave) throw new Error(probe.message);\n const normalizedUrl = probe.serverUrl || serverUrl;\n const existing = values.logto.mattermostConnector;\n const existingUrl = existing && existing.serverUrl ? existing.serverUrl.replace(//+$/, '') : undefined;\n if (!clientSecret && (!existing || existing.clientId !== clientId || existingUrl !== normalizedUrl)) {\n throw new Error('Enter the Mattermost OAuth client secret');\n }\n el('mattermost-secret').value = '';\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...values.logto,\n browser: {\n ...values.logto.browser,\n socialProviders: [...new Set([...values.logto.browser.socialProviders, 'mattermost'])]\n },\n mattermostConnector: { serverUrl: normalizedUrl, clientId }\n }\n },\n clientSecret ? { 'logto.mattermostConnectorClientSecret': clientSecret } : undefined,\n 'Mattermost OAuth configuration saved. Restart AgentConnect to apply it.'\n );\n try {\n await reconcileLogto(Boolean(clientSecret));\n } finally {\n await load();\n showMattermostProbe(probe);\n }\n message('Mattermost sign-in and Logto connector configured. Restart AgentConnect to apply the saved settings.');\n }\n\n async function saveGoogle() {\n const secret = el('google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n clientId: el('google-id').value,\n ...(secret ? { clientSecret: secret } : {})\n })\n }));\n el('google-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n message('Google OAuth client and Logto connector are configured. Restart AgentConnect to apply the saved settings.');\n }\n\n // Agent bots (teams-integration.md §8.6.3): 'create' makes the blueprint through Graph, 'save' takes one entered by hand, 'clear' turns them off.\n async function saveAgentBots(mode) {\n if (mode === 'clear' && !window.confirm('Clear the saved blueprint and its secret? Agents that already have a bot of their own stop answering in Teams.')) return;\n const azure = mode === 'clear' ? {} : {\n subscriptionId: requiredInput('azuread-agent-bots-subscription-input', 'the Azure subscription ID'),\n resourceGroup: requiredInput('azuread-agent-bots-group-input', 'the resource group')\n };\n let saved;\n try {\n if (mode === 'create') {\n const operator = requiredInput('azuread-agent-bots-operator-input', 'your Microsoft Entra user');\n saved = await json(await fetch(api + '/configure/msteams-agent-bots/blueprint', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ operator, ...azure })\n }));\n } else {\n const clientSecret = el('azuread-agent-bots-secret-input').value;\n const agentBots = mode === 'clear' ? null : {\n blueprintId: requiredInput('azuread-agent-bots-blueprint-input', 'the blueprint ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...azure\n };\n saved = await json(await fetch(api + '/configure/msteams-agent-bots', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ agentBots })\n }));\n }\n } finally {\n // The secret never stays in the page once it has been submitted, whatever the outcome.\n el('azuread-agent-bots-secret-input').value = '';\n }\n await load();\n if (mode === 'clear') return message('Agent bots cleared. Restart AgentConnect to apply the saved settings.');\n const settling = mode === 'create' && saved.check !== 'ok';\n message('Blueprint ' + saved.blueprintId + ' saved.' + (settling ? ' Its new secret was not accepted yet; give Microsoft a minute before you restart.' : '') + ' Restart AgentConnect to apply the saved settings.' + (mode === 'create' ? ' You may now remove the three Graph permissions from the application.' : ''));\n }\n\n async function saveLoginApp(provider, clear = false) {\n const app = loginApps[provider];\n if (clear && !window.confirm('Clear the saved ' + app.name + ' login application and secret?')) return;\n const clientSecret = el(provider + '-secret').value;\n const application = clear ? null : {\n clientId: requiredInput(provider + '-id', 'the ' + app.name + ' Client ID'),\n ...(clientSecret ? { clientSecret } : {})\n };\n // Microsoft's home tenant also makes the app the deployment's Teams app; empty turns that off.\n const teams = provider === 'azuread' && !clear ? { teamsTenantId: el('azuread-teams-tenant-input').value.trim() || null } : {};\n try {\n await json(await fetch(api + '/configure/login-app/' + provider, {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application, ...teams })\n }));\n } finally {\n el(provider + '-secret').value = '';\n }\n try {\n await reconcileLogto(Boolean(clientSecret) && !clear);\n } finally {\n await load();\n }\n message(app.name + (clear ? ' sign-in configuration cleared.' : ' login application and Logto connector configured.') + ' Restart AgentConnect to apply the saved settings.');\n }\n\n function renderLoginAppChecks(report) {\n const connectors = report.findings.find((finding) => finding.id === 'logto.connectors');\n if (currentStatus?.values.logto?.browser?.socialProviders.includes('gitlab')) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('gitlab')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n el('gitlab-login-status').textContent = passed\n ? 'GitLab connector matches. Confirm the redirect URLs and OpenID scopes in GitLab.'\n : 'GitLab sign-in could not be verified. Review the Logto check above.';\n }\n for (const [provider, app] of Object.entries(loginApps)) {\n if (!currentStatus?.values.logto?.[provider + 'Connector']) continue;\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith(provider)) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff(provider + '-drift', diff);\n match(provider + '-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el(provider + '-status').textContent = passed\n ? app.name + ' connector matches. Confirm the redirect URLs in the provider settings.'\n : app.name + ' connector could not be verified. Review the Logto check above.';\n }\n if (currentStatus?.values.logto?.mattermostConnector) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('mattermost')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff('mattermost-drift', diff);\n match('mattermost-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el('mattermost-status').textContent = passed\n ? 'Mattermost connector matches. Confirm the redirect URIs in Mattermost OAuth settings.'\n : 'Mattermost connector could not be verified. Review the Logto check above.';\n }\n }\n\n function regionalLoginApp(prefix) {\n const appId = el(prefix + '-login-id').value.trim();\n const appSecret = el(prefix + '-login-secret').value;\n return appId ? { appId, ...(appSecret ? { appSecret } : {}) } : null;\n }\n\n async function saveRegionalLoginApp(region) {\n const app = regionalLoginApp(region);\n if (!app) throw new Error('Enter the ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App ID');\n await json(await fetch(api + '/configure/regional-login-app', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, app })\n }));\n el(region + '-login-secret').value = '';\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' tenant App is saved. Restart AgentConnect services to apply it.');\n }\n\n async function createRegionalLoginApp(region) {\n const popup = window.open('about:blank', '_blank');\n try {\n const started = await json(await fetch(api + '/create/regional-login-app/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, name: el(region + '-create-name').value })\n }));\n if (popup) popup.location.replace(started.authorizationUrl);\n else window.open(started.authorizationUrl, '_blank', 'noopener');\n message('Approve the new ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App in the opened page. This page will finish saving it automatically.');\n while (true) {\n const result = await json(await fetch(api + '/create/regional-login-app/' + encodeURIComponent(started.id), { headers: bearer() }));\n if (result.status === 'completed') {\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' App ' + result.appId + ' was created and saved. Restart AgentConnect services to apply it.');\n return;\n }\n if (result.status === 'failed') throw new Error('Regional App creation ' + result.reason + '. Start it again.');\n await new Promise((resolve) => setTimeout(resolve, Math.max(500, Math.min(result.retryAfterMs || 2000, 5000))));\n }\n } catch (error) {\n if (popup) popup.close();\n throw error;\n }\n }\n\n async function reconcileLogto(refreshConnectorSecrets) {\n return json(await fetch(api + '/reconcile/logto', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ refreshConnectorSecrets: Boolean(refreshConnectorSecrets) })\n }));\n }\n\n async function refreshDeploymentConfig() {\n const status = await json(await fetch(api + '/deployment-config', { headers: bearer() }));\n el('access').hidden = true;\n el('setup').hidden = false;\n el('editor').hidden = false;\n currentRevision = status.revision;\n renderApps(status);\n return status;\n }\n\n async function checkLogto() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n await refreshDeploymentConfig();\n const failures = report.findings.filter((finding) => finding.status !== 'pass');\n el('logto-status').textContent = failures.length === 0\n ? 'SPA redirects, connectors, and social-only sign-in match.'\n : failures.map((finding) => finding.message).join(' ');\n el('logto-status').className = failures.length === 0 ? 'ok' : 'warn';\n match('logto-match', failures.length === 0 ? 'pass' : 'warn', failures.length === 0 ? 'Matches' : 'Update required');\n showDiff(\n 'logto-drift',\n failures.flatMap((finding) => finding.diff && finding.diff.length\n ? finding.diff\n : [{ field: finding.id.replace(/^logto./, '').replaceAll('_', ' '), current: finding.message, expected: 'Matches expected configuration' }])\n );\n el('logto-settings').hidden = failures.length === 0;\n renderLoginAppChecks(report);\n return report;\n }\n\n function githubNotice(value) {\n if (value === 'deployment-created') return 'GitHub integration App created. Its private key and webhook secret are stored.';\n if (value === 'deployment-login-created') return 'GitHub integration App created and connected to Logto sign-in.';\n if (value === 'cancelled') return 'GitHub App creation was cancelled.';\n if (value === 'expired') return 'GitHub App creation expired. Start it again.';\n if (value === 'invalid-callback') return 'GitHub returned an invalid App creation callback.';\n if (value === 'conversion-failed') return 'GitHub may have created the App, but did not return complete credentials. Delete the orphaned App and retry.';\n if (value === 'save-failed') return 'GitHub created the App, but its credentials could not be saved. Delete the orphaned App and retry.';\n return '';\n }\n\n async function load() {\n let publicAuth = await authConfig();\n const currentUrl = new URL(location.href);\n const githubResult = currentUrl.searchParams.get('github');\n const notice = githubNotice(githubResult);\n if (githubResult === 'deployment-login-created' && publicAuth.mode === 'none') {\n await reconcileLogto();\n publicAuth = await authConfig();\n }\n if (githubResult) history.replaceState({}, '', '/');\n const hasToken = Boolean(sessionStorage.getItem(tokenKey));\n el('access').hidden = false;\n el('setup').hidden = true;\n el('login').hidden = true;\n el('open-logto').hidden = true;\n el('show-bootstrap').hidden = true;\n el('editor').hidden = true;\n el('bootstrap').hidden = true;\n if (publicAuth.logtoAdminEndpoint) {\n el('open-logto').href = publicAuth.logtoAdminEndpoint;\n el('logto-settings').href = publicAuth.logtoAdminEndpoint;\n }\n if (publicAuth.mode === 'none') {\n sessionStorage.removeItem(tokenKey);\n await loadBootstrapInfo();\n el('open-logto').hidden = false;\n el('show-bootstrap').hidden = false;\n message(notice || 'Logto sign-in is not configured. Set up the initial Logto administrator first.');\n return;\n }\n if (publicAuth.mode === 'unavailable') {\n el('open-logto').hidden = false;\n message(publicAuth.message || 'Logto sign-in is unavailable. Open Logto Console to review its settings.', true);\n return;\n }\n if (!hasToken) {\n el('login').hidden = false;\n message(notice || 'Sign in with Logto to continue.');\n return;\n }\n if (publicAuth.claimAvailable) {\n try {\n await json(await fetch(api + '/bootstrap/claim', { method: 'POST', headers: bearer() }));\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('This first user is now an ADMIN. Sign in again to refresh the role claim.');\n return;\n } catch (error) {\n if (error.status !== 401 && error.status !== 403) throw error;\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with Logto to continue.', true);\n return;\n }\n }\n try {\n await loadBootstrapInfo();\n await refreshDeploymentConfig();\n message(notice);\n checkLogto().catch((error) => {\n el('logto-status').textContent = error.message;\n el('logto-status').className = 'warn';\n el('logto-settings').hidden = false;\n });\n } catch (error) {\n if (error.status === 401 || error.status === 403) {\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with a Logto ADMIN account.', true);\n }\n else throw error;\n }\n }\n\n async function saveSecretReplacement(key, value) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n if (!value) throw new Error('Enter the replacement secret');\n const refreshLogto =\n (key === 'gitlab.clientSecret' && currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) ||\n (key === 'logto.githubConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.githubConnector) ||\n (key === 'logto.googleConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.googleConnector) ||\n Object.keys(loginApps).some((provider) => key === 'logto.' + provider + 'ConnectorClientSecret' && currentStatus.values.logto?.[provider + 'Connector']) ||\n (key === 'slack.clientSecret' && currentStatus.values.logto && currentStatus.values.logto.slackConnector);\n await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values: currentStatus.values, secrets: { [key]: value } })\n }));\n try {\n if (refreshLogto) await reconcileLogto(true);\n } finally {\n await load();\n }\n if (refreshLogto) {\n message('Secret replaced and applied to the Logto connector. Restart AgentConnect to apply deployment changes.');\n } else {\n message('Secret replaced. Restart AgentConnect to apply it.');\n }\n }\n\n function editSecret(button) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const row = button.closest('.secret-line');\n const display = el(button.dataset.secretDisplay);\n if (!row || !display || row.querySelector('.secret-editor')) return;\n const editor = document.createElement('span'); editor.className = 'secret-editor';\n const input = document.createElement('input');\n input.type = 'password'; input.autocomplete = 'new-password'; input.placeholder = 'Enter replacement secret';\n const save = document.createElement('button'); save.textContent = 'Save';\n const cancel = document.createElement('button'); cancel.textContent = 'Cancel';\n const close = () => { editor.remove(); display.hidden = false; button.hidden = false; };\n save.onclick = async () => {\n save.disabled = true;\n try { await saveSecretReplacement(button.dataset.secretKey, input.value); }\n catch (error) { save.disabled = false; message(error.message, true); }\n };\n cancel.onclick = close;\n input.onkeydown = (event) => { if (event.key === 'Enter') save.click(); if (event.key === 'Escape') close(); };\n display.hidden = true; button.hidden = true;\n editor.append(input, save, cancel); row.append(editor); input.focus();\n }\n\n async function saveOptions() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = {\n ...currentStatus.values,\n features: {\n presetAgentsEnabled: el('preset-agents-enabled').checked,\n maxOrgsPerNonAdminUser: Number(el('max-orgs-per-non-admin-user').value),\n organizationSso: el('organization-sso').checked\n }\n };\n const saved = await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values })\n }));\n try {\n if (currentStatus.values.auth.mode === 'oidc') await reconcileLogto();\n } catch (error) {\n await load();\n throw new Error('Saved deployment options, but Logto was not updated: ' + error.message);\n }\n message('Saved deployment options. Restart AgentConnect to apply them.');\n await load();\n }\n\n el('login').onclick = () => signIn().catch((error) => message(error.message, true));\n el('show-bootstrap').onclick = () => showBootstrap().catch((error) => message(error.message, true));\n el('bootstrap-provider').onchange = updateBootstrapProvider;\n el('bootstrap-github-owner').onchange = () => updateOwner('bootstrap-github');\n el('github-owner').onchange = () => updateOwner('github');\n el('bootstrap-logto-submit').onclick = () => bootstrapLogto().catch((error) => message(error.message, true));\n el('bootstrap-back').onclick = () => showBootstrapStep('logto');\n el('bootstrap-google-submit').onclick = () => bootstrapGoogle().catch((error) => message(error.message, true));\n for (const prefix of ['bootstrap-sso', 'sso']) {\n el(prefix + '-protocol').onchange = () => updateSsoProtocol(prefix);\n el(prefix + '-member-source').onchange = () => updateMemberOrganization(prefix);\n el(prefix + '-create').onclick = () => createSso(prefix).catch((error) => message(error.message, true));\n el(prefix + '-submit').onclick = () => saveSso(prefix).catch((error) => message(error.message, true));\n }\n el('sso-remove').onclick = () => removeSso().catch((error) => message(error.message, true));\n el('bootstrap-github-submit').onclick = () => bootstrapGithub().catch((error) => message(error.message, true));\n el('bootstrap-slack-submit').onclick = () => bootstrapSlack().catch((error) => message(error.message, true));\n el('create-github').onclick = () => startGithub('github').catch((error) => message(error.message, true));\n el('save-logto-configuration').onclick = () => saveLogtoConfiguration().catch((error) => message(error.message, true));\n el('cancel-logto-configuration').onclick = cancelConfigurationEdit;\n el('save-github-configuration').onclick = () => saveGithubConfiguration().catch((error) => message(error.message, true));\n el('cancel-github-configuration').onclick = cancelConfigurationEdit;\n el('clear-github').onclick = () => clearProvider('github').catch((error) => message(error.message, true));\n el('connect-github-login').onclick = () => connectGithubLogin().catch((error) => message(error.message, true));\n el('connect-gitlab-login').onclick = () => configureGitlabLogin(true).catch((error) => message(error.message, true));\n el('disconnect-gitlab-login').onclick = () => configureGitlabLogin(false).catch((error) => message(error.message, true));\n el('check-gitlab-login').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-github').onclick = () => checkGithub().catch((error) => message(error.message, true));\n el('create-slack').onclick = () => createSlack('slack').catch((error) => message(error.message, true));\n el('connect-slack-login').onclick = () => connectSlackLogin().catch((error) => message(error.message, true));\n el('save-slack-configuration').onclick = () => saveSlackConfiguration().catch((error) => message(error.message, true));\n el('cancel-slack-configuration').onclick = cancelConfigurationEdit;\n el('clear-slack').onclick = () => clearProvider('slack').catch((error) => message(error.message, true));\n el('check-slack').onclick = () => checkSlack().catch((error) => message(error.message, true));\n el('reconcile-slack').onclick = () => reconcileSlack().catch((error) => message(error.message, true));\n el('save-gitea').onclick = () => saveGitea().catch((error) => message(error.message, true));\n el('cancel-gitea-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitea').onclick = () => clearProvider('gitea').catch((error) => message(error.message, true));\n el('save-gitlab').onclick = () => saveGitlab().catch((error) => message(error.message, true));\n el('cancel-gitlab-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitlab').onclick = () => clearProvider('gitlab').catch((error) => message(error.message, true));\n el('save-googlechat').onclick = () => saveGoogleChat().catch((error) => message(error.message, true));\n for (const [id, mode] of [['create-azuread-agent-bots-blueprint', 'create'], ['save-azuread-agent-bots', 'save'], ['clear-azuread-agent-bots', 'clear']]) {\n el(id).onclick = () => saveAgentBots(mode).catch((error) => message(error.message, true));\n }\n el('cancel-googlechat-configuration').onclick = cancelConfigurationEdit;\n el('clear-googlechat').onclick = () => clearProvider('googlechat').catch((error) => message(error.message, true));\n el('save-email').onclick = () => saveEmail(false).catch((error) => message(error.message, true));\n el('rotate-email-ingress').onclick = () => confirmEmailIngressRotation(true);\n el('cancel-rotate-email-ingress').onclick = () => confirmEmailIngressRotation(false);\n el('confirm-rotate-email-ingress').onclick = () => {\n confirmEmailIngressRotation(false);\n saveEmail(true).catch((error) => message(error.message, true));\n };\n el('copy-email-ingress').onclick = () => copyEmailIngressSecret().catch(() => message('Copy failed. Select the secret and copy it.', true));\n el('dismiss-email-ingress').onclick = () => showEmailIngressSecret('');\n el('cancel-email-configuration').onclick = cancelConfigurationEdit;\n el('clear-email').onclick = () => clearProvider('email').catch((error) => message(error.message, true));\n el('save-linear').onclick = () => saveLinear().catch((error) => message(error.message, true));\n el('cancel-linear-configuration').onclick = cancelConfigurationEdit;\n el('clear-linear').onclick = () => clearProvider('linear').catch((error) => message(error.message, true));\n el('save-google').onclick = () => saveGoogle().catch((error) => message(error.message, true));\n el('cancel-google-configuration').onclick = cancelConfigurationEdit;\n el('clear-google').onclick = () => clearProvider('google').catch((error) => message(error.message, true));\n el('check-google').onclick = () => checkGoogle().catch((error) => message(error.message, true));\n for (const provider of Object.keys(loginApps)) {\n el('save-' + provider).onclick = () => saveLoginApp(provider).catch((error) => message(error.message, true));\n el('cancel-' + provider + '-configuration').onclick = cancelConfigurationEdit;\n el('clear-' + provider).onclick = () => saveLoginApp(provider, true).catch((error) => message(error.message, true));\n el('check-' + provider).onclick = () => checkLogto().catch((error) => message(error.message, true));\n }\n el('create-feishu-login-app').onclick = () => createRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('save-feishu-login-app').onclick = () => saveRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('cancel-feishu-configuration').onclick = cancelConfigurationEdit;\n el('clear-feishu').onclick = () => clearProvider('feishu').catch((error) => message(error.message, true));\n el('check-feishu-login-app').onclick = () => checkRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('create-lark-login-app').onclick = () => createRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('save-lark-login-app').onclick = () => saveRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('cancel-lark-configuration').onclick = cancelConfigurationEdit;\n el('clear-lark').onclick = () => clearProvider('lark').catch((error) => message(error.message, true));\n el('check-lark-login-app').onclick = () => checkRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('probe-mattermost').onclick = () => probeMattermost().catch((error) => message(error.message, true));\n el('save-mattermost').onclick = () => saveMattermost().catch((error) => message(error.message, true));\n el('cancel-mattermost-configuration').onclick = cancelConfigurationEdit;\n el('clear-mattermost').onclick = () => clearProvider('mattermost').catch((error) => message(error.message, true));\n el('check-mattermost').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-logto').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('reconcile-logto').onclick = () => reconcileLogto().then(load).catch((error) => message(error.message, true));\n el('logout').onclick = () => { sessionStorage.removeItem(tokenKey); load().catch((error) => message(error.message, true)); };\n el('save-options').onclick = () => saveOptions().catch((error) => message(error.message, true));\n for (const button of document.querySelectorAll('.edit-secret')) button.onclick = () => editSecret(button);\n for (const button of document.querySelectorAll('.edit-configuration')) button.onclick = () => beginConfigurationEdit(button.dataset.provider);\n updateBootstrapProvider();\n finishSignIn().then(load).catch((error) => message(error.message, true));\n <\/script>\n</body>\n</html>"
68556
69114
  ], [
68557
69115
  "<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>AgentConnect deployment settings</title>\n <style>\n :root { color-scheme: light dark; font: 15px/1.5 system-ui, sans-serif; }\n body { max-width: 1280px; margin: 48px auto; padding: 0 20px 60px; }\n h1 { margin-bottom: 4px; } h2 { margin-top: 32px; } h3 { margin: 0 0 8px; }\n .muted { color: #777; } .row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }\n button, .button { padding: 8px 13px; cursor: pointer; }\n .button { border: 1px solid #8888; border-radius: 4px; color: inherit; text-decoration: none; display: inline-block; }\n input, select { width: min(520px, 100%); padding: 7px; box-sizing: border-box; }\n input[type=\"checkbox\"] { width: auto; padding: 0; }\n .field { display: grid; gap: 4px; margin: 10px 0; }\n .provider-stack { display: grid; gap: 16px; }\n .panel { border: 1px solid #8886; border-radius: 8px; padding: 16px; }\n .section-head, .provider-head { display: flex; justify-content: space-between; gap: 16px; align-items: start; }\n .section-head h2, .provider-head h3 { margin: 0; }\n .provider-head p { margin: 4px 0 0; }\n .badge { flex: none; border: 1px solid #8886; border-radius: 999px; padding: 3px 9px; font-size: 13px; }\n .badge.pass { color: #198754; border-color: #19875466; background: #19875412; }\n .badge.warn { color: #a66b00; border-color: #d99b1366; background: #d99b1315; }\n .badge.fail { color: #c33; border-color: #c333; background: #c3331111; }\n .credentials { display: grid; grid-template-columns: minmax(160px, 220px) minmax(0, 1fr); gap: 7px 16px; margin: 16px 0; }\n .credentials dt { color: #777; }\n .credentials dd { margin: 0; overflow-wrap: anywhere; }\n .credentials code { user-select: all; }\n .redacted { font-family: ui-monospace, monospace; letter-spacing: .08em; }\n .secret-line, .value-line { display: flex; gap: 10px; align-items: center; min-height: 30px; }\n .edit-secret { padding: 2px 8px; font-size: 13px; }\n .secret-editor { display: flex; gap: 8px; flex-wrap: wrap; width: 100%; }\n .secret-editor input { width: min(420px, 100%); }\n .edit-configuration { padding: 2px 8px; font-size: 13px; }\n .startup-owned { color: #777; font-size: 13px; }\n .danger { color: #c33; border-color: #c336; }\n .subsection { margin-top: 16px; padding-top: 14px; border-top: 1px solid #8883; }\n textarea { width: min(720px, 100%); min-height: 100px; padding: 7px; box-sizing: border-box; }\n .uris { margin: 8px 0; padding-left: 20px; } .uris code { user-select: all; }\n .notice { border-left: 4px solid #d99b13; padding: 8px 12px; background: #d99b1315; }\n .diff-title { display: block; margin-bottom: 8px; }\n .config-diff { display: grid; gap: 1px; border: 1px solid #8884; border-radius: 6px; overflow: hidden; background: #8884; }\n .diff-row { display: grid; grid-template-columns: minmax(140px, .8fr) minmax(0, 1.2fr) minmax(0, 1.2fr); background: Canvas; }\n .diff-row > * { min-width: 0; padding: 7px 9px; overflow-wrap: anywhere; white-space: pre-wrap; }\n .diff-head { font-size: 12px; font-weight: 600; color: #777; }\n .diff-field { font-weight: 600; }\n .diff-value { font-family: ui-monospace, monospace; font-size: 13px; }\n pre { padding: 12px; border-radius: 6px; background: #8881; overflow-x: auto; user-select: all; }\n #message { white-space: pre-wrap; padding: 10px 0; min-height: 1.5em; }\n .error { color: #c33; } .ok { color: #198754; } .warn { color: #a66b00; }\n code { overflow-wrap: anywhere; }\n .setup-layout { display: grid; grid-template-columns: 190px minmax(0, 1fr); gap: 32px; align-items: start; }\n .setup-nav { position: sticky; top: 24px; display: grid; gap: 3px; padding: 10px; border: 1px solid #8886; border-radius: 8px; background: Canvas; }\n .setup-nav a { padding: 7px 9px; border-radius: 5px; color: inherit; text-decoration: none; white-space: nowrap; }\n .setup-nav a:hover { background: #8882; }\n .setup-section { scroll-margin-top: 24px; }\n details.environment { margin: 0 0 24px; } details.environment summary { cursor: pointer; font-weight: 600; }\n @media (max-width: 760px) {\n body { margin-top: 24px; }\n .setup-layout { grid-template-columns: 1fr; gap: 18px; }\n .setup-nav { position: static; display: flex; overflow-x: auto; }\n .credentials { grid-template-columns: 1fr; gap: 2px; }\n .credentials dd { margin-bottom: 8px; }\n .diff-row { grid-template-columns: 1fr; }\n .diff-head { display: none; }\n .diff-value::before { display: block; margin-bottom: 2px; color: #777; font: 11px/1.4 system-ui, sans-serif; }\n .diff-current::before { content: 'Current'; }\n .diff-expected::before { content: 'Expected'; }\n }\n [hidden] { display: none !important; }\n </style>\n</head>\n<body>\n <section id=\"access\">\n <h1>AgentConnect Setup</h1>\n <p id=\"access-message\" class=\"muted\" aria-live=\"polite\">Checking Logto sign-in…</p>\n <div class=\"row\">\n <button id=\"login\" hidden>Sign in with Logto</button>\n <a id=\"open-logto\" class=\"button\" href=\"http://localhost:3002\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n <button id=\"show-bootstrap\" hidden>Continue setup</button>\n </div>\n\n <section id=\"bootstrap\" hidden>\n <h2>Set up sign-in</h2>\n <p id=\"bootstrap-progress\" class=\"muted\">Step 1 of 2</p>\n <div id=\"bootstrap-logto-step\" class=\"panel\">\n <h3>Connect Logto</h3>\n <p class=\"muted\">Enter the one-time Logto Management API credential. It is sealed in the deployment database and verified before continuing.</p>\n <label class=\"field\">Logto M2M App ID<input id=\"logto-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Logto M2M App Secret<input id=\"logto-app-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-management-api-resource\" type=\"url\" autocomplete=\"off\"></label>\n <p class=\"muted\">Logto Cloud uses <code>https://&lt;tenant-id&gt;.logto.app/api</code>. Keep <code>https://default.logto.app/api</code> for Logto OSS.</p>\n <button id=\"bootstrap-logto-submit\">Save Logto and continue</button>\n </div>\n <div id=\"bootstrap-provider-step\" hidden>\n <h3>Choose a sign-in provider</h3>\n <p class=\"muted\">Logto Management API access is ready. Configure one provider to enable sign-in.</p>\n <label class=\"field\">Sign-in provider\n <select id=\"bootstrap-provider\"><option value=\"google\">Google (works on localhost)</option><option value=\"github\">GitHub integration App</option><option id=\"bootstrap-slack-option\" value=\"slack\">Slack integration App</option><option value=\"sso\">Single sign-on (OIDC or SAML)</option></select>\n </label>\n <div id=\"bootstrap-google\" class=\"panel\">\n <h3>Google OAuth client</h3>\n <p class=\"muted\">Create a Web application client in Google Auth Platform, then paste its credentials here.</p>\n <p>Authorized JavaScript origin:</p><ul id=\"bootstrap-google-origins\" class=\"uris\"></ul>\n <p>Authorized redirect URIs:</p><ul id=\"bootstrap-google-redirects\" class=\"uris\"></ul>\n <a class=\"button\" href=\"https://console.cloud.google.com/auth/clients\" target=\"_blank\" rel=\"noopener\">Open Google settings</a>\n <label class=\"field\">Client ID<input id=\"bootstrap-google-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client Secret<input id=\"bootstrap-google-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n <button id=\"bootstrap-google-submit\">Save Google OAuth and configure Logto</button>\n </div>\n <div id=\"bootstrap-github\" class=\"panel\" hidden>\n <h3>GitHub integration App</h3>\n <p id=\"bootstrap-github-note\" class=\"muted\">This creates one complete App for both GitHub sign-in and repository integration.</p>\n <label class=\"field\">Owner\n <select id=\"bootstrap-github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"bootstrap-github-org-field\" class=\"field\" hidden>Organization login<input id=\"bootstrap-github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"bootstrap-github-name\" value=\"AgentConnect\"></label>\n <button id=\"bootstrap-github-submit\">Create GitHub App and configure Logto</button>\n </div>\n <div id=\"bootstrap-slack\" class=\"panel\" hidden>\n <h3>Slack integration App</h3>\n <p id=\"bootstrap-slack-note\" class=\"muted\">Creates one complete Slack App for workspace installation and a separate Sign in with Slack OIDC flow.</p>\n <p>Logto redirect URI:</p><ul id=\"bootstrap-slack-redirects\" class=\"uris\"></ul>\n <label class=\"field\">App name<input id=\"bootstrap-slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"bootstrap-slack-token\" type=\"password\" autocomplete=\"new-password\"></label>\n <button id=\"bootstrap-slack-submit\">Create Slack App and configure Logto</button>\n </div>\n <div id=\"bootstrap-sso\" class=\"panel\" hidden>\n <h3>Single sign-on</h3>\n <p class=\"muted\">Sign in through the organization's identity provider. Logto creates the connector first, so its URLs can be registered with the identity provider.</p>\n ",
68558
- "\n </div>\n <button id=\"bootstrap-back\">Back to Logto credentials</button>\n </div>\n </section>\n </section>\n\n <main id=\"setup\" hidden>\n <div class=\"setup-layout\">\n <nav class=\"setup-nav\" aria-label=\"Deployment settings\">\n <a href=\"#startup-section\">Startup</a>\n <a href=\"#logto-section\">Logto</a>\n <a href=\"#sso-section\">Single sign-on</a>\n <a href=\"#github-section\">GitHub</a>\n <a href=\"#gitlab-section\">GitLab</a>\n <a href=\"#gitea-section\">Gitea</a>\n <a href=\"#slack-section\">Slack</a>\n <a href=\"#linear-section\">Linear</a>\n <a href=\"#google-section\">Google</a>\n <a href=\"#telegram-section\">Telegram</a>\n <a href=\"#discord-section\">Discord</a>\n <a href=\"#azuread-section\">Microsoft</a>\n <a href=\"#googlechat-section\">Google Chat</a>\n <a href=\"#email-section\">Email</a>\n <a href=\"#feishu-section\">Feishu</a>\n <a href=\"#lark-section\">Lark</a>\n <a href=\"#options-section\">Options</a>\n </nav>\n <div class=\"setup-content\">\n <h1>AgentConnect deployment settings</h1>\n <p class=\"muted\">Saved settings take effect after the stack is restarted.</p>\n <div class=\"row\">\n <button id=\"logout\">Log out</button>\n </div>\n <div id=\"message\" aria-live=\"polite\"></div>\n\n <section id=\"editor\" hidden>\n <details id=\"startup-section\" class=\"environment setup-section\" open>\n <summary>Startup environment</summary>\n <p class=\"notice\">Public service URLs come from <code>.env</code>. Provider callbacks below are derived from these values.</p>\n <pre id=\"startup-environment\"></pre>\n </details>\n\n <section id=\"logto-section\" class=\"setup-section\" aria-labelledby=\"logto-heading\">\n <div class=\"section-head\">\n <div><h2 id=\"logto-heading\">Logto</h2><p class=\"muted\">Authentication and administrator access.</p></div>\n <span id=\"logto-match\" class=\"badge\">Not checked</span>\n </div>\n <div class=\"panel\">\n <dl class=\"credentials\">\n <dt>Management endpoint</dt><dd class=\"value-line\"><code id=\"logto-management-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>Management App ID</dt><dd class=\"value-line\"><code id=\"logto-management-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management API resource</dt><dd class=\"value-line\"><code id=\"logto-management-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management App secret</dt><dd class=\"secret-line\"><span id=\"logto-management-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.managementAppSecret\" data-secret-display=\"logto-management-secret-display\">Edit</button></dd>\n <dt>Sign-in endpoint</dt><dd class=\"value-line\"><code id=\"logto-browser-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>SPA App ID</dt><dd class=\"value-line\"><code id=\"logto-browser-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Browser API resource</dt><dd class=\"value-line\"><code id=\"logto-browser-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n </dl>\n <div id=\"logto-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Logto configuration</h3>\n <label class=\"field\">Management App ID<input id=\"logto-edit-management-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-edit-management-resource\" autocomplete=\"off\"></label>\n <label class=\"field\">New Management App secret<input id=\"logto-edit-management-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when management identity changes\"></label>\n <label class=\"field\">SPA App ID<input id=\"logto-edit-browser-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Browser API resource<input id=\"logto-edit-browser-resource\" autocomplete=\"off\" placeholder=\"Optional\"></label>\n <div class=\"row\"><button id=\"save-logto-configuration\">Save configuration</button><button id=\"cancel-logto-configuration\">Cancel</button></div>\n </div>\n <p id=\"logto-status\" class=\"muted\">Checking redirects and sign-in settings…</p>\n <div id=\"logto-drift\" class=\"notice\" hidden></div>\n <div class=\"row\">\n <button id=\"check-logto\">Check match</button>\n <button id=\"reconcile-logto\">Apply expected settings</button>\n <a id=\"logto-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n </div>\n </div>\n </section>\n\n <h2>Providers</h2>\n <div class=\"provider-stack\">\n <section id=\"github-section\" class=\"panel setup-section\" aria-labelledby=\"github-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"github-heading\">GitHub</h3><p class=\"muted\">Repository integration and optional Logto sign-in.</p></div>\n <span id=\"github-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"github-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>App slug</dt><dd class=\"value-line\"><code id=\"github-app-slug\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"github-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Webhook delivery</dt><dd class=\"value-line\"><code id=\"github-webhook-enabled\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"github-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.clientSecret\" data-secret-display=\"github-client-secret-display\">Edit</button></dd>\n <dt>Private key</dt><dd class=\"secret-line\"><span id=\"github-private-key-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.privateKeyB64\" data-secret-display=\"github-private-key-display\">Edit</button></dd>\n <dt>Webhook secret</dt><dd class=\"secret-line\"><span id=\"github-webhook-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.webhookSecret\" data-secret-display=\"github-webhook-secret-display\">Edit</button></dd>\n <dt>Logto connector secret</dt><dd class=\"secret-line\"><span id=\"github-logto-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.githubConnectorClientSecret\" data-secret-display=\"github-logto-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"github-status\" class=\"muted\"></p>\n <div id=\"github-drift\" class=\"notice\" hidden></div>\n <div id=\"github-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit GitHub App identity</h3>\n <label class=\"field\">App ID<input id=\"github-edit-app-id\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n <label class=\"field\">App slug<input id=\"github-edit-slug\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"github-edit-client-id\" autocomplete=\"off\"></label>\n <label><input id=\"github-edit-webhook-enabled\" type=\"checkbox\"> Enable Relay webhook delivery</label>\n <label class=\"field\">New client secret<input id=\"github-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when App or Client ID changes\"></label>\n <label class=\"field\">New private key (base64)<textarea id=\"github-edit-private-key\" autocomplete=\"off\" placeholder=\"Required when App ID changes\"></textarea></label>\n <label class=\"field\">New webhook secret<input id=\"github-edit-webhook-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when an active webhook App ID changes\"></label>\n <label id=\"github-edit-logto-secret-field\" class=\"field\" hidden>New Logto connector client secret<input id=\"github-edit-logto-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when this App is also used for sign-in\"></label>\n <div class=\"row\"><button id=\"save-github-configuration\">Save configuration</button><button id=\"cancel-github-configuration\">Cancel</button></div>\n </div>\n <div id=\"github-create-controls\" class=\"subsection\">\n <label class=\"field\">Owner\n <select id=\"github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"github-org-field\" class=\"field\" hidden>Organization login<input id=\"github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"github-name\" value=\"AgentConnect\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-github\">Create GitHub App</button>\n <button id=\"connect-github-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-github\" hidden>Check match</button>\n <button id=\"clear-github\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"github-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open GitHub settings</a>\n </div>\n </section>\n\n <section id=\"gitlab-section\" class=\"panel setup-section\" aria-labelledby=\"gitlab-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitlab-heading\">GitLab</h3><p class=\"muted\">OAuth application used to administer projects on this deployment's GitLab instance.</p></div>\n <span id=\"gitlab-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitlab-instance\">https://gitlab.com</code></dd>\n <dt>Application ID</dt><dd class=\"value-line\"><code id=\"gitlab-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"gitlab\">Edit</button></dd>\n <dt>Secret</dt><dd class=\"secret-line\"><span id=\"gitlab-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"gitlab.clientSecret\" data-secret-display=\"gitlab-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"gitlab-status\" class=\"muted\"></p>\n <p id=\"gitlab-probe\" class=\"muted\" hidden></p>\n <div id=\"gitlab-drift\" class=\"notice\" hidden></div>\n <p>Redirect URI:</p><ul id=\"gitlab-callbacks\" class=\"uris\"></ul>\n <p>Scopes:</p><ul id=\"gitlab-scopes\" class=\"uris\"></ul>\n <p class=\"muted\">GitLab does not expose OAuth application creation through an API. In User settings &rarr; Applications, or a group's Settings &rarr; Applications, add an application whose redirect URI is exactly the value above, keep Confidential selected, grant the scopes above, then save the generated Application ID and Secret here. GitLab shows the secret only once.</p>\n <p class=\"muted\">Use your own user applications unless you are an instance administrator registering one application for everyone; an instance-wide application lives in the Admin area instead.</p>\n <p class=\"muted\">Creating each agent's bot account later needs authority this page cannot verify — no GitLab API reports it: either connect an instance administrator (whose API token cannot act as one while Admin Mode is enabled), or, on Premium and Ultimate, turn on Admin &rarr; Settings &rarr; General &rarr; Account and limit &rarr; &ldquo;Allow top-level group Owners to create service accounts&rdquo;.</p>\n <div class=\"row\"><a id=\"gitlab-applications\" class=\"button\" href=\"https://gitlab.com/-/user_settings/applications\" target=\"_blank\" rel=\"noopener\">Open GitLab applications</a><a id=\"gitlab-admin-applications\" class=\"button\" href=\"https://gitlab.com/admin/applications\" target=\"_blank\" rel=\"noopener\">Open admin applications</a></div>\n <div id=\"gitlab-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitlab-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitlab.com\"></label>\n <label class=\"field\">Application ID<input id=\"gitlab-id\" autocomplete=\"off\"></label>\n <label id=\"gitlab-initial-secret-field\" class=\"field\">Secret<input id=\"gitlab-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Application ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitlab\">Save GitLab application</button><button id=\"cancel-gitlab-configuration\" hidden>Cancel</button><button id=\"clear-gitlab\" class=\"danger\" hidden>Clear configuration</button></div>\n <div class=\"subsection\">\n <h4>GitLab sign-in</h4>\n <p>Add these redirect URIs and the openid, profile and email scopes to the same confidential OAuth application.</p>\n <ul id=\"gitlab-login-redirects\" class=\"uris\"></ul>\n <p id=\"gitlab-login-status\" class=\"muted\"></p>\n <div class=\"row\"><button id=\"connect-gitlab-login\">Use for Logto sign-in</button><button id=\"disconnect-gitlab-login\" hidden>Disable GitLab sign-in</button><button id=\"check-gitlab-login\" hidden>Check Logto</button></div>\n </div>\n </section>\n\n <section id=\"gitea-section\" class=\"panel setup-section\" aria-labelledby=\"gitea-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitea-heading\">Gitea</h3><p class=\"muted\">The Gitea instance this deployment addresses. Gitea registers no application, so the address is the whole setting.</p></div>\n <span id=\"gitea-match\" class=\"badge\">Default</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitea-instance\">https://gitea.com</code><button class=\"edit-configuration\" data-provider=\"gitea\">Edit</button></dd>\n </dl>\n <p id=\"gitea-status\" class=\"muted\"></p>\n <p id=\"gitea-probe\" class=\"muted\" hidden></p>\n <p class=\"muted\">Each organization connects Gitea by pasting the personal access token of a bot user it created, in the console — nothing about that identity is a deployment setting. Gitea 1.23 or later, or Forgejo 15 or later, is required, and the address is checked against that floor when it is saved.</p>\n <p class=\"muted\">Leave the field empty for gitea.com. A self-hosted instance under a path prefix keeps the prefix. A Forgejo instance, Codeberg included, is entered the same way.</p>\n <div id=\"gitea-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitea-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitea.com\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitea\">Save Gitea instance</button><button id=\"cancel-gitea-configuration\" hidden>Cancel</button><button id=\"clear-gitea\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"slack-section\" class=\"panel setup-section\" aria-labelledby=\"slack-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"slack-heading\">Slack</h3><p class=\"muted\">One App for workspace integration and Logto sign-in.</p></div>\n <span id=\"slack-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"slack-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"slack-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"slack-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.clientSecret\" data-secret-display=\"slack-client-secret-display\">Edit</button></dd>\n <dt>Signing secret</dt><dd class=\"secret-line\"><span id=\"slack-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.signingSecret\" data-secret-display=\"slack-signing-secret-display\">Edit</button></dd>\n <dt>Logto sign-in</dt><dd id=\"slack-logto-status\">Not configured</dd>\n </dl>\n <p id=\"slack-status\" class=\"muted\"></p>\n <div id=\"slack-drift\" class=\"notice\" hidden></div>\n <div id=\"slack-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Slack App identity</h3>\n <label class=\"field\">App ID<input id=\"slack-edit-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"slack-edit-client-id\" autocomplete=\"off\"></label>\n <label class=\"field\">New client secret<input id=\"slack-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <label class=\"field\">New signing secret<input id=\"slack-edit-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <div class=\"row\"><button id=\"save-slack-configuration\">Save configuration</button><button id=\"cancel-slack-configuration\">Cancel</button></div>\n </div>\n <div class=\"subsection\">\n <label id=\"slack-name-field\" class=\"field\">App name<input id=\"slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"slack-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Used only for create, check or update\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-slack\">Create Slack App</button>\n <button id=\"connect-slack-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-slack\" hidden>Check match</button>\n <button id=\"reconcile-slack\" hidden>Apply update</button>\n <button id=\"clear-slack\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"slack-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Slack settings</a>\n </div>\n </section>\n\n <section id=\"linear-section\" class=\"panel setup-section\" aria-labelledby=\"linear-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"linear-heading\">Linear</h3><p class=\"muted\">One OAuth application for the whole deployment. Every workspace connects through it.</p></div>\n <span id=\"linear-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"linear-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"linear\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"linear-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.clientSecret\" data-secret-display=\"linear-client-secret-display\">Edit</button></dd>\n <dt>Webhook signing secret</dt><dd class=\"secret-line\"><span id=\"linear-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.signingSecret\" data-secret-display=\"linear-signing-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"linear-status\" class=\"muted\"></p>\n <div id=\"linear-drift\" class=\"notice\" hidden></div>\n <p>Callback URL:</p><ul id=\"linear-callbacks\" class=\"uris\"></ul>\n <p>Webhook URL:</p><ul id=\"linear-webhooks\" class=\"uris\"></ul>\n <p class=\"muted\">Linear does not expose OAuth application creation through an API. In Settings &rarr; API &rarr; OAuth applications, create one application under the product's own name and icon, add the callback URL above, then save its Client ID, Client secret, and webhook signing secret here.</p>\n <p class=\"muted\">On the same application, enable webhooks, point them at the webhook URL above, and check the <strong>Agent session events</strong> category.</p>\n <p class=\"muted\">Until that category is enabled, agent sessions are disabled for the whole application: delegating an issue only sets the delegate badge and no session is created. Enabling it later raises a new scope, so every already-connected workspace must reconnect before webhooks arrive.</p>\n <div class=\"row\"><a id=\"linear-applications\" class=\"button\" href=\"https://linear.app/settings/api/applications\" target=\"_blank\" rel=\"noopener\">Open Linear OAuth applications</a></div>\n <div id=\"linear-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"linear-id\" autocomplete=\"off\"></label>\n <div id=\"linear-initial-secret-fields\">\n <label class=\"field\">Client secret<input id=\"linear-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n <label class=\"field\">Webhook signing secret<input id=\"linear-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n </div>\n </div>\n <div class=\"row\"><button id=\"save-linear\">Save Linear application</button><button id=\"cancel-linear-configuration\" hidden>Cancel</button><button id=\"clear-linear\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"sso-section\" class=\"panel setup-section\" aria-labelledby=\"sso-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"sso-heading\">Single sign-on</h3><p class=\"muted\">OIDC or SAML identity provider for console sign-in.</p></div>\n <span id=\"sso-match\" class=\"badge\">Not configured</span>\n </div>\n ",
69116
+ "\n </div>\n <button id=\"bootstrap-back\">Back to Logto credentials</button>\n </div>\n </section>\n </section>\n\n <main id=\"setup\" hidden>\n <div class=\"setup-layout\">\n <nav class=\"setup-nav\" aria-label=\"Deployment settings\">\n <a href=\"#startup-section\">Startup</a>\n <a href=\"#logto-section\">Logto</a>\n <a href=\"#sso-section\">Single sign-on</a>\n <a href=\"#github-section\">GitHub</a>\n <a href=\"#gitlab-section\">GitLab</a>\n <a href=\"#gitea-section\">Gitea</a>\n <a href=\"#slack-section\">Slack</a>\n <a href=\"#linear-section\">Linear</a>\n <a href=\"#google-section\">Google</a>\n <a href=\"#telegram-section\">Telegram</a>\n <a href=\"#discord-section\">Discord</a>\n <a href=\"#azuread-section\">Microsoft</a>\n <a href=\"#googlechat-section\">Google Chat</a>\n <a href=\"#email-section\">Email</a>\n <a href=\"#feishu-section\">Feishu</a>\n <a href=\"#lark-section\">Lark</a>\n <a href=\"#mattermost-section\">Mattermost</a>\n <a href=\"#options-section\">Options</a>\n </nav>\n <div class=\"setup-content\">\n <h1>AgentConnect deployment settings</h1>\n <p class=\"muted\">Saved settings take effect after the stack is restarted.</p>\n <div class=\"row\">\n <button id=\"logout\">Log out</button>\n </div>\n <div id=\"message\" aria-live=\"polite\"></div>\n\n <section id=\"editor\" hidden>\n <details id=\"startup-section\" class=\"environment setup-section\" open>\n <summary>Startup environment</summary>\n <p class=\"notice\">Public service URLs come from <code>.env</code>. Provider callbacks below are derived from these values.</p>\n <pre id=\"startup-environment\"></pre>\n </details>\n\n <section id=\"logto-section\" class=\"setup-section\" aria-labelledby=\"logto-heading\">\n <div class=\"section-head\">\n <div><h2 id=\"logto-heading\">Logto</h2><p class=\"muted\">Authentication and administrator access.</p></div>\n <span id=\"logto-match\" class=\"badge\">Not checked</span>\n </div>\n <div class=\"panel\">\n <dl class=\"credentials\">\n <dt>Management endpoint</dt><dd class=\"value-line\"><code id=\"logto-management-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>Management App ID</dt><dd class=\"value-line\"><code id=\"logto-management-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management API resource</dt><dd class=\"value-line\"><code id=\"logto-management-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Management App secret</dt><dd class=\"secret-line\"><span id=\"logto-management-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.managementAppSecret\" data-secret-display=\"logto-management-secret-display\">Edit</button></dd>\n <dt>Sign-in endpoint</dt><dd class=\"value-line\"><code id=\"logto-browser-endpoint\">Not configured</code><span class=\"startup-owned\">startup environment</span></dd>\n <dt>SPA App ID</dt><dd class=\"value-line\"><code id=\"logto-browser-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n <dt>Browser API resource</dt><dd class=\"value-line\"><code id=\"logto-browser-resource\">Not configured</code><button class=\"edit-configuration\" data-provider=\"logto\">Edit</button></dd>\n </dl>\n <div id=\"logto-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Logto configuration</h3>\n <label class=\"field\">Management App ID<input id=\"logto-edit-management-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Management API resource<input id=\"logto-edit-management-resource\" autocomplete=\"off\"></label>\n <label class=\"field\">New Management App secret<input id=\"logto-edit-management-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when management identity changes\"></label>\n <label class=\"field\">SPA App ID<input id=\"logto-edit-browser-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Browser API resource<input id=\"logto-edit-browser-resource\" autocomplete=\"off\" placeholder=\"Optional\"></label>\n <div class=\"row\"><button id=\"save-logto-configuration\">Save configuration</button><button id=\"cancel-logto-configuration\">Cancel</button></div>\n </div>\n <p id=\"logto-status\" class=\"muted\">Checking redirects and sign-in settings…</p>\n <div id=\"logto-drift\" class=\"notice\" hidden></div>\n <div class=\"row\">\n <button id=\"check-logto\">Check match</button>\n <button id=\"reconcile-logto\">Apply expected settings</button>\n <a id=\"logto-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Logto Console</a>\n </div>\n </div>\n </section>\n\n <h2>Providers</h2>\n <div class=\"provider-stack\">\n <section id=\"github-section\" class=\"panel setup-section\" aria-labelledby=\"github-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"github-heading\">GitHub</h3><p class=\"muted\">Repository integration and optional Logto sign-in.</p></div>\n <span id=\"github-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"github-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>App slug</dt><dd class=\"value-line\"><code id=\"github-app-slug\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"github-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Webhook delivery</dt><dd class=\"value-line\"><code id=\"github-webhook-enabled\">Not configured</code><button class=\"edit-configuration\" data-provider=\"github\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"github-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.clientSecret\" data-secret-display=\"github-client-secret-display\">Edit</button></dd>\n <dt>Private key</dt><dd class=\"secret-line\"><span id=\"github-private-key-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.privateKeyB64\" data-secret-display=\"github-private-key-display\">Edit</button></dd>\n <dt>Webhook secret</dt><dd class=\"secret-line\"><span id=\"github-webhook-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"github.webhookSecret\" data-secret-display=\"github-webhook-secret-display\">Edit</button></dd>\n <dt>Logto connector secret</dt><dd class=\"secret-line\"><span id=\"github-logto-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.githubConnectorClientSecret\" data-secret-display=\"github-logto-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"github-status\" class=\"muted\"></p>\n <div id=\"github-drift\" class=\"notice\" hidden></div>\n <div id=\"github-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit GitHub App identity</h3>\n <label class=\"field\">App ID<input id=\"github-edit-app-id\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n <label class=\"field\">App slug<input id=\"github-edit-slug\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"github-edit-client-id\" autocomplete=\"off\"></label>\n <label><input id=\"github-edit-webhook-enabled\" type=\"checkbox\"> Enable Relay webhook delivery</label>\n <label class=\"field\">New client secret<input id=\"github-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when App or Client ID changes\"></label>\n <label class=\"field\">New private key (base64)<textarea id=\"github-edit-private-key\" autocomplete=\"off\" placeholder=\"Required when App ID changes\"></textarea></label>\n <label class=\"field\">New webhook secret<input id=\"github-edit-webhook-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when an active webhook App ID changes\"></label>\n <label id=\"github-edit-logto-secret-field\" class=\"field\" hidden>New Logto connector client secret<input id=\"github-edit-logto-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when this App is also used for sign-in\"></label>\n <div class=\"row\"><button id=\"save-github-configuration\">Save configuration</button><button id=\"cancel-github-configuration\">Cancel</button></div>\n </div>\n <div id=\"github-create-controls\" class=\"subsection\">\n <label class=\"field\">Owner\n <select id=\"github-owner\"><option value=\"personal\">Personal account</option><option value=\"organization\">GitHub organization</option></select>\n </label>\n <label id=\"github-org-field\" class=\"field\" hidden>Organization login<input id=\"github-org\" autocomplete=\"off\"></label>\n <label class=\"field\">App name<input id=\"github-name\" value=\"AgentConnect\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-github\">Create GitHub App</button>\n <button id=\"connect-github-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-github\" hidden>Check match</button>\n <button id=\"clear-github\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"github-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open GitHub settings</a>\n </div>\n </section>\n\n <section id=\"gitlab-section\" class=\"panel setup-section\" aria-labelledby=\"gitlab-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitlab-heading\">GitLab</h3><p class=\"muted\">OAuth application used to administer projects on this deployment's GitLab instance.</p></div>\n <span id=\"gitlab-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitlab-instance\">https://gitlab.com</code></dd>\n <dt>Application ID</dt><dd class=\"value-line\"><code id=\"gitlab-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"gitlab\">Edit</button></dd>\n <dt>Secret</dt><dd class=\"secret-line\"><span id=\"gitlab-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"gitlab.clientSecret\" data-secret-display=\"gitlab-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"gitlab-status\" class=\"muted\"></p>\n <p id=\"gitlab-probe\" class=\"muted\" hidden></p>\n <div id=\"gitlab-drift\" class=\"notice\" hidden></div>\n <p>Redirect URI:</p><ul id=\"gitlab-callbacks\" class=\"uris\"></ul>\n <p>Scopes:</p><ul id=\"gitlab-scopes\" class=\"uris\"></ul>\n <p class=\"muted\">GitLab does not expose OAuth application creation through an API. In User settings &rarr; Applications, or a group's Settings &rarr; Applications, add an application whose redirect URI is exactly the value above, keep Confidential selected, grant the scopes above, then save the generated Application ID and Secret here. GitLab shows the secret only once.</p>\n <p class=\"muted\">Use your own user applications unless you are an instance administrator registering one application for everyone; an instance-wide application lives in the Admin area instead.</p>\n <p class=\"muted\">Creating each agent's bot account later needs authority this page cannot verify — no GitLab API reports it: either connect an instance administrator (whose API token cannot act as one while Admin Mode is enabled), or, on Premium and Ultimate, turn on Admin &rarr; Settings &rarr; General &rarr; Account and limit &rarr; &ldquo;Allow top-level group Owners to create service accounts&rdquo;.</p>\n <div class=\"row\"><a id=\"gitlab-applications\" class=\"button\" href=\"https://gitlab.com/-/user_settings/applications\" target=\"_blank\" rel=\"noopener\">Open GitLab applications</a><a id=\"gitlab-admin-applications\" class=\"button\" href=\"https://gitlab.com/admin/applications\" target=\"_blank\" rel=\"noopener\">Open admin applications</a></div>\n <div id=\"gitlab-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitlab-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitlab.com\"></label>\n <label class=\"field\">Application ID<input id=\"gitlab-id\" autocomplete=\"off\"></label>\n <label id=\"gitlab-initial-secret-field\" class=\"field\">Secret<input id=\"gitlab-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Application ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitlab\">Save GitLab application</button><button id=\"cancel-gitlab-configuration\" hidden>Cancel</button><button id=\"clear-gitlab\" class=\"danger\" hidden>Clear configuration</button></div>\n <div class=\"subsection\">\n <h4>GitLab sign-in</h4>\n <p>Add these redirect URIs and the openid, profile and email scopes to the same confidential OAuth application.</p>\n <ul id=\"gitlab-login-redirects\" class=\"uris\"></ul>\n <p id=\"gitlab-login-status\" class=\"muted\"></p>\n <div class=\"row\"><button id=\"connect-gitlab-login\">Use for Logto sign-in</button><button id=\"disconnect-gitlab-login\" hidden>Disable GitLab sign-in</button><button id=\"check-gitlab-login\" hidden>Check Logto</button></div>\n </div>\n </section>\n\n <section id=\"gitea-section\" class=\"panel setup-section\" aria-labelledby=\"gitea-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"gitea-heading\">Gitea</h3><p class=\"muted\">The Gitea instance this deployment addresses. Gitea registers no application, so the address is the whole setting.</p></div>\n <span id=\"gitea-match\" class=\"badge\">Default</span>\n </div>\n <dl class=\"credentials\">\n <dt>Instance</dt><dd class=\"value-line\"><code id=\"gitea-instance\">https://gitea.com</code><button class=\"edit-configuration\" data-provider=\"gitea\">Edit</button></dd>\n </dl>\n <p id=\"gitea-status\" class=\"muted\"></p>\n <p id=\"gitea-probe\" class=\"muted\" hidden></p>\n <p class=\"muted\">Each organization connects Gitea by pasting the personal access token of a bot user it created, in the console — nothing about that identity is a deployment setting. Gitea 1.23 or later, or Forgejo 15 or later, is required, and the address is checked against that floor when it is saved.</p>\n <p class=\"muted\">Leave the field empty for gitea.com. A self-hosted instance under a path prefix keeps the prefix. A Forgejo instance, Codeberg included, is entered the same way.</p>\n <div id=\"gitea-config-controls\" class=\"subsection\">\n <label class=\"field\">Instance base URL<input id=\"gitea-base-url\" autocomplete=\"off\" placeholder=\"Leave empty for https://gitea.com\"></label>\n </div>\n <div class=\"row\"><button id=\"save-gitea\">Save Gitea instance</button><button id=\"cancel-gitea-configuration\" hidden>Cancel</button><button id=\"clear-gitea\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"slack-section\" class=\"panel setup-section\" aria-labelledby=\"slack-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"slack-heading\">Slack</h3><p class=\"muted\">One App for workspace integration and Logto sign-in.</p></div>\n <span id=\"slack-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"slack-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"slack-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"slack\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"slack-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.clientSecret\" data-secret-display=\"slack-client-secret-display\">Edit</button></dd>\n <dt>Signing secret</dt><dd class=\"secret-line\"><span id=\"slack-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"slack.signingSecret\" data-secret-display=\"slack-signing-secret-display\">Edit</button></dd>\n <dt>Logto sign-in</dt><dd id=\"slack-logto-status\">Not configured</dd>\n </dl>\n <p id=\"slack-status\" class=\"muted\"></p>\n <div id=\"slack-drift\" class=\"notice\" hidden></div>\n <div id=\"slack-edit-controls\" class=\"subsection\" hidden>\n <h3>Edit Slack App identity</h3>\n <label class=\"field\">App ID<input id=\"slack-edit-app-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Client ID<input id=\"slack-edit-client-id\" autocomplete=\"off\"></label>\n <label class=\"field\">New client secret<input id=\"slack-edit-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <label class=\"field\">New signing secret<input id=\"slack-edit-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when identity changes\"></label>\n <div class=\"row\"><button id=\"save-slack-configuration\">Save configuration</button><button id=\"cancel-slack-configuration\">Cancel</button></div>\n </div>\n <div class=\"subsection\">\n <label id=\"slack-name-field\" class=\"field\">App name<input id=\"slack-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Temporary App configuration token<input id=\"slack-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Used only for create, check or update\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-slack\">Create Slack App</button>\n <button id=\"connect-slack-login\" hidden>Use for Logto sign-in</button>\n <button id=\"check-slack\" hidden>Check match</button>\n <button id=\"reconcile-slack\" hidden>Apply update</button>\n <button id=\"clear-slack\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"slack-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Slack settings</a>\n </div>\n </section>\n\n <section id=\"linear-section\" class=\"panel setup-section\" aria-labelledby=\"linear-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"linear-heading\">Linear</h3><p class=\"muted\">One OAuth application for the whole deployment. Every workspace connects through it.</p></div>\n <span id=\"linear-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"linear-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"linear\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"linear-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.clientSecret\" data-secret-display=\"linear-client-secret-display\">Edit</button></dd>\n <dt>Webhook signing secret</dt><dd class=\"secret-line\"><span id=\"linear-signing-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"linear.signingSecret\" data-secret-display=\"linear-signing-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"linear-status\" class=\"muted\"></p>\n <div id=\"linear-drift\" class=\"notice\" hidden></div>\n <p>Callback URL:</p><ul id=\"linear-callbacks\" class=\"uris\"></ul>\n <p>Webhook URL:</p><ul id=\"linear-webhooks\" class=\"uris\"></ul>\n <p class=\"muted\">Linear does not expose OAuth application creation through an API. In Settings &rarr; API &rarr; OAuth applications, create one application under the product's own name and icon, add the callback URL above, then save its Client ID, Client secret, and webhook signing secret here.</p>\n <p class=\"muted\">On the same application, enable webhooks, point them at the webhook URL above, and check the <strong>Agent session events</strong> category.</p>\n <p class=\"muted\">Until that category is enabled, agent sessions are disabled for the whole application: delegating an issue only sets the delegate badge and no session is created. Enabling it later raises a new scope, so every already-connected workspace must reconnect before webhooks arrive.</p>\n <div class=\"row\"><a id=\"linear-applications\" class=\"button\" href=\"https://linear.app/settings/api/applications\" target=\"_blank\" rel=\"noopener\">Open Linear OAuth applications</a></div>\n <div id=\"linear-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"linear-id\" autocomplete=\"off\"></label>\n <div id=\"linear-initial-secret-fields\">\n <label class=\"field\">Client secret<input id=\"linear-client-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n <label class=\"field\">Webhook signing secret<input id=\"linear-signing-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the Client ID changes\"></label>\n </div>\n </div>\n <div class=\"row\"><button id=\"save-linear\">Save Linear application</button><button id=\"cancel-linear-configuration\" hidden>Cancel</button><button id=\"clear-linear\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"sso-section\" class=\"panel setup-section\" aria-labelledby=\"sso-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"sso-heading\">Single sign-on</h3><p class=\"muted\">OIDC or SAML identity provider for console sign-in.</p></div>\n <span id=\"sso-match\" class=\"badge\">Not configured</span>\n </div>\n ",
68559
69117
  "\n <div class=\"row\"><button id=\"sso-remove\" class=\"danger\" hidden>Remove SSO sign-in</button></div>\n </section>\n\n <section id=\"google-section\" class=\"panel setup-section\" aria-labelledby=\"google-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"google-heading\">Google</h3><p class=\"muted\">OAuth client used by the Logto Google connector.</p></div>\n <span id=\"google-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"google-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"google\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"google-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.googleConnectorClientSecret\" data-secret-display=\"google-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"google-status\" class=\"muted\"></p>\n <div id=\"google-drift\" class=\"notice\" hidden></div>\n <p>Authorized JavaScript origin:</p><ul id=\"google-origins\" class=\"uris\"></ul>\n <p>Authorized redirect URIs:</p><ul id=\"google-redirects\" class=\"uris\"></ul>\n <p class=\"muted\">Google does not expose OAuth client redirect settings through an API. Copy these required values into Google Auth Platform; Setup can verify only the Logto connector.</p>\n <div class=\"row\"><a class=\"button\" href=\"https://console.cloud.google.com/auth/clients\" target=\"_blank\" rel=\"noopener\">Open Google settings</a></div>\n <div id=\"google-config-controls\" class=\"subsection\">\n <label class=\"field\">Client ID<input id=\"google-id\" autocomplete=\"off\"></label>\n <label id=\"google-initial-secret-field\" class=\"field\">Client secret<input id=\"google-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when Client ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-google\">Save Google client</button><button id=\"cancel-google-configuration\" hidden>Cancel</button><button id=\"check-google\" hidden>Check match</button><button id=\"clear-google\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n ",
68560
- "\n\n <section id=\"googlechat-section\" class=\"panel setup-section\" aria-labelledby=\"googlechat-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"googlechat-heading\">Google Chat</h3><p class=\"muted\">One Chat app for the deployment. Each Google Workspace organization connects itself from Google Chat.</p></div>\n <span id=\"googlechat-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Project ID</dt><dd class=\"value-line\"><code id=\"googlechat-project-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Project number</dt><dd class=\"value-line\"><code id=\"googlechat-project-number\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Service-account key</dt><dd class=\"value-line\"><span id=\"googlechat-key-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n </dl>\n <p id=\"googlechat-status\" class=\"muted\"></p>\n <div id=\"googlechat-drift\" class=\"notice\" hidden></div>\n <p>HTTP endpoint URL:</p><ul id=\"googlechat-callbacks\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>Use a Google Workspace account that may create a Cloud project and service-account keys. An organization policy can block key creation.</li>\n <li>Create a Google Cloud project for this app and enable the Google Chat API in it.</li>\n <li>On the Chat API Configuration page, build the app as a Google Workspace add-on, the default for a new app (convert an existing app first). Under Connection settings choose HTTP endpoint URL, use one URL for all triggers, and enter the URL above. Allow 1:1 messages and joining spaces, and choose who can use the app.</li>\n <li>Under Commands, add a slash command named /help with the description \"Show how to use this app\" and command ID 1; any free ID works, since AgentConnect matches the name.</li>\n <li>In the same project, create a service account and a JSON key for it, grant it the Browser role on the project, and enable the Cloud Resource Manager API; AgentConnect reads the project number with that key.</li>\n <li>Save the project ID and key here. The project number is optional: it is on the project's settings page and in the add-on's service account email, service-PROJECT_NUMBER@gcp-sa-gsuiteaddons.iam.gserviceaccount.com. When entered, it must match the number read from the key's project.</li>\n <li>Configure Google sign-in above, then add the app in Google Chat and send it a message. Each Google Workspace organization connects itself from Google Chat by signing in to the console with Google; publish the app on the Google Workspace Marketplace to reach other organizations.</li>\n </ol>\n <div class=\"row\"><a id=\"googlechat-configuration\" class=\"button\" href=\"https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat\" target=\"_blank\" rel=\"noopener\">Open Chat API configuration</a></div>\n <div id=\"googlechat-config-controls\" class=\"subsection\">\n <h3 id=\"googlechat-edit-heading\" hidden>Edit Google Chat App identity</h3>\n <label class=\"field\">Project ID<input id=\"googlechat-project-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">Project number (optional)<input id=\"googlechat-project-number-input\" inputmode=\"numeric\" autocomplete=\"off\" placeholder=\"Read from the key's project\"></label>\n <label class=\"field\">Service-account key JSON<input id=\"googlechat-key\" type=\"password\" autocomplete=\"off\" placeholder=\"Required when the project ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-googlechat\">Save Google Chat app</button><button id=\"cancel-googlechat-configuration\" hidden>Cancel</button><button id=\"clear-googlechat\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"email-section\" class=\"panel setup-section\" aria-labelledby=\"email-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"email-heading\">Email</h3><p class=\"muted\">One mail domain for the deployment. Each agent gets an address on it, received and sent through Cloudflare Email Service.</p></div>\n <span id=\"email-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Mail domain</dt><dd class=\"value-line\"><code id=\"email-mail-domain\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Cloudflare account ID</dt><dd class=\"value-line\"><code id=\"email-account-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>API token</dt><dd class=\"value-line\"><span id=\"email-token-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Ingress secret</dt><dd class=\"value-line\"><span id=\"email-ingress-display\" class=\"muted\">Not configured</span></dd>\n <dt>Daily send limit</dt><dd class=\"value-line\"><code id=\"email-send-limit\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n </dl>\n <p id=\"email-status\" class=\"muted\"></p>\n <div id=\"email-drift\" class=\"notice\" hidden></div>\n <div id=\"email-ingress-once\" class=\"notice\" hidden>\n <p>Ingress secret, shown once. Set it as the Worker's secret now:</p>\n <pre id=\"email-ingress-secret\"></pre>\n <div class=\"row\"><button id=\"copy-email-ingress\">Copy</button><button id=\"dismiss-email-ingress\">Dismiss</button></div>\n </div>\n <p>Inbound URL for the ingress Worker:</p><ul id=\"email-inbound\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>In Cloudflare, onboard a zone used for nothing else as the mail domain, for Email Routing and for Email Sending. A domain that already receives mail elsewhere cannot be used.</li>\n <li>Create an API token with the Email Sending: Edit permission for that account, then save the domain, the account ID and the token here. Setup checks the token with one read of the account's Email Sending suppression list and sends nothing.</li>\n <li>Deploy the ingress Worker with the inbound URL above and the ingress secret shown after the first save, and point the zone's catch-all routing rule at it.</li>\n <li>The daily send limit is the most mail the whole deployment sends in a day. Left empty, only the limits for each address and each organization apply.</li>\n </ol>\n <div class=\"row\"><a id=\"email-dashboard\" class=\"button\" href=\"https://dash.cloudflare.com/\" target=\"_blank\" rel=\"noopener\">Open Cloudflare</a></div>\n <div id=\"email-config-controls\" class=\"subsection\">\n <h3 id=\"email-edit-heading\" hidden>Edit Email configuration</h3>\n <label class=\"field\">Mail domain<input id=\"email-mail-domain-input\" autocomplete=\"off\" placeholder=\"mail.example.com\"></label>\n <label class=\"field\">Cloudflare account ID<input id=\"email-account-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">API token<input id=\"email-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the account ID changes\"></label>\n <label class=\"field\">Daily send limit (optional)<input id=\"email-send-limit-input\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n </div>\n <div class=\"row\"><button id=\"save-email\">Save Email</button><button id=\"cancel-email-configuration\" hidden>Cancel</button><button id=\"rotate-email-ingress\" hidden>Replace ingress secret</button><span id=\"email-rotate-confirm\" hidden>Replace? Mail is refused until the Worker has the new one. <button id=\"confirm-rotate-email-ingress\" class=\"danger\">Replace</button><button id=\"cancel-rotate-email-ingress\">Cancel</button></span><button id=\"clear-email\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n\n <section id=\"feishu-section\" class=\"panel setup-section\" aria-labelledby=\"feishu-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"feishu-heading\">Feishu</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Feishu, OAuth callbacks, and published App setup.</p></div>\n <span id=\"feishu-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"feishu-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"feishu\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"feishu-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"feishu.loginAppSecret\" data-secret-display=\"feishu-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"feishu-login-status\" class=\"muted\"></p>\n <div id=\"feishu-drift\" class=\"notice\" hidden></div>\n <div id=\"feishu-config-controls\" class=\"subsection\">\n <label id=\"feishu-create-name-field\" class=\"field\">New App name<input id=\"feishu-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"feishu-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"feishu-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-feishu-login-app\">Create Feishu App</button>\n <button id=\"save-feishu-login-app\">Save existing App</button>\n <button id=\"cancel-feishu-configuration\" hidden>Cancel</button>\n <button id=\"check-feishu-login-app\" hidden>Check setup</button>\n <button id=\"clear-feishu\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"feishu-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Feishu settings</a>\n </div>\n </section>\n\n <section id=\"lark-section\" class=\"panel setup-section\" aria-labelledby=\"lark-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"lark-heading\">Lark</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Lark, OAuth callbacks, and published App setup.</p></div>\n <span id=\"lark-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"lark-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"lark\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"lark-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"lark.loginAppSecret\" data-secret-display=\"lark-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"lark-login-status\" class=\"muted\"></p>\n <div id=\"lark-drift\" class=\"notice\" hidden></div>\n <div id=\"lark-config-controls\" class=\"subsection\">\n <label id=\"lark-create-name-field\" class=\"field\">New App name<input id=\"lark-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"lark-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"lark-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-lark-login-app\">Create Lark App</button>\n <button id=\"save-lark-login-app\">Save existing App</button>\n <button id=\"cancel-lark-configuration\" hidden>Cancel</button>\n <button id=\"check-lark-login-app\" hidden>Check setup</button>\n <button id=\"clear-lark\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"lark-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Lark settings</a>\n </div>\n </section>\n </div>\n\n <section id=\"options-section\" class=\"setup-section\">\n <h2>Deployment options</h2>\n <div class=\"panel\">\n <label class=\"field\"><span><input id=\"preset-agents-enabled\" type=\"checkbox\"> Enable preset Agents</span></label>\n <label class=\"field\">Max organizations created per non-ADMIN user<input id=\"max-orgs-per-non-admin-user\" type=\"number\" min=\"0\" step=\"1\" value=\"1\"></label>\n <label class=\"field\"><span><input id=\"organization-sso\" type=\"checkbox\"> Let organizations set up their own SSO</span></label>\n <div class=\"row\"><button id=\"save-options\">Save options</button></div>\n </div>\n </section>\n </section>\n </div>\n </div>\n </main>\n\n <script>\n const api = '/api/v1';\n const tokenKey = 'agentconnect.setup.token';\n const verifierKey = 'agentconnect.setup.pkce';\n const stateKey = 'agentconnect.setup.state';\n let currentRevision = 0;\n let currentStatus = null;\n let bootstrapInfo = null;\n const el = (id) => document.getElementById(id);\n const message = (text, error = false) => {\n const target = el('setup').hidden ? el('access-message') : el('message');\n target.textContent = text;\n target.className = error ? 'error' : 'ok';\n };\n const bearer = () => {\n const token = sessionStorage.getItem(tokenKey);\n return token ? { authorization: 'Bearer ' + token } : {};\n };\n const json = async (response) => {\n const body = await response.json().catch(() => ({}));\n if (!response.ok) throw Object.assign(new Error(body.message || ('HTTP ' + response.status)), { status: response.status, code: body.code });\n return body;\n };\n const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n const random = () => base64url(crypto.getRandomValues(new Uint8Array(32)));\n const configured = (byKey, key) => Boolean(byKey.get(key) && byKey.get(key).configured);\n const loginApps = ",
68561
- ";\n\n function showIdentityEditors(provider, show) {\n for (const button of document.querySelectorAll('.edit-configuration[data-provider=\"' + provider + '\"]')) {\n button.hidden = !show;\n }\n }\n\n function text(id, value) {\n el(id).textContent = value === null || value === undefined || value === '' ? 'Not configured' : String(value);\n }\n\n function secretText(id, byKey, key, editable) {\n const stored = configured(byKey, key);\n const display = el(id);\n const button = document.querySelector('[data-secret-display=\"' + id + '\"]');\n const row = display.closest('.secret-line');\n const editor = row && row.querySelector('.secret-editor');\n if (editor) editor.remove();\n display.hidden = false;\n display.textContent = stored ? '***' : 'Not configured';\n display.className = stored ? 'redacted' : 'muted';\n button.hidden = !editable;\n button.textContent = stored ? 'Edit' : 'Set';\n }\n\n function match(id, state, label) {\n const target = el(id);\n target.textContent = label;\n target.className = 'badge' + (state ? ' ' + state : '');\n }\n\n async function authConfig() { return json(await fetch(api + '/auth-config')); }\n\n async function signIn() {\n const config = await authConfig();\n if (config.mode !== 'oidc') throw new Error('Save an OIDC configuration first');\n const verifier = random();\n const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));\n const state = random();\n sessionStorage.setItem(verifierKey, verifier);\n sessionStorage.setItem(stateKey, state);\n const url = new URL(config.authorizationEndpoint);\n url.searchParams.set('client_id', config.appId);\n url.searchParams.set('redirect_uri', config.redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', 'openid profile email roles');\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n if (config.resource) url.searchParams.set('resource', config.resource);\n if (config.ssoConnectorId) url.searchParams.set('direct_sign_in', 'sso:' + config.ssoConnectorId);\n location.assign(url);\n }\n\n async function finishSignIn() {\n const url = new URL(location.href);\n const code = url.searchParams.get('code');\n if (!code) return;\n const state = url.searchParams.get('state');\n if (!state || state !== sessionStorage.getItem(stateKey)) throw new Error('OIDC state mismatch');\n const verifier = sessionStorage.getItem(verifierKey);\n if (!verifier) throw new Error('PKCE verifier is missing; start sign-in again');\n const config = await authConfig();\n const body = new URLSearchParams({\n grant_type: 'authorization_code', code, client_id: config.appId,\n redirect_uri: config.redirectUri, code_verifier: verifier\n });\n if (config.resource) body.set('resource', config.resource);\n const tokens = await json(await fetch(config.tokenEndpoint, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body\n }));\n if (typeof tokens.id_token !== 'string') throw new Error('Logto did not return an ID token');\n sessionStorage.setItem(tokenKey, tokens.id_token);\n sessionStorage.removeItem(verifierKey);\n sessionStorage.removeItem(stateKey);\n history.replaceState({}, '', '/');\n }\n\n function renderUriList(id, values) {\n el(id).replaceChildren(...(values || []).map((value) => {\n const item = document.createElement('li');\n const code = document.createElement('code'); code.textContent = value;\n item.append(code); return item;\n }));\n }\n\n function updateBootstrapProvider() {\n const provider = el('bootstrap-provider').value;\n el('bootstrap-google').hidden = provider !== 'google';\n el('bootstrap-github').hidden = provider !== 'github';\n el('bootstrap-slack').hidden = provider !== 'slack';\n el('bootstrap-sso').hidden = provider !== 'sso';\n }\n\n // The SSO connector each form shows: the saved one in settings, the one just created during first-run setup.\n const ssoState = {};\n\n function ssoUrls(connector) {\n const base = ((bootstrapInfo && bootstrapInfo.logtoEndpoint) || '').replace(/\\/+$/, '');\n const id = encodeURIComponent(connector.connectorId);\n return connector.protocol === 'oidc'\n ? ['Redirect URI: ' + base + '/callback/' + id]\n : ['ACS URL: ' + base + '/api/authn/single-sign-on/saml/' + id, 'SP entity ID: ' + base + '/enterprise-sso/' + id];\n }\n\n function renderSso(prefix, connector) {\n ssoState[prefix] = connector || undefined;\n if (connector) {\n el(prefix + '-protocol').value = connector.protocol;\n el(prefix + '-name').value = connector.name;\n el(prefix + '-domains').value = (connector.domains || []).join(', ');\n el(prefix + '-member-source').value = connector.memberSource || 'domain';\n renderMemberOrganizations(prefix, connector.memberOrganization || '');\n renderUriList(prefix + '-urls', ssoUrls(connector));\n const oidc = connector.oidc || {};\n el(prefix + '-issuer').value = oidc.issuer || '';\n el(prefix + '-client-id').value = oidc.clientId || '';\n el(prefix + '-scope').value = oidc.scope || '';\n el(prefix + '-trust-email').checked = connector.oidc ? oidc.trustUnverifiedEmail : true;\n const saml = connector.saml || {};\n el(prefix + '-metadata-url').value = saml.metadataUrl || '';\n el(prefix + '-metadata').value = saml.metadata || '';\n el(prefix + '-email-attribute').value = (saml.attributeMapping && saml.attributeMapping.email) || '';\n }\n updateSsoProtocol(prefix);\n }\n\n // The organizations new members may join; the empty value is the deployment's only one, and a saved id that is gone stays visible.\n let ssoOrganizations = [];\n function renderMemberOrganizations(prefix, selected) {\n const select = el(prefix + '-member-organization');\n select.replaceChildren();\n const option = (value, label) => {\n const item = document.createElement('option');\n item.value = value;\n item.textContent = label;\n select.append(item);\n };\n option('', 'The only organization');\n for (const org of ssoOrganizations) option(org.id, (org.name || org.slug) + ' (' + org.slug + ')');\n if (selected && !ssoOrganizations.some((org) => org.id === selected)) option(selected, 'Missing organization (' + selected + ')');\n select.value = selected;\n updateMemberOrganization(prefix);\n }\n\n function updateMemberOrganization(prefix) {\n el(prefix + '-member-organization').disabled = el(prefix + '-member-source').value === 'invite';\n }\n\n function updateSsoProtocol(prefix) {\n const connector = ssoState[prefix];\n const protocol = el(prefix + '-protocol').value;\n const current = Boolean(connector && connector.protocol === protocol);\n el(prefix + '-oidc').hidden = protocol !== 'oidc';\n el(prefix + '-saml').hidden = protocol !== 'saml';\n // Another protocol is another connector, so its details wait until it is created.\n el(prefix + '-details').hidden = !current;\n el(prefix + '-create').hidden = current;\n }\n\n async function createSso(prefix) {\n const name = el(prefix + '-name').value;\n const result = await json(await fetch(api + '/create/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ protocol: el(prefix + '-protocol').value, name })\n }));\n renderSso(prefix, { connectorId: result.connectorId, protocol: result.protocol, name, domains: [], memberSource: 'domain', oidc: null, saml: null });\n message('SSO connector created. Register its URLs with the identity provider, then enter the provider details.');\n }\n\n async function saveSso(prefix) {\n const protocol = el(prefix + '-protocol').value;\n const secret = el(prefix + '-client-secret').value;\n const metadataUrl = el(prefix + '-metadata-url').value.trim();\n const metadata = el(prefix + '-metadata').value.trim();\n const emailAttribute = el(prefix + '-email-attribute').value.trim();\n const connector = {\n name: el(prefix + '-name').value,\n domains: el(prefix + '-domains').value.split(',').map((domain) => domain.trim()).filter(Boolean),\n memberSource: el(prefix + '-member-source').value,\n memberOrganization: el(prefix + '-member-organization').value || null,\n ...(protocol === 'oidc'\n ? { oidc: {\n issuer: el(prefix + '-issuer').value.trim(),\n clientId: el(prefix + '-client-id').value.trim(),\n ...(secret ? { clientSecret: secret } : {}),\n scope: el(prefix + '-scope').value.trim(),\n trustUnverifiedEmail: el(prefix + '-trust-email').checked\n } }\n : { saml: {\n ...(metadataUrl ? { metadataUrl } : {}),\n ...(metadata ? { metadata } : {}),\n ...(emailAttribute ? { attributeMapping: { email: emailAttribute } } : {})\n } })\n };\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector })\n }));\n el(prefix + '-client-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n }\n\n async function removeSso() {\n if (!window.confirm('Remove SSO sign-in and delete its Logto connector? People who signed in through it lose that sign-in; their accounts stay.')) return;\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector: null })\n }));\n await reconcileLogto();\n await load();\n }\n\n function showBootstrapStep(step) {\n const logto = step === 'logto';\n el('bootstrap-logto-step').hidden = !logto;\n el('bootstrap-provider-step').hidden = logto;\n el('bootstrap-progress').textContent = logto ? 'Step 1 of 2' : 'Step 2 of 2';\n }\n\n function updateOwner(prefix) {\n el(prefix + '-org-field').hidden = el(prefix + '-owner').value !== 'organization';\n }\n\n function ownership(prefix) {\n if (el(prefix + '-owner').value === 'personal') return { owner: 'personal', organization: null };\n const organization = el(prefix + '-org').value.trim();\n if (!organization) throw new Error('Enter the GitHub organization login');\n return { owner: 'organization', organization };\n }\n\n function formatDiffValue(value) {\n if (value === null || value === undefined || value === '') return 'Not configured';\n if (Array.isArray(value)) return value.length ? value.map(formatDiffValue).join('\\n') : '[]';\n if (typeof value === 'object') {\n return Object.entries(value).map(([key, item]) => key + ': ' + (Array.isArray(item) ? item.join(', ') : formatDiffValue(item))).join('\\n');\n }\n return String(value);\n }\n\n function showDiff(id, rows, label = 'Update required') {\n const box = el(id);\n box.hidden = rows.length === 0;\n box.replaceChildren();\n if (rows.length === 0) return;\n const title = document.createElement('strong');\n title.className = 'diff-title';\n title.textContent = label;\n const grid = document.createElement('div');\n grid.className = 'config-diff';\n const head = document.createElement('div');\n head.className = 'diff-row diff-head';\n for (const text of ['Field', 'Current', 'Expected']) {\n const cell = document.createElement('span'); cell.textContent = text; head.append(cell);\n }\n grid.append(head);\n for (const item of rows) {\n const row = document.createElement('div'); row.className = 'diff-row';\n const field = document.createElement('span'); field.className = 'diff-field'; field.textContent = item.field;\n const current = document.createElement('span'); current.className = 'diff-value diff-current'; current.textContent = formatDiffValue(item.current);\n const expected = document.createElement('span'); expected.className = 'diff-value diff-expected'; expected.textContent = formatDiffValue(item.expected);\n row.append(field, current, expected); grid.append(row);\n }\n box.append(title, grid);\n }\n\n function renderStartupEnvironment() {\n const services = bootstrapInfo.services;\n const environment = [\n ['AGENTCONNECT_PUBLIC_CP_URL', services.controlPlane],\n ['AGENTCONNECT_PUBLIC_RELAY_URL', services.relay],\n ['AGENTCONNECT_PUBLIC_WEB_URL', services.web],\n ['LOGTO_ENDPOINT', bootstrapInfo.logtoEndpoint],\n ['LOGTO_MGMT_ENDPOINT', bootstrapInfo.logtoManagementEndpoint]\n ];\n el('startup-environment').textContent = environment\n .filter(([, value]) => value)\n .map(([key, value]) => key + '=' + value)\n .join('\\n');\n }\n\n function renderApps(status) {\n currentStatus = status;\n const byKey = new Map((status.secrets || []).map((item) => [item.key, item]));\n const values = status.values;\n const expected = status.providerExpectations || { github: null, gitlab: null, slack: null, linear: null, googleChat: null, google: { origins: [], redirects: [] } };\n renderStartupEnvironment();\n\n const logto = values.logto;\n text('logto-management-endpoint', logto && bootstrapInfo.logtoManagementEndpoint);\n text('logto-management-id', logto && logto.managementAppId);\n text('logto-management-resource', logto && logto.managementResource);\n secretText('logto-management-secret-display', byKey, 'logto.managementAppSecret', Boolean(logto));\n const sso = logto && logto.ssoConnector;\n ssoOrganizations = status.organizations || [];\n renderSso('sso', sso);\n el('sso-remove').hidden = !sso;\n match('sso-match', !sso ? '' : sso.oidc || sso.saml ? 'pass' : 'warn', !sso ? 'Not configured' : sso.oidc || sso.saml ? 'Configured' : 'Needs identity provider');\n text('logto-browser-endpoint', logto && logto.browser && bootstrapInfo.logtoEndpoint);\n text('logto-browser-id', values.auth.mode === 'oidc' ? values.auth.browserClient.appId : null);\n text('logto-browser-resource', logto && logto.browser && logto.browser.apiResource);\n el('logto-edit-controls').hidden = true;\n showIdentityEditors('logto', Boolean(logto && logto.browser && values.auth.mode === 'oidc'));\n match(\n 'logto-match',\n logto && configured(byKey, 'logto.managementAppSecret') ? '' : 'warn',\n logto && configured(byKey, 'logto.managementAppSecret') ? 'Ready to check' : 'Not configured'\n );\n\n el('preset-agents-enabled').checked = values.features.presetAgentsEnabled;\n el('max-orgs-per-non-admin-user').value = String(values.features.maxOrgsPerNonAdminUser);\n el('organization-sso').checked = values.features.organizationSso === true;\n\n const github = values.github;\n const webhookStored = byKey.get('github.webhookSecret') && byKey.get('github.webhookSecret').configured;\n const webhookInactive = github && github.webhookEnabled === false;\n text('github-app-id', github && github.appId);\n text('github-app-slug', github && github.slug);\n text('github-client-id', github && github.clientId);\n text('github-webhook-enabled', github && (github.webhookEnabled === false ? 'Disabled' : 'Enabled'));\n el('github-edit-controls').hidden = true;\n showIdentityEditors('github', Boolean(github));\n secretText('github-client-secret-display', byKey, 'github.clientSecret', Boolean(github));\n secretText('github-private-key-display', byKey, 'github.privateKeyB64', Boolean(github));\n secretText('github-webhook-secret-display', byKey, 'github.webhookSecret', Boolean(github));\n secretText('github-logto-secret-display', byKey, 'logto.githubConnectorClientSecret', Boolean(values.logto && values.logto.githubConnector));\n el('github-status').textContent = github\n ? github.slug + ' is configured. Webhook secret: ' + (webhookStored ? 'stored' : webhookInactive ? 'not required yet' : 'missing') + '.' +\n (webhookInactive ? ' Relay webhook delivery is disabled.' : '')\n : 'Creates the complete App used for repository installation, webhooks, and optional GitHub sign-in.';\n const githubDrift = github\n ? expected.github\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'Valid Web, API, and ingress URLs' }]\n : [];\n match('github-match', !github ? '' : githubDrift.length ? 'warn' : '', !github ? 'Not configured' : githubDrift.length ? 'Expected URLs changed' : 'Ready to check');\n el('github-create-controls').hidden = Boolean(github);\n el('create-github').hidden = Boolean(github);\n el('clear-github').hidden = !github;\n el('connect-github-login').hidden = !github || !values.logto || Boolean(values.logto.githubConnector);\n el('check-github').hidden = !github;\n if (github) showDiff('github-drift', githubDrift, 'Expected URLs changed since App creation');\n else el('github-drift').hidden = true;\n\n const gitlab = values.gitlab;\n const gitlabSecret = configured(byKey, 'gitlab.clientSecret');\n const expectedGitlab = expected.gitlab;\n renderUriList('gitlab-callbacks', expectedGitlab ? [expectedGitlab.callbackUrl] : []);\n renderUriList('gitlab-scopes', expectedGitlab ? expectedGitlab.scopes : []);\n text('gitlab-client-id', gitlab && gitlab.clientId);\n secretText('gitlab-client-secret-display', byKey, 'gitlab.clientSecret', Boolean(gitlab));\n showIdentityEditors('gitlab', Boolean(gitlab));\n el('gitlab-id').value = gitlab ? gitlab.clientId : '';\n text('gitlab-instance', (gitlab && gitlab.baseUrl) || 'https://gitlab.com');\n // Host-aware application links (§24.1): composed by the server against the\n // configured base, so a path-prefixed install keeps its prefix here too.\n if (expectedGitlab) {\n el('gitlab-applications').href = expectedGitlab.applicationsUrl;\n el('gitlab-admin-applications').href = expectedGitlab.adminApplicationsUrl;\n }\n el('gitlab-base-url').value = (gitlab && gitlab.baseUrl) || '';\n el('gitlab-status').textContent = gitlab\n ? gitlab.clientId + ' is configured.'\n : expectedGitlab\n ? 'Register the OAuth application on the configured GitLab instance, then save its Application ID and Secret here.'\n : 'Publishing the redirect URI needs an HTTPS API public URL.';\n showDiff('gitlab-drift', gitlab && !expectedGitlab\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS API URL' }]\n : []);\n match('gitlab-match', gitlab && gitlabSecret ? 'warn' : '', !gitlab ? 'Not configured' : !gitlabSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('gitlab-initial-secret-field').hidden = Boolean(gitlab) && gitlabSecret;\n el('gitlab-config-controls').hidden = Boolean(gitlab);\n el('save-gitlab').hidden = Boolean(gitlab);\n el('cancel-gitlab-configuration').hidden = true;\n el('clear-gitlab').hidden = !gitlab;\n const gitlabLogin = values.logto?.browser?.socialProviders.includes('gitlab');\n renderUriList('gitlab-login-redirects', expected.gitlabSignIn?.redirects || []);\n el('gitlab-login-status').textContent = gitlabLogin ? 'GitLab sign-in is configured. Use Check Logto to verify it.' : 'GitLab sign-in is not enabled.';\n el('connect-gitlab-login').hidden = Boolean(gitlabLogin);\n el('connect-gitlab-login').disabled = !gitlab || !gitlabSecret || !values.logto?.browser;\n el('disconnect-gitlab-login').hidden = !gitlabLogin;\n el('check-gitlab-login').hidden = !gitlabLogin;\n\n const gitea = values.gitea;\n text('gitea-instance', (gitea && gitea.baseUrl) || 'https://gitea.com');\n el('gitea-base-url').value = (gitea && gitea.baseUrl) || '';\n showIdentityEditors('gitea', Boolean(gitea));\n el('gitea-status').textContent = gitea\n ? ((gitea.baseUrl || 'https://gitea.com') + ' is configured.')\n : 'Organizations can connect gitea.com without saving anything. Save an address only for a self-hosted instance.';\n match('gitea-match', gitea ? 'warn' : '', gitea ? \"Can't verify automatically\" : 'Default');\n el('gitea-config-controls').hidden = Boolean(gitea);\n el('save-gitea').hidden = Boolean(gitea);\n el('cancel-gitea-configuration').hidden = true;\n el('clear-gitea').hidden = !gitea;\n\n const slack = values.slack;\n text('slack-app-id', slack && slack.appId);\n text('slack-client-id', slack && slack.clientId);\n el('slack-edit-controls').hidden = true;\n showIdentityEditors('slack', Boolean(slack));\n secretText('slack-client-secret-display', byKey, 'slack.clientSecret', Boolean(slack));\n secretText('slack-signing-secret-display', byKey, 'slack.signingSecret', Boolean(slack));\n el('slack-logto-status').textContent = values.logto && values.logto.slackConnector\n ? 'Enabled; reuses the Slack client secret above.'\n : 'Not enabled.';\n el('slack-status').textContent = slack ? slack.appId + ' is configured.' : 'Creates the default AgentConnect integration manifest.';\n const slackDrift = slack\n ? expected.slack\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS Web, API, and ingress URLs' }]\n : [];\n match('slack-match', !slack ? '' : slackDrift.length ? 'warn' : '', !slack ? 'Not configured' : slackDrift.length ? 'Update required' : 'Ready to check');\n el('slack-name-field').hidden = Boolean(slack);\n el('create-slack').hidden = Boolean(slack);\n el('connect-slack-login').hidden = !slack || !values.logto || Boolean(values.logto.slackConnector) || !bootstrapInfo?.slackAvailable;\n el('clear-slack').hidden = !slack;\n el('check-slack').hidden = !slack;\n el('reconcile-slack').hidden = !slack;\n el('slack-settings').hidden = !slack;\n if (slack) {\n el('slack-settings').href = 'https://api.slack.com/apps/' + encodeURIComponent(slack.appId);\n showDiff('slack-drift', slackDrift);\n } else el('slack-drift').hidden = true;\n\n const googleChat = values.googleChat;\n const googleChatKey = configured(byKey, 'googleChat.serviceAccountKey');\n const expectedGoogleChat = expected.googleChat;\n renderUriList('googlechat-callbacks', expectedGoogleChat ? [expectedGoogleChat.callbackUrl] : []);\n text('googlechat-project-id', googleChat && googleChat.projectId);\n text('googlechat-project-number', googleChat && googleChat.projectNumber);\n el('googlechat-key-display').textContent = googleChatKey ? '***' : 'Not configured';\n el('googlechat-key-display').className = googleChatKey ? 'redacted' : 'muted';\n showIdentityEditors('googlechat', Boolean(googleChat));\n el('googlechat-project-id-input').value = googleChat ? googleChat.projectId : '';\n el('googlechat-project-number-input').value = googleChat ? googleChat.projectNumber : '';\n el('googlechat-key').value = '';\n if (expectedGoogleChat) el('googlechat-configuration').href = expectedGoogleChat.configurationUrl;\n el('googlechat-status').textContent = googleChat\n ? googleChat.projectId + ' is configured.'\n : expectedGoogleChat\n ? 'Configure the Chat app in Google Cloud Console, then save its project and service-account key here.'\n : 'Publishing the HTTP endpoint URL needs an HTTPS ingress public URL.';\n showDiff('googlechat-drift', googleChat && !expectedGoogleChat\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n match('googlechat-match', googleChat && googleChatKey ? 'pass' : googleChat ? 'warn' : '', !googleChat ? 'Not configured' : !googleChatKey ? 'Missing key' : 'Checked on save');\n el('googlechat-edit-heading').hidden = true;\n el('googlechat-config-controls').hidden = Boolean(googleChat);\n el('save-googlechat').hidden = Boolean(googleChat);\n el('cancel-googlechat-configuration').hidden = true;\n el('clear-googlechat').hidden = !googleChat;\n\n const email = values.email;\n const emailToken = configured(byKey, 'email.apiToken');\n const emailIngress = configured(byKey, 'email.ingressSecret');\n const expectedEmail = expected.email;\n renderUriList('email-inbound', expectedEmail ? [expectedEmail.inboundUrl] : []);\n text('email-mail-domain', email && email.mailDomain);\n text('email-account-id', email && email.accountId);\n text('email-send-limit', email && (email.dailySendLimit ? email.dailySendLimit : 'No deployment-wide limit'));\n for (const [id, stored] of [['email-token-display', emailToken], ['email-ingress-display', emailIngress]]) {\n el(id).textContent = stored ? '***' : 'Not configured';\n el(id).className = stored ? 'redacted' : 'muted';\n }\n showIdentityEditors('email', Boolean(email));\n el('email-mail-domain-input').value = email ? email.mailDomain : '';\n el('email-account-id-input').value = email ? email.accountId : '';\n el('email-send-limit-input').value = email && email.dailySendLimit ? String(email.dailySendLimit) : '';\n el('email-token').value = '';\n if (expectedEmail) el('email-dashboard').href = expectedEmail.dashboardUrl;\n el('email-status').textContent = email\n ? 'Agents get addresses on ' + email.mailDomain + '.'\n : expectedEmail\n ? 'Onboard the mail domain in Cloudflare, then save it with the account ID and an API token here.'\n : 'Publishing the inbound URL needs an HTTPS ingress public URL.';\n showDiff('email-drift', email && !expectedEmail\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n const emailReady = email && emailToken && emailIngress;\n match('email-match', emailReady ? 'pass' : email ? 'warn' : '', !email ? 'Not configured' : !emailReady ? 'Missing secret' : 'Checked on save');\n el('email-edit-heading').hidden = true;\n el('email-config-controls').hidden = Boolean(email);\n el('save-email').hidden = Boolean(email);\n el('cancel-email-configuration').hidden = true;\n // A status render never touches the secret box or a pending Replace: they belong to the operator's own clicks.\n if (!email) el('email-rotate-confirm').hidden = true;\n el('rotate-email-ingress').hidden = !email || !el('email-rotate-confirm').hidden;\n el('clear-email').hidden = !email;\n\n\n const linear = values.linear;\n const linearSecrets = configured(byKey, 'linear.clientSecret') && configured(byKey, 'linear.signingSecret');\n const expectedLinear = expected.linear;\n renderUriList('linear-callbacks', expectedLinear ? [expectedLinear.callbackUrl] : []);\n renderUriList('linear-webhooks', expectedLinear ? [expectedLinear.webhookUrl] : []);\n text('linear-client-id', linear && linear.clientId);\n secretText('linear-client-secret-display', byKey, 'linear.clientSecret', Boolean(linear));\n secretText('linear-signing-secret-display', byKey, 'linear.signingSecret', Boolean(linear));\n showIdentityEditors('linear', Boolean(linear));\n el('linear-id').value = linear ? linear.clientId : '';\n if (expectedLinear) el('linear-applications').href = expectedLinear.applicationsUrl;\n el('linear-status').textContent = linear\n ? linear.clientId + ' is configured.'\n : expectedLinear\n ? 'Register the OAuth application in Linear, then save its Client ID and both secrets here.'\n : 'Publishing the callback and webhook URLs needs HTTPS API and ingress public URLs.';\n showDiff('linear-drift', linear && !expectedLinear\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS API and ingress URLs' }]\n : []);\n match('linear-match', linear && linearSecrets ? 'warn' : '', !linear ? 'Not configured' : !linearSecrets ? 'Missing secret' : \"Can't verify automatically\");\n el('linear-initial-secret-fields').hidden = Boolean(linear) && linearSecrets;\n el('linear-config-controls').hidden = Boolean(linear);\n el('save-linear').hidden = Boolean(linear);\n el('cancel-linear-configuration').hidden = true;\n el('clear-linear').hidden = !linear;\n\n const google = values.logto && values.logto.googleConnector;\n const googleSecret = configured(byKey, 'logto.googleConnectorClientSecret');\n const expectedGoogle = expected.google;\n renderUriList('google-origins', expectedGoogle.origins);\n renderUriList('google-redirects', expectedGoogle.redirects);\n text('google-client-id', google && google.clientId);\n secretText('google-client-secret-display', byKey, 'logto.googleConnectorClientSecret', Boolean(google));\n showIdentityEditors('google', Boolean(google));\n el('google-id').value = google ? google.clientId : '';\n el('google-status').textContent = google ? 'Google OAuth client is configured.' : 'Create a Web application OAuth client manually, then save it here.';\n showDiff('google-drift', []);\n match('google-match', google && googleSecret ? 'warn' : '', !google ? 'Not configured' : !googleSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('google-initial-secret-field').hidden = googleSecret;\n el('save-google').textContent = google ? 'Confirm callback settings' : 'Save Google client';\n el('google-config-controls').hidden = Boolean(google);\n el('save-google').hidden = Boolean(google);\n el('cancel-google-configuration').hidden = true;\n el('check-google').hidden = !google || !googleSecret;\n el('clear-google').hidden = !google;\n\n for (const [provider, app] of Object.entries(loginApps)) {\n const saved = values.logto && values.logto[provider + 'Connector'];\n const secretKey = 'logto.' + provider + 'ConnectorClientSecret';\n const hasSecret = configured(byKey, secretKey);\n renderUriList(provider + '-redirects', expected[provider].redirects);\n text(provider + '-client-id', saved && saved.clientId);\n secretText(provider + '-client-secret-display', byKey, secretKey, Boolean(saved));\n showIdentityEditors(provider, Boolean(saved));\n el(provider + '-id').value = saved ? saved.clientId : '';\n el(provider + '-status').hidden = !saved;\n el(provider + '-status').textContent = saved ? app.name + ' login application is saved.' : '';\n showDiff(provider + '-drift', []);\n match(provider + '-match', saved ? 'warn' : '', !saved ? 'Not configured' : !hasSecret ? 'Missing secret' : 'Not checked');\n el(provider + '-initial-secret-field').hidden = hasSecret;\n el(provider + '-config-controls').hidden = Boolean(saved);\n el('save-' + provider).hidden = Boolean(saved);\n el('save-' + provider).disabled = !values.logto || !values.logto.browser;\n el('cancel-' + provider + '-configuration').hidden = true;\n el('check-' + provider).hidden = !saved || !hasSecret;\n el('clear-' + provider).hidden = !saved;\n }\n const expectedTeams = expected.msTeams;\n text('azuread-teams-tenant-id', values.msTeams && values.msTeams.tenantId);\n el('azuread-teams-tenant-input').value = values.msTeams ? values.msTeams.tenantId : '';\n renderUriList('azuread-teams-endpoint', expectedTeams ? [expectedTeams.messagingEndpoint] : []);\n renderUriList('azuread-teams-redirects', expectedTeams ? [expectedTeams.connectRedirectUri] : []);\n // Agent bots sit beside the Teams app: the group shows once it is configured, and its form until a blueprint is saved.\n const agentBots = values.msTeams && values.msTeams.agentBots;\n const blueprintSecret = configured(byKey, 'msTeams.blueprintClientSecret');\n el('azuread-agent-bots').hidden = !values.msTeams;\n text('azuread-agent-bots-blueprint', agentBots && agentBots.blueprintId);\n el('azuread-agent-bots-secret').textContent = blueprintSecret ? '***' : 'Not configured';\n el('azuread-agent-bots-secret').className = blueprintSecret ? 'redacted' : 'muted';\n text('azuread-agent-bots-subscription', agentBots && agentBots.subscriptionId);\n text('azuread-agent-bots-group', agentBots && agentBots.resourceGroup);\n el('azuread-agent-bots-controls').hidden = Boolean(agentBots);\n el('clear-azuread-agent-bots').hidden = !agentBots;\n renderUriList('azuread-azure-devops-redirects', expected.azureDevOps ? [expected.azureDevOps.connectRedirectUri] : []);\n\n const feishuSecret = byKey.get('feishu.loginAppSecret');\n const larkSecret = byKey.get('lark.loginAppSecret');\n el('feishu-login-id').value = values.feishu ? values.feishu.loginAppId : '';\n el('lark-login-id').value = values.lark ? values.lark.loginAppId : '';\n text('feishu-app-id', values.feishu && values.feishu.loginAppId);\n text('lark-app-id', values.lark && values.lark.loginAppId);\n showIdentityEditors('feishu', Boolean(values.feishu));\n showIdentityEditors('lark', Boolean(values.lark));\n secretText('feishu-app-secret-display', byKey, 'feishu.loginAppSecret', Boolean(values.feishu));\n secretText('lark-app-secret-display', byKey, 'lark.loginAppSecret', Boolean(values.lark));\n el('feishu-login-status').textContent = values.feishu && feishuSecret && feishuSecret.configured\n ? values.feishu.loginAppId + ' is configured.'\n : 'No Feishu tenant App is configured.';\n el('lark-login-status').textContent = values.lark && larkSecret && larkSecret.configured\n ? values.lark.loginAppId + ' is configured.'\n : 'No Lark tenant App is configured.';\n match('feishu-match', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? '' : '', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? 'Ready to check' : 'Not configured');\n match('lark-match', values.lark && configured(byKey, 'lark.loginAppSecret') ? '' : '', values.lark && configured(byKey, 'lark.loginAppSecret') ? 'Ready to check' : 'Not configured');\n showDiff('feishu-drift', []);\n showDiff('lark-drift', []);\n el('feishu-config-controls').hidden = Boolean(values.feishu);\n el('lark-config-controls').hidden = Boolean(values.lark);\n el('feishu-create-name-field').hidden = Boolean(values.feishu);\n el('lark-create-name-field').hidden = Boolean(values.lark);\n el('create-feishu-login-app').hidden = Boolean(values.feishu);\n el('create-lark-login-app').hidden = Boolean(values.lark);\n el('save-feishu-login-app').hidden = Boolean(values.feishu);\n el('save-lark-login-app').hidden = Boolean(values.lark);\n el('cancel-feishu-configuration').hidden = true;\n el('cancel-lark-configuration').hidden = true;\n el('clear-feishu').hidden = !values.feishu;\n el('clear-lark').hidden = !values.lark;\n el('check-feishu-login-app').hidden = !values.feishu || !configured(byKey, 'feishu.loginAppSecret');\n el('check-lark-login-app').hidden = !values.lark || !configured(byKey, 'lark.loginAppSecret');\n el('feishu-settings').hidden = !values.feishu;\n el('lark-settings').hidden = !values.lark;\n if (values.feishu) el('feishu-settings').href = 'https://open.feishu.cn/app/' + encodeURIComponent(values.feishu.loginAppId);\n if (values.lark) el('lark-settings').href = 'https://open.larksuite.com/app/' + encodeURIComponent(values.lark.loginAppId);\n }\n\n function requiredInput(id, label) {\n const value = el(id).value.trim();\n if (!value) throw new Error('Enter ' + label);\n return value;\n }\n\n function githubConnectorUsesDeployment(values) {\n const github = values.github;\n const connector = values.logto && values.logto.githubConnector;\n return Boolean(\n github && connector &&\n connector.appId === github.appId &&\n connector.slug === github.slug &&\n connector.clientId === github.clientId\n );\n }\n\n function beginConfigurationEdit(provider) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const values = currentStatus.values;\n if (provider === 'logto') {\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') return;\n el('logto-edit-management-id').value = logto.managementAppId;\n el('logto-edit-management-resource').value = logto.managementResource;\n el('logto-edit-management-secret').value = '';\n el('logto-edit-browser-id').value = values.auth.browserClient.appId;\n el('logto-edit-browser-resource').value = logto.browser.apiResource || '';\n el('logto-edit-controls').hidden = false;\n el('logto-edit-management-id').focus();\n } else if (provider === 'github') {\n const github = values.github;\n if (!github) return;\n el('github-edit-app-id').value = String(github.appId);\n el('github-edit-slug').value = github.slug;\n el('github-edit-client-id').value = github.clientId || '';\n el('github-edit-webhook-enabled').checked = github.webhookEnabled !== false;\n for (const id of ['github-edit-client-secret', 'github-edit-private-key', 'github-edit-webhook-secret', 'github-edit-logto-secret']) el(id).value = '';\n el('github-edit-logto-secret-field').hidden = !githubConnectorUsesDeployment(values);\n el('github-edit-controls').hidden = false;\n el('clear-github').hidden = true;\n el('github-edit-app-id').focus();\n } else if (provider === 'slack') {\n const slack = values.slack;\n if (!slack) return;\n el('slack-edit-app-id').value = slack.appId;\n el('slack-edit-client-id').value = slack.clientId;\n el('slack-edit-client-secret').value = '';\n el('slack-edit-signing-secret').value = '';\n el('slack-edit-controls').hidden = false;\n el('clear-slack').hidden = true;\n el('slack-edit-app-id').focus();\n } else if (provider === 'gitea') {\n if (!values.gitea) return;\n el('gitea-base-url').value = values.gitea.baseUrl || '';\n el('gitea-config-controls').hidden = false;\n el('save-gitea').hidden = false;\n el('cancel-gitea-configuration').hidden = false;\n el('clear-gitea').hidden = true;\n el('gitea-base-url').focus();\n } else if (provider === 'gitlab') {\n if (!values.gitlab) return;\n el('gitlab-id').value = values.gitlab.clientId;\n el('gitlab-secret').value = '';\n el('gitlab-config-controls').hidden = false;\n el('gitlab-initial-secret-field').hidden = false;\n el('save-gitlab').hidden = false;\n el('cancel-gitlab-configuration').hidden = false;\n el('clear-gitlab').hidden = true;\n el('gitlab-id').focus();\n } else if (provider === 'googlechat') {\n if (!values.googleChat) return;\n el('googlechat-project-id-input').value = values.googleChat.projectId;\n el('googlechat-project-number-input').value = values.googleChat.projectNumber;\n el('googlechat-key').value = '';\n el('googlechat-edit-heading').hidden = false;\n el('googlechat-config-controls').hidden = false;\n el('save-googlechat').hidden = false;\n el('cancel-googlechat-configuration').hidden = false;\n el('clear-googlechat').hidden = true;\n el('googlechat-project-id-input').focus();\n } else if (provider === 'email') {\n if (!values.email) return;\n el('email-mail-domain-input').value = values.email.mailDomain;\n el('email-account-id-input').value = values.email.accountId;\n el('email-send-limit-input').value = values.email.dailySendLimit ? String(values.email.dailySendLimit) : '';\n el('email-token').value = '';\n el('email-edit-heading').hidden = false;\n el('email-config-controls').hidden = false;\n el('save-email').hidden = false;\n el('cancel-email-configuration').hidden = false;\n el('rotate-email-ingress').hidden = true;\n el('email-rotate-confirm').hidden = true;\n el('clear-email').hidden = true;\n el('email-mail-domain-input').focus();\n } else if (provider === 'linear') {\n if (!values.linear) return;\n el('linear-id').value = values.linear.clientId;\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n el('linear-config-controls').hidden = false;\n el('linear-initial-secret-fields').hidden = false;\n el('save-linear').hidden = false;\n el('cancel-linear-configuration').hidden = false;\n el('clear-linear').hidden = true;\n el('linear-id').focus();\n } else if (provider === 'google') {\n const google = values.logto && values.logto.googleConnector;\n if (!google) return;\n el('google-id').value = google.clientId;\n el('google-secret').value = '';\n el('google-config-controls').hidden = false;\n el('google-initial-secret-field').hidden = false;\n el('save-google').hidden = false;\n el('save-google').textContent = 'Save Google client';\n el('cancel-google-configuration').hidden = false;\n el('clear-google').hidden = true;\n el('google-id').focus();\n } else if (Object.hasOwn(loginApps, provider)) {\n el(provider + '-secret').value = '';\n el(provider + '-config-controls').hidden = false;\n el(provider + '-initial-secret-field').hidden = false;\n el('save-' + provider).hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-id').focus();\n } else if (provider === 'feishu' || provider === 'lark') {\n el(provider + '-config-controls').hidden = false;\n el(provider + '-create-name-field').hidden = true;\n el('create-' + provider + '-login-app').hidden = true;\n el('save-' + provider + '-login-app').hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-login-secret').value = '';\n el(provider + '-login-id').focus();\n }\n showIdentityEditors(provider, false);\n }\n\n function cancelConfigurationEdit() {\n if (currentStatus) renderApps(currentStatus);\n }\n\n async function replaceConfiguration(values, secrets, successMessage) {\n const response = await json(await fetch(api + '/deployment-config', {\n method: 'PUT',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values, ...(secrets ? { secrets } : {}) })\n }));\n await load();\n message(successMessage || 'Configuration saved. Restart AgentConnect to apply it.');\n return response;\n }\n\n async function saveLogtoConfiguration() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') throw new Error('Logto is not configured');\n const managementAppId = requiredInput('logto-edit-management-id', 'the Management App ID');\n const managementResource = requiredInput('logto-edit-management-resource', 'the Management API resource');\n const browserAppId = requiredInput('logto-edit-browser-id', 'the SPA App ID');\n const browserResource = el('logto-edit-browser-resource').value.trim() || null;\n const managementIdentityChanged = managementAppId !== logto.managementAppId;\n const managementSecret = el('logto-edit-management-secret').value;\n if (managementIdentityChanged && !managementSecret) throw new Error('Enter the new Management App secret');\n const browser = { ...logto.browser, apiResource: browserResource };\n const auth = {\n ...values.auth,\n audience: browserResource || browserAppId,\n browserClient: { appId: browserAppId, apiResource: browserResource }\n };\n await replaceConfiguration(\n {\n ...values,\n auth,\n logto: { ...logto, managementAppId, managementResource, browser }\n },\n managementSecret ? { 'logto.managementAppSecret': managementSecret } : undefined,\n 'Logto configuration saved. Sign in again if the SPA identity changed, then restart AgentConnect.'\n );\n }\n\n async function saveGithubConfiguration() {\n if (!currentStatus || !currentStatus.values.github) throw new Error('GitHub is not configured');\n const values = currentStatus.values;\n const previous = values.github;\n const appId = Number(requiredInput('github-edit-app-id', 'the GitHub App ID'));\n if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error('GitHub App ID must be a positive integer');\n const slug = requiredInput('github-edit-slug', 'the GitHub App slug');\n const clientId = requiredInput('github-edit-client-id', 'the GitHub Client ID');\n const appChanged = appId !== previous.appId;\n const clientChanged = clientId !== previous.clientId;\n const webhookEnabled = el('github-edit-webhook-enabled').checked;\n const webhookEnabling = webhookEnabled && previous.webhookEnabled === false;\n const connectorReused = githubConnectorUsesDeployment(values);\n const clientSecret = el('github-edit-client-secret').value;\n const privateKey = el('github-edit-private-key').value.trim();\n const webhookSecret = el('github-edit-webhook-secret').value;\n const connectorSecret = el('github-edit-logto-secret').value;\n const webhookSecretStored = currentStatus.secrets.some((secret) => secret.key === 'github.webhookSecret' && secret.configured);\n if ((appChanged || clientChanged) && !clientSecret) throw new Error('Enter the new GitHub client secret');\n if (appChanged && !privateKey) throw new Error('Enter the new GitHub private key as base64');\n if (webhookEnabled && ((appChanged && !webhookSecret) || (webhookEnabling && !webhookSecret && !webhookSecretStored))) throw new Error('Enter the new GitHub webhook secret');\n if (connectorReused && (appChanged || clientChanged) && !connectorSecret) throw new Error('Enter the new Logto connector client secret');\n const secrets = {};\n if (clientSecret) secrets['github.clientSecret'] = clientSecret;\n if (privateKey) secrets['github.privateKeyB64'] = privateKey;\n if (webhookSecret) secrets['github.webhookSecret'] = webhookSecret;\n if (connectorSecret) secrets['logto.githubConnectorClientSecret'] = connectorSecret;\n const nextLogto = connectorReused && values.logto\n ? { ...values.logto, githubConnector: { ...values.logto.githubConnector, appId, slug, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n github: { ...previous, appId, slug, clientId, webhookEnabled },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'GitHub App identity saved. Restart AgentConnect to apply it.'\n );\n if (connectorSecret) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function saveSlackConfiguration() {\n if (!currentStatus || !currentStatus.values.slack) throw new Error('Slack is not configured');\n const values = currentStatus.values;\n const previous = values.slack;\n const appId = requiredInput('slack-edit-app-id', 'the Slack App ID');\n const clientId = requiredInput('slack-edit-client-id', 'the Slack Client ID');\n const changed = appId !== previous.appId || clientId !== previous.clientId;\n const clientSecret = el('slack-edit-client-secret').value;\n const signingSecret = el('slack-edit-signing-secret').value;\n if (changed && (!clientSecret || !signingSecret)) throw new Error('Enter both the new Slack client secret and signing secret');\n const secrets = {};\n if (clientSecret) secrets['slack.clientSecret'] = clientSecret;\n if (signingSecret) secrets['slack.signingSecret'] = signingSecret;\n const nextLogto = values.logto && values.logto.slackConnector\n ? { ...values.logto, slackConnector: { ...values.logto.slackConnector, appId, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n slack: { ...previous, appId, clientId },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'Slack App identity saved. Restart AgentConnect to apply it.'\n );\n if (clientSecret && nextLogto && nextLogto.slackConnector) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function clearProvider(provider) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const label = provider === 'github' ? 'GitHub' : provider === 'gitlab' ? 'GitLab' : provider === 'gitea' ? 'Gitea' : provider === 'slack' ? 'Slack' : provider === 'googlechat' ? 'Google Chat' : provider === 'email' ? 'Email' : provider === 'linear' ? 'Linear' : provider === 'google' ? 'Google' : provider === 'feishu' ? 'Feishu' : 'Lark';\n if (!window.confirm('Clear the saved ' + label + ' configuration and secrets?')) return;\n const values = currentStatus.values;\n let next = values;\n let secrets = {};\n if (provider === 'github') {\n const connectorReused = githubConnectorUsesDeployment(values);\n const logto = connectorReused && values.logto\n ? {\n ...values.logto,\n githubConnector: null\n }\n : values.logto;\n next = { ...values, github: null, ...(logto ? { logto } : {}) };\n secrets = {\n 'github.clientSecret': null,\n 'github.privateKeyB64': null,\n 'github.webhookSecret': null,\n ...(connectorReused ? { 'logto.githubConnectorClientSecret': null } : {})\n };\n } else if (provider === 'gitea') {\n // Gitea holds no deployment secret, so clearing the address clears the whole entry.\n next = { ...values, gitea: null };\n } else if (provider === 'gitlab') {\n await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: null })\n }));\n showGitlabProbe(null);\n await load();\n message('GitLab configuration cleared. Its setup controls are available again.');\n return;\n } else if (provider === 'slack') {\n const logto = values.logto\n ? {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'slack') }\n : values.logto.browser,\n slackConnector: null\n }\n : values.logto;\n next = { ...values, slack: null, ...(logto ? { logto } : {}) };\n secrets = { 'slack.clientSecret': null, 'slack.signingSecret': null };\n } else if (provider === 'googlechat') {\n next = { ...values, googleChat: null };\n secrets = { 'googleChat.serviceAccountKey': null };\n } else if (provider === 'email') {\n next = { ...values, email: null };\n secrets = { 'email.apiToken': null, 'email.ingressSecret': null };\n } else if (provider === 'linear') {\n next = { ...values, linear: null };\n secrets = { 'linear.clientSecret': null, 'linear.signingSecret': null };\n } else if (provider === 'google') {\n if (!values.logto) return;\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'google') }\n : values.logto.browser,\n googleConnector: null\n }\n };\n secrets = { 'logto.googleConnectorClientSecret': null };\n } else if (provider === 'feishu' || provider === 'lark') {\n next = { ...values, [provider]: null };\n secrets = { [provider + '.loginAppSecret']: null };\n }\n await replaceConfiguration(next, secrets, label + ' configuration cleared. Its setup controls are available again.');\n if (provider === 'gitea') el('gitea-probe').hidden = true;\n if (provider === 'email') showEmailIngressSecret('');\n }\n\n async function startGithub(prefix) {\n const result = await json(await fetch(api + '/create/github/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n purpose: 'deployment',\n name: el(prefix + '-name').value,\n ownership: ownership(prefix),\n connectLogto: prefix === 'bootstrap-github'\n })\n }));\n const form = document.createElement('form');\n form.method = 'post'; form.action = result.action;\n const manifest = document.createElement('input');\n manifest.type = 'hidden'; manifest.name = 'manifest'; manifest.value = JSON.stringify(result.manifest);\n form.append(manifest); document.body.append(form);\n message('Opening GitHub to review the complete integration App.');\n form.submit();\n }\n\n async function loadBootstrapInfo() {\n bootstrapInfo = await json(await fetch(api + '/bootstrap-info'));\n el('open-logto').href = bootstrapInfo.logtoAdminEndpoint;\n el('logto-settings').href = bootstrapInfo.logtoAdminEndpoint;\n if (!el('logto-app-id').value && bootstrapInfo.logtoManagementAppId) {\n el('logto-app-id').value = bootstrapInfo.logtoManagementAppId;\n }\n renderUriList('bootstrap-google-origins', bootstrapInfo.google.javascriptOrigins);\n renderUriList('bootstrap-google-redirects', bootstrapInfo.google.redirectUris);\n renderUriList('bootstrap-slack-redirects', [bootstrapInfo.slackLoginRedirectUrl]);\n el('logto-management-api-resource').value = bootstrapInfo.logtoManagementResource;\n el('bootstrap-github-submit').disabled = !bootstrapInfo.githubAvailable;\n if (!bootstrapInfo.githubAvailable) {\n el('bootstrap-github-note').textContent = 'GitHub App creation needs valid saved Web, API, and ingress URLs.';\n } else if (!bootstrapInfo.githubWebhookActive) {\n el('bootstrap-github-note').textContent = 'Creates the complete GitHub App now without submitting the localhost webhook URL. Add it after saving reachable HTTPS ingress.';\n } else {\n el('bootstrap-github-note').textContent = 'This creates one complete App for both GitHub sign-in and repository integration.';\n }\n el('bootstrap-slack-option').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-submit').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-note').textContent = bootstrapInfo.slackAvailable\n ? 'Creates one complete Slack App. Sign-in uses a separate openid profile email flow from workspace installation.'\n : 'Slack sign-in needs all public service URLs to use HTTPS. Use Google locally or expose the stack through trusted HTTPS endpoints.';\n if (!bootstrapInfo.slackAvailable && el('bootstrap-provider').value === 'slack') {\n el('bootstrap-provider').value = 'google';\n updateBootstrapProvider();\n }\n return bootstrapInfo;\n }\n\n async function logtoBootstrapFinding() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n for (const id of ['logto.client_credentials', 'logto.roles_read']) {\n const finding = report.findings.find((candidate) => candidate.id === id);\n if (!finding || finding.status !== 'pass') {\n return finding || { status: 'fail', message: 'Logto Management API permissions could not be verified.' };\n }\n }\n return { status: 'pass', message: 'Logto Management API access is ready.' };\n }\n\n async function showBootstrap() {\n el('bootstrap').hidden = false;\n el('show-bootstrap').hidden = true;\n const info = bootstrapInfo || await loadBootstrapInfo();\n if (!info.logtoConfigured) {\n showBootstrapStep('logto');\n return;\n }\n const finding = await logtoBootstrapFinding();\n if (finding && finding.status === 'pass') {\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n return;\n }\n showBootstrapStep('logto');\n message(finding?.message || 'Logto Management API credentials could not be verified.', true);\n }\n\n async function bootstrapLogto() {\n await json(await fetch(api + '/bootstrap/logto', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n managementAppId: el('logto-app-id').value,\n managementAppSecret: el('logto-app-secret').value,\n managementResource: el('logto-management-api-resource').value\n })\n }));\n el('logto-app-secret').value = '';\n await loadBootstrapInfo();\n const finding = await logtoBootstrapFinding();\n if (!finding || finding.status !== 'pass') {\n throw new Error(finding?.message || 'Logto Management API credentials could not be verified.');\n }\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n }\n\n async function bootstrapGoogle() {\n const secret = el('bootstrap-google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ clientId: el('bootstrap-google-id').value, clientSecret: secret })\n }));\n el('bootstrap-google-secret').value = '';\n await reconcileLogto(true);\n await load();\n }\n\n async function bootstrapGithub() {\n if (!bootstrapInfo || !bootstrapInfo.githubAvailable) throw new Error('GitHub App creation needs valid saved Web, API, and ingress URLs.');\n await startGithub('bootstrap-github');\n }\n\n async function bootstrapSlack() {\n if (!bootstrapInfo || !bootstrapInfo.slackAvailable) throw new Error('Slack sign-in requires all public service URLs to use HTTPS.');\n await createSlack('bootstrap-slack', true);\n await reconcileLogto();\n await load();\n }\n\n async function createSlack(prefix = 'slack', connectLogto = false) {\n const result = await json(await fetch(api + '/create/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n name: el(prefix + '-name').value,\n configToken: el(prefix + '-token').value,\n connectLogto\n })\n }));\n el(prefix + '-token').value = '';\n if (!connectLogto) await load();\n message('Slack App ' + result.app.id + ' was created with the default integration manifest. Restart AgentConnect to apply it.');\n }\n\n async function checkGithub() {\n const result = await json(await fetch(api + '/check/github', { headers: bearer() }));\n el('github-settings').href = result.settingsUrl;\n el('github-settings').hidden = false;\n const label = result.missing.length ? 'Update required' : \"Can't verify automatically\";\n showDiff('github-drift', result.diff || [], label);\n match('github-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : label);\n message(result.status === 'pass' ? 'GitHub App matches the expected integration manifest.' : result.missing.length ? 'GitHub App settings need an update.' : \"GitHub can't expose callback, setup, or webhook-active settings through its API; check them in GitHub.\", result.status === 'fail');\n }\n\n async function connectGithubLogin() {\n await json(await fetch(api + '/configure/github-login', { method: 'POST', headers: bearer() }));\n await reconcileLogto();\n await load();\n message('The deployment GitHub App is now also used for Logto sign-in. Update its displayed callback URLs.');\n }\n\n async function connectSlackLogin() {\n if (!currentStatus || !currentStatus.values.slack || !currentStatus.values.logto) {\n throw new Error('Save the Slack App and Logto configuration first');\n }\n const values = currentStatus.values;\n const slack = values.slack;\n const logto = values.logto;\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...logto,\n browser: logto.browser\n ? { ...logto.browser, socialProviders: [...new Set([...logto.browser.socialProviders, 'slack'])] }\n : logto.browser,\n slackConnector: {\n appId: slack.appId,\n clientId: slack.clientId\n }\n }\n },\n undefined,\n 'Slack App is ready to connect to Logto.'\n );\n await reconcileLogto();\n await load();\n message('The deployment Slack App is now also used for Logto sign-in.');\n }\n\n async function checkSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/check/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(result.status === 'pass' ? 'Slack App matches the default integration manifest.' : 'Slack App settings need an update.', result.status !== 'pass');\n }\n\n async function reconcileSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/reconcile/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(\n result.status !== 'pass'\n ? 'Slack App was updated but some settings still differ.'\n : result.applied.length === 0\n ? 'Slack App already matches the default integration manifest.'\n : result.permissionsUpdated\n ? 'Slack App updated. Reinstall it in each workspace to grant the added scopes.'\n : 'Slack App updated.',\n result.status !== 'pass'\n );\n }\n\n async function checkGoogle() {\n const report = await checkLogto();\n const connector = report.findings.find((finding) => finding.id === 'logto.connectors');\n const google = currentStatus && currentStatus.values.logto && currentStatus.values.logto.googleConnector;\n const connectorDiff = connector && connector.diff\n ? connector.diff.filter((item) => item.field.toLowerCase().startsWith('google'))\n : [];\n const passed = Boolean(google && connector && connectorDiff.length === 0);\n showDiff('google-drift', connectorDiff);\n match('google-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Update required');\n message(\n passed\n ? \"The Logto Google connector matches. Google OAuth redirect settings can't be verified automatically.\"\n : 'The Logto Google connector needs an update.',\n !passed\n );\n }\n\n async function checkRegionalLoginApp(region) {\n const result = await json(await fetch(api + '/check/regional-login-app/' + region, { headers: bearer() }));\n const label = region === 'feishu' ? 'Feishu' : 'Lark';\n showDiff(region + '-drift', result.diff || []);\n match(region + '-match', result.status === 'pass' ? 'pass' : result.status === 'fail' ? 'fail' : 'warn', result.status === 'pass' ? 'Matches' : result.status === 'fail' ? 'Update required' : 'Could not check');\n el(region + '-login-status').textContent = result.message;\n el(region + '-login-status').className = result.status === 'pass' ? 'ok' : result.status === 'fail' ? 'warn' : 'muted';\n message(result.message || (label + ' credential check completed.'), result.status === 'fail');\n }\n\n async function saveGitlab() {\n const clientSecret = el('gitlab-secret').value;\n const baseUrl = el('gitlab-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('gitlab-id', 'the GitLab Application ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(baseUrl ? { baseUrl } : {})\n }\n })\n }));\n el('gitlab-secret').value = '';\n if (currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) await reconcileLogto(Boolean(clientSecret));\n await load();\n showGitlabProbe(saved.probe);\n message('GitLab OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n // Only the URL shape blocks the save, so every other verdict is a line to read.\n function showGitlabProbe(probe) {\n const line = el('gitlab-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function configureGitlabLogin(enabled) {\n await json(await fetch(api + '/configure/gitlab-login', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ enabled })\n }));\n try { await reconcileLogto(enabled); } finally { await load(); }\n message('GitLab sign-in ' + (enabled ? 'configured' : 'disabled') + '. Restart AgentConnect to apply it.');\n }\n\n async function saveGitea() {\n const baseUrl = el('gitea-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitea', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ instance: { ...(baseUrl ? { baseUrl } : {}) } })\n }));\n await load();\n // Shape and the version floor already blocked the save, so any verdict here is a line to read.\n const line = el('gitea-probe');\n line.hidden = !saved.probe;\n line.textContent = saved.probe ? saved.probe.message : '';\n message('Gitea instance saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogleChat() {\n const projectNumber = el('googlechat-project-number-input').value.trim();\n const application = {\n projectId: requiredInput('googlechat-project-id-input', 'the Google Cloud project ID'),\n ...(projectNumber ? { projectNumber } : {})\n };\n const serviceAccountKey = el('googlechat-key').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/google-chat', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: { ...application, ...(serviceAccountKey ? { serviceAccountKey } : {}) } })\n }));\n } finally {\n // The key never stays in the page once it has been submitted, whatever the outcome.\n el('googlechat-key').value = '';\n }\n await load();\n message('Google Chat app saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n }\n\n async function saveEmail(rotateIngressSecret) {\n const stored = currentStatus && currentStatus.values.email;\n const limit = rotateIngressSecret\n ? (stored && stored.dailySendLimit ? String(stored.dailySendLimit) : '')\n : el('email-send-limit-input').value.trim();\n if (limit && !/^[1-9][0-9]*$/.test(limit)) throw new Error('Enter the daily send limit as a whole number, or leave it empty.');\n const apiToken = rotateIngressSecret ? '' : el('email-token').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/email', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n email: {\n mailDomain: rotateIngressSecret ? stored.mailDomain : requiredInput('email-mail-domain-input', 'the mail domain'),\n accountId: rotateIngressSecret ? stored.accountId : requiredInput('email-account-id-input', 'the Cloudflare account ID'),\n dailySendLimit: limit ? Number(limit) : null,\n ...(apiToken ? { apiToken } : {}),\n ...(rotateIngressSecret ? { rotateIngressSecret: true } : {})\n }\n })\n }));\n } finally {\n // The token never stays in the page once it has been submitted, whatever the outcome.\n el('email-token').value = '';\n }\n // The response alone fills the secret box, so no render that follows can take it away.\n showEmailIngressSecret(saved.ingressSecret);\n message('Email saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n await refreshDeploymentConfig();\n }\n\n function showEmailIngressSecret(secret) {\n el('email-ingress-secret').textContent = secret || '';\n el('email-ingress-once').hidden = !secret;\n }\n\n async function copyEmailIngressSecret() {\n await navigator.clipboard.writeText(el('email-ingress-secret').textContent);\n message('Ingress secret copied.');\n }\n\n function confirmEmailIngressRotation(open) {\n el('email-rotate-confirm').hidden = !open;\n el('rotate-email-ingress').hidden = open;\n if (open) el('cancel-rotate-email-ingress').focus();\n }\n\n async function saveLinear() {\n const clientSecret = el('linear-client-secret').value;\n const signingSecret = el('linear-signing-secret').value;\n await json(await fetch(api + '/configure/linear', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('linear-id', 'the Linear Client ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(signingSecret ? { signingSecret } : {})\n }\n })\n }));\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n await load();\n message('Linear OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogle() {\n const secret = el('google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n clientId: el('google-id').value,\n ...(secret ? { clientSecret: secret } : {})\n })\n }));\n el('google-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n message('Google OAuth client and Logto connector are configured. Restart AgentConnect to apply the saved settings.');\n }\n\n // Agent bots (teams-integration.md §8.6.3): 'create' makes the blueprint through Graph, 'save' takes one entered by hand, 'clear' turns them off.\n async function saveAgentBots(mode) {\n if (mode === 'clear' && !window.confirm('Clear the saved blueprint and its secret? Agents that already have a bot of their own stop answering in Teams.')) return;\n const azure = mode === 'clear' ? {} : {\n subscriptionId: requiredInput('azuread-agent-bots-subscription-input', 'the Azure subscription ID'),\n resourceGroup: requiredInput('azuread-agent-bots-group-input', 'the resource group')\n };\n let saved;\n try {\n if (mode === 'create') {\n const operator = requiredInput('azuread-agent-bots-operator-input', 'your Microsoft Entra user');\n saved = await json(await fetch(api + '/configure/msteams-agent-bots/blueprint', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ operator, ...azure })\n }));\n } else {\n const clientSecret = el('azuread-agent-bots-secret-input').value;\n const agentBots = mode === 'clear' ? null : {\n blueprintId: requiredInput('azuread-agent-bots-blueprint-input', 'the blueprint ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...azure\n };\n saved = await json(await fetch(api + '/configure/msteams-agent-bots', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ agentBots })\n }));\n }\n } finally {\n // The secret never stays in the page once it has been submitted, whatever the outcome.\n el('azuread-agent-bots-secret-input').value = '';\n }\n await load();\n if (mode === 'clear') return message('Agent bots cleared. Restart AgentConnect to apply the saved settings.');\n const settling = mode === 'create' && saved.check !== 'ok';\n message('Blueprint ' + saved.blueprintId + ' saved.' + (settling ? ' Its new secret was not accepted yet; give Microsoft a minute before you restart.' : '') + ' Restart AgentConnect to apply the saved settings.' + (mode === 'create' ? ' You may now remove the three Graph permissions from the application.' : ''));\n }\n\n async function saveLoginApp(provider, clear = false) {\n const app = loginApps[provider];\n if (clear && !window.confirm('Clear the saved ' + app.name + ' login application and secret?')) return;\n const clientSecret = el(provider + '-secret').value;\n const application = clear ? null : {\n clientId: requiredInput(provider + '-id', 'the ' + app.name + ' Client ID'),\n ...(clientSecret ? { clientSecret } : {})\n };\n // Microsoft's home tenant also makes the app the deployment's Teams app; empty turns that off.\n const teams = provider === 'azuread' && !clear ? { teamsTenantId: el('azuread-teams-tenant-input').value.trim() || null } : {};\n try {\n await json(await fetch(api + '/configure/login-app/' + provider, {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application, ...teams })\n }));\n } finally {\n el(provider + '-secret').value = '';\n }\n try {\n await reconcileLogto(Boolean(clientSecret) && !clear);\n } finally {\n await load();\n }\n message(app.name + (clear ? ' sign-in configuration cleared.' : ' login application and Logto connector configured.') + ' Restart AgentConnect to apply the saved settings.');\n }\n\n function renderLoginAppChecks(report) {\n const connectors = report.findings.find((finding) => finding.id === 'logto.connectors');\n if (currentStatus?.values.logto?.browser?.socialProviders.includes('gitlab')) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('gitlab')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n el('gitlab-login-status').textContent = passed\n ? 'GitLab connector matches. Confirm the redirect URLs and OpenID scopes in GitLab.'\n : 'GitLab sign-in could not be verified. Review the Logto check above.';\n }\n for (const [provider, app] of Object.entries(loginApps)) {\n if (!currentStatus?.values.logto?.[provider + 'Connector']) continue;\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith(provider)) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff(provider + '-drift', diff);\n match(provider + '-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el(provider + '-status').textContent = passed\n ? app.name + ' connector matches. Confirm the redirect URLs in the provider settings.'\n : app.name + ' connector could not be verified. Review the Logto check above.';\n }\n }\n\n function regionalLoginApp(prefix) {\n const appId = el(prefix + '-login-id').value.trim();\n const appSecret = el(prefix + '-login-secret').value;\n return appId ? { appId, ...(appSecret ? { appSecret } : {}) } : null;\n }\n\n async function saveRegionalLoginApp(region) {\n const app = regionalLoginApp(region);\n if (!app) throw new Error('Enter the ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App ID');\n await json(await fetch(api + '/configure/regional-login-app', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, app })\n }));\n el(region + '-login-secret').value = '';\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' tenant App is saved. Restart AgentConnect services to apply it.');\n }\n\n async function createRegionalLoginApp(region) {\n const popup = window.open('about:blank', '_blank');\n try {\n const started = await json(await fetch(api + '/create/regional-login-app/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, name: el(region + '-create-name').value })\n }));\n if (popup) popup.location.replace(started.authorizationUrl);\n else window.open(started.authorizationUrl, '_blank', 'noopener');\n message('Approve the new ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App in the opened page. This page will finish saving it automatically.');\n while (true) {\n const result = await json(await fetch(api + '/create/regional-login-app/' + encodeURIComponent(started.id), { headers: bearer() }));\n if (result.status === 'completed') {\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' App ' + result.appId + ' was created and saved. Restart AgentConnect services to apply it.');\n return;\n }\n if (result.status === 'failed') throw new Error('Regional App creation ' + result.reason + '. Start it again.');\n await new Promise((resolve) => setTimeout(resolve, Math.max(500, Math.min(result.retryAfterMs || 2000, 5000))));\n }\n } catch (error) {\n if (popup) popup.close();\n throw error;\n }\n }\n\n async function reconcileLogto(refreshConnectorSecrets) {\n return json(await fetch(api + '/reconcile/logto', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ refreshConnectorSecrets: Boolean(refreshConnectorSecrets) })\n }));\n }\n\n async function refreshDeploymentConfig() {\n const status = await json(await fetch(api + '/deployment-config', { headers: bearer() }));\n el('access').hidden = true;\n el('setup').hidden = false;\n el('editor').hidden = false;\n currentRevision = status.revision;\n renderApps(status);\n return status;\n }\n\n async function checkLogto() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n await refreshDeploymentConfig();\n const failures = report.findings.filter((finding) => finding.status !== 'pass');\n el('logto-status').textContent = failures.length === 0\n ? 'SPA redirects, connectors, and social-only sign-in match.'\n : failures.map((finding) => finding.message).join(' ');\n el('logto-status').className = failures.length === 0 ? 'ok' : 'warn';\n match('logto-match', failures.length === 0 ? 'pass' : 'warn', failures.length === 0 ? 'Matches' : 'Update required');\n showDiff(\n 'logto-drift',\n failures.flatMap((finding) => finding.diff && finding.diff.length\n ? finding.diff\n : [{ field: finding.id.replace(/^logto\\./, '').replaceAll('_', ' '), current: finding.message, expected: 'Matches expected configuration' }])\n );\n el('logto-settings').hidden = failures.length === 0;\n renderLoginAppChecks(report);\n return report;\n }\n\n function githubNotice(value) {\n if (value === 'deployment-created') return 'GitHub integration App created. Its private key and webhook secret are stored.';\n if (value === 'deployment-login-created') return 'GitHub integration App created and connected to Logto sign-in.';\n if (value === 'cancelled') return 'GitHub App creation was cancelled.';\n if (value === 'expired') return 'GitHub App creation expired. Start it again.';\n if (value === 'invalid-callback') return 'GitHub returned an invalid App creation callback.';\n if (value === 'conversion-failed') return 'GitHub may have created the App, but did not return complete credentials. Delete the orphaned App and retry.';\n if (value === 'save-failed') return 'GitHub created the App, but its credentials could not be saved. Delete the orphaned App and retry.';\n return '';\n }\n\n async function load() {\n let publicAuth = await authConfig();\n const currentUrl = new URL(location.href);\n const githubResult = currentUrl.searchParams.get('github');\n const notice = githubNotice(githubResult);\n if (githubResult === 'deployment-login-created' && publicAuth.mode === 'none') {\n await reconcileLogto();\n publicAuth = await authConfig();\n }\n if (githubResult) history.replaceState({}, '', '/');\n const hasToken = Boolean(sessionStorage.getItem(tokenKey));\n el('access').hidden = false;\n el('setup').hidden = true;\n el('login').hidden = true;\n el('open-logto').hidden = true;\n el('show-bootstrap').hidden = true;\n el('editor').hidden = true;\n el('bootstrap').hidden = true;\n if (publicAuth.logtoAdminEndpoint) {\n el('open-logto').href = publicAuth.logtoAdminEndpoint;\n el('logto-settings').href = publicAuth.logtoAdminEndpoint;\n }\n if (publicAuth.mode === 'none') {\n sessionStorage.removeItem(tokenKey);\n await loadBootstrapInfo();\n el('open-logto').hidden = false;\n el('show-bootstrap').hidden = false;\n message(notice || 'Logto sign-in is not configured. Set up the initial Logto administrator first.');\n return;\n }\n if (publicAuth.mode === 'unavailable') {\n el('open-logto').hidden = false;\n message(publicAuth.message || 'Logto sign-in is unavailable. Open Logto Console to review its settings.', true);\n return;\n }\n if (!hasToken) {\n el('login').hidden = false;\n message(notice || 'Sign in with Logto to continue.');\n return;\n }\n if (publicAuth.claimAvailable) {\n try {\n await json(await fetch(api + '/bootstrap/claim', { method: 'POST', headers: bearer() }));\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('This first user is now an ADMIN. Sign in again to refresh the role claim.');\n return;\n } catch (error) {\n if (error.status !== 401 && error.status !== 403) throw error;\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with Logto to continue.', true);\n return;\n }\n }\n try {\n await loadBootstrapInfo();\n await refreshDeploymentConfig();\n message(notice);\n checkLogto().catch((error) => {\n el('logto-status').textContent = error.message;\n el('logto-status').className = 'warn';\n el('logto-settings').hidden = false;\n });\n } catch (error) {\n if (error.status === 401 || error.status === 403) {\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with a Logto ADMIN account.', true);\n }\n else throw error;\n }\n }\n\n async function saveSecretReplacement(key, value) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n if (!value) throw new Error('Enter the replacement secret');\n const refreshLogto =\n (key === 'gitlab.clientSecret' && currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) ||\n (key === 'logto.githubConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.githubConnector) ||\n (key === 'logto.googleConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.googleConnector) ||\n Object.keys(loginApps).some((provider) => key === 'logto.' + provider + 'ConnectorClientSecret' && currentStatus.values.logto?.[provider + 'Connector']) ||\n (key === 'slack.clientSecret' && currentStatus.values.logto && currentStatus.values.logto.slackConnector);\n await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values: currentStatus.values, secrets: { [key]: value } })\n }));\n try {\n if (refreshLogto) await reconcileLogto(true);\n } finally {\n await load();\n }\n if (refreshLogto) {\n message('Secret replaced and applied to the Logto connector. Restart AgentConnect to apply deployment changes.');\n } else {\n message('Secret replaced. Restart AgentConnect to apply it.');\n }\n }\n\n function editSecret(button) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const row = button.closest('.secret-line');\n const display = el(button.dataset.secretDisplay);\n if (!row || !display || row.querySelector('.secret-editor')) return;\n const editor = document.createElement('span'); editor.className = 'secret-editor';\n const input = document.createElement('input');\n input.type = 'password'; input.autocomplete = 'new-password'; input.placeholder = 'Enter replacement secret';\n const save = document.createElement('button'); save.textContent = 'Save';\n const cancel = document.createElement('button'); cancel.textContent = 'Cancel';\n const close = () => { editor.remove(); display.hidden = false; button.hidden = false; };\n save.onclick = async () => {\n save.disabled = true;\n try { await saveSecretReplacement(button.dataset.secretKey, input.value); }\n catch (error) { save.disabled = false; message(error.message, true); }\n };\n cancel.onclick = close;\n input.onkeydown = (event) => { if (event.key === 'Enter') save.click(); if (event.key === 'Escape') close(); };\n display.hidden = true; button.hidden = true;\n editor.append(input, save, cancel); row.append(editor); input.focus();\n }\n\n async function saveOptions() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = {\n ...currentStatus.values,\n features: {\n presetAgentsEnabled: el('preset-agents-enabled').checked,\n maxOrgsPerNonAdminUser: Number(el('max-orgs-per-non-admin-user').value),\n organizationSso: el('organization-sso').checked\n }\n };\n const saved = await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values })\n }));\n try {\n if (currentStatus.values.auth.mode === 'oidc') await reconcileLogto();\n } catch (error) {\n await load();\n throw new Error('Saved deployment options, but Logto was not updated: ' + error.message);\n }\n message('Saved deployment options. Restart AgentConnect to apply them.');\n await load();\n }\n\n el('login').onclick = () => signIn().catch((error) => message(error.message, true));\n el('show-bootstrap').onclick = () => showBootstrap().catch((error) => message(error.message, true));\n el('bootstrap-provider').onchange = updateBootstrapProvider;\n el('bootstrap-github-owner').onchange = () => updateOwner('bootstrap-github');\n el('github-owner').onchange = () => updateOwner('github');\n el('bootstrap-logto-submit').onclick = () => bootstrapLogto().catch((error) => message(error.message, true));\n el('bootstrap-back').onclick = () => showBootstrapStep('logto');\n el('bootstrap-google-submit').onclick = () => bootstrapGoogle().catch((error) => message(error.message, true));\n for (const prefix of ['bootstrap-sso', 'sso']) {\n el(prefix + '-protocol').onchange = () => updateSsoProtocol(prefix);\n el(prefix + '-member-source').onchange = () => updateMemberOrganization(prefix);\n el(prefix + '-create').onclick = () => createSso(prefix).catch((error) => message(error.message, true));\n el(prefix + '-submit').onclick = () => saveSso(prefix).catch((error) => message(error.message, true));\n }\n el('sso-remove').onclick = () => removeSso().catch((error) => message(error.message, true));\n el('bootstrap-github-submit').onclick = () => bootstrapGithub().catch((error) => message(error.message, true));\n el('bootstrap-slack-submit').onclick = () => bootstrapSlack().catch((error) => message(error.message, true));\n el('create-github').onclick = () => startGithub('github').catch((error) => message(error.message, true));\n el('save-logto-configuration').onclick = () => saveLogtoConfiguration().catch((error) => message(error.message, true));\n el('cancel-logto-configuration').onclick = cancelConfigurationEdit;\n el('save-github-configuration').onclick = () => saveGithubConfiguration().catch((error) => message(error.message, true));\n el('cancel-github-configuration').onclick = cancelConfigurationEdit;\n el('clear-github').onclick = () => clearProvider('github').catch((error) => message(error.message, true));\n el('connect-github-login').onclick = () => connectGithubLogin().catch((error) => message(error.message, true));\n el('connect-gitlab-login').onclick = () => configureGitlabLogin(true).catch((error) => message(error.message, true));\n el('disconnect-gitlab-login').onclick = () => configureGitlabLogin(false).catch((error) => message(error.message, true));\n el('check-gitlab-login').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-github').onclick = () => checkGithub().catch((error) => message(error.message, true));\n el('create-slack').onclick = () => createSlack('slack').catch((error) => message(error.message, true));\n el('connect-slack-login').onclick = () => connectSlackLogin().catch((error) => message(error.message, true));\n el('save-slack-configuration').onclick = () => saveSlackConfiguration().catch((error) => message(error.message, true));\n el('cancel-slack-configuration').onclick = cancelConfigurationEdit;\n el('clear-slack').onclick = () => clearProvider('slack').catch((error) => message(error.message, true));\n el('check-slack').onclick = () => checkSlack().catch((error) => message(error.message, true));\n el('reconcile-slack').onclick = () => reconcileSlack().catch((error) => message(error.message, true));\n el('save-gitea').onclick = () => saveGitea().catch((error) => message(error.message, true));\n el('cancel-gitea-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitea').onclick = () => clearProvider('gitea').catch((error) => message(error.message, true));\n el('save-gitlab').onclick = () => saveGitlab().catch((error) => message(error.message, true));\n el('cancel-gitlab-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitlab').onclick = () => clearProvider('gitlab').catch((error) => message(error.message, true));\n el('save-googlechat').onclick = () => saveGoogleChat().catch((error) => message(error.message, true));\n for (const [id, mode] of [['create-azuread-agent-bots-blueprint', 'create'], ['save-azuread-agent-bots', 'save'], ['clear-azuread-agent-bots', 'clear']]) {\n el(id).onclick = () => saveAgentBots(mode).catch((error) => message(error.message, true));\n }\n el('cancel-googlechat-configuration').onclick = cancelConfigurationEdit;\n el('clear-googlechat').onclick = () => clearProvider('googlechat').catch((error) => message(error.message, true));\n el('save-email').onclick = () => saveEmail(false).catch((error) => message(error.message, true));\n el('rotate-email-ingress').onclick = () => confirmEmailIngressRotation(true);\n el('cancel-rotate-email-ingress').onclick = () => confirmEmailIngressRotation(false);\n el('confirm-rotate-email-ingress').onclick = () => {\n confirmEmailIngressRotation(false);\n saveEmail(true).catch((error) => message(error.message, true));\n };\n el('copy-email-ingress').onclick = () => copyEmailIngressSecret().catch(() => message('Copy failed. Select the secret and copy it.', true));\n el('dismiss-email-ingress').onclick = () => showEmailIngressSecret('');\n el('cancel-email-configuration').onclick = cancelConfigurationEdit;\n el('clear-email').onclick = () => clearProvider('email').catch((error) => message(error.message, true));\n el('save-linear').onclick = () => saveLinear().catch((error) => message(error.message, true));\n el('cancel-linear-configuration').onclick = cancelConfigurationEdit;\n el('clear-linear').onclick = () => clearProvider('linear').catch((error) => message(error.message, true));\n el('save-google').onclick = () => saveGoogle().catch((error) => message(error.message, true));\n el('cancel-google-configuration').onclick = cancelConfigurationEdit;\n el('clear-google').onclick = () => clearProvider('google').catch((error) => message(error.message, true));\n el('check-google').onclick = () => checkGoogle().catch((error) => message(error.message, true));\n for (const provider of Object.keys(loginApps)) {\n el('save-' + provider).onclick = () => saveLoginApp(provider).catch((error) => message(error.message, true));\n el('cancel-' + provider + '-configuration').onclick = cancelConfigurationEdit;\n el('clear-' + provider).onclick = () => saveLoginApp(provider, true).catch((error) => message(error.message, true));\n el('check-' + provider).onclick = () => checkLogto().catch((error) => message(error.message, true));\n }\n el('create-feishu-login-app').onclick = () => createRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('save-feishu-login-app').onclick = () => saveRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('cancel-feishu-configuration').onclick = cancelConfigurationEdit;\n el('clear-feishu').onclick = () => clearProvider('feishu').catch((error) => message(error.message, true));\n el('check-feishu-login-app').onclick = () => checkRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('create-lark-login-app').onclick = () => createRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('save-lark-login-app').onclick = () => saveRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('cancel-lark-configuration').onclick = cancelConfigurationEdit;\n el('clear-lark').onclick = () => clearProvider('lark').catch((error) => message(error.message, true));\n el('check-lark-login-app').onclick = () => checkRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('check-logto').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('reconcile-logto').onclick = () => reconcileLogto().then(load).catch((error) => message(error.message, true));\n el('logout').onclick = () => { sessionStorage.removeItem(tokenKey); load().catch((error) => message(error.message, true)); };\n el('save-options').onclick = () => saveOptions().catch((error) => message(error.message, true));\n for (const button of document.querySelectorAll('.edit-secret')) button.onclick = () => editSecret(button);\n for (const button of document.querySelectorAll('.edit-configuration')) button.onclick = () => beginConfigurationEdit(button.dataset.provider);\n updateBootstrapProvider();\n finishSignIn().then(load).catch((error) => message(error.message, true));\n <\/script>\n</body>\n</html>"
69118
+ "\n\n <section id=\"googlechat-section\" class=\"panel setup-section\" aria-labelledby=\"googlechat-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"googlechat-heading\">Google Chat</h3><p class=\"muted\">One Chat app for the deployment. Each Google Workspace organization connects itself from Google Chat.</p></div>\n <span id=\"googlechat-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Project ID</dt><dd class=\"value-line\"><code id=\"googlechat-project-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Project number</dt><dd class=\"value-line\"><code id=\"googlechat-project-number\">Not configured</code><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n <dt>Service-account key</dt><dd class=\"value-line\"><span id=\"googlechat-key-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"googlechat\">Edit</button></dd>\n </dl>\n <p id=\"googlechat-status\" class=\"muted\"></p>\n <div id=\"googlechat-drift\" class=\"notice\" hidden></div>\n <p>HTTP endpoint URL:</p><ul id=\"googlechat-callbacks\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>Use a Google Workspace account that may create a Cloud project and service-account keys. An organization policy can block key creation.</li>\n <li>Create a Google Cloud project for this app and enable the Google Chat API in it.</li>\n <li>On the Chat API Configuration page, build the app as a Google Workspace add-on, the default for a new app (convert an existing app first). Under Connection settings choose HTTP endpoint URL, use one URL for all triggers, and enter the URL above. Allow 1:1 messages and joining spaces, and choose who can use the app.</li>\n <li>Under Commands, add a slash command named /help with the description \"Show how to use this app\" and command ID 1; any free ID works, since AgentConnect matches the name.</li>\n <li>In the same project, create a service account and a JSON key for it, grant it the Browser role on the project, and enable the Cloud Resource Manager API; AgentConnect reads the project number with that key.</li>\n <li>Save the project ID and key here. The project number is optional: it is on the project's settings page and in the add-on's service account email, service-PROJECT_NUMBER@gcp-sa-gsuiteaddons.iam.gserviceaccount.com. When entered, it must match the number read from the key's project.</li>\n <li>Configure Google sign-in above, then add the app in Google Chat and send it a message. Each Google Workspace organization connects itself from Google Chat by signing in to the console with Google; publish the app on the Google Workspace Marketplace to reach other organizations.</li>\n </ol>\n <div class=\"row\"><a id=\"googlechat-configuration\" class=\"button\" href=\"https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat\" target=\"_blank\" rel=\"noopener\">Open Chat API configuration</a></div>\n <div id=\"googlechat-config-controls\" class=\"subsection\">\n <h3 id=\"googlechat-edit-heading\" hidden>Edit Google Chat App identity</h3>\n <label class=\"field\">Project ID<input id=\"googlechat-project-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">Project number (optional)<input id=\"googlechat-project-number-input\" inputmode=\"numeric\" autocomplete=\"off\" placeholder=\"Read from the key's project\"></label>\n <label class=\"field\">Service-account key JSON<input id=\"googlechat-key\" type=\"password\" autocomplete=\"off\" placeholder=\"Required when the project ID changes\"></label>\n </div>\n <div class=\"row\"><button id=\"save-googlechat\">Save Google Chat app</button><button id=\"cancel-googlechat-configuration\" hidden>Cancel</button><button id=\"clear-googlechat\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n <section id=\"email-section\" class=\"panel setup-section\" aria-labelledby=\"email-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"email-heading\">Email</h3><p class=\"muted\">One mail domain for the deployment. Each agent gets an address on it, received and sent through Cloudflare Email Service.</p></div>\n <span id=\"email-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Mail domain</dt><dd class=\"value-line\"><code id=\"email-mail-domain\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Cloudflare account ID</dt><dd class=\"value-line\"><code id=\"email-account-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>API token</dt><dd class=\"value-line\"><span id=\"email-token-display\" class=\"muted\">Not configured</span><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n <dt>Ingress secret</dt><dd class=\"value-line\"><span id=\"email-ingress-display\" class=\"muted\">Not configured</span></dd>\n <dt>Daily send limit</dt><dd class=\"value-line\"><code id=\"email-send-limit\">Not configured</code><button class=\"edit-configuration\" data-provider=\"email\">Edit</button></dd>\n </dl>\n <p id=\"email-status\" class=\"muted\"></p>\n <div id=\"email-drift\" class=\"notice\" hidden></div>\n <div id=\"email-ingress-once\" class=\"notice\" hidden>\n <p>Ingress secret, shown once. Set it as the Worker's secret now:</p>\n <pre id=\"email-ingress-secret\"></pre>\n <div class=\"row\"><button id=\"copy-email-ingress\">Copy</button><button id=\"dismiss-email-ingress\">Dismiss</button></div>\n </div>\n <p>Inbound URL for the ingress Worker:</p><ul id=\"email-inbound\" class=\"uris\"></ul>\n <ol class=\"muted\">\n <li>In Cloudflare, onboard a zone used for nothing else as the mail domain, for Email Routing and for Email Sending. A domain that already receives mail elsewhere cannot be used.</li>\n <li>Create an API token with the Email Sending: Edit permission for that account, then save the domain, the account ID and the token here. Setup checks the token with one read of the account's Email Sending suppression list and sends nothing.</li>\n <li>Deploy the ingress Worker with the inbound URL above and the ingress secret shown after the first save, and point the zone's catch-all routing rule at it.</li>\n <li>The daily send limit is the most mail the whole deployment sends in a day. Left empty, only the limits for each address and each organization apply.</li>\n </ol>\n <div class=\"row\"><a id=\"email-dashboard\" class=\"button\" href=\"https://dash.cloudflare.com/\" target=\"_blank\" rel=\"noopener\">Open Cloudflare</a></div>\n <div id=\"email-config-controls\" class=\"subsection\">\n <h3 id=\"email-edit-heading\" hidden>Edit Email configuration</h3>\n <label class=\"field\">Mail domain<input id=\"email-mail-domain-input\" autocomplete=\"off\" placeholder=\"mail.example.com\"></label>\n <label class=\"field\">Cloudflare account ID<input id=\"email-account-id-input\" autocomplete=\"off\"></label>\n <label class=\"field\">API token<input id=\"email-token\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when the account ID changes\"></label>\n <label class=\"field\">Daily send limit (optional)<input id=\"email-send-limit-input\" inputmode=\"numeric\" autocomplete=\"off\"></label>\n </div>\n <div class=\"row\"><button id=\"save-email\">Save Email</button><button id=\"cancel-email-configuration\" hidden>Cancel</button><button id=\"rotate-email-ingress\" hidden>Replace ingress secret</button><span id=\"email-rotate-confirm\" hidden>Replace? Mail is refused until the Worker has the new one. <button id=\"confirm-rotate-email-ingress\" class=\"danger\">Replace</button><button id=\"cancel-rotate-email-ingress\">Cancel</button></span><button id=\"clear-email\" class=\"danger\" hidden>Clear configuration</button></div>\n </section>\n\n\n <section id=\"feishu-section\" class=\"panel setup-section\" aria-labelledby=\"feishu-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"feishu-heading\">Feishu</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Feishu, OAuth callbacks, and published App setup.</p></div>\n <span id=\"feishu-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"feishu-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"feishu\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"feishu-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"feishu.loginAppSecret\" data-secret-display=\"feishu-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"feishu-login-status\" class=\"muted\"></p>\n <div id=\"feishu-drift\" class=\"notice\" hidden></div>\n <div id=\"feishu-config-controls\" class=\"subsection\">\n <label id=\"feishu-create-name-field\" class=\"field\">New App name<input id=\"feishu-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"feishu-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"feishu-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-feishu-login-app\">Create Feishu App</button>\n <button id=\"save-feishu-login-app\">Save existing App</button>\n <button id=\"cancel-feishu-configuration\" hidden>Cancel</button>\n <button id=\"check-feishu-login-app\" hidden>Check setup</button>\n <button id=\"clear-feishu\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"feishu-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Feishu settings</a>\n </div>\n </section>\n\n <section id=\"lark-section\" class=\"panel setup-section\" aria-labelledby=\"lark-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"lark-heading\">Lark</h3><p class=\"muted\">Matches the Logto OAuth 2.0 connector named Lark, OAuth callbacks, and published App setup.</p></div>\n <span id=\"lark-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>App ID</dt><dd class=\"value-line\"><code id=\"lark-app-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"lark\">Edit</button></dd>\n <dt>App secret</dt><dd class=\"secret-line\"><span id=\"lark-app-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"lark.loginAppSecret\" data-secret-display=\"lark-app-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"lark-login-status\" class=\"muted\"></p>\n <div id=\"lark-drift\" class=\"notice\" hidden></div>\n <div id=\"lark-config-controls\" class=\"subsection\">\n <label id=\"lark-create-name-field\" class=\"field\">New App name<input id=\"lark-create-name\" value=\"AgentConnect\"></label>\n <label class=\"field\">Existing App ID<input id=\"lark-login-id\" autocomplete=\"off\"></label>\n <label class=\"field\">Existing App secret<input id=\"lark-login-secret\" type=\"password\" autocomplete=\"new-password\"></label>\n </div>\n <div class=\"row\">\n <button id=\"create-lark-login-app\">Create Lark App</button>\n <button id=\"save-lark-login-app\">Save existing App</button>\n <button id=\"cancel-lark-configuration\" hidden>Cancel</button>\n <button id=\"check-lark-login-app\" hidden>Check setup</button>\n <button id=\"clear-lark\" class=\"danger\" hidden>Clear configuration</button>\n <a id=\"lark-settings\" class=\"button\" target=\"_blank\" rel=\"noopener\" hidden>Open Lark settings</a>\n </div>\n </section>\n\n <section id=\"mattermost-section\" class=\"panel setup-section\" aria-labelledby=\"mattermost-heading\">\n <div class=\"provider-head\">\n <div><h3 id=\"mattermost-heading\">Mattermost</h3><p class=\"muted\">Self-hosted OAuth 2.0 application used by the Logto Mattermost sign-in connector and conversation access checks.</p></div>\n <span id=\"mattermost-match\" class=\"badge\">Not configured</span>\n </div>\n <dl class=\"credentials\">\n <dt>Server URL</dt><dd class=\"value-line\"><code id=\"mattermost-server-url\">Not configured</code><button class=\"edit-configuration\" data-provider=\"mattermost\">Edit</button></dd>\n <dt>Client ID</dt><dd class=\"value-line\"><code id=\"mattermost-client-id\">Not configured</code><button class=\"edit-configuration\" data-provider=\"mattermost\">Edit</button></dd>\n <dt>Client secret</dt><dd class=\"secret-line\"><span id=\"mattermost-client-secret-display\" class=\"redacted\">Not configured</span><button class=\"edit-secret\" data-secret-key=\"logto.mattermostConnectorClientSecret\" data-secret-display=\"mattermost-client-secret-display\">Edit</button></dd>\n </dl>\n <p id=\"mattermost-status\" class=\"muted\"></p>\n <div id=\"mattermost-probe\" class=\"notice\" hidden></div>\n <div id=\"mattermost-drift\" class=\"notice\" hidden></div>\n <p>Redirect URIs:</p><ul id=\"mattermost-redirects\" class=\"uris\"></ul>\n <p class=\"muted\">Create an OAuth 2.0 application in Mattermost (System Console &rarr; Integrations &rarr; OAuth 2.0 Applications) with trusted client enabled and the redirect URIs above.</p>\n <div id=\"mattermost-config-controls\" class=\"subsection\">\n <label class=\"field\">Server URL<input id=\"mattermost-server-url-input\" autocomplete=\"off\" placeholder=\"https://mattermost.example.com\"></label>\n <label class=\"field\">Client ID<input id=\"mattermost-id\" autocomplete=\"off\"></label>\n <label id=\"mattermost-initial-secret-field\" class=\"field\">Client secret<input id=\"mattermost-secret\" type=\"password\" autocomplete=\"new-password\" placeholder=\"Required when Server URL or Client ID changes\"></label>\n </div>\n <div class=\"row\">\n <button id=\"probe-mattermost\">Check Server URL</button>\n <button id=\"save-mattermost\">Save and configure sign-in</button>\n <button id=\"cancel-mattermost-configuration\" hidden>Cancel</button>\n <button id=\"check-mattermost\" hidden>Check Logto</button>\n <button id=\"clear-mattermost\" class=\"danger\" hidden>Clear configuration</button>\n </div>\n </section>\n </div>\n\n <section id=\"options-section\" class=\"setup-section\">\n <h2>Deployment options</h2>\n <div class=\"panel\">\n <label class=\"field\"><span><input id=\"preset-agents-enabled\" type=\"checkbox\"> Enable preset Agents</span></label>\n <label class=\"field\">Max organizations created per non-ADMIN user<input id=\"max-orgs-per-non-admin-user\" type=\"number\" min=\"0\" step=\"1\" value=\"1\"></label>\n <label class=\"field\"><span><input id=\"organization-sso\" type=\"checkbox\"> Let organizations set up their own SSO</span></label>\n <div class=\"row\"><button id=\"save-options\">Save options</button></div>\n </div>\n </section>\n </section>\n </div>\n </div>\n </main>\n\n <script>\n const api = '/api/v1';\n const tokenKey = 'agentconnect.setup.token';\n const verifierKey = 'agentconnect.setup.pkce';\n const stateKey = 'agentconnect.setup.state';\n let currentRevision = 0;\n let currentStatus = null;\n let bootstrapInfo = null;\n const el = (id) => document.getElementById(id);\n const message = (text, error = false) => {\n const target = el('setup').hidden ? el('access-message') : el('message');\n target.textContent = text;\n target.className = error ? 'error' : 'ok';\n };\n const bearer = () => {\n const token = sessionStorage.getItem(tokenKey);\n return token ? { authorization: 'Bearer ' + token } : {};\n };\n const json = async (response) => {\n const body = await response.json().catch(() => ({}));\n if (!response.ok) throw Object.assign(new Error(body.message || ('HTTP ' + response.status)), { status: response.status, code: body.code });\n return body;\n };\n const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n const random = () => base64url(crypto.getRandomValues(new Uint8Array(32)));\n const configured = (byKey, key) => Boolean(byKey.get(key) && byKey.get(key).configured);\n const loginApps = ",
69119
+ ";\n\n function showIdentityEditors(provider, show) {\n for (const button of document.querySelectorAll('.edit-configuration[data-provider=\"' + provider + '\"]')) {\n button.hidden = !show;\n }\n }\n\n function text(id, value) {\n el(id).textContent = value === null || value === undefined || value === '' ? 'Not configured' : String(value);\n }\n\n function secretText(id, byKey, key, editable) {\n const stored = configured(byKey, key);\n const display = el(id);\n const button = document.querySelector('[data-secret-display=\"' + id + '\"]');\n const row = display.closest('.secret-line');\n const editor = row && row.querySelector('.secret-editor');\n if (editor) editor.remove();\n display.hidden = false;\n display.textContent = stored ? '***' : 'Not configured';\n display.className = stored ? 'redacted' : 'muted';\n button.hidden = !editable;\n button.textContent = stored ? 'Edit' : 'Set';\n }\n\n function match(id, state, label) {\n const target = el(id);\n target.textContent = label;\n target.className = 'badge' + (state ? ' ' + state : '');\n }\n\n async function authConfig() { return json(await fetch(api + '/auth-config')); }\n\n async function signIn() {\n const config = await authConfig();\n if (config.mode !== 'oidc') throw new Error('Save an OIDC configuration first');\n const verifier = random();\n const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));\n const state = random();\n sessionStorage.setItem(verifierKey, verifier);\n sessionStorage.setItem(stateKey, state);\n const url = new URL(config.authorizationEndpoint);\n url.searchParams.set('client_id', config.appId);\n url.searchParams.set('redirect_uri', config.redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', 'openid profile email roles');\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n if (config.resource) url.searchParams.set('resource', config.resource);\n if (config.ssoConnectorId) url.searchParams.set('direct_sign_in', 'sso:' + config.ssoConnectorId);\n location.assign(url);\n }\n\n async function finishSignIn() {\n const url = new URL(location.href);\n const code = url.searchParams.get('code');\n if (!code) return;\n const state = url.searchParams.get('state');\n if (!state || state !== sessionStorage.getItem(stateKey)) throw new Error('OIDC state mismatch');\n const verifier = sessionStorage.getItem(verifierKey);\n if (!verifier) throw new Error('PKCE verifier is missing; start sign-in again');\n const config = await authConfig();\n const body = new URLSearchParams({\n grant_type: 'authorization_code', code, client_id: config.appId,\n redirect_uri: config.redirectUri, code_verifier: verifier\n });\n if (config.resource) body.set('resource', config.resource);\n const tokens = await json(await fetch(config.tokenEndpoint, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body\n }));\n if (typeof tokens.id_token !== 'string') throw new Error('Logto did not return an ID token');\n sessionStorage.setItem(tokenKey, tokens.id_token);\n sessionStorage.removeItem(verifierKey);\n sessionStorage.removeItem(stateKey);\n history.replaceState({}, '', '/');\n }\n\n function renderUriList(id, values) {\n el(id).replaceChildren(...(values || []).map((value) => {\n const item = document.createElement('li');\n const code = document.createElement('code'); code.textContent = value;\n item.append(code); return item;\n }));\n }\n\n function updateBootstrapProvider() {\n const provider = el('bootstrap-provider').value;\n el('bootstrap-google').hidden = provider !== 'google';\n el('bootstrap-github').hidden = provider !== 'github';\n el('bootstrap-slack').hidden = provider !== 'slack';\n el('bootstrap-sso').hidden = provider !== 'sso';\n }\n\n // The SSO connector each form shows: the saved one in settings, the one just created during first-run setup.\n const ssoState = {};\n\n function ssoUrls(connector) {\n const base = ((bootstrapInfo && bootstrapInfo.logtoEndpoint) || '').replace(/\\/+$/, '');\n const id = encodeURIComponent(connector.connectorId);\n return connector.protocol === 'oidc'\n ? ['Redirect URI: ' + base + '/callback/' + id]\n : ['ACS URL: ' + base + '/api/authn/single-sign-on/saml/' + id, 'SP entity ID: ' + base + '/enterprise-sso/' + id];\n }\n\n function renderSso(prefix, connector) {\n ssoState[prefix] = connector || undefined;\n if (connector) {\n el(prefix + '-protocol').value = connector.protocol;\n el(prefix + '-name').value = connector.name;\n el(prefix + '-domains').value = (connector.domains || []).join(', ');\n el(prefix + '-member-source').value = connector.memberSource || 'domain';\n renderMemberOrganizations(prefix, connector.memberOrganization || '');\n renderUriList(prefix + '-urls', ssoUrls(connector));\n const oidc = connector.oidc || {};\n el(prefix + '-issuer').value = oidc.issuer || '';\n el(prefix + '-client-id').value = oidc.clientId || '';\n el(prefix + '-scope').value = oidc.scope || '';\n el(prefix + '-trust-email').checked = connector.oidc ? oidc.trustUnverifiedEmail : true;\n const saml = connector.saml || {};\n el(prefix + '-metadata-url').value = saml.metadataUrl || '';\n el(prefix + '-metadata').value = saml.metadata || '';\n el(prefix + '-email-attribute').value = (saml.attributeMapping && saml.attributeMapping.email) || '';\n }\n updateSsoProtocol(prefix);\n }\n\n // The organizations new members may join; the empty value is the deployment's only one, and a saved id that is gone stays visible.\n let ssoOrganizations = [];\n function renderMemberOrganizations(prefix, selected) {\n const select = el(prefix + '-member-organization');\n select.replaceChildren();\n const option = (value, label) => {\n const item = document.createElement('option');\n item.value = value;\n item.textContent = label;\n select.append(item);\n };\n option('', 'The only organization');\n for (const org of ssoOrganizations) option(org.id, (org.name || org.slug) + ' (' + org.slug + ')');\n if (selected && !ssoOrganizations.some((org) => org.id === selected)) option(selected, 'Missing organization (' + selected + ')');\n select.value = selected;\n updateMemberOrganization(prefix);\n }\n\n function updateMemberOrganization(prefix) {\n el(prefix + '-member-organization').disabled = el(prefix + '-member-source').value === 'invite';\n }\n\n function updateSsoProtocol(prefix) {\n const connector = ssoState[prefix];\n const protocol = el(prefix + '-protocol').value;\n const current = Boolean(connector && connector.protocol === protocol);\n el(prefix + '-oidc').hidden = protocol !== 'oidc';\n el(prefix + '-saml').hidden = protocol !== 'saml';\n // Another protocol is another connector, so its details wait until it is created.\n el(prefix + '-details').hidden = !current;\n el(prefix + '-create').hidden = current;\n }\n\n async function createSso(prefix) {\n const name = el(prefix + '-name').value;\n const result = await json(await fetch(api + '/create/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ protocol: el(prefix + '-protocol').value, name })\n }));\n renderSso(prefix, { connectorId: result.connectorId, protocol: result.protocol, name, domains: [], memberSource: 'domain', oidc: null, saml: null });\n message('SSO connector created. Register its URLs with the identity provider, then enter the provider details.');\n }\n\n async function saveSso(prefix) {\n const protocol = el(prefix + '-protocol').value;\n const secret = el(prefix + '-client-secret').value;\n const metadataUrl = el(prefix + '-metadata-url').value.trim();\n const metadata = el(prefix + '-metadata').value.trim();\n const emailAttribute = el(prefix + '-email-attribute').value.trim();\n const connector = {\n name: el(prefix + '-name').value,\n domains: el(prefix + '-domains').value.split(',').map((domain) => domain.trim()).filter(Boolean),\n memberSource: el(prefix + '-member-source').value,\n memberOrganization: el(prefix + '-member-organization').value || null,\n ...(protocol === 'oidc'\n ? { oidc: {\n issuer: el(prefix + '-issuer').value.trim(),\n clientId: el(prefix + '-client-id').value.trim(),\n ...(secret ? { clientSecret: secret } : {}),\n scope: el(prefix + '-scope').value.trim(),\n trustUnverifiedEmail: el(prefix + '-trust-email').checked\n } }\n : { saml: {\n ...(metadataUrl ? { metadataUrl } : {}),\n ...(metadata ? { metadata } : {}),\n ...(emailAttribute ? { attributeMapping: { email: emailAttribute } } : {})\n } })\n };\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector })\n }));\n el(prefix + '-client-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n }\n\n async function removeSso() {\n if (!window.confirm('Remove SSO sign-in and delete its Logto connector? People who signed in through it lose that sign-in; their accounts stay.')) return;\n await json(await fetch(api + '/configure/sso', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ connector: null })\n }));\n await reconcileLogto();\n await load();\n }\n\n function showBootstrapStep(step) {\n const logto = step === 'logto';\n el('bootstrap-logto-step').hidden = !logto;\n el('bootstrap-provider-step').hidden = logto;\n el('bootstrap-progress').textContent = logto ? 'Step 1 of 2' : 'Step 2 of 2';\n }\n\n function updateOwner(prefix) {\n el(prefix + '-org-field').hidden = el(prefix + '-owner').value !== 'organization';\n }\n\n function ownership(prefix) {\n if (el(prefix + '-owner').value === 'personal') return { owner: 'personal', organization: null };\n const organization = el(prefix + '-org').value.trim();\n if (!organization) throw new Error('Enter the GitHub organization login');\n return { owner: 'organization', organization };\n }\n\n function formatDiffValue(value) {\n if (value === null || value === undefined || value === '') return 'Not configured';\n if (Array.isArray(value)) return value.length ? value.map(formatDiffValue).join('\\n') : '[]';\n if (typeof value === 'object') {\n return Object.entries(value).map(([key, item]) => key + ': ' + (Array.isArray(item) ? item.join(', ') : formatDiffValue(item))).join('\\n');\n }\n return String(value);\n }\n\n function showDiff(id, rows, label = 'Update required') {\n const box = el(id);\n box.hidden = rows.length === 0;\n box.replaceChildren();\n if (rows.length === 0) return;\n const title = document.createElement('strong');\n title.className = 'diff-title';\n title.textContent = label;\n const grid = document.createElement('div');\n grid.className = 'config-diff';\n const head = document.createElement('div');\n head.className = 'diff-row diff-head';\n for (const text of ['Field', 'Current', 'Expected']) {\n const cell = document.createElement('span'); cell.textContent = text; head.append(cell);\n }\n grid.append(head);\n for (const item of rows) {\n const row = document.createElement('div'); row.className = 'diff-row';\n const field = document.createElement('span'); field.className = 'diff-field'; field.textContent = item.field;\n const current = document.createElement('span'); current.className = 'diff-value diff-current'; current.textContent = formatDiffValue(item.current);\n const expected = document.createElement('span'); expected.className = 'diff-value diff-expected'; expected.textContent = formatDiffValue(item.expected);\n row.append(field, current, expected); grid.append(row);\n }\n box.append(title, grid);\n }\n\n function renderStartupEnvironment() {\n const services = bootstrapInfo.services;\n const environment = [\n ['AGENTCONNECT_PUBLIC_CP_URL', services.controlPlane],\n ['AGENTCONNECT_PUBLIC_RELAY_URL', services.relay],\n ['AGENTCONNECT_PUBLIC_WEB_URL', services.web],\n ['LOGTO_ENDPOINT', bootstrapInfo.logtoEndpoint],\n ['LOGTO_MGMT_ENDPOINT', bootstrapInfo.logtoManagementEndpoint]\n ];\n el('startup-environment').textContent = environment\n .filter(([, value]) => value)\n .map(([key, value]) => key + '=' + value)\n .join('\\n');\n }\n\n function renderApps(status) {\n currentStatus = status;\n const byKey = new Map((status.secrets || []).map((item) => [item.key, item]));\n const values = status.values;\n const expected = status.providerExpectations || { github: null, gitlab: null, slack: null, linear: null, googleChat: null, google: { origins: [], redirects: [] } };\n renderStartupEnvironment();\n\n const logto = values.logto;\n text('logto-management-endpoint', logto && bootstrapInfo.logtoManagementEndpoint);\n text('logto-management-id', logto && logto.managementAppId);\n text('logto-management-resource', logto && logto.managementResource);\n secretText('logto-management-secret-display', byKey, 'logto.managementAppSecret', Boolean(logto));\n const sso = logto && logto.ssoConnector;\n ssoOrganizations = status.organizations || [];\n renderSso('sso', sso);\n el('sso-remove').hidden = !sso;\n match('sso-match', !sso ? '' : sso.oidc || sso.saml ? 'pass' : 'warn', !sso ? 'Not configured' : sso.oidc || sso.saml ? 'Configured' : 'Needs identity provider');\n text('logto-browser-endpoint', logto && logto.browser && bootstrapInfo.logtoEndpoint);\n text('logto-browser-id', values.auth.mode === 'oidc' ? values.auth.browserClient.appId : null);\n text('logto-browser-resource', logto && logto.browser && logto.browser.apiResource);\n el('logto-edit-controls').hidden = true;\n showIdentityEditors('logto', Boolean(logto && logto.browser && values.auth.mode === 'oidc'));\n match(\n 'logto-match',\n logto && configured(byKey, 'logto.managementAppSecret') ? '' : 'warn',\n logto && configured(byKey, 'logto.managementAppSecret') ? 'Ready to check' : 'Not configured'\n );\n\n el('preset-agents-enabled').checked = values.features.presetAgentsEnabled;\n el('max-orgs-per-non-admin-user').value = String(values.features.maxOrgsPerNonAdminUser);\n el('organization-sso').checked = values.features.organizationSso === true;\n\n const github = values.github;\n const webhookStored = byKey.get('github.webhookSecret') && byKey.get('github.webhookSecret').configured;\n const webhookInactive = github && github.webhookEnabled === false;\n text('github-app-id', github && github.appId);\n text('github-app-slug', github && github.slug);\n text('github-client-id', github && github.clientId);\n text('github-webhook-enabled', github && (github.webhookEnabled === false ? 'Disabled' : 'Enabled'));\n el('github-edit-controls').hidden = true;\n showIdentityEditors('github', Boolean(github));\n secretText('github-client-secret-display', byKey, 'github.clientSecret', Boolean(github));\n secretText('github-private-key-display', byKey, 'github.privateKeyB64', Boolean(github));\n secretText('github-webhook-secret-display', byKey, 'github.webhookSecret', Boolean(github));\n secretText('github-logto-secret-display', byKey, 'logto.githubConnectorClientSecret', Boolean(values.logto && values.logto.githubConnector));\n el('github-status').textContent = github\n ? github.slug + ' is configured. Webhook secret: ' + (webhookStored ? 'stored' : webhookInactive ? 'not required yet' : 'missing') + '.' +\n (webhookInactive ? ' Relay webhook delivery is disabled.' : '')\n : 'Creates the complete App used for repository installation, webhooks, and optional GitHub sign-in.';\n const githubDrift = github\n ? expected.github\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'Valid Web, API, and ingress URLs' }]\n : [];\n match('github-match', !github ? '' : githubDrift.length ? 'warn' : '', !github ? 'Not configured' : githubDrift.length ? 'Expected URLs changed' : 'Ready to check');\n el('github-create-controls').hidden = Boolean(github);\n el('create-github').hidden = Boolean(github);\n el('clear-github').hidden = !github;\n el('connect-github-login').hidden = !github || !values.logto || Boolean(values.logto.githubConnector);\n el('check-github').hidden = !github;\n if (github) showDiff('github-drift', githubDrift, 'Expected URLs changed since App creation');\n else el('github-drift').hidden = true;\n\n const gitlab = values.gitlab;\n const gitlabSecret = configured(byKey, 'gitlab.clientSecret');\n const expectedGitlab = expected.gitlab;\n renderUriList('gitlab-callbacks', expectedGitlab ? [expectedGitlab.callbackUrl] : []);\n renderUriList('gitlab-scopes', expectedGitlab ? expectedGitlab.scopes : []);\n text('gitlab-client-id', gitlab && gitlab.clientId);\n secretText('gitlab-client-secret-display', byKey, 'gitlab.clientSecret', Boolean(gitlab));\n showIdentityEditors('gitlab', Boolean(gitlab));\n el('gitlab-id').value = gitlab ? gitlab.clientId : '';\n text('gitlab-instance', (gitlab && gitlab.baseUrl) || 'https://gitlab.com');\n // Host-aware application links (§24.1): composed by the server against the\n // configured base, so a path-prefixed install keeps its prefix here too.\n if (expectedGitlab) {\n el('gitlab-applications').href = expectedGitlab.applicationsUrl;\n el('gitlab-admin-applications').href = expectedGitlab.adminApplicationsUrl;\n }\n el('gitlab-base-url').value = (gitlab && gitlab.baseUrl) || '';\n el('gitlab-status').textContent = gitlab\n ? gitlab.clientId + ' is configured.'\n : expectedGitlab\n ? 'Register the OAuth application on the configured GitLab instance, then save its Application ID and Secret here.'\n : 'Publishing the redirect URI needs an HTTPS API public URL.';\n showDiff('gitlab-drift', gitlab && !expectedGitlab\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS API URL' }]\n : []);\n match('gitlab-match', gitlab && gitlabSecret ? 'warn' : '', !gitlab ? 'Not configured' : !gitlabSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('gitlab-initial-secret-field').hidden = Boolean(gitlab) && gitlabSecret;\n el('gitlab-config-controls').hidden = Boolean(gitlab);\n el('save-gitlab').hidden = Boolean(gitlab);\n el('cancel-gitlab-configuration').hidden = true;\n el('clear-gitlab').hidden = !gitlab;\n const gitlabLogin = values.logto?.browser?.socialProviders.includes('gitlab');\n renderUriList('gitlab-login-redirects', expected.gitlabSignIn?.redirects || []);\n el('gitlab-login-status').textContent = gitlabLogin ? 'GitLab sign-in is configured. Use Check Logto to verify it.' : 'GitLab sign-in is not enabled.';\n el('connect-gitlab-login').hidden = Boolean(gitlabLogin);\n el('connect-gitlab-login').disabled = !gitlab || !gitlabSecret || !values.logto?.browser;\n el('disconnect-gitlab-login').hidden = !gitlabLogin;\n el('check-gitlab-login').hidden = !gitlabLogin;\n\n const gitea = values.gitea;\n text('gitea-instance', (gitea && gitea.baseUrl) || 'https://gitea.com');\n el('gitea-base-url').value = (gitea && gitea.baseUrl) || '';\n showIdentityEditors('gitea', Boolean(gitea));\n el('gitea-status').textContent = gitea\n ? ((gitea.baseUrl || 'https://gitea.com') + ' is configured.')\n : 'Organizations can connect gitea.com without saving anything. Save an address only for a self-hosted instance.';\n match('gitea-match', gitea ? 'warn' : '', gitea ? \"Can't verify automatically\" : 'Default');\n el('gitea-config-controls').hidden = Boolean(gitea);\n el('save-gitea').hidden = Boolean(gitea);\n el('cancel-gitea-configuration').hidden = true;\n el('clear-gitea').hidden = !gitea;\n\n const slack = values.slack;\n text('slack-app-id', slack && slack.appId);\n text('slack-client-id', slack && slack.clientId);\n el('slack-edit-controls').hidden = true;\n showIdentityEditors('slack', Boolean(slack));\n secretText('slack-client-secret-display', byKey, 'slack.clientSecret', Boolean(slack));\n secretText('slack-signing-secret-display', byKey, 'slack.signingSecret', Boolean(slack));\n el('slack-logto-status').textContent = values.logto && values.logto.slackConnector\n ? 'Enabled; reuses the Slack client secret above.'\n : 'Not enabled.';\n el('slack-status').textContent = slack ? slack.appId + ' is configured.' : 'Creates the default AgentConnect integration manifest.';\n const slackDrift = slack\n ? expected.slack\n ? []\n : [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS Web, API, and ingress URLs' }]\n : [];\n match('slack-match', !slack ? '' : slackDrift.length ? 'warn' : '', !slack ? 'Not configured' : slackDrift.length ? 'Update required' : 'Ready to check');\n el('slack-name-field').hidden = Boolean(slack);\n el('create-slack').hidden = Boolean(slack);\n el('connect-slack-login').hidden = !slack || !values.logto || Boolean(values.logto.slackConnector) || !bootstrapInfo?.slackAvailable;\n el('clear-slack').hidden = !slack;\n el('check-slack').hidden = !slack;\n el('reconcile-slack').hidden = !slack;\n el('slack-settings').hidden = !slack;\n if (slack) {\n el('slack-settings').href = 'https://api.slack.com/apps/' + encodeURIComponent(slack.appId);\n showDiff('slack-drift', slackDrift);\n } else el('slack-drift').hidden = true;\n\n const googleChat = values.googleChat;\n const googleChatKey = configured(byKey, 'googleChat.serviceAccountKey');\n const expectedGoogleChat = expected.googleChat;\n renderUriList('googlechat-callbacks', expectedGoogleChat ? [expectedGoogleChat.callbackUrl] : []);\n text('googlechat-project-id', googleChat && googleChat.projectId);\n text('googlechat-project-number', googleChat && googleChat.projectNumber);\n el('googlechat-key-display').textContent = googleChatKey ? '***' : 'Not configured';\n el('googlechat-key-display').className = googleChatKey ? 'redacted' : 'muted';\n showIdentityEditors('googlechat', Boolean(googleChat));\n el('googlechat-project-id-input').value = googleChat ? googleChat.projectId : '';\n el('googlechat-project-number-input').value = googleChat ? googleChat.projectNumber : '';\n el('googlechat-key').value = '';\n if (expectedGoogleChat) el('googlechat-configuration').href = expectedGoogleChat.configurationUrl;\n el('googlechat-status').textContent = googleChat\n ? googleChat.projectId + ' is configured.'\n : expectedGoogleChat\n ? 'Configure the Chat app in Google Cloud Console, then save its project and service-account key here.'\n : 'Publishing the HTTP endpoint URL needs an HTTPS ingress public URL.';\n showDiff('googlechat-drift', googleChat && !expectedGoogleChat\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n match('googlechat-match', googleChat && googleChatKey ? 'pass' : googleChat ? 'warn' : '', !googleChat ? 'Not configured' : !googleChatKey ? 'Missing key' : 'Checked on save');\n el('googlechat-edit-heading').hidden = true;\n el('googlechat-config-controls').hidden = Boolean(googleChat);\n el('save-googlechat').hidden = Boolean(googleChat);\n el('cancel-googlechat-configuration').hidden = true;\n el('clear-googlechat').hidden = !googleChat;\n\n const email = values.email;\n const emailToken = configured(byKey, 'email.apiToken');\n const emailIngress = configured(byKey, 'email.ingressSecret');\n const expectedEmail = expected.email;\n renderUriList('email-inbound', expectedEmail ? [expectedEmail.inboundUrl] : []);\n text('email-mail-domain', email && email.mailDomain);\n text('email-account-id', email && email.accountId);\n text('email-send-limit', email && (email.dailySendLimit ? email.dailySendLimit : 'No deployment-wide limit'));\n for (const [id, stored] of [['email-token-display', emailToken], ['email-ingress-display', emailIngress]]) {\n el(id).textContent = stored ? '***' : 'Not configured';\n el(id).className = stored ? 'redacted' : 'muted';\n }\n showIdentityEditors('email', Boolean(email));\n el('email-mail-domain-input').value = email ? email.mailDomain : '';\n el('email-account-id-input').value = email ? email.accountId : '';\n el('email-send-limit-input').value = email && email.dailySendLimit ? String(email.dailySendLimit) : '';\n el('email-token').value = '';\n if (expectedEmail) el('email-dashboard').href = expectedEmail.dashboardUrl;\n el('email-status').textContent = email\n ? 'Agents get addresses on ' + email.mailDomain + '.'\n : expectedEmail\n ? 'Onboard the mail domain in Cloudflare, then save it with the account ID and an API token here.'\n : 'Publishing the inbound URL needs an HTTPS ingress public URL.';\n showDiff('email-drift', email && !expectedEmail\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'An HTTPS ingress URL' }]\n : []);\n const emailReady = email && emailToken && emailIngress;\n match('email-match', emailReady ? 'pass' : email ? 'warn' : '', !email ? 'Not configured' : !emailReady ? 'Missing secret' : 'Checked on save');\n el('email-edit-heading').hidden = true;\n el('email-config-controls').hidden = Boolean(email);\n el('save-email').hidden = Boolean(email);\n el('cancel-email-configuration').hidden = true;\n // A status render never touches the secret box or a pending Replace: they belong to the operator's own clicks.\n if (!email) el('email-rotate-confirm').hidden = true;\n el('rotate-email-ingress').hidden = !email || !el('email-rotate-confirm').hidden;\n el('clear-email').hidden = !email;\n\n\n const linear = values.linear;\n const linearSecrets = configured(byKey, 'linear.clientSecret') && configured(byKey, 'linear.signingSecret');\n const expectedLinear = expected.linear;\n renderUriList('linear-callbacks', expectedLinear ? [expectedLinear.callbackUrl] : []);\n renderUriList('linear-webhooks', expectedLinear ? [expectedLinear.webhookUrl] : []);\n text('linear-client-id', linear && linear.clientId);\n secretText('linear-client-secret-display', byKey, 'linear.clientSecret', Boolean(linear));\n secretText('linear-signing-secret-display', byKey, 'linear.signingSecret', Boolean(linear));\n showIdentityEditors('linear', Boolean(linear));\n el('linear-id').value = linear ? linear.clientId : '';\n if (expectedLinear) el('linear-applications').href = expectedLinear.applicationsUrl;\n el('linear-status').textContent = linear\n ? linear.clientId + ' is configured.'\n : expectedLinear\n ? 'Register the OAuth application in Linear, then save its Client ID and both secrets here.'\n : 'Publishing the callback and webhook URLs needs HTTPS API and ingress public URLs.';\n showDiff('linear-drift', linear && !expectedLinear\n ? [{ field: 'Startup public URLs', current: 'Unavailable', expected: 'HTTPS API and ingress URLs' }]\n : []);\n match('linear-match', linear && linearSecrets ? 'warn' : '', !linear ? 'Not configured' : !linearSecrets ? 'Missing secret' : \"Can't verify automatically\");\n el('linear-initial-secret-fields').hidden = Boolean(linear) && linearSecrets;\n el('linear-config-controls').hidden = Boolean(linear);\n el('save-linear').hidden = Boolean(linear);\n el('cancel-linear-configuration').hidden = true;\n el('clear-linear').hidden = !linear;\n\n const google = values.logto && values.logto.googleConnector;\n const googleSecret = configured(byKey, 'logto.googleConnectorClientSecret');\n const expectedGoogle = expected.google;\n renderUriList('google-origins', expectedGoogle.origins);\n renderUriList('google-redirects', expectedGoogle.redirects);\n text('google-client-id', google && google.clientId);\n secretText('google-client-secret-display', byKey, 'logto.googleConnectorClientSecret', Boolean(google));\n showIdentityEditors('google', Boolean(google));\n el('google-id').value = google ? google.clientId : '';\n el('google-status').textContent = google ? 'Google OAuth client is configured.' : 'Create a Web application OAuth client manually, then save it here.';\n showDiff('google-drift', []);\n match('google-match', google && googleSecret ? 'warn' : '', !google ? 'Not configured' : !googleSecret ? 'Missing secret' : \"Can't verify automatically\");\n el('google-initial-secret-field').hidden = googleSecret;\n el('save-google').textContent = google ? 'Confirm callback settings' : 'Save Google client';\n el('google-config-controls').hidden = Boolean(google);\n el('save-google').hidden = Boolean(google);\n el('cancel-google-configuration').hidden = true;\n el('check-google').hidden = !google || !googleSecret;\n el('clear-google').hidden = !google;\n\n for (const [provider, app] of Object.entries(loginApps)) {\n const saved = values.logto && values.logto[provider + 'Connector'];\n const secretKey = 'logto.' + provider + 'ConnectorClientSecret';\n const hasSecret = configured(byKey, secretKey);\n renderUriList(provider + '-redirects', expected[provider].redirects);\n text(provider + '-client-id', saved && saved.clientId);\n secretText(provider + '-client-secret-display', byKey, secretKey, Boolean(saved));\n showIdentityEditors(provider, Boolean(saved));\n el(provider + '-id').value = saved ? saved.clientId : '';\n el(provider + '-status').hidden = !saved;\n el(provider + '-status').textContent = saved ? app.name + ' login application is saved.' : '';\n showDiff(provider + '-drift', []);\n match(provider + '-match', saved ? 'warn' : '', !saved ? 'Not configured' : !hasSecret ? 'Missing secret' : 'Not checked');\n el(provider + '-initial-secret-field').hidden = hasSecret;\n el(provider + '-config-controls').hidden = Boolean(saved);\n el('save-' + provider).hidden = Boolean(saved);\n el('save-' + provider).disabled = !values.logto || !values.logto.browser;\n el('cancel-' + provider + '-configuration').hidden = true;\n el('check-' + provider).hidden = !saved || !hasSecret;\n el('clear-' + provider).hidden = !saved;\n }\n const expectedTeams = expected.msTeams;\n text('azuread-teams-tenant-id', values.msTeams && values.msTeams.tenantId);\n el('azuread-teams-tenant-input').value = values.msTeams ? values.msTeams.tenantId : '';\n renderUriList('azuread-teams-endpoint', expectedTeams ? [expectedTeams.messagingEndpoint] : []);\n renderUriList('azuread-teams-redirects', expectedTeams ? [expectedTeams.connectRedirectUri] : []);\n // Agent bots sit beside the Teams app: the group shows once it is configured, and its form until a blueprint is saved.\n const agentBots = values.msTeams && values.msTeams.agentBots;\n const blueprintSecret = configured(byKey, 'msTeams.blueprintClientSecret');\n el('azuread-agent-bots').hidden = !values.msTeams;\n text('azuread-agent-bots-blueprint', agentBots && agentBots.blueprintId);\n el('azuread-agent-bots-secret').textContent = blueprintSecret ? '***' : 'Not configured';\n el('azuread-agent-bots-secret').className = blueprintSecret ? 'redacted' : 'muted';\n text('azuread-agent-bots-subscription', agentBots && agentBots.subscriptionId);\n text('azuread-agent-bots-group', agentBots && agentBots.resourceGroup);\n el('azuread-agent-bots-controls').hidden = Boolean(agentBots);\n el('clear-azuread-agent-bots').hidden = !agentBots;\n renderUriList('azuread-azure-devops-redirects', expected.azureDevOps ? [expected.azureDevOps.connectRedirectUri] : []);\n\n const feishuSecret = byKey.get('feishu.loginAppSecret');\n const larkSecret = byKey.get('lark.loginAppSecret');\n el('feishu-login-id').value = values.feishu ? values.feishu.loginAppId : '';\n el('lark-login-id').value = values.lark ? values.lark.loginAppId : '';\n text('feishu-app-id', values.feishu && values.feishu.loginAppId);\n text('lark-app-id', values.lark && values.lark.loginAppId);\n showIdentityEditors('feishu', Boolean(values.feishu));\n showIdentityEditors('lark', Boolean(values.lark));\n secretText('feishu-app-secret-display', byKey, 'feishu.loginAppSecret', Boolean(values.feishu));\n secretText('lark-app-secret-display', byKey, 'lark.loginAppSecret', Boolean(values.lark));\n el('feishu-login-status').textContent = values.feishu && feishuSecret && feishuSecret.configured\n ? values.feishu.loginAppId + ' is configured.'\n : 'No Feishu tenant App is configured.';\n el('lark-login-status').textContent = values.lark && larkSecret && larkSecret.configured\n ? values.lark.loginAppId + ' is configured.'\n : 'No Lark tenant App is configured.';\n match('feishu-match', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? '' : '', values.feishu && configured(byKey, 'feishu.loginAppSecret') ? 'Ready to check' : 'Not configured');\n match('lark-match', values.lark && configured(byKey, 'lark.loginAppSecret') ? '' : '', values.lark && configured(byKey, 'lark.loginAppSecret') ? 'Ready to check' : 'Not configured');\n showDiff('feishu-drift', []);\n showDiff('lark-drift', []);\n el('feishu-config-controls').hidden = Boolean(values.feishu);\n el('lark-config-controls').hidden = Boolean(values.lark);\n el('feishu-create-name-field').hidden = Boolean(values.feishu);\n el('lark-create-name-field').hidden = Boolean(values.lark);\n el('create-feishu-login-app').hidden = Boolean(values.feishu);\n el('create-lark-login-app').hidden = Boolean(values.lark);\n el('save-feishu-login-app').hidden = Boolean(values.feishu);\n el('save-lark-login-app').hidden = Boolean(values.lark);\n el('cancel-feishu-configuration').hidden = true;\n el('cancel-lark-configuration').hidden = true;\n el('clear-feishu').hidden = !values.feishu;\n el('clear-lark').hidden = !values.lark;\n el('check-feishu-login-app').hidden = !values.feishu || !configured(byKey, 'feishu.loginAppSecret');\n el('check-lark-login-app').hidden = !values.lark || !configured(byKey, 'lark.loginAppSecret');\n el('feishu-settings').hidden = !values.feishu;\n el('lark-settings').hidden = !values.lark;\n if (values.feishu) el('feishu-settings').href = 'https://open.feishu.cn/app/' + encodeURIComponent(values.feishu.loginAppId);\n if (values.lark) el('lark-settings').href = 'https://open.larksuite.com/app/' + encodeURIComponent(values.lark.loginAppId);\n\n const mattermost = values.logto && values.logto.mattermostConnector;\n const mattermostSecret = configured(byKey, 'logto.mattermostConnectorClientSecret');\n const expectedMattermost = expected.mattermostSignIn;\n renderUriList('mattermost-redirects', expectedMattermost ? expectedMattermost.redirects : []);\n text('mattermost-server-url', mattermost && mattermost.serverUrl);\n text('mattermost-client-id', mattermost && mattermost.clientId);\n secretText('mattermost-client-secret-display', byKey, 'logto.mattermostConnectorClientSecret', Boolean(mattermost));\n showIdentityEditors('mattermost', Boolean(mattermost));\n el('mattermost-server-url-input').value = mattermost ? mattermost.serverUrl : '';\n el('mattermost-id').value = mattermost ? mattermost.clientId : '';\n el('mattermost-status').hidden = !mattermost;\n el('mattermost-status').textContent = mattermost ? 'Mattermost sign-in OAuth application is saved.' : '';\n showDiff('mattermost-drift', []);\n match('mattermost-match', mattermost ? 'warn' : '', !mattermost ? 'Not configured' : !mattermostSecret ? 'Missing secret' : 'Not checked');\n el('mattermost-initial-secret-field').hidden = Boolean(mattermost) && mattermostSecret;\n el('mattermost-config-controls').hidden = Boolean(mattermost);\n el('save-mattermost').hidden = Boolean(mattermost);\n el('save-mattermost').disabled = !values.logto || !values.logto.browser;\n el('cancel-mattermost-configuration').hidden = true;\n el('check-mattermost').hidden = !mattermost || !mattermostSecret;\n el('clear-mattermost').hidden = !mattermost;\n }\n\n function requiredInput(id, label) {\n const value = el(id).value.trim();\n if (!value) throw new Error('Enter ' + label);\n return value;\n }\n\n function githubConnectorUsesDeployment(values) {\n const github = values.github;\n const connector = values.logto && values.logto.githubConnector;\n return Boolean(\n github && connector &&\n connector.appId === github.appId &&\n connector.slug === github.slug &&\n connector.clientId === github.clientId\n );\n }\n\n function beginConfigurationEdit(provider) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const values = currentStatus.values;\n if (provider === 'logto') {\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') return;\n el('logto-edit-management-id').value = logto.managementAppId;\n el('logto-edit-management-resource').value = logto.managementResource;\n el('logto-edit-management-secret').value = '';\n el('logto-edit-browser-id').value = values.auth.browserClient.appId;\n el('logto-edit-browser-resource').value = logto.browser.apiResource || '';\n el('logto-edit-controls').hidden = false;\n el('logto-edit-management-id').focus();\n } else if (provider === 'github') {\n const github = values.github;\n if (!github) return;\n el('github-edit-app-id').value = String(github.appId);\n el('github-edit-slug').value = github.slug;\n el('github-edit-client-id').value = github.clientId || '';\n el('github-edit-webhook-enabled').checked = github.webhookEnabled !== false;\n for (const id of ['github-edit-client-secret', 'github-edit-private-key', 'github-edit-webhook-secret', 'github-edit-logto-secret']) el(id).value = '';\n el('github-edit-logto-secret-field').hidden = !githubConnectorUsesDeployment(values);\n el('github-edit-controls').hidden = false;\n el('clear-github').hidden = true;\n el('github-edit-app-id').focus();\n } else if (provider === 'slack') {\n const slack = values.slack;\n if (!slack) return;\n el('slack-edit-app-id').value = slack.appId;\n el('slack-edit-client-id').value = slack.clientId;\n el('slack-edit-client-secret').value = '';\n el('slack-edit-signing-secret').value = '';\n el('slack-edit-controls').hidden = false;\n el('clear-slack').hidden = true;\n el('slack-edit-app-id').focus();\n } else if (provider === 'gitea') {\n if (!values.gitea) return;\n el('gitea-base-url').value = values.gitea.baseUrl || '';\n el('gitea-config-controls').hidden = false;\n el('save-gitea').hidden = false;\n el('cancel-gitea-configuration').hidden = false;\n el('clear-gitea').hidden = true;\n el('gitea-base-url').focus();\n } else if (provider === 'gitlab') {\n if (!values.gitlab) return;\n el('gitlab-id').value = values.gitlab.clientId;\n el('gitlab-secret').value = '';\n el('gitlab-config-controls').hidden = false;\n el('gitlab-initial-secret-field').hidden = false;\n el('save-gitlab').hidden = false;\n el('cancel-gitlab-configuration').hidden = false;\n el('clear-gitlab').hidden = true;\n el('gitlab-id').focus();\n } else if (provider === 'googlechat') {\n if (!values.googleChat) return;\n el('googlechat-project-id-input').value = values.googleChat.projectId;\n el('googlechat-project-number-input').value = values.googleChat.projectNumber;\n el('googlechat-key').value = '';\n el('googlechat-edit-heading').hidden = false;\n el('googlechat-config-controls').hidden = false;\n el('save-googlechat').hidden = false;\n el('cancel-googlechat-configuration').hidden = false;\n el('clear-googlechat').hidden = true;\n el('googlechat-project-id-input').focus();\n } else if (provider === 'email') {\n if (!values.email) return;\n el('email-mail-domain-input').value = values.email.mailDomain;\n el('email-account-id-input').value = values.email.accountId;\n el('email-send-limit-input').value = values.email.dailySendLimit ? String(values.email.dailySendLimit) : '';\n el('email-token').value = '';\n el('email-edit-heading').hidden = false;\n el('email-config-controls').hidden = false;\n el('save-email').hidden = false;\n el('cancel-email-configuration').hidden = false;\n el('rotate-email-ingress').hidden = true;\n el('email-rotate-confirm').hidden = true;\n el('clear-email').hidden = true;\n el('email-mail-domain-input').focus();\n } else if (provider === 'linear') {\n if (!values.linear) return;\n el('linear-id').value = values.linear.clientId;\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n el('linear-config-controls').hidden = false;\n el('linear-initial-secret-fields').hidden = false;\n el('save-linear').hidden = false;\n el('cancel-linear-configuration').hidden = false;\n el('clear-linear').hidden = true;\n el('linear-id').focus();\n } else if (provider === 'google') {\n const google = values.logto && values.logto.googleConnector;\n if (!google) return;\n el('google-id').value = google.clientId;\n el('google-secret').value = '';\n el('google-config-controls').hidden = false;\n el('google-initial-secret-field').hidden = false;\n el('save-google').hidden = false;\n el('save-google').textContent = 'Save Google client';\n el('cancel-google-configuration').hidden = false;\n el('clear-google').hidden = true;\n el('google-id').focus();\n } else if (Object.hasOwn(loginApps, provider)) {\n el(provider + '-secret').value = '';\n el(provider + '-config-controls').hidden = false;\n el(provider + '-initial-secret-field').hidden = false;\n el('save-' + provider).hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-id').focus();\n } else if (provider === 'mattermost') {\n const mattermost = values.logto && values.logto.mattermostConnector;\n if (!mattermost) return;\n el('mattermost-server-url-input').value = mattermost.serverUrl;\n el('mattermost-id').value = mattermost.clientId;\n el('mattermost-secret').value = '';\n el('mattermost-config-controls').hidden = false;\n el('mattermost-initial-secret-field').hidden = false;\n el('save-mattermost').hidden = false;\n el('cancel-mattermost-configuration').hidden = false;\n el('clear-mattermost').hidden = true;\n el('mattermost-server-url-input').focus();\n } else if (provider === 'feishu' || provider === 'lark') {\n el(provider + '-config-controls').hidden = false;\n el(provider + '-create-name-field').hidden = true;\n el('create-' + provider + '-login-app').hidden = true;\n el('save-' + provider + '-login-app').hidden = false;\n el('cancel-' + provider + '-configuration').hidden = false;\n el('clear-' + provider).hidden = true;\n el(provider + '-login-secret').value = '';\n el(provider + '-login-id').focus();\n }\n showIdentityEditors(provider, false);\n }\n\n function cancelConfigurationEdit() {\n if (currentStatus) renderApps(currentStatus);\n }\n\n async function replaceConfiguration(values, secrets, successMessage) {\n const response = await json(await fetch(api + '/deployment-config', {\n method: 'PUT',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values, ...(secrets ? { secrets } : {}) })\n }));\n await load();\n message(successMessage || 'Configuration saved. Restart AgentConnect to apply it.');\n return response;\n }\n\n async function saveLogtoConfiguration() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n const logto = values.logto;\n if (!logto || !logto.browser || values.auth.mode !== 'oidc') throw new Error('Logto is not configured');\n const managementAppId = requiredInput('logto-edit-management-id', 'the Management App ID');\n const managementResource = requiredInput('logto-edit-management-resource', 'the Management API resource');\n const browserAppId = requiredInput('logto-edit-browser-id', 'the SPA App ID');\n const browserResource = el('logto-edit-browser-resource').value.trim() || null;\n const managementIdentityChanged = managementAppId !== logto.managementAppId;\n const managementSecret = el('logto-edit-management-secret').value;\n if (managementIdentityChanged && !managementSecret) throw new Error('Enter the new Management App secret');\n const browser = { ...logto.browser, apiResource: browserResource };\n const auth = {\n ...values.auth,\n audience: browserResource || browserAppId,\n browserClient: { appId: browserAppId, apiResource: browserResource }\n };\n await replaceConfiguration(\n {\n ...values,\n auth,\n logto: { ...logto, managementAppId, managementResource, browser }\n },\n managementSecret ? { 'logto.managementAppSecret': managementSecret } : undefined,\n 'Logto configuration saved. Sign in again if the SPA identity changed, then restart AgentConnect.'\n );\n }\n\n async function saveGithubConfiguration() {\n if (!currentStatus || !currentStatus.values.github) throw new Error('GitHub is not configured');\n const values = currentStatus.values;\n const previous = values.github;\n const appId = Number(requiredInput('github-edit-app-id', 'the GitHub App ID'));\n if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error('GitHub App ID must be a positive integer');\n const slug = requiredInput('github-edit-slug', 'the GitHub App slug');\n const clientId = requiredInput('github-edit-client-id', 'the GitHub Client ID');\n const appChanged = appId !== previous.appId;\n const clientChanged = clientId !== previous.clientId;\n const webhookEnabled = el('github-edit-webhook-enabled').checked;\n const webhookEnabling = webhookEnabled && previous.webhookEnabled === false;\n const connectorReused = githubConnectorUsesDeployment(values);\n const clientSecret = el('github-edit-client-secret').value;\n const privateKey = el('github-edit-private-key').value.trim();\n const webhookSecret = el('github-edit-webhook-secret').value;\n const connectorSecret = el('github-edit-logto-secret').value;\n const webhookSecretStored = currentStatus.secrets.some((secret) => secret.key === 'github.webhookSecret' && secret.configured);\n if ((appChanged || clientChanged) && !clientSecret) throw new Error('Enter the new GitHub client secret');\n if (appChanged && !privateKey) throw new Error('Enter the new GitHub private key as base64');\n if (webhookEnabled && ((appChanged && !webhookSecret) || (webhookEnabling && !webhookSecret && !webhookSecretStored))) throw new Error('Enter the new GitHub webhook secret');\n if (connectorReused && (appChanged || clientChanged) && !connectorSecret) throw new Error('Enter the new Logto connector client secret');\n const secrets = {};\n if (clientSecret) secrets['github.clientSecret'] = clientSecret;\n if (privateKey) secrets['github.privateKeyB64'] = privateKey;\n if (webhookSecret) secrets['github.webhookSecret'] = webhookSecret;\n if (connectorSecret) secrets['logto.githubConnectorClientSecret'] = connectorSecret;\n const nextLogto = connectorReused && values.logto\n ? { ...values.logto, githubConnector: { ...values.logto.githubConnector, appId, slug, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n github: { ...previous, appId, slug, clientId, webhookEnabled },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'GitHub App identity saved. Restart AgentConnect to apply it.'\n );\n if (connectorSecret) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function saveSlackConfiguration() {\n if (!currentStatus || !currentStatus.values.slack) throw new Error('Slack is not configured');\n const values = currentStatus.values;\n const previous = values.slack;\n const appId = requiredInput('slack-edit-app-id', 'the Slack App ID');\n const clientId = requiredInput('slack-edit-client-id', 'the Slack Client ID');\n const changed = appId !== previous.appId || clientId !== previous.clientId;\n const clientSecret = el('slack-edit-client-secret').value;\n const signingSecret = el('slack-edit-signing-secret').value;\n if (changed && (!clientSecret || !signingSecret)) throw new Error('Enter both the new Slack client secret and signing secret');\n const secrets = {};\n if (clientSecret) secrets['slack.clientSecret'] = clientSecret;\n if (signingSecret) secrets['slack.signingSecret'] = signingSecret;\n const nextLogto = values.logto && values.logto.slackConnector\n ? { ...values.logto, slackConnector: { ...values.logto.slackConnector, appId, clientId } }\n : values.logto;\n await replaceConfiguration(\n {\n ...values,\n slack: { ...previous, appId, clientId },\n ...(nextLogto ? { logto: nextLogto } : {})\n },\n Object.keys(secrets).length ? secrets : undefined,\n 'Slack App identity saved. Restart AgentConnect to apply it.'\n );\n if (clientSecret && nextLogto && nextLogto.slackConnector) {\n await reconcileLogto(true);\n await load();\n }\n }\n\n async function clearProvider(provider) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const label = provider === 'github' ? 'GitHub' : provider === 'gitlab' ? 'GitLab' : provider === 'gitea' ? 'Gitea' : provider === 'slack' ? 'Slack' : provider === 'googlechat' ? 'Google Chat' : provider === 'email' ? 'Email' : provider === 'linear' ? 'Linear' : provider === 'google' ? 'Google' : provider === 'mattermost' ? 'Mattermost' : provider === 'feishu' ? 'Feishu' : 'Lark';\n if (!window.confirm('Clear the saved ' + label + ' configuration and secrets?')) return;\n const values = currentStatus.values;\n let next = values;\n let secrets = {};\n if (provider === 'github') {\n const connectorReused = githubConnectorUsesDeployment(values);\n const logto = connectorReused && values.logto\n ? {\n ...values.logto,\n githubConnector: null\n }\n : values.logto;\n next = { ...values, github: null, ...(logto ? { logto } : {}) };\n secrets = {\n 'github.clientSecret': null,\n 'github.privateKeyB64': null,\n 'github.webhookSecret': null,\n ...(connectorReused ? { 'logto.githubConnectorClientSecret': null } : {})\n };\n } else if (provider === 'gitea') {\n // Gitea holds no deployment secret, so clearing the address clears the whole entry.\n next = { ...values, gitea: null };\n } else if (provider === 'gitlab') {\n await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: null })\n }));\n showGitlabProbe(null);\n await load();\n message('GitLab configuration cleared. Its setup controls are available again.');\n return;\n } else if (provider === 'slack') {\n const logto = values.logto\n ? {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'slack') }\n : values.logto.browser,\n slackConnector: null\n }\n : values.logto;\n next = { ...values, slack: null, ...(logto ? { logto } : {}) };\n secrets = { 'slack.clientSecret': null, 'slack.signingSecret': null };\n } else if (provider === 'googlechat') {\n next = { ...values, googleChat: null };\n secrets = { 'googleChat.serviceAccountKey': null };\n } else if (provider === 'email') {\n next = { ...values, email: null };\n secrets = { 'email.apiToken': null, 'email.ingressSecret': null };\n } else if (provider === 'linear') {\n next = { ...values, linear: null };\n secrets = { 'linear.clientSecret': null, 'linear.signingSecret': null };\n } else if (provider === 'google') {\n if (!values.logto) return;\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: values.logto.browser\n ? { ...values.logto.browser, socialProviders: values.logto.browser.socialProviders.filter((item) => item !== 'google') }\n : values.logto.browser,\n googleConnector: null\n }\n };\n secrets = { 'logto.googleConnectorClientSecret': null };\n } else if (provider === 'mattermost') {\n if (!values.logto || !values.logto.browser) return;\n const socialProviders = values.logto.browser.socialProviders.filter((item) => item !== 'mattermost');\n if (socialProviders.length === 0 && (!values.logto.ssoConnector || (!values.logto.ssoConnector.oidc && !values.logto.ssoConnector.saml))) {\n throw new Error('Keep at least one sign-in provider configured');\n }\n next = {\n ...values,\n logto: {\n ...values.logto,\n browser: { ...values.logto.browser, socialProviders },\n mattermostConnector: null\n }\n };\n secrets = { 'logto.mattermostConnectorClientSecret': null };\n } else if (provider === 'feishu' || provider === 'lark') {\n next = { ...values, [provider]: null };\n secrets = { [provider + '.loginAppSecret']: null };\n }\n await replaceConfiguration(next, secrets, label + ' configuration cleared. Its setup controls are available again.');\n if (provider === 'mattermost') {\n try { await reconcileLogto(false); } finally { await load(); }\n showMattermostProbe(null);\n }\n if (provider === 'gitea') el('gitea-probe').hidden = true;\n if (provider === 'email') showEmailIngressSecret('');\n }\n\n async function startGithub(prefix) {\n const result = await json(await fetch(api + '/create/github/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n purpose: 'deployment',\n name: el(prefix + '-name').value,\n ownership: ownership(prefix),\n connectLogto: prefix === 'bootstrap-github'\n })\n }));\n const form = document.createElement('form');\n form.method = 'post'; form.action = result.action;\n const manifest = document.createElement('input');\n manifest.type = 'hidden'; manifest.name = 'manifest'; manifest.value = JSON.stringify(result.manifest);\n form.append(manifest); document.body.append(form);\n message('Opening GitHub to review the complete integration App.');\n form.submit();\n }\n\n async function loadBootstrapInfo() {\n bootstrapInfo = await json(await fetch(api + '/bootstrap-info'));\n el('open-logto').href = bootstrapInfo.logtoAdminEndpoint;\n el('logto-settings').href = bootstrapInfo.logtoAdminEndpoint;\n if (!el('logto-app-id').value && bootstrapInfo.logtoManagementAppId) {\n el('logto-app-id').value = bootstrapInfo.logtoManagementAppId;\n }\n renderUriList('bootstrap-google-origins', bootstrapInfo.google.javascriptOrigins);\n renderUriList('bootstrap-google-redirects', bootstrapInfo.google.redirectUris);\n renderUriList('bootstrap-slack-redirects', [bootstrapInfo.slackLoginRedirectUrl]);\n el('logto-management-api-resource').value = bootstrapInfo.logtoManagementResource;\n el('bootstrap-github-submit').disabled = !bootstrapInfo.githubAvailable;\n if (!bootstrapInfo.githubAvailable) {\n el('bootstrap-github-note').textContent = 'GitHub App creation needs valid saved Web, API, and ingress URLs.';\n } else if (!bootstrapInfo.githubWebhookActive) {\n el('bootstrap-github-note').textContent = 'Creates the complete GitHub App now without submitting the localhost webhook URL. Add it after saving reachable HTTPS ingress.';\n } else {\n el('bootstrap-github-note').textContent = 'This creates one complete App for both GitHub sign-in and repository integration.';\n }\n el('bootstrap-slack-option').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-submit').disabled = !bootstrapInfo.slackAvailable;\n el('bootstrap-slack-note').textContent = bootstrapInfo.slackAvailable\n ? 'Creates one complete Slack App. Sign-in uses a separate openid profile email flow from workspace installation.'\n : 'Slack sign-in needs all public service URLs to use HTTPS. Use Google locally or expose the stack through trusted HTTPS endpoints.';\n if (!bootstrapInfo.slackAvailable && el('bootstrap-provider').value === 'slack') {\n el('bootstrap-provider').value = 'google';\n updateBootstrapProvider();\n }\n return bootstrapInfo;\n }\n\n async function logtoBootstrapFinding() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n for (const id of ['logto.client_credentials', 'logto.roles_read']) {\n const finding = report.findings.find((candidate) => candidate.id === id);\n if (!finding || finding.status !== 'pass') {\n return finding || { status: 'fail', message: 'Logto Management API permissions could not be verified.' };\n }\n }\n return { status: 'pass', message: 'Logto Management API access is ready.' };\n }\n\n async function showBootstrap() {\n el('bootstrap').hidden = false;\n el('show-bootstrap').hidden = true;\n const info = bootstrapInfo || await loadBootstrapInfo();\n if (!info.logtoConfigured) {\n showBootstrapStep('logto');\n return;\n }\n const finding = await logtoBootstrapFinding();\n if (finding && finding.status === 'pass') {\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n return;\n }\n showBootstrapStep('logto');\n message(finding?.message || 'Logto Management API credentials could not be verified.', true);\n }\n\n async function bootstrapLogto() {\n await json(await fetch(api + '/bootstrap/logto', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n managementAppId: el('logto-app-id').value,\n managementAppSecret: el('logto-app-secret').value,\n managementResource: el('logto-management-api-resource').value\n })\n }));\n el('logto-app-secret').value = '';\n await loadBootstrapInfo();\n const finding = await logtoBootstrapFinding();\n if (!finding || finding.status !== 'pass') {\n throw new Error(finding?.message || 'Logto Management API credentials could not be verified.');\n }\n showBootstrapStep('provider');\n message('Logto Management API access is ready. Choose a sign-in provider.');\n }\n\n async function bootstrapGoogle() {\n const secret = el('bootstrap-google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ clientId: el('bootstrap-google-id').value, clientSecret: secret })\n }));\n el('bootstrap-google-secret').value = '';\n await reconcileLogto(true);\n await load();\n }\n\n async function bootstrapGithub() {\n if (!bootstrapInfo || !bootstrapInfo.githubAvailable) throw new Error('GitHub App creation needs valid saved Web, API, and ingress URLs.');\n await startGithub('bootstrap-github');\n }\n\n async function bootstrapSlack() {\n if (!bootstrapInfo || !bootstrapInfo.slackAvailable) throw new Error('Slack sign-in requires all public service URLs to use HTTPS.');\n await createSlack('bootstrap-slack', true);\n await reconcileLogto();\n await load();\n }\n\n async function createSlack(prefix = 'slack', connectLogto = false) {\n const result = await json(await fetch(api + '/create/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n name: el(prefix + '-name').value,\n configToken: el(prefix + '-token').value,\n connectLogto\n })\n }));\n el(prefix + '-token').value = '';\n if (!connectLogto) await load();\n message('Slack App ' + result.app.id + ' was created with the default integration manifest. Restart AgentConnect to apply it.');\n }\n\n async function checkGithub() {\n const result = await json(await fetch(api + '/check/github', { headers: bearer() }));\n el('github-settings').href = result.settingsUrl;\n el('github-settings').hidden = false;\n const label = result.missing.length ? 'Update required' : \"Can't verify automatically\";\n showDiff('github-drift', result.diff || [], label);\n match('github-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : label);\n message(result.status === 'pass' ? 'GitHub App matches the expected integration manifest.' : result.missing.length ? 'GitHub App settings need an update.' : \"GitHub can't expose callback, setup, or webhook-active settings through its API; check them in GitHub.\", result.status === 'fail');\n }\n\n async function connectGithubLogin() {\n await json(await fetch(api + '/configure/github-login', { method: 'POST', headers: bearer() }));\n await reconcileLogto();\n await load();\n message('The deployment GitHub App is now also used for Logto sign-in. Update its displayed callback URLs.');\n }\n\n async function connectSlackLogin() {\n if (!currentStatus || !currentStatus.values.slack || !currentStatus.values.logto) {\n throw new Error('Save the Slack App and Logto configuration first');\n }\n const values = currentStatus.values;\n const slack = values.slack;\n const logto = values.logto;\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...logto,\n browser: logto.browser\n ? { ...logto.browser, socialProviders: [...new Set([...logto.browser.socialProviders, 'slack'])] }\n : logto.browser,\n slackConnector: {\n appId: slack.appId,\n clientId: slack.clientId\n }\n }\n },\n undefined,\n 'Slack App is ready to connect to Logto.'\n );\n await reconcileLogto();\n await load();\n message('The deployment Slack App is now also used for Logto sign-in.');\n }\n\n async function checkSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/check/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(result.status === 'pass' ? 'Slack App matches the default integration manifest.' : 'Slack App settings need an update.', result.status !== 'pass');\n }\n\n async function reconcileSlack() {\n const token = requiredInput('slack-token', 'the temporary Slack App configuration token');\n const result = await json(await fetch(api + '/reconcile/slack', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ configToken: token })\n }));\n el('slack-token').value = '';\n showDiff('slack-drift', result.diff || []);\n match('slack-match', result.status === 'pass' ? 'pass' : 'warn', result.status === 'pass' ? 'Matches' : 'Update required');\n message(\n result.status !== 'pass'\n ? 'Slack App was updated but some settings still differ.'\n : result.applied.length === 0\n ? 'Slack App already matches the default integration manifest.'\n : result.permissionsUpdated\n ? 'Slack App updated. Reinstall it in each workspace to grant the added scopes.'\n : 'Slack App updated.',\n result.status !== 'pass'\n );\n }\n\n async function checkGoogle() {\n const report = await checkLogto();\n const connector = report.findings.find((finding) => finding.id === 'logto.connectors');\n const google = currentStatus && currentStatus.values.logto && currentStatus.values.logto.googleConnector;\n const connectorDiff = connector && connector.diff\n ? connector.diff.filter((item) => item.field.toLowerCase().startsWith('google'))\n : [];\n const passed = Boolean(google && connector && connectorDiff.length === 0);\n showDiff('google-drift', connectorDiff);\n match('google-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Update required');\n message(\n passed\n ? \"The Logto Google connector matches. Google OAuth redirect settings can't be verified automatically.\"\n : 'The Logto Google connector needs an update.',\n !passed\n );\n }\n\n async function checkRegionalLoginApp(region) {\n const result = await json(await fetch(api + '/check/regional-login-app/' + region, { headers: bearer() }));\n const label = region === 'feishu' ? 'Feishu' : 'Lark';\n showDiff(region + '-drift', result.diff || []);\n match(region + '-match', result.status === 'pass' ? 'pass' : result.status === 'fail' ? 'fail' : 'warn', result.status === 'pass' ? 'Matches' : result.status === 'fail' ? 'Update required' : 'Could not check');\n el(region + '-login-status').textContent = result.message;\n el(region + '-login-status').className = result.status === 'pass' ? 'ok' : result.status === 'fail' ? 'warn' : 'muted';\n message(result.message || (label + ' credential check completed.'), result.status === 'fail');\n }\n\n async function saveGitlab() {\n const clientSecret = el('gitlab-secret').value;\n const baseUrl = el('gitlab-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitlab', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('gitlab-id', 'the GitLab Application ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(baseUrl ? { baseUrl } : {})\n }\n })\n }));\n el('gitlab-secret').value = '';\n if (currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) await reconcileLogto(Boolean(clientSecret));\n await load();\n showGitlabProbe(saved.probe);\n message('GitLab OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n // Only the URL shape blocks the save, so every other verdict is a line to read.\n function showGitlabProbe(probe) {\n const line = el('gitlab-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function configureGitlabLogin(enabled) {\n await json(await fetch(api + '/configure/gitlab-login', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ enabled })\n }));\n try { await reconcileLogto(enabled); } finally { await load(); }\n message('GitLab sign-in ' + (enabled ? 'configured' : 'disabled') + '. Restart AgentConnect to apply it.');\n }\n\n async function saveGitea() {\n const baseUrl = el('gitea-base-url').value.trim();\n const saved = await json(await fetch(api + '/configure/gitea', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ instance: { ...(baseUrl ? { baseUrl } : {}) } })\n }));\n await load();\n // Shape and the version floor already blocked the save, so any verdict here is a line to read.\n const line = el('gitea-probe');\n line.hidden = !saved.probe;\n line.textContent = saved.probe ? saved.probe.message : '';\n message('Gitea instance saved. Restart AgentConnect to apply it.');\n }\n\n async function saveGoogleChat() {\n const projectNumber = el('googlechat-project-number-input').value.trim();\n const application = {\n projectId: requiredInput('googlechat-project-id-input', 'the Google Cloud project ID'),\n ...(projectNumber ? { projectNumber } : {})\n };\n const serviceAccountKey = el('googlechat-key').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/google-chat', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application: { ...application, ...(serviceAccountKey ? { serviceAccountKey } : {}) } })\n }));\n } finally {\n // The key never stays in the page once it has been submitted, whatever the outcome.\n el('googlechat-key').value = '';\n }\n await load();\n message('Google Chat app saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n }\n\n async function saveEmail(rotateIngressSecret) {\n const stored = currentStatus && currentStatus.values.email;\n const limit = rotateIngressSecret\n ? (stored && stored.dailySendLimit ? String(stored.dailySendLimit) : '')\n : el('email-send-limit-input').value.trim();\n if (limit && !/^[1-9][0-9]*$/.test(limit)) throw new Error('Enter the daily send limit as a whole number, or leave it empty.');\n const apiToken = rotateIngressSecret ? '' : el('email-token').value.trim();\n let saved;\n try {\n saved = await json(await fetch(api + '/configure/email', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n email: {\n mailDomain: rotateIngressSecret ? stored.mailDomain : requiredInput('email-mail-domain-input', 'the mail domain'),\n accountId: rotateIngressSecret ? stored.accountId : requiredInput('email-account-id-input', 'the Cloudflare account ID'),\n dailySendLimit: limit ? Number(limit) : null,\n ...(apiToken ? { apiToken } : {}),\n ...(rotateIngressSecret ? { rotateIngressSecret: true } : {})\n }\n })\n }));\n } finally {\n // The token never stays in the page once it has been submitted, whatever the outcome.\n el('email-token').value = '';\n }\n // The response alone fills the secret box, so no render that follows can take it away.\n showEmailIngressSecret(saved.ingressSecret);\n message('Email saved. ' + saved.probe.message + '. Restart AgentConnect to apply it.');\n await refreshDeploymentConfig();\n }\n\n function showEmailIngressSecret(secret) {\n el('email-ingress-secret').textContent = secret || '';\n el('email-ingress-once').hidden = !secret;\n }\n\n async function copyEmailIngressSecret() {\n await navigator.clipboard.writeText(el('email-ingress-secret').textContent);\n message('Ingress secret copied.');\n }\n\n function confirmEmailIngressRotation(open) {\n el('email-rotate-confirm').hidden = !open;\n el('rotate-email-ingress').hidden = open;\n if (open) el('cancel-rotate-email-ingress').focus();\n }\n\n async function saveLinear() {\n const clientSecret = el('linear-client-secret').value;\n const signingSecret = el('linear-signing-secret').value;\n await json(await fetch(api + '/configure/linear', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n application: {\n clientId: requiredInput('linear-id', 'the Linear Client ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...(signingSecret ? { signingSecret } : {})\n }\n })\n }));\n el('linear-client-secret').value = '';\n el('linear-signing-secret').value = '';\n await load();\n message('Linear OAuth application saved. Restart AgentConnect to apply it.');\n }\n\n function showMattermostProbe(probe) {\n const line = el('mattermost-probe');\n line.hidden = !probe;\n line.textContent = probe ? probe.message : '';\n }\n\n async function probeMattermost() {\n const serverUrl = el('mattermost-server-url-input').value.trim();\n const probe = await json(await fetch(api + '/check/mattermost', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify(serverUrl ? { serverUrl } : {})\n }));\n showMattermostProbe(probe);\n message(probe.ok ? 'Mattermost instance reachable.' : probe.message, !probe.ok);\n return probe;\n }\n\n async function saveMattermost() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = currentStatus.values;\n if (!values.logto || !values.logto.browser) throw new Error('Save Logto configuration before Mattermost sign-in');\n const serverUrl = requiredInput('mattermost-server-url-input', 'the Mattermost server URL').replace(/\\/+$/, '');\n const clientId = requiredInput('mattermost-id', 'the Mattermost Client ID');\n const clientSecret = el('mattermost-secret').value;\n const probe = await json(await fetch(api + '/check/mattermost', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ serverUrl })\n }));\n showMattermostProbe(probe);\n if (probe.blocksSave) throw new Error(probe.message);\n const normalizedUrl = probe.serverUrl || serverUrl;\n const existing = values.logto.mattermostConnector;\n const existingUrl = existing && existing.serverUrl ? existing.serverUrl.replace(/\\/+$/, '') : undefined;\n if (!clientSecret && (!existing || existing.clientId !== clientId || existingUrl !== normalizedUrl)) {\n throw new Error('Enter the Mattermost OAuth client secret');\n }\n el('mattermost-secret').value = '';\n await replaceConfiguration(\n {\n ...values,\n logto: {\n ...values.logto,\n browser: {\n ...values.logto.browser,\n socialProviders: [...new Set([...values.logto.browser.socialProviders, 'mattermost'])]\n },\n mattermostConnector: { serverUrl: normalizedUrl, clientId }\n }\n },\n clientSecret ? { 'logto.mattermostConnectorClientSecret': clientSecret } : undefined,\n 'Mattermost OAuth configuration saved. Restart AgentConnect to apply it.'\n );\n try {\n await reconcileLogto(Boolean(clientSecret));\n } finally {\n await load();\n showMattermostProbe(probe);\n }\n message('Mattermost sign-in and Logto connector configured. Restart AgentConnect to apply the saved settings.');\n }\n\n async function saveGoogle() {\n const secret = el('google-secret').value;\n await json(await fetch(api + '/configure/google', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({\n clientId: el('google-id').value,\n ...(secret ? { clientSecret: secret } : {})\n })\n }));\n el('google-secret').value = '';\n await reconcileLogto(Boolean(secret));\n await load();\n message('Google OAuth client and Logto connector are configured. Restart AgentConnect to apply the saved settings.');\n }\n\n // Agent bots (teams-integration.md §8.6.3): 'create' makes the blueprint through Graph, 'save' takes one entered by hand, 'clear' turns them off.\n async function saveAgentBots(mode) {\n if (mode === 'clear' && !window.confirm('Clear the saved blueprint and its secret? Agents that already have a bot of their own stop answering in Teams.')) return;\n const azure = mode === 'clear' ? {} : {\n subscriptionId: requiredInput('azuread-agent-bots-subscription-input', 'the Azure subscription ID'),\n resourceGroup: requiredInput('azuread-agent-bots-group-input', 'the resource group')\n };\n let saved;\n try {\n if (mode === 'create') {\n const operator = requiredInput('azuread-agent-bots-operator-input', 'your Microsoft Entra user');\n saved = await json(await fetch(api + '/configure/msteams-agent-bots/blueprint', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ operator, ...azure })\n }));\n } else {\n const clientSecret = el('azuread-agent-bots-secret-input').value;\n const agentBots = mode === 'clear' ? null : {\n blueprintId: requiredInput('azuread-agent-bots-blueprint-input', 'the blueprint ID'),\n ...(clientSecret ? { clientSecret } : {}),\n ...azure\n };\n saved = await json(await fetch(api + '/configure/msteams-agent-bots', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ agentBots })\n }));\n }\n } finally {\n // The secret never stays in the page once it has been submitted, whatever the outcome.\n el('azuread-agent-bots-secret-input').value = '';\n }\n await load();\n if (mode === 'clear') return message('Agent bots cleared. Restart AgentConnect to apply the saved settings.');\n const settling = mode === 'create' && saved.check !== 'ok';\n message('Blueprint ' + saved.blueprintId + ' saved.' + (settling ? ' Its new secret was not accepted yet; give Microsoft a minute before you restart.' : '') + ' Restart AgentConnect to apply the saved settings.' + (mode === 'create' ? ' You may now remove the three Graph permissions from the application.' : ''));\n }\n\n async function saveLoginApp(provider, clear = false) {\n const app = loginApps[provider];\n if (clear && !window.confirm('Clear the saved ' + app.name + ' login application and secret?')) return;\n const clientSecret = el(provider + '-secret').value;\n const application = clear ? null : {\n clientId: requiredInput(provider + '-id', 'the ' + app.name + ' Client ID'),\n ...(clientSecret ? { clientSecret } : {})\n };\n // Microsoft's home tenant also makes the app the deployment's Teams app; empty turns that off.\n const teams = provider === 'azuread' && !clear ? { teamsTenantId: el('azuread-teams-tenant-input').value.trim() || null } : {};\n try {\n await json(await fetch(api + '/configure/login-app/' + provider, {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ application, ...teams })\n }));\n } finally {\n el(provider + '-secret').value = '';\n }\n try {\n await reconcileLogto(Boolean(clientSecret) && !clear);\n } finally {\n await load();\n }\n message(app.name + (clear ? ' sign-in configuration cleared.' : ' login application and Logto connector configured.') + ' Restart AgentConnect to apply the saved settings.');\n }\n\n function renderLoginAppChecks(report) {\n const connectors = report.findings.find((finding) => finding.id === 'logto.connectors');\n if (currentStatus?.values.logto?.browser?.socialProviders.includes('gitlab')) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('gitlab')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n el('gitlab-login-status').textContent = passed\n ? 'GitLab connector matches. Confirm the redirect URLs and OpenID scopes in GitLab.'\n : 'GitLab sign-in could not be verified. Review the Logto check above.';\n }\n for (const [provider, app] of Object.entries(loginApps)) {\n if (!currentStatus?.values.logto?.[provider + 'Connector']) continue;\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith(provider)) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff(provider + '-drift', diff);\n match(provider + '-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el(provider + '-status').textContent = passed\n ? app.name + ' connector matches. Confirm the redirect URLs in the provider settings.'\n : app.name + ' connector could not be verified. Review the Logto check above.';\n }\n if (currentStatus?.values.logto?.mattermostConnector) {\n const diff = connectors?.diff?.filter((item) => item.field.toLowerCase().startsWith('mattermost')) || [];\n const passed = Boolean(connectors && diff.length === 0 && (connectors.status === 'pass' || connectors.diff?.length));\n showDiff('mattermost-drift', diff);\n match('mattermost-match', passed ? 'pass' : 'warn', passed ? 'Logto matches' : 'Could not verify');\n el('mattermost-status').textContent = passed\n ? 'Mattermost connector matches. Confirm the redirect URIs in Mattermost OAuth settings.'\n : 'Mattermost connector could not be verified. Review the Logto check above.';\n }\n }\n\n function regionalLoginApp(prefix) {\n const appId = el(prefix + '-login-id').value.trim();\n const appSecret = el(prefix + '-login-secret').value;\n return appId ? { appId, ...(appSecret ? { appSecret } : {}) } : null;\n }\n\n async function saveRegionalLoginApp(region) {\n const app = regionalLoginApp(region);\n if (!app) throw new Error('Enter the ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App ID');\n await json(await fetch(api + '/configure/regional-login-app', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, app })\n }));\n el(region + '-login-secret').value = '';\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' tenant App is saved. Restart AgentConnect services to apply it.');\n }\n\n async function createRegionalLoginApp(region) {\n const popup = window.open('about:blank', '_blank');\n try {\n const started = await json(await fetch(api + '/create/regional-login-app/start', {\n method: 'POST', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ region, name: el(region + '-create-name').value })\n }));\n if (popup) popup.location.replace(started.authorizationUrl);\n else window.open(started.authorizationUrl, '_blank', 'noopener');\n message('Approve the new ' + (region === 'feishu' ? 'Feishu' : 'Lark') + ' App in the opened page. This page will finish saving it automatically.');\n while (true) {\n const result = await json(await fetch(api + '/create/regional-login-app/' + encodeURIComponent(started.id), { headers: bearer() }));\n if (result.status === 'completed') {\n await load();\n message((region === 'feishu' ? 'Feishu' : 'Lark') + ' App ' + result.appId + ' was created and saved. Restart AgentConnect services to apply it.');\n return;\n }\n if (result.status === 'failed') throw new Error('Regional App creation ' + result.reason + '. Start it again.');\n await new Promise((resolve) => setTimeout(resolve, Math.max(500, Math.min(result.retryAfterMs || 2000, 5000))));\n }\n } catch (error) {\n if (popup) popup.close();\n throw error;\n }\n }\n\n async function reconcileLogto(refreshConnectorSecrets) {\n return json(await fetch(api + '/reconcile/logto', {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ refreshConnectorSecrets: Boolean(refreshConnectorSecrets) })\n }));\n }\n\n async function refreshDeploymentConfig() {\n const status = await json(await fetch(api + '/deployment-config', { headers: bearer() }));\n el('access').hidden = true;\n el('setup').hidden = false;\n el('editor').hidden = false;\n currentRevision = status.revision;\n renderApps(status);\n return status;\n }\n\n async function checkLogto() {\n const report = await json(await fetch(api + '/check/logto', { headers: bearer() }));\n await refreshDeploymentConfig();\n const failures = report.findings.filter((finding) => finding.status !== 'pass');\n el('logto-status').textContent = failures.length === 0\n ? 'SPA redirects, connectors, and social-only sign-in match.'\n : failures.map((finding) => finding.message).join(' ');\n el('logto-status').className = failures.length === 0 ? 'ok' : 'warn';\n match('logto-match', failures.length === 0 ? 'pass' : 'warn', failures.length === 0 ? 'Matches' : 'Update required');\n showDiff(\n 'logto-drift',\n failures.flatMap((finding) => finding.diff && finding.diff.length\n ? finding.diff\n : [{ field: finding.id.replace(/^logto\\./, '').replaceAll('_', ' '), current: finding.message, expected: 'Matches expected configuration' }])\n );\n el('logto-settings').hidden = failures.length === 0;\n renderLoginAppChecks(report);\n return report;\n }\n\n function githubNotice(value) {\n if (value === 'deployment-created') return 'GitHub integration App created. Its private key and webhook secret are stored.';\n if (value === 'deployment-login-created') return 'GitHub integration App created and connected to Logto sign-in.';\n if (value === 'cancelled') return 'GitHub App creation was cancelled.';\n if (value === 'expired') return 'GitHub App creation expired. Start it again.';\n if (value === 'invalid-callback') return 'GitHub returned an invalid App creation callback.';\n if (value === 'conversion-failed') return 'GitHub may have created the App, but did not return complete credentials. Delete the orphaned App and retry.';\n if (value === 'save-failed') return 'GitHub created the App, but its credentials could not be saved. Delete the orphaned App and retry.';\n return '';\n }\n\n async function load() {\n let publicAuth = await authConfig();\n const currentUrl = new URL(location.href);\n const githubResult = currentUrl.searchParams.get('github');\n const notice = githubNotice(githubResult);\n if (githubResult === 'deployment-login-created' && publicAuth.mode === 'none') {\n await reconcileLogto();\n publicAuth = await authConfig();\n }\n if (githubResult) history.replaceState({}, '', '/');\n const hasToken = Boolean(sessionStorage.getItem(tokenKey));\n el('access').hidden = false;\n el('setup').hidden = true;\n el('login').hidden = true;\n el('open-logto').hidden = true;\n el('show-bootstrap').hidden = true;\n el('editor').hidden = true;\n el('bootstrap').hidden = true;\n if (publicAuth.logtoAdminEndpoint) {\n el('open-logto').href = publicAuth.logtoAdminEndpoint;\n el('logto-settings').href = publicAuth.logtoAdminEndpoint;\n }\n if (publicAuth.mode === 'none') {\n sessionStorage.removeItem(tokenKey);\n await loadBootstrapInfo();\n el('open-logto').hidden = false;\n el('show-bootstrap').hidden = false;\n message(notice || 'Logto sign-in is not configured. Set up the initial Logto administrator first.');\n return;\n }\n if (publicAuth.mode === 'unavailable') {\n el('open-logto').hidden = false;\n message(publicAuth.message || 'Logto sign-in is unavailable. Open Logto Console to review its settings.', true);\n return;\n }\n if (!hasToken) {\n el('login').hidden = false;\n message(notice || 'Sign in with Logto to continue.');\n return;\n }\n if (publicAuth.claimAvailable) {\n try {\n await json(await fetch(api + '/bootstrap/claim', { method: 'POST', headers: bearer() }));\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('This first user is now an ADMIN. Sign in again to refresh the role claim.');\n return;\n } catch (error) {\n if (error.status !== 401 && error.status !== 403) throw error;\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with Logto to continue.', true);\n return;\n }\n }\n try {\n await loadBootstrapInfo();\n await refreshDeploymentConfig();\n message(notice);\n checkLogto().catch((error) => {\n el('logto-status').textContent = error.message;\n el('logto-status').className = 'warn';\n el('logto-settings').hidden = false;\n });\n } catch (error) {\n if (error.status === 401 || error.status === 403) {\n sessionStorage.removeItem(tokenKey);\n el('login').hidden = false;\n message('Sign in with a Logto ADMIN account.', true);\n }\n else throw error;\n }\n }\n\n async function saveSecretReplacement(key, value) {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n if (!value) throw new Error('Enter the replacement secret');\n const refreshLogto =\n (key === 'gitlab.clientSecret' && currentStatus.values.logto?.browser?.socialProviders.includes('gitlab')) ||\n (key === 'logto.githubConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.githubConnector) ||\n (key === 'logto.googleConnectorClientSecret' && currentStatus.values.logto && currentStatus.values.logto.googleConnector) ||\n Object.keys(loginApps).some((provider) => key === 'logto.' + provider + 'ConnectorClientSecret' && currentStatus.values.logto?.[provider + 'Connector']) ||\n (key === 'slack.clientSecret' && currentStatus.values.logto && currentStatus.values.logto.slackConnector);\n await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values: currentStatus.values, secrets: { [key]: value } })\n }));\n try {\n if (refreshLogto) await reconcileLogto(true);\n } finally {\n await load();\n }\n if (refreshLogto) {\n message('Secret replaced and applied to the Logto connector. Restart AgentConnect to apply deployment changes.');\n } else {\n message('Secret replaced. Restart AgentConnect to apply it.');\n }\n }\n\n function editSecret(button) {\n if (!currentStatus) return message('Deployment configuration is not loaded', true);\n const row = button.closest('.secret-line');\n const display = el(button.dataset.secretDisplay);\n if (!row || !display || row.querySelector('.secret-editor')) return;\n const editor = document.createElement('span'); editor.className = 'secret-editor';\n const input = document.createElement('input');\n input.type = 'password'; input.autocomplete = 'new-password'; input.placeholder = 'Enter replacement secret';\n const save = document.createElement('button'); save.textContent = 'Save';\n const cancel = document.createElement('button'); cancel.textContent = 'Cancel';\n const close = () => { editor.remove(); display.hidden = false; button.hidden = false; };\n save.onclick = async () => {\n save.disabled = true;\n try { await saveSecretReplacement(button.dataset.secretKey, input.value); }\n catch (error) { save.disabled = false; message(error.message, true); }\n };\n cancel.onclick = close;\n input.onkeydown = (event) => { if (event.key === 'Enter') save.click(); if (event.key === 'Escape') close(); };\n display.hidden = true; button.hidden = true;\n editor.append(input, save, cancel); row.append(editor); input.focus();\n }\n\n async function saveOptions() {\n if (!currentStatus) throw new Error('Deployment configuration is not loaded');\n const values = {\n ...currentStatus.values,\n features: {\n presetAgentsEnabled: el('preset-agents-enabled').checked,\n maxOrgsPerNonAdminUser: Number(el('max-orgs-per-non-admin-user').value),\n organizationSso: el('organization-sso').checked\n }\n };\n const saved = await json(await fetch(api + '/deployment-config', {\n method: 'PUT', headers: { 'content-type': 'application/json', ...bearer() },\n body: JSON.stringify({ expectedRevision: currentRevision, values })\n }));\n try {\n if (currentStatus.values.auth.mode === 'oidc') await reconcileLogto();\n } catch (error) {\n await load();\n throw new Error('Saved deployment options, but Logto was not updated: ' + error.message);\n }\n message('Saved deployment options. Restart AgentConnect to apply them.');\n await load();\n }\n\n el('login').onclick = () => signIn().catch((error) => message(error.message, true));\n el('show-bootstrap').onclick = () => showBootstrap().catch((error) => message(error.message, true));\n el('bootstrap-provider').onchange = updateBootstrapProvider;\n el('bootstrap-github-owner').onchange = () => updateOwner('bootstrap-github');\n el('github-owner').onchange = () => updateOwner('github');\n el('bootstrap-logto-submit').onclick = () => bootstrapLogto().catch((error) => message(error.message, true));\n el('bootstrap-back').onclick = () => showBootstrapStep('logto');\n el('bootstrap-google-submit').onclick = () => bootstrapGoogle().catch((error) => message(error.message, true));\n for (const prefix of ['bootstrap-sso', 'sso']) {\n el(prefix + '-protocol').onchange = () => updateSsoProtocol(prefix);\n el(prefix + '-member-source').onchange = () => updateMemberOrganization(prefix);\n el(prefix + '-create').onclick = () => createSso(prefix).catch((error) => message(error.message, true));\n el(prefix + '-submit').onclick = () => saveSso(prefix).catch((error) => message(error.message, true));\n }\n el('sso-remove').onclick = () => removeSso().catch((error) => message(error.message, true));\n el('bootstrap-github-submit').onclick = () => bootstrapGithub().catch((error) => message(error.message, true));\n el('bootstrap-slack-submit').onclick = () => bootstrapSlack().catch((error) => message(error.message, true));\n el('create-github').onclick = () => startGithub('github').catch((error) => message(error.message, true));\n el('save-logto-configuration').onclick = () => saveLogtoConfiguration().catch((error) => message(error.message, true));\n el('cancel-logto-configuration').onclick = cancelConfigurationEdit;\n el('save-github-configuration').onclick = () => saveGithubConfiguration().catch((error) => message(error.message, true));\n el('cancel-github-configuration').onclick = cancelConfigurationEdit;\n el('clear-github').onclick = () => clearProvider('github').catch((error) => message(error.message, true));\n el('connect-github-login').onclick = () => connectGithubLogin().catch((error) => message(error.message, true));\n el('connect-gitlab-login').onclick = () => configureGitlabLogin(true).catch((error) => message(error.message, true));\n el('disconnect-gitlab-login').onclick = () => configureGitlabLogin(false).catch((error) => message(error.message, true));\n el('check-gitlab-login').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-github').onclick = () => checkGithub().catch((error) => message(error.message, true));\n el('create-slack').onclick = () => createSlack('slack').catch((error) => message(error.message, true));\n el('connect-slack-login').onclick = () => connectSlackLogin().catch((error) => message(error.message, true));\n el('save-slack-configuration').onclick = () => saveSlackConfiguration().catch((error) => message(error.message, true));\n el('cancel-slack-configuration').onclick = cancelConfigurationEdit;\n el('clear-slack').onclick = () => clearProvider('slack').catch((error) => message(error.message, true));\n el('check-slack').onclick = () => checkSlack().catch((error) => message(error.message, true));\n el('reconcile-slack').onclick = () => reconcileSlack().catch((error) => message(error.message, true));\n el('save-gitea').onclick = () => saveGitea().catch((error) => message(error.message, true));\n el('cancel-gitea-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitea').onclick = () => clearProvider('gitea').catch((error) => message(error.message, true));\n el('save-gitlab').onclick = () => saveGitlab().catch((error) => message(error.message, true));\n el('cancel-gitlab-configuration').onclick = cancelConfigurationEdit;\n el('clear-gitlab').onclick = () => clearProvider('gitlab').catch((error) => message(error.message, true));\n el('save-googlechat').onclick = () => saveGoogleChat().catch((error) => message(error.message, true));\n for (const [id, mode] of [['create-azuread-agent-bots-blueprint', 'create'], ['save-azuread-agent-bots', 'save'], ['clear-azuread-agent-bots', 'clear']]) {\n el(id).onclick = () => saveAgentBots(mode).catch((error) => message(error.message, true));\n }\n el('cancel-googlechat-configuration').onclick = cancelConfigurationEdit;\n el('clear-googlechat').onclick = () => clearProvider('googlechat').catch((error) => message(error.message, true));\n el('save-email').onclick = () => saveEmail(false).catch((error) => message(error.message, true));\n el('rotate-email-ingress').onclick = () => confirmEmailIngressRotation(true);\n el('cancel-rotate-email-ingress').onclick = () => confirmEmailIngressRotation(false);\n el('confirm-rotate-email-ingress').onclick = () => {\n confirmEmailIngressRotation(false);\n saveEmail(true).catch((error) => message(error.message, true));\n };\n el('copy-email-ingress').onclick = () => copyEmailIngressSecret().catch(() => message('Copy failed. Select the secret and copy it.', true));\n el('dismiss-email-ingress').onclick = () => showEmailIngressSecret('');\n el('cancel-email-configuration').onclick = cancelConfigurationEdit;\n el('clear-email').onclick = () => clearProvider('email').catch((error) => message(error.message, true));\n el('save-linear').onclick = () => saveLinear().catch((error) => message(error.message, true));\n el('cancel-linear-configuration').onclick = cancelConfigurationEdit;\n el('clear-linear').onclick = () => clearProvider('linear').catch((error) => message(error.message, true));\n el('save-google').onclick = () => saveGoogle().catch((error) => message(error.message, true));\n el('cancel-google-configuration').onclick = cancelConfigurationEdit;\n el('clear-google').onclick = () => clearProvider('google').catch((error) => message(error.message, true));\n el('check-google').onclick = () => checkGoogle().catch((error) => message(error.message, true));\n for (const provider of Object.keys(loginApps)) {\n el('save-' + provider).onclick = () => saveLoginApp(provider).catch((error) => message(error.message, true));\n el('cancel-' + provider + '-configuration').onclick = cancelConfigurationEdit;\n el('clear-' + provider).onclick = () => saveLoginApp(provider, true).catch((error) => message(error.message, true));\n el('check-' + provider).onclick = () => checkLogto().catch((error) => message(error.message, true));\n }\n el('create-feishu-login-app').onclick = () => createRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('save-feishu-login-app').onclick = () => saveRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('cancel-feishu-configuration').onclick = cancelConfigurationEdit;\n el('clear-feishu').onclick = () => clearProvider('feishu').catch((error) => message(error.message, true));\n el('check-feishu-login-app').onclick = () => checkRegionalLoginApp('feishu').catch((error) => message(error.message, true));\n el('create-lark-login-app').onclick = () => createRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('save-lark-login-app').onclick = () => saveRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('cancel-lark-configuration').onclick = cancelConfigurationEdit;\n el('clear-lark').onclick = () => clearProvider('lark').catch((error) => message(error.message, true));\n el('check-lark-login-app').onclick = () => checkRegionalLoginApp('lark').catch((error) => message(error.message, true));\n el('probe-mattermost').onclick = () => probeMattermost().catch((error) => message(error.message, true));\n el('save-mattermost').onclick = () => saveMattermost().catch((error) => message(error.message, true));\n el('cancel-mattermost-configuration').onclick = cancelConfigurationEdit;\n el('clear-mattermost').onclick = () => clearProvider('mattermost').catch((error) => message(error.message, true));\n el('check-mattermost').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('check-logto').onclick = () => checkLogto().catch((error) => message(error.message, true));\n el('reconcile-logto').onclick = () => reconcileLogto().then(load).catch((error) => message(error.message, true));\n el('logout').onclick = () => { sessionStorage.removeItem(tokenKey); load().catch((error) => message(error.message, true)); };\n el('save-options').onclick = () => saveOptions().catch((error) => message(error.message, true));\n for (const button of document.querySelectorAll('.edit-secret')) button.onclick = () => editSecret(button);\n for (const button of document.querySelectorAll('.edit-configuration')) button.onclick = () => beginConfigurationEdit(button.dataset.provider);\n updateBootstrapProvider();\n finishSignIn().then(load).catch((error) => message(error.message, true));\n <\/script>\n</body>\n</html>"
68562
69120
  ])), ssoForm("bootstrap-sso"), ssoForm("sso"), Object.entries(LOGTO_LOGIN_APPS).map(([provider, app]) => String.raw`
68563
69121
  <section id="${provider}-section" class="panel setup-section" aria-labelledby="${provider}-heading">
68564
69122
  <div class="provider-head">
@@ -68834,9 +69392,38 @@ function desiredConnector(target, desired) {
68834
69392
  trustUnverifiedEmail: false
68835
69393
  }
68836
69394
  };
69395
+ if (target === "mattermost" && desired.mattermost) {
69396
+ const { clientId, clientSecret } = desired.mattermost;
69397
+ const serverUrl = desired.mattermost.serverUrl.replace(/\/+$/, "");
69398
+ return {
69399
+ id: LOGTO_MATTERMOST_CONNECTOR_ID,
69400
+ connectorId: "oauth2",
69401
+ metadata: {
69402
+ target: "mattermost",
69403
+ name: { en: "Mattermost" }
69404
+ },
69405
+ config: {
69406
+ clientId,
69407
+ clientSecret,
69408
+ authorizationEndpoint: `${serverUrl}/oauth/authorize`,
69409
+ tokenEndpoint: `${serverUrl}/oauth/access_token`,
69410
+ userInfoEndpoint: `${serverUrl}/api/v4/users/me`,
69411
+ tokenEndpointResponseType: "json",
69412
+ profileMap: {
69413
+ id: "id",
69414
+ name: "username",
69415
+ email: "__disabled_unverified_email__"
69416
+ }
69417
+ }
69418
+ };
69419
+ }
68837
69420
  }
68838
69421
  function connectorMatches(connector, desired) {
68839
- return connector.connectorId === desired.connectorId && Object.entries(desired.config).every(([key, value]) => key === "clientSecret" || isDeepStrictEqual(connector.config[key] ?? {}, value));
69422
+ return connector.connectorId === desired.connectorId && !(desired.connectorId === "oauth2" && !("scope" in desired.config) && connector.config.scope !== void 0) && (desired.connectorId !== "oauth2" || connector.config.userInfoEndpoint === desired.config.userInfoEndpoint) && Object.entries(desired.config).every(([key, value]) => {
69423
+ if (key === "clientSecret") return true;
69424
+ if (value === void 0) return connector.config[key] === void 0;
69425
+ return isDeepStrictEqual(connector.config[key] ?? {}, value);
69426
+ });
68840
69427
  }
68841
69428
  function selectConnector(connectors, target) {
68842
69429
  const matches = connectors.filter((connector) => !connector.isDemo && connector.target === target);
@@ -69654,6 +70241,7 @@ const CreateRegionalLoginAppBody = strictObject({
69654
70241
  name: string().trim().min(1).max(100)
69655
70242
  });
69656
70243
  const CheckSlackBody = strictObject({ configToken: string().trim().min(1).max(1e4) });
70244
+ const CheckMattermostBody = strictObject({ serverUrl: string().trim().min(1).max(2e3).optional() });
69657
70245
  const ReconcileLogtoBody = strictObject({ refreshConnectorSecrets: boolean().optional().default(false) });
69658
70246
  function problem(reply, statusCode, message, code) {
69659
70247
  return reply.code(statusCode).send({
@@ -69819,6 +70407,7 @@ function logtoSetup(record, setupUrl, services, endpoint) {
69819
70407
  const githubSecret = record.secrets["logto.githubConnectorClientSecret"];
69820
70408
  const googleSecret = record.secrets["logto.googleConnectorClientSecret"];
69821
70409
  const slackSecret = record.secrets["slack.clientSecret"];
70410
+ const mattermostSecret = record.secrets["logto.mattermostConnectorClientSecret"];
69822
70411
  const applicationId = auth.mode === "oidc" ? auth.browserClient.appId : void 0;
69823
70412
  const webOrigin = new URL(services.web).origin;
69824
70413
  const setupOrigin = new URL(setupUrl).origin;
@@ -69858,6 +70447,11 @@ function logtoSetup(record, setupUrl, services, endpoint) {
69858
70447
  clientSecret: slackSecret,
69859
70448
  scope: "openid profile email"
69860
70449
  } } : {},
70450
+ ...logto.mattermostConnector && mattermostSecret ? { mattermost: {
70451
+ clientId: logto.mattermostConnector.clientId,
70452
+ clientSecret: mattermostSecret,
70453
+ serverUrl: logto.mattermostConnector.serverUrl
70454
+ } } : {},
69861
70455
  ...Object.fromEntries(LoginAppProvider.options.flatMap((provider) => {
69862
70456
  const app = logto[`${provider}Connector`];
69863
70457
  const clientSecret = record.secrets[`logto.${provider}ConnectorClientSecret`];
@@ -69908,6 +70502,7 @@ function buildSetupServer(deps, options = {}) {
69908
70502
  "gitlab",
69909
70503
  "google",
69910
70504
  "slack",
70505
+ "mattermost",
69911
70506
  ...LoginAppProvider.options
69912
70507
  ]);
69913
70508
  };
@@ -69978,6 +70573,7 @@ function buildSetupServer(deps, options = {}) {
69978
70573
  "email"
69979
70574
  ]
69980
70575
  },
70576
+ mattermostSignIn: { redirects: values.logto?.browser ? socialRedirectUris(logtoEndpoint, connectorIds.mattermost ?? "agentconnect-mattermost", localAuthBootstrap.services.web) : [] },
69981
70577
  slack,
69982
70578
  linear,
69983
70579
  googleChat,
@@ -70991,6 +71587,18 @@ function buildSetupServer(deps, options = {}) {
70991
71587
  restartRequired: false
70992
71588
  };
70993
71589
  });
71590
+ app.post("/api/v1/check/mattermost", { preHandler: requireDiagnosticAccess }, async (request, reply) => {
71591
+ const parsed = CheckMattermostBody.safeParse(request.body ?? {});
71592
+ if (!parsed.success) return problem(reply, 400, "a valid Mattermost server URL is required");
71593
+ const serverUrl = parsed.data.serverUrl ?? (await deps.store.getAdmin())?.values.logto?.mattermostConnector?.serverUrl;
71594
+ if (!serverUrl) return problem(reply, 400, "a Mattermost server URL is required");
71595
+ const probe = await probeMattermostInstance(serverUrl, deps.fetch, deps.mattermostLookup);
71596
+ return {
71597
+ ...probe,
71598
+ ok: probe.status === "ok",
71599
+ blocksSave: probeMattermostBlocksSave(probe)
71600
+ };
71601
+ });
70994
71602
  app.post("/api/v1/reconcile/slack", { preHandler: requireConfigurationAccess }, async (request, reply) => {
70995
71603
  const parsed = CheckSlackBody.safeParse(request.body);
70996
71604
  if (!parsed.success) return problem(reply, 400, "a Slack App configuration token is required");
@@ -71110,6 +71718,7 @@ function buildSetupServer(deps, options = {}) {
71110
71718
  "logto.telegramConnectorClientSecret",
71111
71719
  "logto.discordConnectorClientSecret",
71112
71720
  "logto.azureadConnectorClientSecret",
71721
+ "logto.mattermostConnectorClientSecret",
71113
71722
  "logto.ssoConnectorClientSecret",
71114
71723
  "slack.clientSecret",
71115
71724
  "github.clientSecret",
@@ -71189,6 +71798,7 @@ function buildSetupServer(deps, options = {}) {
71189
71798
  "logto.telegramConnectorClientSecret",
71190
71799
  "logto.discordConnectorClientSecret",
71191
71800
  "logto.azureadConnectorClientSecret",
71801
+ "logto.mattermostConnectorClientSecret",
71192
71802
  "logto.ssoConnectorClientSecret",
71193
71803
  "gitlab.clientSecret",
71194
71804
  "slack.clientSecret"