UNPKG

@fntio/infra-client

Version:

Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.

10,531 lines • 404 kB
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// lambdacode/api/services/httpErrors.ts
var ConflictError, NotFoundError, ValidationError, ForbiddenError;
var init_httpErrors = __esm({
  "lambdacode/api/services/httpErrors.ts"() {
    "use strict";
    ConflictError = class extends Error {
    };
    NotFoundError = class extends Error {
    };
    ValidationError = class extends Error {
    };
    ForbiddenError = class extends Error {
    };
  }
});

// ../infra-client-plugin-sdk/src/contracts/manifest.ts
var PLUGIN_PERMISSIONS, PLUGIN_MANIFEST_SCHEMA_VERSION, PLUGIN_HOST_API_VERSION, PLUGIN_ID_PATTERN, AWS_ACCOUNT_PATTERN;
var init_manifest = __esm({
  "../infra-client-plugin-sdk/src/contracts/manifest.ts"() {
    "use strict";
    PLUGIN_PERMISSIONS = ["user", "admin"];
    PLUGIN_MANIFEST_SCHEMA_VERSION = 1;
    PLUGIN_HOST_API_VERSION = 1;
    PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
    AWS_ACCOUNT_PATTERN = /^\d{12}$/;
  }
});

// ../infra-client-plugin-sdk/src/contracts/validate.ts
var init_validate = __esm({
  "../infra-client-plugin-sdk/src/contracts/validate.ts"() {
    "use strict";
  }
});

// ../infra-client-plugin-sdk/src/contracts/canonical.ts
var init_canonical = __esm({
  "../infra-client-plugin-sdk/src/contracts/canonical.ts"() {
    "use strict";
  }
});

// ../infra-client-plugin-sdk/src/contracts/paths.ts
function pluginApiBaseUrl(pluginId) {
  return `${PLUGIN_API_ROOT}/${pluginId}`;
}
var PLUGIN_API_ROOT;
var init_paths = __esm({
  "../infra-client-plugin-sdk/src/contracts/paths.ts"() {
    "use strict";
    PLUGIN_API_ROOT = "/api/plugins";
  }
});

// ../infra-client-plugin-sdk/src/contracts/access.ts
function pluginTargetKey(target) {
  return `${PLUGIN_TARGET_PREFIX}${target.pluginId}#${target.accountNumber}#${target.permission}`;
}
function parsePluginTargetKey(key) {
  if (!key.startsWith(PLUGIN_TARGET_PREFIX)) return null;
  const parts = key.slice(PLUGIN_TARGET_PREFIX.length).split("#");
  if (parts.length !== 3) return null;
  const [pluginId, accountNumber, permission] = parts;
  if (!PLUGIN_ID_PATTERN.test(pluginId) || !AWS_ACCOUNT_PATTERN.test(accountNumber)) return null;
  if (!PLUGIN_PERMISSIONS.includes(permission)) return null;
  return { pluginId, accountNumber, permission };
}
function pluginPermissionsImpliedBy(granted, declared) {
  if (!declared.includes(granted)) return [];
  if (granted === "admin" && declared.includes("user")) return ["admin", "user"];
  return [granted];
}
var PLUGIN_TARGET_PREFIX;
var init_access = __esm({
  "../infra-client-plugin-sdk/src/contracts/access.ts"() {
    "use strict";
    init_manifest();
    PLUGIN_TARGET_PREFIX = "plugin#";
  }
});

// ../infra-client-plugin-sdk/src/contracts/catalog.ts
function pluginCatalogStatus(record) {
  if (!record.installed) return "removed";
  if (record.schemaVersion !== PLUGIN_MANIFEST_SCHEMA_VERSION || record.manifest.hostApiVersion !== PLUGIN_HOST_API_VERSION) {
    return "unsupported";
  }
  return record.manifest.enabled ? "active" : "disabled";
}
var init_catalog = __esm({
  "../infra-client-plugin-sdk/src/contracts/catalog.ts"() {
    "use strict";
    init_manifest();
  }
});

// ../infra-client-plugin-sdk/src/contracts/discovery.ts
var PLUGIN_DISCOVERY_DEFAULT_REFRESH_SECONDS, PLUGIN_DISCOVERY_MIN_REFRESH_SECONDS, PLUGIN_DISCOVERY_MAX_REFRESH_SECONDS;
var init_discovery = __esm({
  "../infra-client-plugin-sdk/src/contracts/discovery.ts"() {
    "use strict";
    PLUGIN_DISCOVERY_DEFAULT_REFRESH_SECONDS = 60;
    PLUGIN_DISCOVERY_MIN_REFRESH_SECONDS = 15;
    PLUGIN_DISCOVERY_MAX_REFRESH_SECONDS = 300;
  }
});

// ../infra-client-plugin-sdk/src/contracts/authorizer.ts
var init_authorizer = __esm({
  "../infra-client-plugin-sdk/src/contracts/authorizer.ts"() {
    "use strict";
  }
});

// ../infra-client-plugin-sdk/src/backend/context.ts
var init_context = __esm({
  "../infra-client-plugin-sdk/src/backend/context.ts"() {
    "use strict";
  }
});

// ../infra-client-plugin-sdk/src/backend/index.ts
var init_backend = __esm({
  "../infra-client-plugin-sdk/src/backend/index.ts"() {
    "use strict";
    init_manifest();
    init_validate();
    init_canonical();
    init_paths();
    init_access();
    init_catalog();
    init_discovery();
    init_authorizer();
    init_context();
  }
});

// lambdacode/api/services/access.ts
function parsePrincipal(p) {
  if (p.startsWith("user#")) return { kind: "user", userId: p.slice(5) };
  if (p.startsWith("group#")) return { kind: "group", groupId: p.slice(6) };
  return null;
}
function parseTarget(t) {
  if (t.startsWith("role#")) {
    const rest = t.slice(5);
    const hash = rest.indexOf("#");
    if (hash < 0) return null;
    return { kind: "role", accountNumber: rest.slice(0, hash), roleName: rest.slice(hash + 1) };
  }
  if (t.startsWith("resource#")) return { kind: "resource", resourceId: t.slice(9) };
  if (t.startsWith("share#")) return { kind: "share", shareId: t.slice(6) };
  if (t.startsWith("plugin#")) {
    const p = parsePluginTargetKey(t);
    return p ? { kind: "plugin", ...p } : null;
  }
  if (t.startsWith("member#")) return { kind: "member", groupId: t.slice(7) };
  if (t.startsWith("pref#role#")) {
    const rest = t.slice(10);
    const hash = rest.indexOf("#");
    if (hash < 0) return null;
    return { kind: "pref", accountNumber: rest.slice(0, hash), roleName: rest.slice(hash + 1) };
  }
  return null;
}
function isExpired(row, now = Date.now()) {
  return Boolean(row.expiresAt) && !(Date.parse(row.expiresAt) > now);
}
async function getRow(principal, target, opts = {}) {
  const res = await ddb.send(
    new import_lib_dynamodb.GetCommand({ TableName: ACCESS_TABLE_NAME, Key: { principal, target }, ...consistentRead(opts) })
  );
  return res.Item;
}
async function queryPrincipal(principal, targetPrefix, opts = {}) {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb.send(
      new import_lib_dynamodb.QueryCommand({
        TableName: ACCESS_TABLE_NAME,
        KeyConditionExpression: targetPrefix ? "principal = :p AND begins_with(#t, :pre)" : "principal = :p",
        ExpressionAttributeValues: {
          ":p": principal,
          ...targetPrefix ? { ":pre": targetPrefix } : {}
        },
        ...targetPrefix ? { ExpressionAttributeNames: { "#t": "target" } } : {},
        ...consistentRead(opts),
        ExclusiveStartKey
      })
    );
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
async function hasGrantTargetBesides(principal, opts = {}) {
  const accepts = opts.kinds ?? isGrantTarget;
  let ExclusiveStartKey;
  do {
    const page = await ddb.send(
      new import_lib_dynamodb.QueryCommand({
        TableName: ACCESS_TABLE_NAME,
        KeyConditionExpression: "principal = :p",
        ExpressionAttributeValues: { ":p": principal },
        Limit: 3,
        ...consistentRead(opts),
        ExclusiveStartKey
      })
    );
    for (const r of page.Items ?? []) {
      if (r.target !== opts.except && accepts(r.target)) return true;
    }
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return false;
}
async function queryTarget(target) {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb.send(
      new import_lib_dynamodb.QueryCommand({
        TableName: ACCESS_TABLE_NAME,
        IndexName: "byTarget",
        KeyConditionExpression: "#t = :t",
        ExpressionAttributeNames: { "#t": "target" },
        ExpressionAttributeValues: { ":t": target },
        ExclusiveStartKey
      })
    );
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
async function scanAll(opts = {}) {
  const rows = [];
  const prefixes = opts.targetPrefixes ?? [];
  const filter = prefixes.length ? {
    FilterExpression: prefixes.map((_, i) => `begins_with(#t, :p${i})`).join(" OR "),
    ExpressionAttributeNames: { "#t": "target" },
    ExpressionAttributeValues: Object.fromEntries(prefixes.map((p, i) => [`:p${i}`, p]))
  } : {};
  let ExclusiveStartKey;
  do {
    const page = await ddb.send(
      new import_lib_dynamodb.ScanCommand({ TableName: ACCESS_TABLE_NAME, ExclusiveStartKey, ...filter })
    );
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
async function putRow(row) {
  await ddb.send(new import_lib_dynamodb.PutCommand({ TableName: ACCESS_TABLE_NAME, Item: row }));
}
async function putRowIfAbsent(row) {
  try {
    await ddb.send(
      new import_lib_dynamodb.PutCommand({ TableName: ACCESS_TABLE_NAME, Item: row, ConditionExpression: "attribute_not_exists(principal)" })
    );
    return true;
  } catch (err) {
    if (err.name === CONDITION_FAILED) return false;
    throw err;
  }
}
async function deleteRow(principal, target) {
  try {
    await ddb.send(
      new import_lib_dynamodb.DeleteCommand({
        TableName: ACCESS_TABLE_NAME,
        Key: { principal, target },
        ConditionExpression: "attribute_exists(principal)"
      })
    );
    return true;
  } catch (err) {
    if (err.name === CONDITION_FAILED) return false;
    throw err;
  }
}
async function updateExisting(principal, target, set, remove = []) {
  const names = {};
  const values = {};
  const sets = Object.entries(set).map(([k, v], i) => {
    names[`#s${i}`] = k;
    values[`:s${i}`] = v;
    return `#s${i} = :s${i}`;
  });
  const removes = remove.map((k, i) => {
    names[`#r${i}`] = k;
    return `#r${i}`;
  });
  const expr = [
    sets.length ? `SET ${sets.join(", ")}` : "",
    removes.length ? `REMOVE ${removes.join(", ")}` : ""
  ].filter(Boolean).join(" ");
  if (!expr) return true;
  try {
    await ddb.send(
      new import_lib_dynamodb.UpdateCommand({
        TableName: ACCESS_TABLE_NAME,
        Key: { principal, target },
        UpdateExpression: expr,
        ConditionExpression: "attribute_exists(principal)",
        ExpressionAttributeNames: names,
        ...Object.keys(values).length ? { ExpressionAttributeValues: values } : {}
      })
    );
    return true;
  } catch (err) {
    if (err.name === CONDITION_FAILED) return false;
    throw err;
  }
}
async function upsertPref(userId, target, set, remove = []) {
  const names = {};
  const values = {};
  const sets = Object.entries(set).map(([k, v], i) => {
    names[`#s${i}`] = k;
    values[`:s${i}`] = v;
    return `#s${i} = :s${i}`;
  });
  const removes = remove.map((k, i) => {
    names[`#r${i}`] = k;
    return `#r${i}`;
  });
  const expr = [
    sets.length ? `SET ${sets.join(", ")}` : "",
    removes.length ? `REMOVE ${removes.join(", ")}` : ""
  ].filter(Boolean).join(" ");
  if (!expr) return;
  await ddb.send(
    new import_lib_dynamodb.UpdateCommand({
      TableName: ACCESS_TABLE_NAME,
      Key: { principal: userPrincipal(userId), target },
      UpdateExpression: expr,
      ExpressionAttributeNames: names,
      ...Object.keys(values).length ? { ExpressionAttributeValues: values } : {}
    })
  );
}
async function membersOf(groupId) {
  return (await queryTarget(memberTarget(groupId))).map((r) => parsePrincipal(r.principal)).filter((p) => p?.kind === "user").map((p) => p.userId);
}
function entryOf(target, direct, groups, now) {
  const d = direct ? { grantedBy: direct.grantedBy, grantedAt: direct.grantedAt, expiresAt: direct.expiresAt } : void 0;
  const directActive = Boolean(direct && !isExpired(direct, now));
  const active = directActive || groups.length > 0;
  return {
    target,
    direct: d,
    groups,
    active,
    expiresAt: groups.length === 0 && directActive ? direct?.expiresAt : void 0
  };
}
function tokenRoleLimit(opts) {
  if (!opts.roleLimit?.length) return void 0;
  const allowed = new Set(opts.roleLimit.map((r) => roleTarget(r.accountNumber, r.roleName)));
  return (target) => !target.startsWith("role#") || allowed.has(target);
}
async function effectiveAccess(userId, opts = {}) {
  const now = Date.now();
  const own = await queryPrincipal(userPrincipal(userId));
  const directByTarget = /* @__PURE__ */ new Map();
  const groupIds = [];
  for (const r of own) {
    if (isGrantTarget(r.target)) directByTarget.set(r.target, r);
    else if (r.target.startsWith("member#")) groupIds.push(r.target.slice("member#".length));
  }
  const groupsByTarget = /* @__PURE__ */ new Map();
  for (const g of groupIds) {
    for (const r of await queryPrincipal(groupPrincipal(g))) {
      if (!isGrantTarget(r.target) || isExpired(r, now)) continue;
      const list = groupsByTarget.get(r.target) ?? [];
      list.push(g);
      groupsByTarget.set(r.target, list);
    }
  }
  const out = /* @__PURE__ */ new Map();
  const limit = tokenRoleLimit(opts);
  const targets = /* @__PURE__ */ new Set([...directByTarget.keys(), ...groupsByTarget.keys()]);
  for (const t of targets) {
    if (limit && !limit(t)) continue;
    out.set(t, entryOf(t, directByTarget.get(t), groupsByTarget.get(t) ?? [], now));
  }
  return out;
}
async function batchGetAll(table, keys, opts = {}) {
  const out = [];
  for (let i = 0; i < keys.length; i += 100) {
    let chunk = keys.slice(i, i + 100);
    for (let attempt = 0; chunk.length; attempt++) {
      if (attempt >= BATCH_GET_ATTEMPTS) {
        throw new Error(`${table} BatchGet left ${chunk.length} keys unprocessed after ${attempt} attempts`);
      }
      if (attempt) await sleep(20 * attempt);
      const res = await ddb.send(
        new import_lib_dynamodb.BatchGetCommand({ RequestItems: { [table]: { Keys: chunk, ...consistentRead(opts) } } })
      );
      out.push(...res?.Responses?.[table] ?? []);
      chunk = res?.UnprocessedKeys?.[table]?.Keys ?? [];
    }
  }
  return out;
}
async function effectiveForMany(userId, targets, opts = {}) {
  const out = /* @__PURE__ */ new Map();
  const limit = tokenRoleLimit(opts);
  const wanted = [...new Set(targets)].filter((t) => !limit || limit(t));
  if (!wanted.length) return out;
  const [ownWanted, memberships] = await Promise.all([
    batchGetAll(ACCESS_TABLE_NAME, wanted.map((target) => ({ principal: userPrincipal(userId), target })), opts),
    queryPrincipal(userPrincipal(userId), "member#", opts)
  ]);
  const direct = new Map(ownWanted.map((r) => [r.target, r]));
  const groupIds = memberships.map((r) => r.target.slice("member#".length));
  const holding = /* @__PURE__ */ new Map();
  const keys = groupIds.flatMap((g) => wanted.map((target) => ({ principal: groupPrincipal(g), target })));
  for (const it of await batchGetAll(ACCESS_TABLE_NAME, keys, opts)) {
    const row = it;
    const p = parsePrincipal(row.principal);
    if (p?.kind !== "group" || isExpired(row)) continue;
    const list = holding.get(row.target) ?? [];
    list.push(p.groupId);
    holding.set(row.target, list);
  }
  const now = Date.now();
  for (const t of wanted) {
    const d = direct.get(t);
    const g = holding.get(t) ?? [];
    if (!d && !g.length) continue;
    out.set(t, entryOf(t, d, g, now));
  }
  return out;
}
async function effectiveFor(userId, target, opts = {}) {
  return (await effectiveForMany(userId, [target], opts)).get(target);
}
async function holdersOf(target) {
  const rows = await queryTarget(target);
  const byUser = /* @__PURE__ */ new Map();
  const now = Date.now();
  const ensure = (userId) => {
    let h = byUser.get(userId);
    if (!h) {
      h = { userId, groups: [], active: false };
      byUser.set(userId, h);
    }
    return h;
  };
  for (const r of rows) {
    const p = parsePrincipal(r.principal);
    if (p?.kind === "user") {
      const h = ensure(p.userId);
      h.direct = { grantedBy: r.grantedBy, grantedAt: r.grantedAt, expiresAt: r.expiresAt };
      if (!isExpired(r, now)) h.active = true;
    } else if (p?.kind === "group" && !isExpired(r, now)) {
      for (const userId of await membersOf(p.groupId)) {
        const h = ensure(userId);
        h.groups.push(p.groupId);
        h.active = true;
      }
    }
  }
  return [...byUser.values()];
}
function buildSnapshot(rows, now = Date.now()) {
  const groupTargets = /* @__PURE__ */ new Map();
  const groupMembers = /* @__PURE__ */ new Map();
  const directRows = /* @__PURE__ */ new Map();
  const userRows = [];
  const presence = /* @__PURE__ */ new Map();
  for (const r of rows) {
    const p = parsePrincipal(r.principal);
    if (!p) continue;
    if (p.kind === "user" && r.target === PRESENCE_TARGET) {
      if (typeof r.lastSeenAt === "string") presence.set(p.userId, r.lastSeenAt);
      continue;
    }
    if (p.kind === "group") {
      if (!isGrantTarget(r.target) || isExpired(r, now)) continue;
      const list = groupTargets.get(p.groupId) ?? [];
      list.push(r.target);
      groupTargets.set(p.groupId, list);
    } else if (r.target.startsWith("member#")) {
      const g = r.target.slice("member#".length);
      const list = groupMembers.get(g) ?? [];
      list.push(p.userId);
      groupMembers.set(g, list);
    } else if (isGrantTarget(r.target)) {
      const m = directRows.get(p.userId) ?? /* @__PURE__ */ new Map();
      m.set(r.target, r);
      directRows.set(p.userId, m);
      userRows.push(r);
    }
  }
  const users = /* @__PURE__ */ new Map();
  const groupsByUserTarget = /* @__PURE__ */ new Map();
  for (const [g, members] of groupMembers) {
    for (const u of members) {
      const m = groupsByUserTarget.get(u) ?? /* @__PURE__ */ new Map();
      for (const t of groupTargets.get(g) ?? []) {
        const list = m.get(t) ?? [];
        list.push(g);
        m.set(t, list);
      }
      groupsByUserTarget.set(u, m);
    }
  }
  const userIds = /* @__PURE__ */ new Set([...directRows.keys(), ...groupsByUserTarget.keys()]);
  for (const u of userIds) {
    const direct = directRows.get(u) ?? /* @__PURE__ */ new Map();
    const viaGroups = groupsByUserTarget.get(u) ?? /* @__PURE__ */ new Map();
    const targets = /* @__PURE__ */ new Set([...direct.keys(), ...viaGroups.keys()]);
    const m = /* @__PURE__ */ new Map();
    for (const t of targets) m.set(t, entryOf(t, direct.get(t), viaGroups.get(t) ?? [], now));
    users.set(u, m);
  }
  return { users, groupTargets, groupMembers, userRows, presence };
}
async function snapshot() {
  return buildSnapshot(await scanAll());
}
async function deleteShareRows(shareId, rows) {
  const target = shareTarget(shareId);
  const all = rows ?? await queryTarget(target);
  const grants = all.filter((r) => r.target === target && r.principal !== SHARE_DEF_PRINCIPAL);
  for (let i = 0; i < grants.length; i += DELETE_BATCH) {
    await Promise.all(grants.slice(i, i + DELETE_BATCH).map((r) => deleteRow(r.principal, r.target)));
  }
  await deleteRow(SHARE_DEF_PRINCIPAL, target);
}
var import_client_dynamodb, import_lib_dynamodb, ddb, ACCESS_TABLE_NAME, CONDITION_FAILED, userPrincipal, groupPrincipal, roleTarget, resourceTarget, pluginTarget, shareTarget, SHARE_DEF_PRINCIPAL, memberTarget, groupTarget, prefTarget, PRESENCE_TARGET, ADMIN_REVIEW_TARGET, NETWORK_PREFS_TARGET, NOTIFICATION_PREFS_TARGET, FAVORITE_PREFIX, favoriteTarget, RECENT_TARGET, principalOf, isGrantTarget, consistentRead, BATCH_GET_ATTEMPTS, sleep, isShareDefRow, DELETE_BATCH;
var init_access2 = __esm({
  "lambdacode/api/services/access.ts"() {
    "use strict";
    import_client_dynamodb = require("@aws-sdk/client-dynamodb");
    init_backend();
    import_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
    ddb = import_lib_dynamodb.DynamoDBDocumentClient.from(new import_client_dynamodb.DynamoDBClient({}));
    ACCESS_TABLE_NAME = process.env.ACCESS_TABLE_NAME;
    CONDITION_FAILED = "ConditionalCheckFailedException";
    userPrincipal = (sub) => `user#${sub}`;
    groupPrincipal = (groupId) => `group#${groupId}`;
    roleTarget = (accountNumber, roleName) => `role#${accountNumber}#${roleName}`;
    resourceTarget = (resourceId) => `resource#${resourceId}`;
    pluginTarget = (pluginId, accountNumber, permission) => pluginTargetKey({ pluginId, accountNumber, permission });
    shareTarget = (shareId) => `share#${shareId}`;
    SHARE_DEF_PRINCIPAL = "sharedef";
    memberTarget = (groupId) => `member#${groupId}`;
    groupTarget = groupPrincipal;
    prefTarget = (accountNumber, roleName) => `pref#role#${accountNumber}#${roleName}`;
    PRESENCE_TARGET = "pref#presence";
    ADMIN_REVIEW_TARGET = "pref#adminReview";
    NETWORK_PREFS_TARGET = "pref#network";
    NOTIFICATION_PREFS_TARGET = "pref#notifications";
    FAVORITE_PREFIX = "pref#fav#";
    favoriteTarget = (accountNumber) => `${FAVORITE_PREFIX}${accountNumber}`;
    RECENT_TARGET = "pref#recent";
    principalOf = (p) => p.kind === "user" ? userPrincipal(p.userId) : groupPrincipal(p.groupId);
    isGrantTarget = (t) => t.startsWith("role#") || t.startsWith("resource#") || t.startsWith("share#") || t.startsWith("plugin#");
    consistentRead = (opts) => opts.consistent ? { ConsistentRead: true } : {};
    BATCH_GET_ATTEMPTS = 5;
    sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    isShareDefRow = (r) => r.principal === SHARE_DEF_PRINCIPAL && typeof r.shareId === "string" && typeof r.ownerSub === "string" && typeof r.port === "number" && typeof r.siteId === "string" && typeof r.expiresAt === "string";
    DELETE_BATCH = 25;
  }
});

// lambdacode/api/services/pluginCatalog.ts
function isPluginCatalogRecord(item) {
  if (!item || typeof item !== "object") return false;
  const r = item;
  const m = r.manifest;
  return typeof r.pluginId === "string" && typeof r.schemaVersion === "number" && typeof r.installed === "boolean" && typeof r.revision === "string" && !!m && typeof m === "object" && m.id === r.pluginId && typeof m.enabled === "boolean" && typeof m.hostApiVersion === "number" && Array.isArray(m.accounts) && Array.isArray(m.permissions) && Array.isArray(r.routes);
}
function dynamoPluginCatalog(tableName2) {
  const accept = (item) => {
    if (isPluginCatalogRecord(item)) return item;
    log("WARN: malformed plugin catalog record skipped", {
      pluginId: item?.pluginId
    });
    return void 0;
  };
  return {
    async list(opts = {}) {
      const out = [];
      let ExclusiveStartKey;
      do {
        const page = await ddb2.send(
          new import_lib_dynamodb2.ScanCommand({ TableName: tableName2, ExclusiveStartKey, ...opts.consistent ? { ConsistentRead: true } : {} })
        );
        for (const item of page?.Items ?? []) {
          const r = accept(item);
          if (r) out.push(r);
        }
        ExclusiveStartKey = page?.LastEvaluatedKey;
      } while (ExclusiveStartKey);
      return out;
    },
    async get(pluginId, opts = {}) {
      const res = await ddb2.send(
        new import_lib_dynamodb2.GetCommand({
          TableName: tableName2,
          Key: { pluginId },
          ...opts.consistent ? { ConsistentRead: true } : {}
        })
      );
      return res.Item ? accept(res.Item) : void 0;
    }
  };
}
function pluginCatalog() {
  const table = process.env.PLUGIN_CATALOG_TABLE_NAME;
  return table ? dynamoPluginCatalog(table) : emptyPluginCatalog;
}
var import_client_dynamodb2, import_lib_dynamodb2, ddb2, emptyPluginCatalog, log;
var init_pluginCatalog = __esm({
  "lambdacode/api/services/pluginCatalog.ts"() {
    "use strict";
    import_client_dynamodb2 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb2 = require("@aws-sdk/lib-dynamodb");
    ddb2 = import_lib_dynamodb2.DynamoDBDocumentClient.from(new import_client_dynamodb2.DynamoDBClient({}));
    emptyPluginCatalog = {
      async list() {
        return [];
      },
      async get() {
        return void 0;
      }
    };
    log = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
  }
});

// lambdacode/api/services/pluginAccess.ts
function pluginAvailability(record, accountNumber, permission, registeredAccounts2) {
  if (!record) return { available: false, reason: "plugin-unknown" };
  const status = pluginCatalogStatus(record);
  if (status !== "active") return { available: false, reason: `plugin-${status}` };
  if (!record.manifest.permissions.some((p) => p.id === permission)) {
    return { available: false, reason: "permission-undeclared" };
  }
  if (!record.manifest.accounts.some((a) => a.accountNumber === accountNumber)) {
    return { available: false, reason: "account-unbound" };
  }
  if (!registeredAccounts2.has(accountNumber)) return { available: false, reason: "account-unregistered" };
  return { available: true };
}
async function loadPluginContext(opts = {}) {
  const records = await (opts.catalog ?? pluginCatalog()).list(opts);
  const catalog2 = new Map(records.map((r) => [r.pluginId, r]));
  const bound = /* @__PURE__ */ new Set();
  for (const r of records) for (const a of r.manifest.accounts) bound.add(a.accountNumber);
  return withAccounts(catalog2, await registeredAccounts([...bound], opts));
}
function withAccounts(catalog2, accounts) {
  const accountNames = /* @__PURE__ */ new Map();
  for (const [n, meta] of accounts) if (meta.name) accountNames.set(n, meta.name);
  return { catalog: catalog2, registeredAccounts: new Set(accounts.keys()), accountNames };
}
function deriveCapabilities(pluginId, accountNumber, held, ctx) {
  const record = ctx.catalog.get(pluginId);
  const declared = record?.manifest.permissions.map((p) => p.id) ?? [];
  const out = [];
  for (const permission of PLUGIN_PERMISSIONS) {
    const sources = [...held.values()].filter(
      (s) => s.permission === permission || pluginPermissionsImpliedBy(s.permission, declared).includes(permission)
    );
    if (!sources.length) continue;
    const a = pluginAvailability(record, accountNumber, permission, ctx.registeredAccounts);
    out.push({ pluginId, accountNumber, permission, sources, ...a.available ? { available: true } : a });
  }
  return out;
}
function resolvePluginCapabilities(entries, ctx) {
  const byBinding = /* @__PURE__ */ new Map();
  for (const e of entries) {
    if (!e.active) continue;
    const p = parseTarget(e.target);
    if (p?.kind !== "plugin") continue;
    const key = `${p.pluginId}#${p.accountNumber}`;
    const b = byBinding.get(key) ?? { pluginId: p.pluginId, accountNumber: p.accountNumber, held: /* @__PURE__ */ new Map() };
    b.held.set(p.permission, sourceOf(p.permission, e.direct, e.groups));
    byBinding.set(key, b);
  }
  const out = [];
  for (const b of byBinding.values()) out.push(...deriveCapabilities(b.pluginId, b.accountNumber, b.held, ctx));
  return out.sort(byBindingThenPermission);
}
async function pluginCapabilitiesFor(userId, ctx) {
  const context = ctx ?? await loadPluginContext();
  return resolvePluginCapabilities((await effectiveAccess(userId)).values(), context);
}
function availableCapabilityKeys(capabilities) {
  return new Set(capabilities.filter((c) => c.available).map((c) => pluginTarget(c.pluginId, c.accountNumber, c.permission)));
}
async function pluginHolders(pluginId, accountNumber, ctx) {
  const held = /* @__PURE__ */ new Map();
  for (const permission of PLUGIN_PERMISSIONS) {
    for (const h of await holdersOf(pluginTarget(pluginId, accountNumber, permission))) {
      if (!h.active) continue;
      const m = held.get(h.userId) ?? /* @__PURE__ */ new Map();
      m.set(permission, sourceOf(permission, h.direct, h.groups));
      held.set(h.userId, m);
    }
  }
  return [...held].map(([userId, m]) => ({ userId, capabilities: deriveCapabilities(pluginId, accountNumber, m, ctx) })).sort((a, b) => a.userId.localeCompare(b.userId));
}
async function registeredAccounts(numbers, opts = {}) {
  const out = /* @__PURE__ */ new Map();
  const ids = [...new Set(numbers)];
  if (!ids.length) return out;
  const table = process.env.ACCOUNTS_TABLE_NAME;
  if (!table) throw new Error("ACCOUNTS_TABLE_NAME is not set (plugin catalog readers need the Accounts table)");
  for (const item of await batchGetAll(table, ids.map((accountNumber) => ({ accountNumber })), opts)) {
    out.set(item.accountNumber, { name: item.name || void 0 });
  }
  return out;
}
var sourceOf, byBindingThenPermission;
var init_pluginAccess = __esm({
  "lambdacode/api/services/pluginAccess.ts"() {
    "use strict";
    init_backend();
    init_access2();
    init_pluginCatalog();
    sourceOf = (permission, direct, groups) => ({
      permission,
      ...direct && !isExpired(direct) ? { direct } : {},
      groups
    });
    byBindingThenPermission = (a, b) => a.pluginId.localeCompare(b.pluginId) || a.accountNumber.localeCompare(b.accountNumber) || PLUGIN_PERMISSIONS.indexOf(a.permission) - PLUGIN_PERMISSIONS.indexOf(b.permission);
  }
});

// lambdacode/api/services/revocationsService.ts
function noticeItem(userId, input, revokedAt) {
  return {
    userId,
    // Timestamp-first sort key: a plain descending Query returns
    // newest-first without a GSI.
    noticeId: `${revokedAt}#${(0, import_crypto.randomUUID)().slice(0, 8)}`,
    change: input.change ?? "REVOKED",
    kind: input.kind,
    ...input.accountNumber ? { accountNumber: input.accountNumber } : {},
    ...input.roleName ? { roleName: input.roleName } : {},
    ...input.resourceId ? { resourceId: input.resourceId } : {},
    ...input.resourceName ? { resourceName: input.resourceName } : {},
    ...input.pluginId ? { pluginId: input.pluginId } : {},
    ...input.permission ? { permission: input.permission } : {},
    ...input.pluginName ? { pluginName: input.pluginName } : {},
    ...input.count ? { count: input.count } : {},
    ...input.groupId ? { groupId: input.groupId } : {},
    ...input.groupName ? { groupName: input.groupName } : {},
    revokedAt,
    via: input.via,
    seen: false,
    ttl: Math.floor(Date.now() / 1e3) + NOTICE_RETENTION_DAYS * 24 * 60 * 60
  };
}
async function recordRevocations(notices) {
  if (!REVOCATIONS_TABLE_NAME) return;
  const items = notices.filter((n) => n.userId).map((n) => noticeItem(n.userId, n.input, (/* @__PURE__ */ new Date()).toISOString()));
  for (let i = 0; i < items.length; i += 25) {
    let requests = items.slice(i, i + 25).map((Item) => ({ PutRequest: { Item } }));
    try {
      for (let attempt = 0; attempt < 3 && requests.length; attempt++) {
        const res = await ddb3.send(new import_lib_dynamodb3.BatchWriteCommand({ RequestItems: { [REVOCATIONS_TABLE_NAME]: requests } }));
        requests = res.UnprocessedItems?.[REVOCATIONS_TABLE_NAME] ?? [];
      }
      if (requests.length) log2("access notices left unprocessed", { count: requests.length });
    } catch (err) {
      log2("access notice batch write failed", { count: requests.length, error: err.message });
    }
  }
  if (items.length) log2("recorded access notices", { count: items.length });
}
async function listRevocationNotices(userId) {
  if (!REVOCATIONS_TABLE_NAME) return [];
  const notices = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb3.send(
      new import_lib_dynamodb3.QueryCommand({
        TableName: REVOCATIONS_TABLE_NAME,
        KeyConditionExpression: "userId = :u",
        ExpressionAttributeValues: { ":u": userId },
        ScanIndexForward: false,
        ExclusiveStartKey
      })
    );
    for (const it of page.Items ?? []) {
      notices.push({
        noticeId: it.noticeId,
        change: it.change ?? "REVOKED",
        kind: it.kind,
        accountNumber: it.accountNumber,
        roleName: it.roleName,
        resourceId: it.resourceId,
        resourceName: it.resourceName,
        pluginId: it.pluginId,
        permission: it.permission,
        pluginName: it.pluginName,
        count: it.count,
        groupId: it.groupId,
        groupName: it.groupName,
        revokedAt: it.revokedAt,
        via: it.via,
        seen: Boolean(it.seen)
      });
    }
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return notices;
}
async function markRevocationNoticesSeen(userId) {
  const unseen = (await listRevocationNotices(userId)).filter((n) => !n.seen);
  const markOne = async (n) => {
    try {
      await ddb3.send(
        new import_lib_dynamodb3.UpdateCommand({
          TableName: REVOCATIONS_TABLE_NAME,
          Key: { userId, noticeId: n.noticeId },
          UpdateExpression: "SET seen = :true",
          // Guards a notice TTL-purged between read and write.
          ConditionExpression: "attribute_exists(userId)",
          ExpressionAttributeValues: { ":true": true }
        })
      );
    } catch (err) {
      if (err.name !== CONDITION_FAILED2) throw err;
    }
  };
  for (let i = 0; i < unseen.length; i += MARK_SEEN_CONCURRENCY) {
    await Promise.all(unseen.slice(i, i + MARK_SEEN_CONCURRENCY).map(markOne));
  }
  if (unseen.length) {
    log2("marked revocation notices seen", { userId, count: unseen.length });
  }
  return unseen.length;
}
var import_crypto, import_client_dynamodb3, import_lib_dynamodb3, ddb3, REVOCATIONS_TABLE_NAME, log2, CONDITION_FAILED2, NOTICE_RETENTION_DAYS, MARK_SEEN_CONCURRENCY;
var init_revocationsService = __esm({
  "lambdacode/api/services/revocationsService.ts"() {
    "use strict";
    import_crypto = require("crypto");
    import_client_dynamodb3 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb3 = require("@aws-sdk/lib-dynamodb");
    ddb3 = import_lib_dynamodb3.DynamoDBDocumentClient.from(new import_client_dynamodb3.DynamoDBClient({}));
    REVOCATIONS_TABLE_NAME = process.env.REVOCATIONS_TABLE_NAME;
    log2 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    CONDITION_FAILED2 = "ConditionalCheckFailedException";
    NOTICE_RETENTION_DAYS = 30;
    MARK_SEEN_CONCURRENCY = 25;
  }
});

// lambdacode/api/services/actorContext.ts
function runAsActor(actor, fn) {
  return store.run(actor, fn);
}
function currentActor() {
  return store.getStore();
}
function callerRoleLimit(userId) {
  const actor = currentActor();
  const roles = actor?.token?.roles;
  return roles?.length && actor?.id === userId ? roles : void 0;
}
var import_async_hooks, store;
var init_actorContext = __esm({
  "lambdacode/api/services/actorContext.ts"() {
    "use strict";
    import_async_hooks = require("async_hooks");
    store = new import_async_hooks.AsyncLocalStorage();
  }
});

// lambdacode/api/services/auditService.ts
function retentionDays() {
  const n = Number(process.env.AUDIT_RETENTION_DAYS);
  return Number.isInteger(n) && n > 0 ? n : DEFAULT_RETENTION_DAYS;
}
function tableOr() {
  const table = tableName();
  if (table) return table;
  if (!warnedNoTable) {
    warnedNoTable = true;
    log3("WARN: AUDIT_TABLE_NAME unset \u2014 activity is not recorded");
  }
  return void 0;
}
function compact(value) {
  if (Array.isArray(value)) return value.map(compact);
  if (value && typeof value === "object" && !(value instanceof Set)) {
    const out = {};
    for (const [k, v] of Object.entries(value)) {
      if (v !== void 0) out[k] = compact(v);
    }
    return out;
  }
  return value;
}
function toRow(input, now) {
  const bound = input.actor ?? currentActor();
  if (!bound) log3("ERROR: activity row without a bound actor (missing runAsActor?)", { action: input.action, target: input.target });
  const actor = bound ?? UNKNOWN_ACTOR;
  const token = actor.token;
  const details = input.details ? { ...input.details } : void 0;
  if (details?.note !== void 0) details.note = String(details.note).slice(0, NOTE_MAX);
  if (details?.affected && details.affected.length > AFFECTED_CAP) {
    details.affectedCount = details.affected.length;
    details.affected = details.affected.slice(0, AFFECTED_CAP);
  }
  if (details?.unchanged && details.unchanged.length > AFFECTED_CAP) {
    details.unchangedCount = details.unchanged.length;
    details.unchanged = details.unchanged.slice(0, AFFECTED_CAP);
  }
  const accountNumber = input.accountNumber ?? accountOf(input.target);
  return compact({
    ...input,
    eventId: (0, import_crypto2.randomUUID)(),
    outcome: input.outcome ?? "OK",
    reason: input.reason === void 0 ? void 0 : String(input.reason).slice(0, REASON_MAX),
    actor: {
      kind: actor.kind,
      id: actor.id,
      name: actor.name,
      claims: actor.claims && Object.keys(actor.claims).length ? actor.claims : void 0,
      token: token && { id: token.id, name: token.name }
    },
    accountNumber,
    details,
    at: now.toISOString(),
    day: now.toISOString().slice(0, 10),
    userId: input.subject?.id,
    actorId: SESSION_ACTIONS.has(input.action) && input.subject?.kind === "user" ? input.subject.id : actor.id,
    expiresAt: Math.floor(now.getTime() / 1e3) + retentionDays() * 24 * 60 * 60
  });
}
function accountOf(target) {
  if (!target) return void 0;
  const p = parseTarget(target);
  if (p?.kind === "role" || p?.kind === "plugin") return p.accountNumber;
  if (target.startsWith("account#")) return target.slice("account#".length);
  return void 0;
}
async function recordEvent(input) {
  const table = tableOr();
  if (!table) return;
  const row = toRow(input, /* @__PURE__ */ new Date());
  try {
    await ddb4.send(new import_lib_dynamodb4.PutCommand({ TableName: table, Item: row }));
    log3("activity recorded", { action: row.action, outcome: row.outcome, actor: row.actorId, subject: row.userId, target: row.target, eventId: row.eventId });
  } catch (err) {
    log3("ERROR: activity write failed (mutation unaffected)", { action: row.action, target: row.target, error: err.message });
  }
}
async function recordEvents(inputs) {
  if (!inputs.length) return;
  const table = tableOr();
  if (!table) return;
  const start = Date.now();
  const rows = inputs.map((input, i) => toRow(input, new Date(start + i)));
  for (let i = 0; i < rows.length; i += 25) {
    let requests = rows.slice(i, i + 25).map((Item) => ({ PutRequest: { Item } }));
    try {
      for (let attempt = 0; attempt < 3 && requests.length; attempt++) {
        const res = await ddb4.send(new import_lib_dynamodb4.BatchWriteCommand({ RequestItems: { [table]: requests } }));
        requests = res.UnprocessedItems?.[table] ?? [];
      }
      if (requests.length) log3("ERROR: activity batch left unprocessed rows", { count: requests.length });
    } catch (err) {
      log3("ERROR: activity batch write failed (mutation unaffected)", { count: requests.length, error: err.message });
    }
  }
  log3("activity batch recorded", { count: rows.length, actions: [...new Set(rows.map((r) => r.action))] });
}
async function recordVendEvent(event) {
  const actor = currentActor() ?? {
    kind: event.serviceUser ? "service" : "user",
    id: event.userId,
    name: event.userName,
    claims: event.claims
  };
  const enrollment = event.action === "NETWORK_KEY";
  await recordEvent({
    category: "vend",
    action: VEND_ACTION[event.action],
    outcome: event.outcome === "VENDED" ? "OK" : event.outcome,
    reason: event.outcome === "DENIED" ? event.deniedReason ?? "NO_GRANT" : event.outcome === "FAILED" ? event.failureReason : void 0,
    actor,
    subject: { kind: event.serviceUser ? "serviceUser" : "user", id: event.userId, name: event.userName },
    ...enrollment ? {} : { target: roleTarget(event.accountNumber, event.roleName), targetName: event.roleName, accountNumber: event.accountNumber },
    ...event.outcome === "DENIED" ? { details: { deniedReason: event.deniedReason ?? "NO_GRANT" } } : {}
  });
}
function vendAuditor(base) {
  return (outcome, extra) => recordVendEvent({ ...base, outcome, ...extra });
}
function legacyToEvent(row) {
  const enrollment = row.action === "NETWORK_KEY";
  const outcome = row.outcome === "VENDED" ? "OK" : enrollment && row.outcome === "DENIED" && !row.deniedReason ? "FAILED" : row.outcome;
  const actor = { kind: "user", id: row.userId, name: row.userName, claims: row.claims };
  return compact({
    eventId: row.eventId,
    category: "vend",
    action: VEND_ACTION[row.action] ?? String(row.action).toLowerCase(),
    outcome,
    reason: outcome === "DENIED" ? row.deniedReason ?? "NO_GRANT" : outcome === "FAILED" ? row.failureReason : void 0,
    actor,
    subject: { kind: "user", id: row.userId, name: row.userName },
    ...enrollment || row.accountNumber === "-" ? {} : { target: roleTarget(row.accountNumber, row.roleName), targetName: row.roleName, accountNumber: row.accountNumber },
    details: outcome === "DENIED" ? { deniedReason: row.deniedReason ?? "NO_GRANT" } : void 0,
    at: row.at,
    day: row.day
  });
}
function toEvent(row) {
  if (isLegacy(row)) return legacyToEvent(row);
  const { userId: _u, actorId: _a, expiresAt: _e, ...event } = row;
  return event;
}
function resolveWindow(q, now = Date.now()) {
  const parse = (label, iso) => {
    if (iso === void 0) return void 0;
    const t = Date.parse(iso);
    if (Number.isNaN(t)) throw new AuditQueryError(`${label} must be an ISO-8601 timestamp`);
    return t;
  };
  let to = Math.min(parse("to", q.to) ?? now, now);
  const before = parse("before", q.before);
  if (before !== void 0) to = Math.min(to, before);
  const days = q.days ?? 7;
  if (!Number.isInteger(days) || days < 1 || days > MAX_SPAN_DAYS) throw new AuditQueryError(`days must be between 1 and ${MAX_SPAN_DAYS}`);
  const from = parse("from", q.from) ?? to - days * DAY_MS;
  if (from > to) throw new AuditQueryError("from must be before to");
  if (to - from > MAX_SPAN_DAYS * DAY_MS) throw new AuditQueryError(`the window may span at most ${MAX_SPAN_DAYS} days`);
  const floor = now - retentionDays() * DAY_MS;
  return { from: new Date(Math.max(from, floor)).toISOString(), to: new Date(to).toISOString() };
}
function buildFilter(q, skip) {
  const parts = [];
  const names = {};
  const values = {};
  if (q.category?.length) {
    names["#c"] = "category";
    const keys = q.category.map((c, i) => {
      values[`:c${i}`] = c;
      return `:c${i}`;
    });
    parts.push(q.category.includes("vend") ? `(#c IN (${keys.join(",")}) OR attribute_not_exists(#c))` : `#c IN (${keys.join(",")})`);
  }
  if (q.outcome?.length) {
    names["#o"] = "outcome";
    const outcomes = q.outcome.includes("OK") ? [...q.outcome, "VENDED"] : q.outcome;
    const keys = outcomes.map((o, i) => {
      values[`:o${i}`] = o;
      return `:o${i}`;
    });
    const wantsFailed = q.outcome.includes("FAILED");
    const wantsDenied = q.outcome.includes("DENIED");
    let cond = `#o IN (${keys.join(",")})`;
    if (wantsFailed !== wantsDenied) {
      names["#a"] = "action";
      names["#dr"] = "deniedReason";
      values[":legacyKey"] = "NETWORK_KEY";
      values[":legacyDenied"] = "DENIED";
      const legacyFailed = "(#a = :legacyKey AND #o = :legacyDenied AND attribute_not_exists(#dr))";
      cond = wantsFailed ? `(${cond} OR ${legacyFailed})` : `(${cond} AND NOT ${legacyFailed})`;
    }
    parts.push(cond);
  }
  if (q.account?.length) {
    names["#acct"] = "accountNumber";
    const keys = q.account.map((a, i) => {
      values[`:acct${i}`] = a;
      return `:acct${i}`;
    });
    parts.push(`#acct IN (${keys.join(",")})`);
  }
  if (q.target?.length) {
    names["#t"] = "target";
    const keys = q.target.map((t, i) => {
      values[`:t${i}`] = t;
      return `:t${i}`;
    });
    parts.push(`#t IN (${keys.join(",")})`);
  }
  if (q.group?.length) {
    names["#t"] = "target";
    names["#d"] = "details";
    if (!skip.user) names["#u"] = "userId";
    const ors = [];
    q.group.forEach((g, i) => {
      values[`:g${i}`] = g;
      values[`:gt${i}`] = groupTarget(g);
      ors.push(`#t = :gt${i} OR #d.groupId = :g${i}${skip.user ? "" : ` OR #u = :g${i}`}`);
    });
    parts.push(`(${ors.join(" OR ")})`);
  }
  if (q.actor?.length && !skip.actor) {
    names["#ai"] = "actorId";
    const keys = q.actor.map((a, i) => {
      values[`:ai${i}`] = a;
      return `:ai${i}`;
    });
    let cond = `#ai IN (${keys.join(",")})`;
    if (skip.user && q.user?.length === 1 && q.actor.includes(q.user[0])) {
      names["#cat"] = "category";
      cond = `(${cond} OR attribute_not_exists(#cat))`;
    }
    parts.push(cond);
  }
  if (q.user?.length && !skip.user) {
    names["#u"] = "userId";
    const keys = q.user.map((u, i) => {
      values[`:u${i}`] = u;
      return `:u${i}`;
    });
    parts.push(`#u IN (${keys.join(",")})`);
  }
  if (!q.derived) {
    names["#dv"] = "derived";
    parts.push("attribute_not_exists(#dv)");
  }
  return { expression: parts.length ? parts.join(" AND ") : void 0, names, values };
}
async function listAuditEvents(q = {}) {
  for (const key of ["user", "actor"]) {
    const many = q[key];
    if (many && many.length > 1) {
      if (many.length > FANOUT_MAX) throw new AuditQueryError(`${key} takes at most ${FANOUT_MAX} ids`);
      const limit2 = Math.min(Math.max(q.limit ?? 200, 1), MAX_EVENTS);
      const pages = await Promise.all(many.map((one) => listAuditEvents({ ...q, [key]: [one] })));
      const seen = /* @__PURE__ */ new Set();
      const merged = pages.flatMap((p) => p.events).filter((e) => seen.has(e.eventId) ? false : (seen.add(e.eventId), true)).sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : 0);
      const events2 = merged.slice(0, limit2);
      const full2 = merged.length > limit2 || pages.some((p) => p.nextBefore !== void 0);
      return { events: events2, from: pages[0].from, to: pages[0].to, ...full2 && events2.length ? { nextBefore: events2[events2.length - 1].at } : {} };
    }
  }
  const { from, to } = resolveWindow(q);
  const limit = Math.min(Math.max(q.limit ?? 200, 1), MAX_EVENTS);
  const events = [];
  const skip = new Set(q.skip ?? []);
  const push = (items) => {
    for (const it of items) if (!skip.has(it.eventId)) events.push(toEvent(it));
  };
  const indexed = q.user?.length ? { index: "byUser", key: "userId", value: q.user[0] } : q.actor?.length ? { index: "byActor", key: "actorId", value: q.actor[0] } : void 0;
  const f = buildFilter(q, { user: indexed?.index === "byUser", actor: indexed?.index === "byActor" });
  const drain = async (index, key, value, filter = f) => {
    let ExclusiveStartKey;
    do {
      const page = await ddb4.send(
        new import_lib_dynamodb4.QueryCommand({
          TableName: tableName(),
          IndexName: index,
          KeyConditionExpression: "#k = :k AND #at BETWEEN :from AND :to",
          FilterExpression: filter.expression,
          ExpressionAttributeNames: { "#k": key, "#at": "at", ...filter.names },
          ExpressionAttributeValues: { ":k": value, ":from": from, ":to": to, ...filter.values },
          ScanIndexForward: false,
          Limit: limit - events.length,
          ExclusiveStartKey
        })
      );
      push(page.Items ?? []);
      ExclusiveStartKey = page.LastEvaluatedKey;
    } while (ExclusiveStartKey && events.length < limit);
  };
  if (indexed) {
    await drain(indexed.index, indexed.key, indexed.value);
    if (indexed.index === "byActor" && events.length < limit) {
      const g = buildFilter(q, { user: true, actor: true });
      const legacy = { ...g, expression: [g.expression, "attribute_not_exists(#cat)"].filter(Boolean).join(" AND "), names: { ...g.names, "#cat": "category" } };
      await drain("byUser", "userId", indexed.value, legacy);
    }
  } else {
    const lastDay = from.slice(0, 10);
    for (let t = Date.parse(to); events.length < limit; t -= DAY_MS) {
      const day = new Date(t).toISOString().slice(0, 10);
      await drain("byDay", "day", day);
      if (day <= lastDay) break;
    }
  }
  events.sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : 0);
  const full = events.length >= limit;
  log3("listed activity", { from, to, count: events.length, full });
  return { events, from, to, ...full ? { nextBefore: events[events.length - 1].at } : {} };
}
async function countRoleUsage(userId, accountNumber, roleName, days = 365) {
  const from = new Date(Date.now() - days * DAY_MS).toISOString();
  const target = roleTarget(accountNumber, roleName);
  let count = 0;
  let lastAt;
  let ExclusiveStartKey;
  do {
    const page = await ddb4.send(
      new import_lib_dynamodb4.QueryCommand({
        TableName: tableName(),
        IndexName: "byUser",
        KeyConditionExpression: "userId = :u AND #at >= :from",
        FilterExpression: "(#t = :t OR (accountNumber = :a AND roleName = :r)) AND #o IN (:vended, :ok) AND #action IN (:cred, :console, :legacyCred, :legacyConsole)",
        ExpressionAttributeNames: { "#at": "at", "#t": "target", "#o": "outcome", "#action": "action" },
        ExpressionAttributeValues: {
          ":u": userId,
          ":from": from,
          ":t": target,
          ":a": accountNumber,
          ":r": roleName,
          ":vended": "VENDED",
          ":ok": "OK",
          ":cred": VEND_ACTION.CREDENTIALS,
          ":console": VEND_ACTION.CONSOLE,
          ":legacyCred": "CREDENTIALS",
          ":legacyConsole": "CONSOLE"
        },
        ScanIndexForward: false,
        // newest first — first hit IS lastAt
        ExclusiveStartKey
      })
    );
    for (const e of page.Items ?? []) {
      count++;
      lastAt ??= e.at;
    }
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return { count, ...lastAt ? { lastAt } : {} };
}
var import_crypto2, import_client_dynamodb4, import_lib_dynamodb4, ddb4, tableName, log3, AUDIT_CATEGORIES, AUDIT_OUTCOMES, DEFAULT_RETENTION_DAYS, REASON_MAX, NOTE_MAX, AFFECTED_CAP, MAX_SPAN_DAYS, MAX_EVENTS, DAY_MS, newBatchId, UNKNOWN_ACTOR, warnedNoTable, SESSION_ACTIONS, VEND_ACTION, isLegacy, AuditQueryError, FANOUT_MAX;
var init_auditService = __esm({
  "lambdacode/api/services/auditService.ts"() {
    "use strict";
    import_crypto2 = require("crypto");
    import_client_dynamodb4 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb4 = require("@aws-sdk/lib-dynamodb");
    init_actorContext();
    init_access2();
    ddb4 = import_lib_dynamodb4.DynamoDBDocumentClient.from(new import_client_dynamodb4.DynamoDBClient({}));
    tableName = () => process.env.AUDIT_TABLE_NAME ?? "";
    log3 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    AUDIT_CATEGORIES = ["access", "request", "vend", "network", "catalog", "users", "auth"];
    AUDIT_OUTCOMES = ["OK", "DENIED", "FAILED"];
    DEFAULT_RETENTION_DAYS = 400;
    REASON_MAX = 300;
    NOTE_MAX = 500;
    AFFECTED_CAP = 50;
    MAX_SPAN_DAYS = 90;
    MAX_EVENTS = 1e3;
    DAY_MS = 24 * 60 * 60 * 1e3;
    newBatchId = () => (0, import_crypto2.randomUUID)();
    UNKNOWN_ACTOR = { kind: "system", id: "system:unknown" };
    warnedNoTable = false;
    SESSION_ACTIONS = /* @__PURE__ */ new Set(["vpn.connect", "vpn.disconnect"]);
    VEND_ACTION = {
      CREDENTIALS: "credentials.vend",
      CONSOLE: "console.open",
      NETWORK_KEY: "device.enroll"
    };
    isLegacy = (row) => !("category" in row);
    AuditQueryError = class extends Error {
    };
    FANOUT_MAX = 10;
  }
});

// lambdacode/api/services/accessNotices.ts
async function activeTargets(userId, plugins = loadPluginContext) {
  const entries = await effectiveAccess(userId);
  const out = /* @__PURE__ */ new Set();
  const pluginEntries = [];
  for (const [t, e] of entries) {
    if (!e.active) continue;
    if (parseTarget(t)?.kind === "plugin") pluginEntries.push(e);
    else out.add(t);
  }
  if (pluginEntries.length) {
    for (const k of availableCapabilityKeys(resolvePluginCapabilities(pluginEntries, await plugins()))) out.add(k);
  }
  return out;
}
async function mapLimit(items, fn) {
  const out = new Array(items.length);
  let next = 0;
  const worker = async () => {
    for (let i = next++; i < items.length; i = next++) out[i] = await fn(items[i]);
  };
  await Promise.all(Array.from({ length: Math.min(DIFF_CONCURRENCY, items.length) }, worker));
  return out;
}
function affectedOf(changes, only = {}) {
  const out = [];
  for (const c of changes) {
    for (const [change, targets] of [["gained", c.gained], ["lost", c.lost]]) {
      if (only.change && only.change !== change) continue;
      for (const t of targets) {
        if (only.target && only.target !== t) continue;
        out.push({ userId: c.userId, change, target: t });
      }
    }
  }
  return out;
}
function unchangedOf(changes, only = {}) {
  const moved = (c) => {
    const lists = only.change === "gained" ? [c.gained] : only.change === "lost" ? [c.lost] : [c.gained, c.lost];
    return lists.some((l) => only.target ? l.includes(only.target) : l.length > 0);
  };
  return changes.filter((c) => !moved(c)).map((c) => ({ userId: c.userId }));
}
async function activeAmong(userId, targets) {
  const out = /* @__PURE__ */ new Set();
  for (const [t, e] of await effectiveForMany(userId, targets)) if (e.active) out.add(t);
  return out;
}
async function withAccessDiff(userIds, via, mutate, resourceNames, opts = {}) {
  const users = [...new Set(userIds)].filter(Boolean);
  const scoped = opts.targets?.length ? [...new Set(opts.targets)] : void 0;
  const narrow = scoped !== void 0 && scoped.length <= NARROW_MAX_TARGETS && !scoped.some((t) => parseTarget(t)?.kind === "plugin");
  const read = (u, plugins) => narrow ? activeAmong(u, scoped) : activeTargets(u, plugins);
  const pluginsBefore = memo(() => loadPluginContext());
  const before = /* @__PURE__ */ new Map();
  for (const [i, set] of (await mapLimit(users, (u) => read(u, pluginsBefore))).entries()) before.set(users[i], set);
  const result = await mutate();
  const pluginsAfter = opts.catalogChanges ? memo(() => loadPluginContext({ consistent: true })) : pluginsBefore;
  const batchId = opts.batchId ?? newBatchId();
  const changes = [];
  const derived = [];
  const notices = [];
  const afterSets = await mapLimit(users, (u) => read(u, pluginsAfter));
  const shareLabel = memoBy(
    async (shareId, t) => resourceNames?.get(shareId) ?? (await getRow(SHARE_DEF_PRINCIPAL, t))?.label
  );
  const pluginName = memoBy(async (pluginId) => {
    const record = (await pluginsAfter()).catalog.get(pluginId) ?? (await pluginsBefore()).catalog.get(pluginId);
    return record?.manifest.displayName;
  });
  for (const [i, u] of users.entries()) {
    const after = afterSets[i];
    const change = { userId: u, gained: [], lost: [], after };
    for (const t of after) if (!before.get(u).has(t)) change.gained.push(t);
    for (const t of before.get(u)) if (!after.has(t)) change.lost.push(t);
    const notice = async (t, kind) => {
      const parsed = parseTarget(t);
      let input;
      if (parsed?.kind === "role") {
        input = { change: kind, kind: "ROLE", accountNumber: parsed.accountNumber, roleName: parsed.roleName, via };
      } else if (parsed?.kind === "resource") {
        input = { change: kind, kind: "RESOURCE", resourceId: parsed.resourceId, resourceName: resourceNames?.get(parsed.resourceId), via };
      } else if (parsed?.kind === "share") {
        input = { change: kind, kind: "SHARE", resourceId: parsed.shareId, resourceName: await shareLabel(parsed.shareId, t), via };
      } else if (parsed?.kind === "plugin") {
        input = {
          change: kind,
          kind: "PLUGIN",
          pluginId: parsed.pluginId,
          accountNumber: parsed.accountNumber,
          permission: parsed.permission,
          pluginName: await pluginName(parsed.pluginId),
          via
        };
      }
      if (input) notices.push({ userId: u, input });
    };
    const noticeAll = async (targets, kind) => {
      if (bundled(via, targets)) {
        notices.push({
          userId: u,
          input: {
            change: kind,
            kind: "BUNDLE",
            count: targets.length,
            ...opts.groupId ? { groupId: opts.groupId } : {},
            ...opts.groupName ? { groupName: opts.groupName } : {},
            via
          }
        });
        return;
      }
      for (const t of targets) await notice(t, kind);
    };
    await noticeAll(change.lost, "REVOKED");
    if (opts.gainNotices !== false) await noticeAll(change.gained, "GRANTED");
    changes.push(change);
    if (opts.derived !== false) {
      for (const [list, action] of [
        [change.gained, "access.gain"],
        [change.lost, "access.lose"]
      ]) {
        const groupDetails = {
          ...opts.groupId ? { groupId: opts.groupId } : {},
          ...opts.groupName ? { groupName: opts.groupName } : {}
        };
        if (bundled(via, list)) {
          derived.push({
            category: "access",
            action,
            subject: { kind: "user", id: u },
            details: { via, batchId, count: list.length, ...groupDetails },
            derived: true
          });
          continue;
        }
        for (const t of list) {
          derived.push({
            category: "access",
            action,
            subject: { kind: "user", id: u },
            target: t,
            targetName: targetLabel(t, resourceNames),
            details: { via, batchId, ...groupDetails },
            derived: true
          });
        }
      }
    }
  }
  await recordRevocations(notices);
  await recordEvents(derived);
  opts.onDiff?.(changes);
  if (notices.length || derived.length) log4("access diff", { via, users: users.length, notices: notices.length, derived: derived.length });
  return result;
}
function memoBy(load) {
  const cache = /* @__PURE__ */ new Map();
  return (...args) => {
    const k = args[0];
    let p = cache.get(k);
    if (!p) {
      p = load(...args);
      cache.set(k, p);
    }
    return p;
  };
}
function targetLabel(target, names) {
  const p = parseTarget(target);
  if (p?.kind === "role") return p.roleName;
  if (p?.kind === "resource") return names?.get(p.resourceId);
  if (p?.kind === "share") return names?.get(p.shareId);
  return void 0;
}
var log4, memo, DIFF_CONCURRENCY, NARROW_MAX_TARGETS, NOTICE_BUNDLE_THRESHOLD, BUNDLED_VIAS, bundled;
var init_accessNotices = __esm({
  "lambdacode/api/services/accessNotices.ts"() {
    "use strict";
    init_access2();
    init_pluginAccess();
    init_revocationsService();
    init_auditService();
    log4 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    memo = (load) => {
      let p;
      return () => p ??= load();
    };
    DIFF_CONCURRENCY = 8;
    NARROW_MAX_TARGETS = 100;
    NOTICE_BUNDLE_THRESHOLD = 5;
    BUNDLED_VIAS = /* @__PURE__ */ new Set(["GROUP", "CASCADE"]);
    bundled = (via, targets) => BUNDLED_VIAS.has(via) && targets.length > NOTICE_BUNDLE_THRESHOLD;
  }
});

// lambdacode/api/services/accountOrder.ts
function compareAccounts(a, b) {
  const ao = order(a.sortOrder);
  const bo = order(b.sortOrder);
  if (ao !== bo) return ao - bo;
  const an = text(a.name);
  const bn = text(b.name);
  if (!!an !== !!bn) return an ? -1 : 1;
  return an.localeCompare(bn) || String(a.accountNumber).localeCompare(String(b.accountNumber));
}
function compareRoles(a, b) {
  const ao = order(a.sortOrder);
  const bo = order(b.sortOrder);
  if (ao !== bo) return ao - bo;
  const al = text(a.displayName) || String(a.roleName);
  const bl = text(b.displayName) || String(b.roleName);
  return al.localeCompare(bl) || String(a.roleName).localeCompare(String(b.roleName));
}
var text, order;
var init_accountOrder = __esm({
  "lambdacode/api/services/accountOrder.ts"() {
    "use strict";
    text = (v) => typeof v === "string" ? v : "";
    order = (v) => typeof v === "number" && Number.isFinite(v) ? v : Number.MAX_SAFE_INTEGER;
  }
});

// lambdacode/api/services/dimensions.ts
function parseAccountName(name) {
  if (!name) return void 0;
  const parts = name.trim().split("-").map((p) => p.trim()).filter(Boolean);
  if (parts.length < 2) return void 0;
  const tenant = parts[0];
  const stage = parts[parts.length - 1];
  const project = parts.slice(1, -1).join("-");
  return { tenant, stage, ...project ? { project } : {} };
}
function dimensionsSettings() {
  const raw = process.env.ACCOUNT_DIMENSIONS;
  if (!raw) return { enabled: false };
  try {
    const parsed = JSON.parse(raw);
    return { enabled: parsed?.enabled === true };
  } catch {
    return { enabled: false };
  }
}
function matchesDims(dims, filter) {
  for (const key of DIMENSION_KEYS) {
    const wanted = filter[key];
    if (!wanted?.length) continue;
    if (!wanted.includes(dims?.[key] ?? UNCLASSIFIED)) return false;
  }
  return true;
}
function dimensionFacets() {
  if (!dimensionsSettings().enabled) return {};
  const value = (key) => (item) => item.dims?.[key] ?? UNCLASSIFIED;
  return { tenant: value("tenant"), project: value("project"), stage: value("stage") };
}
function parseDimsFilter(input) {
  if (!input || typeof input !== "object" || Array.isArray(input)) return void 0;
  const out = {};
  for (const [k, v] of Object.entries(input)) {
    if (!DIMENSION_KEYS.includes(k)) return void 0;
    const values = Array.isArray(v) ? v : typeof v === "string" ? [v] : void 0;
    if (!values || !values.every((x) => typeof x === "string")) return void 0;
    const clean = values.map((x) => x.trim()).filter(Boolean);
    if (clean.length) out[k] = clean;
  }
  return out;
}
function cleanDims(input) {
  if (!input || typeof input !== "object") return void 0;
  const o = input;
  const pick = (k) => typeof o[k] === "string" && o[k].trim() ? o[k].trim() : void 0;
  const tenant = pick("tenant");
  const stage = pick("stage");
  const project = pick("project");
  if (!tenant || !stage) return void 0;
  return { tenant, stage, ...project ? { project } : {} };
}
var DIMENSION_KEYS, UNCLASSIFIED;
var init_dimensions = __esm({
  "lambdacode/api/services/dimensions.ts"() {
    "use strict";
    DIMENSION_KEYS = ["tenant", "project", "stage"];
    UNCLASSIFIED = "unclassified";
  }
});

// lambdacode/api/services/catalogIndex.ts
async function readVersion() {
  const res = await ddb5.send(
    new import_lib_dynamodb5.GetCommand({ TableName: RESOURCES_TABLE_NAME, Key: { resourceId: CATALOG_VERSION_KEY }, ConsistentRead: true })
  );
  const v = res?.Item?.version;
  return typeof v === "number" ? v : void 0;
}
async function scanAll2(TableName) {
  const items = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb5.send(new import_lib_dynamodb5.ScanCommand({ TableName, ExclusiveStartKey, ConsistentRead: true }));
    items.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return items;
}
async function build(version) {
  const started = Date.now();
  const [accountItems, roleItems, groupItems] = await Promise.all([
    scanAll2(ACCOUNTS_TABLE_NAME),
    scanAll2(ROLES_TABLE_NAME),
    scanAll2(GROUPS_TABLE_NAME)
  ]);
  const byNumber = /* @__PURE__ */ new Map();
  for (const a of accountItems) {
    const accountNumber = String(a.accountNumber);
    byNumber.set(accountNumber, {
      accountNumber,
      name: str(a.name),
      environment: str(a.environment),
      status: str(a.status),
      profileName: str(a.profileName),
      sortOrder: num(a.sortOrder),
      main: a.notMain !== true,
      registered: true,
      dims: cleanDims(a.dims),
      roles: []
    });
  }
  const roleByKey = /* @__PURE__ */ new Map();
  for (const r of roleItems) {
    const accountNumber = String(r.accountNumber);
    const roleName = String(r.roleName);
    const role = {
      accountNumber,
      roleName,
      roleArn: str(r.roleArn) ?? `arn:aws:iam::${accountNumber}:role/${roleName}`,
      displayName: str(r.displayName),
      description: str(r.description),
      icon: str(r.icon),
      color: str(r.color),
      policyTier: str(r.policyTier),
      profileName: str(r.profileName),
      sessionDurationSeconds: num(r.sessionDurationSeconds),
      sortOrder: num(r.sortOrder)
    };
    let account = byNumber.get(accountNumber);
    if (!account) {
      account = { accountNumber, main: true, registered: false, roles: [] };
      byNumber.set(accountNumber, account);
    }
    account.roles.push(role);
    roleByKey.set(roleKey(accountNumber, roleName), role);
  }
  const accounts = [...byNumber.values()].sort(compareAccounts);
  for (const a of accounts) a.roles.sort(compareRoles);
  const groups = groupItems.filter((g) => typeof g.groupId === "string" && typeof g.name === "string").map((g) => ({ groupId: g.groupId, name: g.name, description: str(g.description) })).sort((a, b) => a.name.localeCompare(b.name));
  log5("catalog index built", {
    version,
    accounts: accounts.length,
    roles: roleByKey.size,
    groups: groups.length,
    ms: Date.now() - started
  });
  return {
    version,
    builtAt: Date.now(),
    accounts,
    byNumber,
    roleByKey,
    groups,
    groupName: new Map(groups.map((g) => [g.groupId, g.name]))
  };
}
async function ensureVersionRow() {
  try {
    await ddb5.send(
      new import_lib_dynamodb5.PutCommand({
        TableName: RESOURCES_TABLE_NAME,
        Item: { resourceId: CATALOG_VERSION_KEY, version: 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString() },
        ConditionExpression: "attribute_not_exists(resourceId)"
      })
    );
    return 1;
  } catch (err) {
    if (err.name !== "ConditionalCheckFailedException") throw err;
    return await readVersion() ?? 1;
  }
}
async function catalog() {
  let version = await readVersion();
  if (cached && version !== void 0 && cached.version === version) return cached;
  if (!building) {
    if (version === void 0) version = await ensureVersionRow();
    building = build(version).then((c) => {
      cached = c;
      return c;
    }).finally(() => {
      building = void 0;
    });
  }
  return building;
}
async function bumpCatalogVersion() {
  cached = void 0;
  try {
    await ddb5.send(
      new import_lib_dynamodb5.UpdateCommand({
        TableName: RESOURCES_TABLE_NAME,
        Key: { resourceId: CATALOG_VERSION_KEY },
        UpdateExpression: "ADD #v :one SET updatedAt = :now",
        ExpressionAttributeNames: { "#v": "version" },
        ExpressionAttributeValues: { ":one": 1, ":now": (/* @__PURE__ */ new Date()).toISOString() }
      })
    );
  } catch (err) {
    log5("ERROR: catalog version bump failed \u2014 other containers list stale until the next write", {
      error: err.message
    });
  }
}
var import_client_dynamodb5, import_lib_dynamodb5, ddb5, ACCOUNTS_TABLE_NAME, ROLES_TABLE_NAME, GROUPS_TABLE_NAME, RESOURCES_TABLE_NAME, CATALOG_VERSION_KEY, log5, roleKey, cached, building, str, num;
var init_catalogIndex = __esm({
  "lambdacode/api/services/catalogIndex.ts"() {
    "use strict";
    import_client_dynamodb5 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb5 = require("@aws-sdk/lib-dynamodb");
    init_accountOrder();
    init_dimensions();
    ddb5 = import_lib_dynamodb5.DynamoDBDocumentClient.from(new import_client_dynamodb5.DynamoDBClient({}));
    ACCOUNTS_TABLE_NAME = process.env.ACCOUNTS_TABLE_NAME;
    ROLES_TABLE_NAME = process.env.ROLES_TABLE_NAME;
    GROUPS_TABLE_NAME = process.env.GROUPS_TABLE_NAME;
    RESOURCES_TABLE_NAME = process.env.RESOURCES_TABLE_NAME;
    CATALOG_VERSION_KEY = "__catalog-version__";
    log5 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    roleKey = (accountNumber, roleName) => `${accountNumber}#${roleName}`;
    str = (v) => typeof v === "string" && v ? v : void 0;
    num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
  }
});

// lambdacode/api/services/groupsService.ts
async function bundlesAndMembers() {
  const targets = /* @__PURE__ */ new Map();
  const members = /* @__PURE__ */ new Map();
  for (const r of await scanAll()) {
    const p = parsePrincipal(r.principal);
    if (p?.kind === "group") {
      const list = targets.get(p.groupId) ?? [];
      list.push(r.target);
      targets.set(p.groupId, list);
    } else if (p?.kind === "user" && r.target.startsWith("member#")) {
      const g = r.target.slice("member#".length);
      const list = members.get(g) ?? [];
      list.push(p.userId);
      members.set(g, list);
    }
  }
  return { targets, members };
}
function toGroup(row, targets, members) {
  const roles = [];
  const resources = [];
  const plugins = [];
  for (const t of targets) {
    const p = parseTarget(t);
    if (p?.kind === "role") roles.push({ accountNumber: p.accountNumber, roleName: p.roleName });
    else if (p?.kind === "resource") resources.push(p.resourceId);
    else if (p?.kind === "plugin") plugins.push({ pluginId: p.pluginId, accountNumber: p.accountNumber, permission: p.permission });
  }
  return {
    groupId: row.groupId,
    name: row.name,
    description: row.description,
    roles,
    resources,
    plugins,
    members: [...members].sort(),
    createdAt: row.createdAt,
    createdBy: row.createdBy,
    ...row.reviewedAt ? { reviewedAt: row.reviewedAt } : {}
  };
}
async function markGroupReviewed(groupId, adminUserId) {
  try {
    await ddb6.send(
      new import_lib_dynamodb6.UpdateCommand({
        TableName: GROUPS_TABLE_NAME2,
        Key: { groupId },
        UpdateExpression: "SET reviewedAt = :at, reviewedBy = :by",
        ExpressionAttributeValues: { ":at": (/* @__PURE__ */ new Date()).toISOString(), ":by": adminUserId },
        ConditionExpression: "attribute_exists(groupId)"
      })
    );
  } catch (err) {
    if (err.name === "ConditionalCheckFailedException") throw new NotFoundError(`Group ${groupId} not found`);
    throw err;
  }
  log6("group reviewed", { groupId, by: adminUserId });
}
async function listGroups() {
  const [rows, { targets, members }] = await Promise.all([scanAllGroups(), bundlesAndMembers()]);
  return rows.map((r) => toGroup(r, targets.get(r.groupId) ?? [], members.get(r.groupId) ?? [])).sort((a, b) => a.name.localeCompare(b.name));
}
async function getGroup(groupId) {
  const row = await getGroupRow(groupId);
  const [targets, memberRows] = await Promise.all([
    queryPrincipal(groupPrincipal(groupId)),
    queryTarget(memberTarget(groupId))
  ]);
  return toGroup(
    row,
    targets.map((t) => t.target),
    memberRows.map((r) => parsePrincipal(r.principal)).filter((p) => p?.kind === "user").map((p) => p.userId)
  );
}
async function createGroup(name, roles, createdBy, description, resources) {
  const cleanName = validateName(name);
  const cleanDescription = validateDescription(description);
  const roleKeys = await validateRoles(roles ?? []);
  const resourceIds = await validateResources(resources ?? []);
  if (roleKeys.length === 0 && resourceIds.length === 0) {
    throw new ValidationError("a group needs at least one role or resource");
  }
  await assertNameFree(cleanName);
  const row = {
    groupId: (0, import_crypto3.randomUUID)(),
    name: cleanName,
    ...cleanDescription ? { description: cleanDescription } : {},
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    createdBy
  };
  await ddb6.send(new import_lib_dynamodb6.PutCommand({ TableName: GROUPS_TABLE_NAME2, Item: row }));
  await bumpCatalogVersion();
  const grantedAt = row.createdAt;
  for (const t of [...roleKeys, ...resourceIds.map(resourceTarget)]) {
    await putRow({ principal: groupPrincipal(row.groupId), target: t, grantedBy: createdBy, grantedAt });
  }
  await recordEvent({
    category: "catalog",
    action: "group.create",
    subject: { kind: "group", id: row.groupId, name: cleanName },
    target: groupTarget(row.groupId),
    targetName: cleanName,
    details: { roles: roleKeys.length, resources: resourceIds.length }
  });
  log6("created group", { groupId: row.groupId, name: cleanName, roles: roleKeys, resources: resourceIds });
  return toGroup(row, [...roleKeys, ...resourceIds.map(resourceTarget)], []);
}
async function updateGroup(groupId, fields, adminUserId) {
  const current = await getGroup(groupId);
  const row = await getGroupRow(groupId);
  const next = { ...row };
  if (fields.name !== void 0) {
    next.name = validateName(fields.name);
    if (next.name.toLowerCase() !== row.name.toLowerCase()) await assertNameFree(next.name);
  }
  if (fields.description !== void 0) {
    const clean = validateDescription(fields.description);
    if (clean) next.description = clean;
    else delete next.description;
  }
  const roleKeys = fields.roles !== void 0 ? await validateRoles(fields.roles) : current.roles.map(toKey);
  const resourceIds = fields.resources !== void 0 ? await validateResources(fields.resources) : current.resources;
  const pluginKeys = current.plugins.map((p) => pluginTarget(p.pluginId, p.accountNumber, p.permission));
  const wanted = /* @__PURE__ */ new Set([...roleKeys, ...resourceIds.map(resourceTarget), ...pluginKeys]);
  if (wanted.size === 0) {
    throw new ValidationError("a group needs at least one role, resource or plugin permission");
  }
  const have = /* @__PURE__ */ new Set([...current.roles.map(toKey), ...current.resources.map(resourceTarget), ...pluginKeys]);
  const added = [...wanted].filter((t) => !have.has(t));
  const removed = [...have].filter((t) => !wanted.has(t));
  const batchId = newBatchId();
  let changes = [];
  await withAccessDiff(
    added.length || removed.length ? current.members : [],
    "GROUP",
    async () => {
      const grantedAt = (/* @__PURE__ */ new Date()).toISOString();
      for (const t of added) {
        await putRow({ principal: groupPrincipal(groupId), target: t, grantedBy: adminUserId, grantedAt });
      }
      for (const t of removed) await deleteRow(groupPrincipal(groupId), t);
    },
    void 0,
    { batchId, groupId, groupName: current.name, onDiff: (c) => changes = c, targets: [...added, ...removed] }
  );
  if (removed.length) await clearPendingGroupReviews(groupId);
  await ddb6.send(new import_lib_dynamodb6.PutCommand({ TableName: GROUPS_TABLE_NAME2, Item: next }));
  await bumpCatalogVersion();
  const changed = {};
  if (next.name !== row.name) changed.name = { from: row.name, to: next.name };
  if (next.description !== row.description) changed.description = { from: row.description ?? null, to: next.description ?? null };
  const subject = { kind: "group", id: groupId, name: next.name };
  await recordEvents([
    ...Object.keys(changed).length ? [{ category: "catalog", action: "group.update", subject, target: groupTarget(groupId), targetName: next.name, details: { changed } }] : [],
    ...added.map(
      (t) => bundleEvent("group.bundle.add", subject, t, {
        batchId,
        affected: affectedOf(changes, { target: t, change: "gained" }),
        unchanged: unchangedOf(changes, { target: t, change: "gained" })
      })
    ),
    ...removed.map(
      (t) => bundleEvent("group.bundle.remove", subject, t, {
        batchId,
        affected: affectedOf(changes, { target: t, change: "lost" }),
        unchanged: unchangedOf(changes, { target: t, change: "lost" })
      })
    )
  ]);
  log6("updated group", { groupId, name: next.name, added, removed });
  return toGroup(next, [...wanted], current.members);
}
async function addGroupRole(groupId, role, adminUserId) {
  const [row, [target]] = await Promise.all([getGroupRow(groupId), validateRoles([role])]);
  const change = { groupId, name: row.name, role: { accountNumber: role.accountNumber, roleName: role.roleName } };
  if (await getRow(groupPrincipal(groupId), target)) return { ...change, added: false };
  const members = await membersOf(groupId);
  const batchId = newBatchId();
  let changes = [];
  try {
    await withAccessDiff(
      members,
      "GROUP",
      async () => {
        const written = await putRowIfAbsent({ principal: groupPrincipal(groupId), target, grantedBy: adminUserId, grantedAt: (/* @__PURE__ */ new Date()).toISOString() });
        if (!written) throw new AlreadyBundled();
      },
      void 0,
      { batchId, groupId, groupName: row.name, onDiff: (c) => changes = c, targets: [target] }
    );
  } catch (err) {
    if (err instanceof AlreadyBundled) return { ...change, added: false };
    throw err;
  }
  await recordEvent(
    bundleEvent("group.bundle.add", { kind: "group", id: groupId, name: row.name }, target, {
      batchId,
      affected: affectedOf(changes, { target, change: "gained" }),
      unchanged: unchangedOf(changes, { target, change: "gained" })
    })
  );
  log6("added role to group", { groupId, target });
  return { ...change, added: true };
}
async function suggestGroupsForRole(accountNumber, roleName) {
  const index = await catalog();
  const dims = index.byNumber.get(accountNumber)?.dims;
  if (!dims) return [];
  const siblings = new Set(
    index.accounts.filter((a) => a.accountNumber !== accountNumber && a.dims?.tenant === dims.tenant && a.dims?.stage === dims.stage).map((a) => a.accountNumber)
  );
  if (!siblings.size) return [];
  const { targets } = await bundlesAndMembers();
  const out = [];
  for (const [groupId, bundled2] of targets) {
    const name = index.groupName.get(groupId);
    if (!name) continue;
    let n = 0;
    for (const t of bundled2) {
      const p = parseTarget(t);
      if (p?.kind === "role" && p.roleName === roleName && siblings.has(p.accountNumber)) n++;
    }
    if (n) out.push({ groupId, name, siblingAccounts: n });
  }
  return out.sort((a, b) => b.siblingAccounts - a.siblingAccounts || a.name.localeCompare(b.name)).slice(0, 10);
}
async function addGroupRoles(groupId, roles, adminUserId) {
  const current = await getGroup(groupId);
  const index = await catalog();
  const have = targetsOf(current);
  const targets = [];
  for (const r of roles) {
    if (!index.roleByKey.has(roleKey(r.accountNumber, r.roleName))) {
      throw new NotFoundError(`Role ${r.roleName} not found in account ${r.accountNumber}`);
    }
    const t = toKey(r);
    if (!have.has(t) && !targets.includes(t)) targets.push(t);
  }
  if (targets.length === 0) return { group: current, added: 0, skipped: roles.length };
  const batchId = newBatchId();
  let changes = [];
  const written = [];
  await withAccessDiff(
    current.members,
    "GROUP",
    async () => {
      const grantedAt = (/* @__PURE__ */ new Date()).toISOString();
      for (let i = 0; i < targets.length; i += 25) {
        const results = await Promise.all(
          targets.slice(i, i + 25).map(async (target) => ({
            target,
            written: await putRowIfAbsent({ principal: groupPrincipal(groupId), target, grantedBy: adminUserId, grantedAt })
          }))
        );
        for (const r of results) if (r.written) written.push(r.target);
      }
    },
    void 0,
    { batchId, groupId, groupName: current.name, onDiff: (c) => changes = c, targets }
  );
  const subject = { kind: "group", id: groupId, name: current.name };
  await recordEvents(
    written.map(
      (t) => bundleEvent("group.bundle.add", subject, t, {
        batchId,
        affected: affectedOf(changes, { target: t, change: "gained" }),
        unchanged: unchangedOf(changes, { target: t, change: "gained" })
      })
    )
  );
  log6("added roles to group", { groupId, requested: roles.length, added: written.length });
  return {
    group: toGroup(rowOf(current), [...have, ...written], current.members),
    added: written.length,
    skipped: roles.length - written.length
  };
}
async function removeGroupRole(groupId, role) {
  const row = await getGroupRow(groupId);
  const target = toKey(role);
  const change = { groupId, name: row.name, role: { accountNumber: role.accountNumber, roleName: role.roleName } };
  const existing = await getRow(groupPrincipal(groupId), target);
  if (!existing) return { ...change, removed: false };
  const another = { except: target, kinds: isBundleTarget };
  if (!await hasGrantTargetBesides(groupPrincipal(groupId), another)) {
    throw new ValidationError("a group needs at least one role, resource or plugin permission \u2014 delete the group instead");
  }
  const members = await membersOf(groupId);
  const batchId = newBatchId();
  let changes = [];
  const removed = await withAccessDiff(
    members,
    "GROUP",
    async () => {
      const gone = await deleteRow(groupPrincipal(groupId), target);
      if (gone && !await hasGrantTargetBesides(groupPrincipal(groupId), { ...another, consistent: true })) {
        await putRow(existing);
        throw new ValidationError("a group needs at least one role, resource or plugin permission \u2014 delete the group instead");
      }
      return gone;
    },
    void 0,
    { batchId, groupId, groupName: row.name, onDiff: (c) => changes = c, targets: [target] }
  );
  if (removed) {
    await clearPendingGroupReviews(groupId);
    await recordEvent(
      bundleEvent("group.bundle.remove", { kind: "group", id: groupId, name: row.name }, target, {
        batchId,
        affected: affectedOf(changes, { target, change: "lost" }),
        unchanged: unchangedOf(changes, { target, change: "lost" })
      })
    );
    log6("removed role from group", { groupId, target });
  }
  return { ...change, removed };
}
async function deleteGroup(groupId) {
  const group = await getGroup(groupId);
  const batchId = newBatchId();
  let changes = [];
  await withAccessDiff(
    group.members,
    "GROUP",
    async () => {
      for (const r of await queryPrincipal(groupPrincipal(groupId))) await deleteRow(r.principal, r.target);
      for (const u of group.members) await deleteRow(userPrincipal(u), memberTarget(groupId));
    },
    void 0,
    { batchId, groupId, groupName: group.name, onDiff: (c) => changes = c }
  );
  await ddb6.send(new import_lib_dynamodb6.DeleteCommand({ TableName: GROUPS_TABLE_NAME2, Key: { groupId } }));
  await bumpCatalogVersion();
  const { deleteRequestsForUser: deleteRequestsForUser2 } = (init_requestsService(), __toCommonJS(requestsService_exports));
  await deleteRequestsForUser2(groupId, { onlyPending: true });
  await recordEvent({
    category: "catalog",
    action: "group.delete",
    subject: { kind: "group", id: groupId, name: group.name },
    target: groupTarget(groupId),
    targetName: group.name,
    details: { members: group.members.length, batchId, affected: affectedOf(changes, { change: "lost" }), unchanged: unchangedOf(changes, { change: "lost" }) }
  });
  log6("deleted group", { groupId, name: group.name, members: group.members.length });
}
async function groupHoldingTarget(groupId, target) {
  const group = await getGroup(groupId);
  if (!targetsOf(group).has(target)) {
    throw new NotFoundError(`Group ${groupId} does not hold ${target}`);
  }
  return group;
}
async function revokeGroupTarget(groupId, target) {
  const group = await groupHoldingTarget(groupId, target);
  if (targetsOf(group).size === 1) {
    await deleteGroup(groupId);
    return;
  }
  const batchId = newBatchId();
  let changes = [];
  await withAccessDiff(
    group.members,
    "GROUP",
    async () => {
      await deleteRow(groupPrincipal(groupId), target);
    },
    void 0,
    { batchId, groupId, groupName: group.name, onDiff: (c) => changes = c }
  );
  await clearPendingGroupReviews(groupId);
  await recordEvent(
    bundleEvent("group.bundle.remove", { kind: "group", id: groupId, name: group.name }, target, {
      via: "REAPPROVAL",
      batchId,
      affected: affectedOf(changes, { target, change: "lost" }),
      unchanged: unchangedOf(changes, { target, change: "lost" })
    })
  );
  log6("revoked group target", { groupId, name: group.name, target });
}
async function restampGroupTarget(groupId, target, adminUserId) {
  const group = await groupHoldingTarget(groupId, target);
  await putRow({
    principal: groupPrincipal(groupId),
    target,
    grantedBy: adminUserId,
    grantedAt: (/* @__PURE__ */ new Date()).toISOString()
  });
  log6("restamped group target", { groupId, name: group.name, target });
}
async function clearPendingGroupReviews(groupId) {
  const { deleteRequestsForUser: deleteRequestsForUser2 } = (init_requestsService(), __toCommonJS(requestsService_exports));
  await deleteRequestsForUser2(groupId, { onlyPending: true, exceptKinds: ["GROUP"] });
}
async function addMembers(groupId, userIds, adminUserId) {
  const { name } = await getGroupRow(groupId);
  const current = new Set(
    (await queryTarget(memberTarget(groupId))).map((r) => parsePrincipal(r.principal)).filter((p) => p?.kind === "user").map((p) => p.userId)
  );
  const toAdd = [...new Set(userIds)].filter((u) => u && !current.has(u));
  const addedAt = (/* @__PURE__ */ new Date()).toISOString();
  const batchId = newBatchId();
  let changes = [];
  await withAccessDiff(
    toAdd,
    "GROUP",
    async () => {
      for (const userId of toAdd) {
        await putRow({ principal: userPrincipal(userId), target: memberTarget(groupId), addedBy: adminUserId, addedAt });
      }
    },
    void 0,
    { batchId, groupId, groupName: name, onDiff: (c) => changes = c }
  );
  const bundle = (await queryPrincipal(groupPrincipal(groupId))).map((r) => r.target);
  await recordEvents(
    toAdd.map((userId) => {
      const mine = changes.filter((c) => c.userId === userId);
      const gained = new Set(mine.flatMap((c) => c.gained));
      return memberEvent("group.member.add", userId, groupId, name, batchId, affectedOf(mine, { change: "gained" }), bundle.filter((t) => !gained.has(t)));
    })
  );
  if (toAdd.length) log6("added group members", { groupId, added: toAdd.length });
  return toAdd.length;
}
async function removeMembers(groupId, userIds) {
  const { name } = await getGroupRow(groupId);
  const unique = [...new Set(userIds)].filter(Boolean);
  const removed = [];
  const batchId = newBatchId();
  let changes = [];
  await withAccessDiff(
    unique,
    "GROUP",
    async () => {
      for (const userId of unique) {
        if (await deleteRow(userPrincipal(userId), memberTarget(groupId))) removed.push(userId);
      }
    },
    void 0,
    { batchId, groupId, groupName: name, onDiff: (c) => changes = c }
  );
  const bundle = (await queryPrincipal(groupPrincipal(groupId))).map((r) => r.target);
  await recordEvents(
    removed.map((userId) => {
      const mine = changes.filter((c) => c.userId === userId);
      const lost = new Set(mine.flatMap((c) => c.lost));
      return memberEvent("group.member.remove", userId, groupId, name, batchId, affectedOf(mine, { change: "lost" }), bundle.filter((t) => !lost.has(t)));
    })
  );
  if (removed.length) log6("removed group members", { groupId, removed: removed.length });
  return removed.length;
}
async function removeUserFromAllGroups(userId) {
  const rows = await queryPrincipal(userPrincipal(userId), "member#");
  for (const r of rows) await deleteRow(r.principal, r.target);
  if (rows.length) log6("removed deleted user from groups", { userId, touched: rows.length });
  return rows.length;
}
async function removeRoleFromAllGroups(accountNumber, roleName) {
  return removeTargetFromGroups(roleTarget(accountNumber, roleName));
}
async function removeResourceFromAllGroups(resourceId) {
  return removeTargetFromGroups(resourceTarget(resourceId));
}
async function removeTargetFromGroups(target) {
  const rows = (await queryTarget(target)).filter((r) => r.principal.startsWith("group#"));
  for (const r of rows) await deleteRow(r.principal, r.target);
  if (rows.length) log6("stripped deleted target from groups", { target, touched: rows.length });
  return rows.length;
}
async function groupsBundling(target) {
  return (await queryTarget(target)).filter((r) => r.principal.startsWith("group#")).map((r) => r.principal.slice("group#".length));
}
async function deleteGroupsLeftEmpty(groupIds) {
  let removed = 0;
  for (const groupId of new Set(groupIds)) {
    if (await hasGrantTargetBesides(groupPrincipal(groupId))) continue;
    try {
      await deleteGroup(groupId);
      removed++;
    } catch (err) {
      if (!(err instanceof NotFoundError)) throw err;
    }
  }
  return removed;
}
async function assertGroupExists(groupId) {
  await getGroupRow(groupId);
}
async function getGroupRow(groupId) {
  const res = await ddb6.send(new import_lib_dynamodb6.GetCommand({ TableName: GROUPS_TABLE_NAME2, Key: { groupId } }));
  if (!res.Item) throw new NotFoundError(`Group ${groupId} not found`);
  return res.Item;
}
async function scanAllGroups() {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb6.send(new import_lib_dynamodb6.ScanCommand({ TableName: GROUPS_TABLE_NAME2, ExclusiveStartKey }));
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
function validateName(name) {
  const clean = typeof name === "string" ? name.trim() : "";
  if (!clean || clean.length > NAME_MAX) {
    throw new ValidationError(`name is required and must be ${NAME_MAX} characters or fewer`);
  }
  return clean;
}
function validateDescription(description) {
  if (description === void 0 || description === null) return void 0;
  if (typeof description !== "string" || description.length > DESCRIPTION_MAX) {
    throw new ValidationError(`description must be ${DESCRIPTION_MAX} characters or fewer`);
  }
  return description.trim() || void 0;
}
async function validateRoles(roles) {
  if (!Array.isArray(roles)) throw new ValidationError("roles must be an array");
  const keys = [];
  for (const r of roles) {
    if (!r?.accountNumber || !r?.roleName) {
      throw new ValidationError("each role needs accountNumber and roleName");
    }
    const key = toKey(r);
    if (keys.includes(key)) continue;
    const found = await ddb6.send(
      new import_lib_dynamodb6.GetCommand({ TableName: ROLES_TABLE_NAME2, Key: { accountNumber: r.accountNumber, roleName: r.roleName } })
    );
    if (!found.Item) throw new NotFoundError(`Role ${r.roleName} not found in account ${r.accountNumber}`);
    keys.push(key);
  }
  return keys;
}
async function validateResources(resources) {
  if (!Array.isArray(resources)) throw new ValidationError("resources must be an array");
  const ids = [];
  for (const resourceId of resources) {
    if (!resourceId || typeof resourceId !== "string") {
      throw new ValidationError("each resource needs a resourceId");
    }
    if (ids.includes(resourceId)) continue;
    const found = isSentinelRow(resourceId) ? void 0 : await ddb6.send(new import_lib_dynamodb6.GetCommand({ TableName: RESOURCES_TABLE_NAME2, Key: { resourceId } }));
    if (!found?.Item) throw new NotFoundError(`Resource ${resourceId} not found`);
    ids.push(resourceId);
  }
  return ids;
}
async function assertNameFree(name) {
  const rows = await scanAllGroups();
  if (rows.some((g) => g.name.toLowerCase() === name.toLowerCase())) {
    throw new ConflictError(`A group named "${name}" already exists`);
  }
}
var import_crypto3, import_client_dynamodb6, import_lib_dynamodb6, ddb6, GROUPS_TABLE_NAME2, ROLES_TABLE_NAME2, RESOURCES_TABLE_NAME2, log6, NAME_MAX, DESCRIPTION_MAX, toKey, memberEvent, bundleEvent, AlreadyBundled, rowOf, isBundleTarget, targetsOf;
var init_groupsService = __esm({
  "lambdacode/api/services/groupsService.ts"() {
    "use strict";
    import_crypto3 = require("crypto");
    import_client_dynamodb6 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb6 = require("@aws-sdk/lib-dynamodb");
    init_httpErrors();
    init_access2();
    init_accessNotices();
    init_auditService();
    init_catalogIndex();
    init_resourcesService();
    ddb6 = import_lib_dynamodb6.DynamoDBDocumentClient.from(new import_client_dynamodb6.DynamoDBClient({}));
    GROUPS_TABLE_NAME2 = process.env.GROUPS_TABLE_NAME;
    ROLES_TABLE_NAME2 = process.env.ROLES_TABLE_NAME;
    RESOURCES_TABLE_NAME2 = process.env.RESOURCES_TABLE_NAME;
    log6 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    NAME_MAX = 60;
    DESCRIPTION_MAX = 200;
    toKey = (r) => roleTarget(r.accountNumber, r.roleName);
    memberEvent = (action, userId, groupId, groupName, batchId, affected, alreadyHeld) => ({
      category: "access",
      action,
      subject: { kind: "user", id: userId },
      target: groupTarget(groupId),
      targetName: groupName,
      details: { groupId, batchId, affected, ...alreadyHeld.length ? { alreadyHeld } : {} }
    });
    bundleEvent = (action, subject, target, details) => {
      const p = parseTarget(target);
      return { category: "access", action, subject, target, targetName: p?.kind === "role" ? p.roleName : void 0, details };
    };
    AlreadyBundled = class extends Error {
    };
    rowOf = (g) => ({
      groupId: g.groupId,
      name: g.name,
      ...g.description ? { description: g.description } : {},
      createdAt: g.createdAt,
      createdBy: g.createdBy,
      ...g.reviewedAt ? { reviewedAt: g.reviewedAt } : {}
    });
    isBundleTarget = (t) => t.startsWith("role#") || t.startsWith("resource#") || t.startsWith("plugin#");
    targetsOf = (group) => /* @__PURE__ */ new Set([
      ...group.roles.map(toKey),
      ...group.resources.map(resourceTarget),
      ...group.plugins.map((p) => pluginTarget(p.pluginId, p.accountNumber, p.permission))
    ]);
  }
});

// lambdacode/api/services/resourcesService.ts
function normalizeCidr(raw) {
  const m = raw.trim().match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?$/);
  if (!m) throw new ValidationError("Address must be an IPv4 address or CIDR");
  const octets = m.slice(1, 5).map(Number);
  if (octets.some((o) => o > 255)) {
    throw new ValidationError("Address must be an IPv4 address or CIDR");
  }
  const prefix = m[5] === void 0 ? 32 : Number(m[5]);
  if (prefix < 16 || prefix > 32) {
    throw new ValidationError("CIDR prefix must be between /16 and /32");
  }
  const base = (octets[0] << 24 | octets[1] << 16 | octets[2] << 8 | octets[3]) >>> 0;
  const mask = prefix === 0 ? 0 : ~0 << 32 - prefix >>> 0;
  if ((base & ~mask) >>> 0 !== 0) {
    throw new ValidationError(
      `Host bits must be zero for /${prefix} (e.g. 10.0.1.0/${prefix})`
    );
  }
  return `${octets.join(".")}/${prefix}`;
}
function validatePorts(raw) {
  if (!Array.isArray(raw) || raw.length === 0) {
    throw new ValidationError("At least one port is required");
  }
  const ports = [...new Set(raw)];
  if (ports.length > 10) {
    throw new ValidationError("At most 10 ports per resource");
  }
  for (const p of ports) {
    if (!Number.isInteger(p) || p < 1 || p > 65535) {
      throw new ValidationError("Ports must be integers between 1 and 65535");
    }
  }
  return ports.sort((a, b) => a - b);
}
function validateCommon(fields) {
  if (fields.name !== void 0) {
    if (typeof fields.name !== "string" || !fields.name.trim() || fields.name.trim().length > 100) {
      throw new ValidationError("Name must be 1-100 characters");
    }
  }
  if (fields.type !== void 0 && !RESOURCE_TYPES.includes(fields.type)) {
    throw new ValidationError(`Type must be one of ${RESOURCE_TYPES.join(", ")}`);
  }
  if (fields.dnsName !== void 0 && fields.dnsName !== "") {
    if (typeof fields.dnsName !== "string" || fields.dnsName.length > 253 || !HOSTNAME_RE.test(fields.dnsName)) {
      throw new ValidationError("DNS name must be a valid hostname");
    }
  }
  if (fields.sshUser !== void 0 && fields.sshUser !== "") {
    if (typeof fields.sshUser !== "string" || !SSH_USER_RE.test(fields.sshUser)) {
      throw new ValidationError("SSH user must be a valid unix username");
    }
  }
  if (fields.securityGroupId !== void 0 && fields.securityGroupId !== "") {
    if (typeof fields.securityGroupId !== "string" || !SG_ID_RE.test(fields.securityGroupId)) {
      throw new ValidationError(
        "Security group ID must look like sg-0123456789abcdef0"
      );
    }
  }
  if (fields.description !== void 0 && fields.description !== "") {
    if (typeof fields.description !== "string" || fields.description.length > 1e3) {
      throw new ValidationError(
        "Description must be a string of at most 1000 characters"
      );
    }
  }
}
function toResource(it) {
  return {
    resourceId: it.resourceId,
    accountNumber: it.accountNumber,
    name: it.name,
    type: it.type,
    cidr: it.cidr,
    ports: it.ports,
    dnsName: it.dnsName,
    sshUser: it.sshUser,
    securityGroupId: it.securityGroupId,
    description: it.description,
    createdAt: it.createdAt,
    createdBy: it.createdBy
  };
}
async function listResources() {
  const items = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb7.send(
      new import_lib_dynamodb7.ScanCommand({ TableName: RESOURCES_TABLE_NAME3, ExclusiveStartKey })
    );
    items.push(...page.Items ?? []);
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return items.filter((it) => !isSentinelRow(it.resourceId)).map(toResource).sort((a, b) => a.name.localeCompare(b.name));
}
async function getResource(resourceId) {
  if (isSentinelRow(resourceId)) {
    throw new NotFoundError(`Resource ${resourceId} not found`);
  }
  const res = await ddb7.send(
    new import_lib_dynamodb7.GetCommand({ TableName: RESOURCES_TABLE_NAME3, Key: { resourceId } })
  );
  if (!res.Item) throw new NotFoundError(`Resource ${resourceId} not found`);
  return toResource(res.Item);
}
async function createResource(input, createdBy) {
  validateCommon(input);
  if (input.name === void 0) throw new ValidationError("Name is required");
  if (input.type === void 0) throw new ValidationError("Type is required");
  const cidr = normalizeCidr(String(input.cidr ?? ""));
  const ports = validatePorts(input.ports);
  const acct = await ddb7.send(
    new import_lib_dynamodb7.GetCommand({
      TableName: ACCOUNTS_TABLE_NAME2,
      Key: { accountNumber: input.accountNumber }
    })
  );
  if (!acct.Item) {
    throw new NotFoundError(`Account ${input.accountNumber} not found`);
  }
  const resource = {
    resourceId: (0, import_crypto4.randomUUID)(),
    accountNumber: input.accountNumber,
    name: input.name.trim(),
    type: input.type,
    cidr,
    ports,
    ...input.dnsName ? { dnsName: input.dnsName } : {},
    ...input.sshUser ? { sshUser: input.sshUser } : {},
    ...input.securityGroupId ? { securityGroupId: input.securityGroupId } : {},
    ...input.description ? { description: input.description } : {},
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    createdBy
  };
  try {
    await ddb7.send(
      new import_lib_dynamodb7.PutCommand({
        TableName: RESOURCES_TABLE_NAME3,
        Item: compact2({ ...resource }),
        ConditionExpression: "attribute_not_exists(resourceId)"
      })
    );
  } catch (err) {
    if (err.name === CONDITION_FAILED3) {
      throw new ConflictError(`Resource ${resource.resourceId} already exists`);
    }
    throw err;
  }
  await recordEvent({
    category: "catalog",
    action: "resource.create",
    target: resourceTarget(resource.resourceId),
    targetName: resource.name,
    accountNumber: resource.accountNumber
  });
  log7("created resource", {
    resourceId: resource.resourceId,
    accountNumber: resource.accountNumber,
    name: resource.name,
    cidr,
    ports,
    createdBy
  });
  return resource;
}
function buildUpdate(fields) {
  const names = {};
  const values = {};
  const sets = [];
  const removes = [];
  for (const [k, v] of Object.entries(fields)) {
    names[`#${k}`] = k;
    if (v === "") {
      removes.push(`#${k}`);
      continue;
    }
    values[`:${k}`] = v;
    sets.push(`#${k} = :${k}`);
  }
  return {
    UpdateExpression: [
      sets.length ? `SET ${sets.join(", ")}` : "",
      removes.length ? `REMOVE ${removes.join(", ")}` : ""
    ].filter(Boolean).join(" "),
    ExpressionAttributeNames: names,
    ...Object.keys(values).length ? { ExpressionAttributeValues: values } : {}
  };
}
async function updateResource(resourceId, patch) {
  validateCommon(patch);
  const fields = compact2({
    name: patch.name?.trim(),
    type: patch.type,
    cidr: patch.cidr !== void 0 ? normalizeCidr(String(patch.cidr)) : void 0,
    ports: patch.ports !== void 0 ? validatePorts(patch.ports) : void 0,
    dnsName: patch.dnsName,
    sshUser: patch.sshUser,
    securityGroupId: patch.securityGroupId,
    description: patch.description
  });
  const current = (await ddb7.send(new import_lib_dynamodb7.GetCommand({ TableName: RESOURCES_TABLE_NAME3, Key: { resourceId } }))).Item;
  try {
    const res = await ddb7.send(
      new import_lib_dynamodb7.UpdateCommand({
        TableName: RESOURCES_TABLE_NAME3,
        Key: { resourceId },
        ...buildUpdate(fields),
        ConditionExpression: "attribute_exists(resourceId)",
        ReturnValues: "ALL_NEW"
      })
    );
    const updated = toResource(res.Attributes);
    const changed = changedFields(current, fields);
    if (Object.keys(changed).length) {
      await recordEvent({
        category: "catalog",
        action: "resource.update",
        target: resourceTarget(resourceId),
        targetName: updated.name,
        accountNumber: updated.accountNumber,
        details: { changed }
      });
    }
    log7("updated resource", { resourceId, fields: Object.keys(fields) });
    return updated;
  } catch (err) {
    if (err.name === CONDITION_FAILED3) {
      throw new NotFoundError(`Resource ${resourceId} not found`);
    }
    throw err;
  }
}
function changedFields(current, fields) {
  const changed = {};
  for (const [k, v] of Object.entries(fields)) {
    const from = current?.[k];
    const to = v === "" ? void 0 : v;
    if (JSON.stringify(from) !== JSON.stringify(to)) changed[k] = { from, to };
  }
  return changed;
}
async function deleteResource(resourceId) {
  const existing = await ddb7.send(
    new import_lib_dynamodb7.GetCommand({ TableName: RESOURCES_TABLE_NAME3, Key: { resourceId } })
  );
  const deletedName = existing.Item?.name;
  const accountNumber = existing.Item?.accountNumber;
  const batchId = newBatchId();
  let changes = [];
  const bundling = await groupsBundling(resourceTarget(resourceId));
  const revoked = await revokeAllForResource(resourceId, deletedName, batchId, (c) => changes = c);
  await removeResourceFromAllGroups(resourceId);
  await deleteGroupsLeftEmpty(bundling);
  const { closePendingRequestsFor: closePendingRequestsFor2 } = (init_requestsService(), __toCommonJS(requestsService_exports));
  const closedRequests = await closePendingRequestsFor2(
    resourceTarget(resourceId),
    `Resource ${deletedName ?? resourceId} was removed`
  );
  if (!existing.Item) {
    if (revoked || closedRequests) log7("re-swept deleted resource", { resourceId, revoked, closedRequests });
    throw new NotFoundError(`Resource ${resourceId} not found`);
  }
  try {
    await ddb7.send(
      new import_lib_dynamodb7.DeleteCommand({
        TableName: RESOURCES_TABLE_NAME3,
        Key: { resourceId },
        ConditionExpression: "attribute_exists(resourceId)"
      })
    );
  } catch (err) {
    if (err.name !== CONDITION_FAILED3) throw err;
    log7("resource deleted concurrently", { resourceId });
    throw new NotFoundError(`Resource ${resourceId} not found`);
  }
  await recordEvent({
    category: "catalog",
    action: "resource.delete",
    target: resourceTarget(resourceId),
    targetName: deletedName,
    accountNumber,
    details: { batchId, removedRows: revoked, closedRequests, affected: affectedOf(changes, { change: "lost" }), unchanged: unchangedOf(changes, { change: "lost" }) }
  });
  log7("deleted resource", { resourceId, revokedGrants: revoked });
}
var import_client_dynamodb7, import_lib_dynamodb7, import_crypto4, ddb7, RESOURCES_TABLE_NAME3, ACCOUNTS_TABLE_NAME2, log7, CONDITION_FAILED3, isSentinelRow, RESOURCE_TYPES, HOSTNAME_RE, SSH_USER_RE, SG_ID_RE, compact2;
var init_resourcesService = __esm({
  "lambdacode/api/services/resourcesService.ts"() {
    "use strict";
    import_client_dynamodb7 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb7 = require("@aws-sdk/lib-dynamodb");
    import_crypto4 = require("crypto");
    init_httpErrors();
    init_resourceGrantsService();
    init_groupsService();
    init_access2();
    init_auditService();
    init_accessNotices();
    ddb7 = import_lib_dynamodb7.DynamoDBDocumentClient.from(new import_client_dynamodb7.DynamoDBClient({}));
    RESOURCES_TABLE_NAME3 = process.env.RESOURCES_TABLE_NAME;
    ACCOUNTS_TABLE_NAME2 = process.env.ACCOUNTS_TABLE_NAME;
    log7 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    CONDITION_FAILED3 = "ConditionalCheckFailedException";
    isSentinelRow = (resourceId) => String(resourceId).startsWith("__");
    RESOURCE_TYPES = ["DATABASE", "WEB", "HOST"];
    HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    SSH_USER_RE = /^[a-z_][a-z0-9._-]{0,31}$/;
    SG_ID_RE = /^sg-[0-9a-f]{8,17}$/;
    compact2 = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
  }
});

// lambdacode/api/services/resourceGrantsService.ts
async function catalogRow(resourceId) {
  if (isSentinelRow(resourceId)) return void 0;
  const res = await ddb8.send(new import_lib_dynamodb8.GetCommand({ TableName: RESOURCES_TABLE_NAME4, Key: { resourceId } }));
  return res.Item;
}
async function assignResource(resourceId, userId, grantedBy, expiresAt, opts) {
  const resource = await catalogRow(resourceId);
  if (!resource) throw new NotFoundError(`Resource ${resourceId} not found`);
  const target = resourceTarget(resourceId);
  if (expiresAt) {
    const existing = await getRow(userPrincipal(userId), target);
    if (existing && !existing.expiresAt) {
      log8("kept long-term resource grant (no downgrade)", { userId, resourceId, requestedExpiresAt: expiresAt });
      return { resourceId, grantedBy: existing.grantedBy, grantedAt: existing.grantedAt };
    }
  }
  await withAccessDiff(
    [userId],
    "ADMIN",
    () => putRow({
      principal: userPrincipal(userId),
      target,
      grantedBy,
      grantedAt: (/* @__PURE__ */ new Date()).toISOString(),
      ...expiresAt ? { expiresAt } : {}
    }),
    nameMap(resourceId, resource.name),
    { derived: false, gainNotices: !opts?.fromRequestId }
  );
  await recordEvent({
    category: "access",
    action: "resource.grant",
    subject: { kind: "user", id: userId },
    target,
    targetName: resource.name,
    accountNumber: resource.accountNumber,
    details: { expiresAt, requestId: opts?.fromRequestId }
  });
  log8("assigned resource", { userId, resourceId, grantedBy, expiresAt });
  return { resourceId, grantedBy, expiresAt };
}
async function renewResourceGrant(resourceId, userId, grantedBy, opts) {
  const resource = await catalogRow(resourceId);
  if (!resource) throw new NotFoundError(`Resource ${resourceId} not found`);
  const target = resourceTarget(resourceId);
  const renewed = await updateExisting(userPrincipal(userId), target, {
    grantedBy,
    grantedAt: (/* @__PURE__ */ new Date()).toISOString()
  });
  if (!renewed) {
    throw new ConflictError(`${userId} no longer has access to ${resource.name} \u2014 there is nothing to renew`);
  }
  await recordEvent({
    category: "access",
    action: "resource.grant",
    subject: { kind: "user", id: userId },
    target,
    targetName: resource.name,
    accountNumber: resource.accountNumber,
    details: { requestId: opts?.fromRequestId, renewed: true }
  });
  log8("renewed resource grant", { userId, resourceId, grantedBy });
}
async function revokeResourceGrant(resourceId, userId, via = "ADMIN") {
  const resource = await catalogRow(resourceId);
  const removed = await revokeDirectRow(
    userId,
    resourceTarget(resourceId),
    via,
    { action: "resource.revoke", targetName: resource?.name, accountNumber: resource?.accountNumber },
    nameMap(resourceId, resource?.name)
  );
  if (!removed) throw new NotFoundError(`No grant for user ${userId} on resource ${resourceId}`);
  log8("revoked resource grant", { userId, resourceId });
}
async function listResourceGrantees(resourceId) {
  const holders = await holdersOf(resourceTarget(resourceId));
  return holders.map((h) => ({
    userId: h.userId,
    grantedBy: h.direct?.grantedBy,
    grantedAt: h.direct?.grantedAt,
    expiresAt: h.direct?.expiresAt,
    direct: Boolean(h.direct),
    viaGroup: h.direct ? void 0 : h.groups[0],
    viaGroups: h.groups
  }));
}
async function listUserResourceGrants(userId) {
  const out = [];
  for (const [t, e] of await effectiveAccess(userId)) {
    const p = parseTarget(t);
    if (p?.kind !== "resource") continue;
    out.push({
      resourceId: p.resourceId,
      grantedBy: e.direct?.grantedBy,
      grantedAt: e.direct?.grantedAt,
      expiresAt: e.groups.length ? void 0 : e.direct?.expiresAt,
      // effective
      viaGroup: e.direct ? void 0 : e.groups[0],
      viaGroups: e.groups
    });
  }
  return out;
}
async function revokeAllForResource(resourceId, resourceName, batchId, onDiff) {
  const target = resourceTarget(resourceId);
  const holders = await holdersOf(target);
  const rows = await queryTarget(target);
  await withAccessDiff(
    holders.map((h) => h.userId),
    "CASCADE",
    async () => {
      for (const r of rows) await deleteRow(r.principal, r.target);
    },
    nameMap(resourceId, resourceName),
    { batchId, onDiff }
  );
  if (rows.length) log8("revoked all grants for resource", { resourceId, count: rows.length });
  return rows.length;
}
async function revokeAllResourcesForUser(userId) {
  const rows = await queryPrincipal(userPrincipal(userId), "resource#");
  for (const r of rows) await deleteRow(r.principal, r.target);
  if (rows.length) log8("revoked all resource grants for user", { userId, count: rows.length });
  return rows.length;
}
async function listResourceExpiryNotices(userId) {
  const rows = await queryPrincipal(userPrincipal(userId), "resource#");
  return expiryPhases(rows, (t) => {
    const p = parseTarget(t);
    return p?.kind === "resource" ? { resourceId: p.resourceId } : null;
  });
}
async function markResourceExpiryNoticesSeen(userId) {
  const count = await markExpiryPhasesSeen(userId, await listResourceExpiryNotices(userId), (n) => resourceTarget(n.resourceId));
  if (count) log8("marked resource expiry notices seen", { userId, count });
  return count;
}
var import_client_dynamodb8, import_lib_dynamodb8, ddb8, RESOURCES_TABLE_NAME4, log8, nameMap;
var init_resourceGrantsService = __esm({
  "lambdacode/api/services/resourceGrantsService.ts"() {
    "use strict";
    import_client_dynamodb8 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb8 = require("@aws-sdk/lib-dynamodb");
    init_httpErrors();
    init_access2();
    init_accessNotices();
    init_auditService();
    init_grantsService();
    init_resourcesService();
    ddb8 = import_lib_dynamodb8.DynamoDBDocumentClient.from(new import_client_dynamodb8.DynamoDBClient({}));
    RESOURCES_TABLE_NAME4 = process.env.RESOURCES_TABLE_NAME;
    log8 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    nameMap = (resourceId, name) => name ? /* @__PURE__ */ new Map([[resourceId, name]]) : void 0;
  }
});

// lambdacode/api/services/pluginGrantsService.ts
function validatePluginGrantKey(key) {
  if (!PLUGIN_ID_PATTERN.test(key.pluginId)) throw new ValidationError("pluginId is not a valid plugin id");
  if (!AWS_ACCOUNT_PATTERN.test(key.accountNumber)) throw new ValidationError("accountNumber must be 12 digits");
  if (!PLUGIN_PERMISSIONS.includes(key.permission)) throw new ValidationError(`permission must be "user" or "admin"`);
}
function toAssignment(row, ctx) {
  const t = parseTarget(row.target);
  const p = parsePrincipal(row.principal);
  if (t?.kind !== "plugin" || !p) return null;
  const a = pluginAvailability(ctx.catalog.get(t.pluginId), t.accountNumber, t.permission, ctx.registeredAccounts);
  return {
    pluginId: t.pluginId,
    accountNumber: t.accountNumber,
    permission: t.permission,
    principal: p,
    grantedBy: row.grantedBy,
    grantedAt: row.grantedAt,
    expiresAt: row.expiresAt,
    expired: isExpired(row),
    ...a.available ? { available: true } : a
  };
}
async function assertPluginAssignable(key, ctx) {
  validatePluginGrantKey(key);
  const context = ctx ?? await loadPluginContext();
  const record = context.catalog.get(key.pluginId);
  if (!record) throw new NotFoundError(`Plugin ${key.pluginId} is not installed`);
  const a = pluginAvailability(record, key.accountNumber, key.permission, context.registeredAccounts);
  if (a.available) return context;
  if (a.reason === "permission-undeclared") {
    throw new ValidationError(`Plugin ${key.pluginId} does not declare the "${key.permission}" permission`);
  }
  if (a.reason === "account-unbound") {
    throw new NotFoundError(`Plugin ${key.pluginId} is not bound to account ${key.accountNumber}`);
  }
  throw new ConflictError(`Plugin ${key.pluginId} is not available for account ${key.accountNumber} (${a.reason})`);
}
async function assignPlugin(input, ctx) {
  if (input.expiresAt !== void 0) {
    if (input.principal.kind === "group") throw new ValidationError("group assignments are standing \u2014 no expiry");
    if (!(Date.parse(input.expiresAt) > Date.now())) throw new ValidationError("expiresAt must be in the future");
  }
  const context = await assertPluginAssignable(input, ctx);
  const principal = principalOf(input.principal);
  const target = pluginTarget(input.pluginId, input.accountNumber, input.permission);
  if (input.expiresAt) {
    const existing = await getRow(principal, target);
    if (existing && !existing.expiresAt) {
      log9("kept long-term plugin grant (no downgrade)", { principal, target, requestedExpiresAt: input.expiresAt });
      return toAssignment(existing, context);
    }
  }
  const row = {
    principal,
    target,
    grantedBy: input.grantedBy,
    grantedAt: (/* @__PURE__ */ new Date()).toISOString(),
    ...input.expiresAt ? { expiresAt: input.expiresAt } : {}
  };
  const targetName = context.catalog.get(input.pluginId)?.manifest.displayName;
  if (input.principal.kind === "user") {
    await withAccessDiff([input.principal.userId], "ADMIN", () => putRow(row), void 0, {
      derived: false,
      gainNotices: !input.fromRequestId
    });
    await recordEvent({
      category: "access",
      action: "plugin.grant",
      subject: { kind: "user", id: input.principal.userId },
      target,
      targetName,
      details: { expiresAt: input.expiresAt, requestId: input.fromRequestId }
    });
  } else {
    const { groupId } = input.principal;
    const batchId = newBatchId();
    await withAccessDiff(await membersOf(groupId), "ADMIN", () => putRow(row), void 0, { batchId, groupId });
    await recordEvent({
      category: "access",
      action: "plugin.grant",
      subject: { kind: "group", id: groupId },
      target,
      targetName,
      details: { batchId }
    });
  }
  log9("assigned plugin permission", { principal, target, grantedBy: input.grantedBy, expiresAt: input.expiresAt });
  return toAssignment(row, context);
}
async function revokePlugin(input) {
  validatePluginGrantKey(input);
  const principal = principalOf(input.principal);
  const target = pluginTarget(input.pluginId, input.accountNumber, input.permission);
  const via = input.via ?? "ADMIN";
  const notFound = () => new NotFoundError(`No ${input.permission} assignment for ${describe(input.principal)} on plugin ${input.pluginId} in account ${input.accountNumber}`);
  const targetName = await pluginCatalog().get(input.pluginId).then((r) => r?.manifest.displayName, () => void 0);
  if (input.principal.kind === "user") {
    if (!await revokeDirectRow(input.principal.userId, target, via, { action: "plugin.revoke", targetName })) throw notFound();
  } else {
    const rows = await queryPrincipal(principal);
    const others = rows.filter((r) => r.target !== target && BUNDLE_KINDS.has(parseTarget(r.target)?.kind ?? ""));
    if (rows.some((r) => r.target === target) && !others.length) {
      throw new ConflictError("This is the group's last permission \u2014 delete the group instead");
    }
    const { groupId } = input.principal;
    const batchId = newBatchId();
    const affected = (await holdersOf(target)).map((h) => h.userId);
    const removed = await withAccessDiff(affected, via, () => deleteRow(principal, target), void 0, { batchId, groupId });
    if (!removed) throw notFound();
    await recordEvent({
      category: "access",
      action: "plugin.revoke",
      subject: { kind: "group", id: groupId },
      target,
      targetName,
      details: { via, batchId }
    });
  }
  log9("revoked plugin permission", { principal, target, via });
}
async function listPluginGrants(pluginId, accountNumber, ctx) {
  validatePluginGrantKey({ pluginId, accountNumber, permission: "user" });
  const context = ctx ?? await loadPluginContext();
  if (!context.catalog.has(pluginId)) throw new NotFoundError(`Plugin ${pluginId} is not installed`);
  const rows = [];
  for (const permission of PLUGIN_PERMISSIONS) rows.push(...await queryTarget(pluginTarget(pluginId, accountNumber, permission)));
  const assignments = rows.map((r) => toAssignment(r, context)).filter((a) => a !== null).sort(byPrincipalThenPermission);
  return { assignments, holders: await pluginHolders(pluginId, accountNumber, context) };
}
async function listUserPluginAccess(userId, ctx) {
  const context = ctx ?? await loadPluginContext();
  const entries = await effectiveAccess(userId);
  const assignments = [];
  for (const e of entries.values()) {
    if (!e.direct) continue;
    const a = toAssignment({ principal: userPrincipal(userId), target: e.target, ...e.direct }, context);
    if (a) assignments.push(a);
  }
  return {
    assignments: assignments.sort(byPrincipalThenPermission),
    capabilities: resolvePluginCapabilities(entries.values(), context)
  };
}
async function listGroupPluginAssignments(groupId, ctx) {
  const context = ctx ?? await loadPluginContext();
  return (await queryPrincipal(groupPrincipal(groupId), "plugin#")).map((r) => toAssignment(r, context)).filter((a) => a !== null).sort(byPrincipalThenPermission);
}
async function revokeAllPluginGrantsForAccount(accountNumber, ctx, batchId, onDiff) {
  const context = ctx ?? await loadPluginContext();
  const targets = [];
  for (const record of context.catalog.values()) {
    for (const permission of PLUGIN_PERMISSIONS) targets.push(pluginTarget(record.pluginId, accountNumber, permission));
  }
  const affected = /* @__PURE__ */ new Set();
  const rows = [];
  for (const t of targets) {
    for (const h of await holdersOf(t)) affected.add(h.userId);
    rows.push(...await queryTarget(t));
  }
  const bundlingGroups = [...new Set(rows.filter((r) => r.principal.startsWith("group#")).map((r) => r.principal.slice("group#".length)))];
  if (!rows.length) return { removedRows: 0, targets, bundlingGroups };
  await withAccessDiff(
    [...affected],
    "CASCADE",
    async () => {
      for (const r of rows) await deleteRow(r.principal, r.target);
    },
    void 0,
    { batchId, onDiff }
  );
  log9("revoked plugin grants for deleted account", { accountNumber, removed: rows.length });
  return { removedRows: rows.length, targets, bundlingGroups };
}
async function listPluginExpiryFeed(userId) {
  const phases = await listPluginExpiryNotices(userId);
  const all = [...phases.expiring, ...phases.expired];
  if (!all.length) return { expiring: [], expired: [] };
  const reader = pluginCatalog();
  const records = new Map(await Promise.all([...new Set(all.map((n) => n.pluginId))].map(async (id) => [id, await reader.get(id)])));
  const accounts = await registeredAccounts(all.map((n) => n.accountNumber));
  const named = (n) => ({
    ...n,
    pluginName: records.get(n.pluginId)?.manifest.displayName ?? n.pluginId,
    accountName: accounts.get(n.accountNumber)?.name ?? n.accountNumber
  });
  return { expiring: phases.expiring.map(named), expired: phases.expired.map(named) };
}
async function listPluginExpiryNotices(userId) {
  const rows = await queryPrincipal(userPrincipal(userId), "plugin#");
  return expiryPhases(rows, (t) => {
    const p = parseTarget(t);
    return p?.kind === "plugin" ? { pluginId: p.pluginId, accountNumber: p.accountNumber, permission: p.permission } : null;
  });
}
async function markPluginExpiryNoticesSeen(userId) {
  const count = await markExpiryPhasesSeen(userId, await listPluginExpiryNotices(userId), (n) => pluginTarget(n.pluginId, n.accountNumber, n.permission));
  if (count) log9("marked plugin expiry notices seen", { userId, count });
  return count;
}
var log9, describe, BUNDLE_KINDS, byPrincipalThenPermission;
var init_pluginGrantsService = __esm({
  "lambdacode/api/services/pluginGrantsService.ts"() {
    "use strict";
    init_backend();
    init_httpErrors();
    init_access2();
    init_accessNotices();
    init_auditService();
    init_grantsService();
    init_pluginCatalog();
    init_pluginAccess();
    log9 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    describe = (p) => p.kind === "user" ? `user ${p.userId}` : `group ${p.groupId}`;
    BUNDLE_KINDS = /* @__PURE__ */ new Set(["role", "resource", "plugin"]);
    byPrincipalThenPermission = (a, b) => a.principal.kind.localeCompare(b.principal.kind) || principalOf(a.principal).localeCompare(principalOf(b.principal)) || PLUGIN_PERMISSIONS.indexOf(a.permission) - PLUGIN_PERMISSIONS.indexOf(b.permission);
  }
});

// lambdacode/api/services/claims.ts
function customClaims(source) {
  const out = {};
  for (const [k, v] of Object.entries(source)) {
    if (k.startsWith(CUSTOM_PREFIX) && typeof v === "string" && v !== "") {
      out[k.slice(CUSTOM_PREFIX.length)] = v;
    }
  }
  return out;
}
var CUSTOM_PREFIX;
var init_claims = __esm({
  "lambdacode/api/services/claims.ts"() {
    "use strict";
    CUSTOM_PREFIX = "custom:";
  }
});

// lambdacode/api/services/directory.ts
async function listDirectoryUsers() {
  const users = [];
  let PaginationToken;
  do {
    const page = await cognito.send(new import_client_cognito_identity_provider.ListUsersCommand({ UserPoolId: USER_POOL_ID, PaginationToken }));
    for (const u of page?.Users ?? []) {
      const attrs = u.Attributes ?? [];
      const sub = attrs.find((a) => a.Name === "sub")?.Value;
      if (!sub) continue;
      if (u.UserStatus === "EXTERNAL_PROVIDER") continue;
      const claims = customClaims(Object.fromEntries(attrs.map((a) => [a.Name ?? "", a.Value])));
      users.push({
        userId: sub,
        email: attrs.find((a) => a.Name === "email")?.Value ?? "",
        pendingInvite: u.UserStatus === "FORCE_CHANGE_PASSWORD",
        ...Object.keys(claims).length ? { claims } : {}
      });
    }
    PaginationToken = page.PaginationToken;
  } while (PaginationToken);
  return users;
}
var import_client_cognito_identity_provider, cognito, USER_POOL_ID;
var init_directory = __esm({
  "lambdacode/api/services/directory.ts"() {
    "use strict";
    import_client_cognito_identity_provider = require("@aws-sdk/client-cognito-identity-provider");
    init_claims();
    cognito = new import_client_cognito_identity_provider.CognitoIdentityProviderClient({});
    USER_POOL_ID = process.env.USER_POOL_ID;
  }
});

// lambdacode/api/services/preferencesService.ts
async function touchPresence(userId) {
  const now = Date.now();
  const prev = lastStamped.get(userId);
  if (prev !== void 0 && now - prev < PRESENCE_THROTTLE_MS) return;
  lastStamped.set(userId, now);
  try {
    await upsertPref(userId, PRESENCE_TARGET, { lastSeenAt: new Date(now).toISOString() });
  } catch (err) {
    lastStamped.delete(userId);
    log10("WARN: could not stamp presence", { userId, error: err.message });
  }
}
async function seenUsers(userIds) {
  const seen = /* @__PURE__ */ new Set();
  const ids = [...new Set(userIds)];
  for (let i = 0; i < ids.length; i += 100) {
    let keys = ids.slice(i, i + 100).map((id) => ({ principal: userPrincipal(id), target: PRESENCE_TARGET }));
    while (keys.length) {
      const res = await ddb9.send(
        new import_lib_dynamodb9.BatchGetCommand({ RequestItems: { [ACCESS_TABLE_NAME]: { Keys: keys, ProjectionExpression: "principal" } } })
      );
      for (const row of res.Responses?.[ACCESS_TABLE_NAME] ?? []) {
        seen.add(String(row.principal).slice("user#".length));
      }
      keys = res.UnprocessedKeys?.[ACCESS_TABLE_NAME]?.Keys ?? [];
    }
  }
  return seen;
}
async function getProfileName(userId, accountNumber, roleName) {
  const row = await getRow(userPrincipal(userId), prefTarget(accountNumber, roleName));
  return row?.profileName ?? null;
}
async function setProfileName(userId, accountNumber, roleName, profileName) {
  await upsertPref(userId, prefTarget(accountNumber, roleName), { profileName });
  log10("setProfileName", { userId, accountNumber, roleName });
}
async function clearProfileName(userId, accountNumber, roleName) {
  await upsertPref(userId, prefTarget(accountNumber, roleName), {}, ["profileName"]);
}
async function setRoleLabel(userId, accountNumber, roleName, roleLabel) {
  await upsertPref(userId, prefTarget(accountNumber, roleName), { roleLabel });
}
async function clearRoleLabel(userId, accountNumber, roleName) {
  await upsertPref(userId, prefTarget(accountNumber, roleName), {}, ["roleLabel"]);
}
async function setAutoVend(userId, accountNumber, roleName, on) {
  await upsertPref(
    userId,
    prefTarget(accountNumber, roleName),
    on ? { autoVend: true } : {},
    on ? [] : ["autoVend"]
  );
}
async function listFavorites(userId) {
  return (await queryPrincipal(userPrincipal(userId), FAVORITE_PREFIX)).map((r) => r.target.slice(FAVORITE_PREFIX.length));
}
async function setFavorite(userId, accountNumber, on) {
  if (!on) {
    await deleteRow(userPrincipal(userId), favoriteTarget(accountNumber));
    return;
  }
  const current = await listFavorites(userId);
  if (current.includes(accountNumber)) return;
  if (current.length >= FAVORITES_MAX) {
    throw new ValidationError(`You can favorite up to ${FAVORITES_MAX} accounts \u2014 remove one first`);
  }
  await putRow({ principal: userPrincipal(userId), target: favoriteTarget(accountNumber), grantedAt: (/* @__PURE__ */ new Date()).toISOString() });
}
async function listRecent(userId) {
  const row = await getRow(userPrincipal(userId), RECENT_TARGET);
  return Array.isArray(row?.accounts) ? row.accounts.filter((a) => typeof a === "string") : [];
}
async function touchRecent(userId, accountNumber) {
  try {
    const current = await listRecent(userId);
    if (current[0] === accountNumber) return;
    const next = [accountNumber, ...current.filter((a) => a !== accountNumber)].slice(0, RECENT_MAX);
    await upsertPref(userId, RECENT_TARGET, { accounts: next, touchedAt: (/* @__PURE__ */ new Date()).toISOString() });
  } catch (err) {
    log10("recent not recorded", { userId, accountNumber, error: err.message });
  }
}
async function getNetworkPrefs(userId) {
  const row = await getRow(userPrincipal(userId), NETWORK_PREFS_TARGET);
  return {
    autoReconnect: Boolean(row?.autoReconnect),
    lastSiteId: row?.lastSiteId ?? null
  };
}
async function setNetworkPrefs(userId, patch) {
  const set = {};
  const remove = [];
  if (patch.autoReconnect !== void 0) {
    if (patch.autoReconnect) set.autoReconnect = true;
    else remove.push("autoReconnect");
  }
  if (patch.lastSiteId !== void 0) set.lastSiteId = patch.lastSiteId;
  await upsertPref(userId, NETWORK_PREFS_TARGET, set, remove);
  log10("setNetworkPrefs", { userId, ...patch });
}
async function getNotificationPrefs(userId) {
  const row = await getRow(userPrincipal(userId), NOTIFICATION_PREFS_TARGET);
  const off = new Set(Array.isArray(row?.kindsOff) ? row.kindsOff : []);
  const kinds = allKinds(true);
  for (const k of NOTIFICATION_KINDS) if (off.has(k)) kinds[k] = false;
  return { enabled: row?.enabled !== false, kinds };
}
async function setNotificationPrefs(userId, patch) {
  const current = await getNotificationPrefs(userId);
  const next = { ...current.kinds, ...patch.kinds ?? {} };
  const enabled2 = patch.enabled ?? current.enabled;
  const kindsOff = NOTIFICATION_KINDS.filter((k) => !next[k]);
  const set = {};
  const remove = [];
  if (enabled2) remove.push("enabled");
  else set.enabled = false;
  if (kindsOff.length) set.kindsOff = kindsOff;
  else remove.push("kindsOff");
  await upsertPref(userId, NOTIFICATION_PREFS_TARGET, set, remove);
  log10("setNotificationPrefs", { userId, enabled: enabled2, kindsOff });
  return { enabled: enabled2, kinds: next };
}
async function listPreferences(userId) {
  const out = [];
  for (const row of await queryPrincipal(userPrincipal(userId), "pref#")) {
    const p = parseTarget(row.target);
    if (p?.kind !== "pref") continue;
    const profileName = row.profileName ?? null;
    const roleLabel = row.roleLabel ?? null;
    const autoVend = Boolean(row.autoVend);
    if (!profileName && !roleLabel && !autoVend) continue;
    out.push({ accountNumber: p.accountNumber, role: p.roleName, profileName, roleLabel, autoVend });
  }
  return out;
}
var import_client_dynamodb9, import_lib_dynamodb9, ddb9, log10, PRESENCE_THROTTLE_MS, lastStamped, FAVORITES_MAX, RECENT_MAX, NOTIFICATION_KINDS, allKinds;
var init_preferencesService = __esm({
  "lambdacode/api/services/preferencesService.ts"() {
    "use strict";
    import_client_dynamodb9 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb9 = require("@aws-sdk/lib-dynamodb");
    init_access2();
    init_httpErrors();
    ddb9 = import_lib_dynamodb9.DynamoDBDocumentClient.from(new import_client_dynamodb9.DynamoDBClient({}));
    log10 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    PRESENCE_THROTTLE_MS = 5 * 60 * 1e3;
    lastStamped = /* @__PURE__ */ new Map();
    FAVORITES_MAX = 50;
    RECENT_MAX = 10;
    NOTIFICATION_KINDS = ["granted", "revoked", "decided", "expiring", "session", "requests", "reviews"];
    allKinds = (on) => Object.fromEntries(NOTIFICATION_KINDS.map((k) => [k, on]));
  }
});

// lambdacode/network/naming.ts
var NODE_NAME_LABEL, NODE_NAME_RE;
var init_naming = __esm({
  "lambdacode/network/naming.ts"() {
    "use strict";
    NODE_NAME_LABEL = "[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?";
    NODE_NAME_RE = new RegExp(`^${NODE_NAME_LABEL}$`);
  }
});

// lambdacode/api/services/sharesService.ts
function parseConfig() {
  const off = { enabled: false, maxDurationHours: 8, allowGroupTargets: true, maxActiveSharesPerOwner: DEFAULT_MAX_ACTIVE_SHARES_PER_OWNER };
  const raw = process.env.DEV_SHARES;
  if (!raw) return off;
  try {
    const parsed = JSON.parse(raw);
    const max = Number(parsed.maxDurationHours);
    const perOwner = Number(parsed.maxActiveSharesPerOwner);
    return {
      enabled: parsed.enabled === true,
      maxDurationHours: Number.isInteger(max) && max >= 1 && max <= 72 ? max : 8,
      allowGroupTargets: parsed.allowGroupTargets !== false,
      maxActiveSharesPerOwner: Number.isInteger(perOwner) && perOwner >= 1 && perOwner <= 200 ? perOwner : DEFAULT_MAX_ACTIVE_SHARES_PER_OWNER
    };
  } catch {
    return off;
  }
}
function isTailnetIpv4(s) {
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
  if (!m) return false;
  const [a, b, c, d] = m.slice(1).map(Number);
  return a === 100 && b >= 64 && b <= 127 && c <= 255 && d <= 255;
}
function isOwnNodeName(hostname, siteId) {
  return new RegExp(`^${NODE_NAME_LABEL}\\.${siteId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.tail\\.internal$`).test(hostname);
}
function urlOf(row) {
  const host = row.hostname || row.ip;
  return host ? `http://${host}:${row.port}` : null;
}
async function listShareDefs(now = Date.now()) {
  const live2 = [];
  for (const row of await queryPrincipal(SHARE_DEF_PRINCIPAL, "share#")) {
    if (!isShareDefRow(row)) continue;
    if (!isExpired(row, now)) {
      live2.push(row);
      continue;
    }
    await deleteShareRows(row.shareId).catch(
      (err) => log11("WARN: expired share cleanup failed", { shareId: row.shareId, error: err.message })
    );
  }
  return live2;
}
async function getDef(shareId) {
  const row = await getRow(SHARE_DEF_PRINCIPAL, shareTarget(shareId));
  if (!row || !isShareDefRow(row) || isExpired(row)) throw new NotFoundError(`No share ${shareId}`);
  return row;
}
async function listShareDirectory() {
  const [users, groups] = await Promise.all([listDirectoryUsers(), listGroups()]);
  const seen = await seenUsers(users.filter((u) => u.pendingInvite).map((u) => u.userId));
  return {
    users: users.filter((u) => (!u.pendingInvite || seen.has(u.userId)) && u.email).map((u) => ({ userId: u.userId, email: u.email })).sort((a, b) => a.email.localeCompare(b.email)),
    groups: groups.map((g) => ({ groupId: g.groupId, name: g.name, members: g.members.length })).sort((a, b) => a.name.localeCompare(b.name))
  };
}
function labelRows(rows) {
  const out = [];
  for (const r of rows) {
    const p = parsePrincipal(r.principal);
    const name = typeof r.name === "string" ? r.name : void 0;
    if (p?.kind === "user") out.push({ kind: "user", id: p.userId, name: name ?? p.userId });
    else if (p?.kind === "group") out.push({ kind: "group", id: p.groupId, name: name ?? p.groupId });
  }
  return out.sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name));
}
function toShare(def, grantees) {
  return {
    shareId: def.shareId,
    ownerSub: def.ownerSub,
    ownerName: def.ownerName,
    port: def.port,
    label: def.label,
    siteId: def.siteId,
    ...def.hostname ? { hostname: def.hostname } : {},
    ...def.ip ? { ip: def.ip } : {},
    ...def.device ? { device: def.device } : {},
    url: urlOf(def),
    createdAt: def.createdAt,
    expiresAt: def.expiresAt,
    grantees
  };
}
async function createShare(ownerSub, ownerName, input, siteIds, cfg = devSharesConfig()) {
  const port = Number(input.port);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new ValidationError("port must be an integer between 1 and 65535");
  }
  const label = String(input.label ?? "").trim();
  if (label.length > LABEL_MAX) throw new ValidationError(`label must be at most ${LABEL_MAX} characters`);
  if (!siteIds.includes(input.siteId)) throw new ValidationError(`Unknown site "${input.siteId}"`);
  const asked = Number(input.durationHours);
  if (!Number.isInteger(asked) || asked < 1) {
    throw new ValidationError(`durationHours must be an integer between 1 and ${cfg.maxDurationHours}`);
  }
  const hours = Math.min(asked, cfg.maxDurationHours);
  const device = input.device === void 0 || input.device === null || input.device === "" ? void 0 : String(input.device).trim().toLowerCase();
  if (device !== void 0 && !NODE_NAME_RE.test(device)) {
    throw new ValidationError("device must be the name of one of your devices on this site");
  }
  const hostname = input.hostname ? String(input.hostname).trim().replace(/\.$/, "").toLowerCase() : device ? `${device}.${input.siteId}.tail.internal` : void 0;
  if (hostname && !isOwnNodeName(hostname, input.siteId)) {
    throw new ValidationError(`hostname must be your device's name on this site (<name>.${input.siteId}.tail.internal)`);
  }
  if (device && hostname && hostname.split(".")[0] !== device) {
    throw new ValidationError(`hostname must be the bound device's name (${device}.${input.siteId}.tail.internal)`);
  }
  const ip = input.ip ? String(input.ip).trim() : void 0;
  if (ip && !isTailnetIpv4(ip)) throw new ValidationError("ip must be a tailnet IPv4 address (100.64.0.0/10)");
  const grantees = Array.isArray(input.grantees) ? input.grantees : [];
  if (!grantees.length && !device) throw new ValidationError("pick at least one user or group");
  if (grantees.length > MAX_GRANTEES) throw new ValidationError(`at most ${MAX_GRANTEES} grantees per share`);
  const seen = /* @__PURE__ */ new Set();
  for (const g of grantees) {
    if (g?.kind !== "user" && g?.kind !== "group" || typeof g.id !== "string" || !ID_RE.test(g.id)) {
      throw new ValidationError("grantees must be {kind: user|group, id}");
    }
    if (g.kind === "group" && !cfg.allowGroupTargets) {
      throw new ValidationError("sharing with groups is disabled on this deployment");
    }
    if (g.kind === "user" && g.id === ownerSub) throw new ValidationError("you can't share with yourself");
    const key = `${g.kind}#${g.id}`;
    if (seen.has(key)) throw new ValidationError("duplicate grantee");
    seen.add(key);
  }
  const [users, groups, defs] = await Promise.all([listDirectoryUsers(), listGroups(), listShareDefs()]);
  const email = new Map(users.map((u) => [u.userId, u.email]));
  const groupName = new Map(groups.map((g) => [g.groupId, g.name]));
  for (const g of grantees) {
    if (g.kind === "user" && !email.has(g.id)) throw new ValidationError(`Unknown user ${g.id}`);
    if (g.kind === "group" && !groupName.has(g.id)) throw new ValidationError(`Unknown group ${g.id}`);
  }
  const mine = defs.filter((d) => d.ownerSub === ownerSub);
  if (mine.length >= cfg.maxActiveSharesPerOwner) {
    throw new ValidationError(`at most ${cfg.maxActiveSharesPerOwner} active shares \u2014 stop one first`);
  }
  const clashes = (d) => d.port === port && (!d.device || !device || d.device === device && d.siteId === input.siteId);
  if (mine.some(clashes)) {
    throw new ValidationError(`port ${port} is already shared${device ? ` on ${device}` : ""} \u2014 stop that share first, or add people to it`);
  }
  const shareId = (0, import_crypto5.randomBytes)(6).toString("hex");
  const now = Date.now();
  const createdAt = new Date(now).toISOString();
  const expiresAt = new Date(now + hours * 36e5).toISOString();
  const ttl = ttlOf(expiresAt);
  const target = shareTarget(shareId);
  const def = {
    principal: SHARE_DEF_PRINCIPAL,
    target,
    shareId,
    ownerSub,
    ownerName,
    port,
    label: label || `Port ${port}`,
    siteId: input.siteId,
    ...hostname ? { hostname } : {},
    ...ip ? { ip } : {},
    ...device ? { device } : {},
    createdAt,
    expiresAt,
    ttl
  };
  await putRow(def);
  const labelled = grantees.map((g) => ({
    kind: g.kind,
    id: g.id,
    name: (g.kind === "user" ? email.get(g.id) : groupName.get(g.id)) ?? g.id
  }));
  const holders = /* @__PURE__ */ new Set();
  for (const g of labelled) {
    if (g.kind === "user") holders.add(g.id);
    else for (const u of await membersOf(g.id)) holders.add(u);
  }
  holders.delete(ownerSub);
  const batchId = newBatchId();
  await withAccessDiff(
    [...holders],
    "OWNER",
    async () => {
      for (let i = 0; i < labelled.length; i += WRITE_BATCH) {
        await Promise.all(
          labelled.slice(i, i + WRITE_BATCH).map(
            (g) => putRow({
              principal: g.kind === "user" ? userPrincipal(g.id) : groupPrincipal(g.id),
              target,
              grantedBy: ownerSub,
              grantedAt: createdAt,
              expiresAt,
              name: g.name,
              ttl
            })
          )
        );
      }
    },
    /* @__PURE__ */ new Map([[shareId, def.label]]),
    { batchId }
  );
  await recordEvent({
    category: "access",
    action: "share.create",
    subject: { kind: "user", id: ownerSub, name: ownerName },
    target,
    targetName: def.label,
    details: { port, siteId: input.siteId, expiresAt, grantees: labelled.length, batchId, ...device ? { device } : {} }
  });
  log11("share created", { shareId, ownerSub, port, siteId: input.siteId, hours, device, grantees: grantees.length });
  return toShare(def, labelled.sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name)));
}
async function listShares(userSub) {
  const [defs, access] = await Promise.all([listShareDefs(), effectiveAccess(userSub)]);
  const mine = [];
  const sharedWithMe = [];
  for (const d of defs) {
    if (d.ownerSub === userSub) {
      mine.push(toShare(d, labelRows(await queryTarget(d.target))));
      continue;
    }
    const e = access.get(d.target);
    if (!e?.active) continue;
    let viaGroups = [];
    if (e.groups.length) {
      const nameOf = new Map(
        labelRows(await queryTarget(d.target)).filter((g) => g.kind === "group").map((g) => [g.id, g.name])
      );
      viaGroups = e.groups.map((g) => nameOf.get(g) ?? g).sort();
    }
    sharedWithMe.push({
      shareId: d.shareId,
      ownerSub: d.ownerSub,
      ownerName: d.ownerName,
      port: d.port,
      label: d.label,
      siteId: d.siteId,
      url: urlOf(d),
      expiresAt: d.expiresAt,
      viaGroups
    });
  }
  const byExpiry = (a, b) => a.expiresAt.localeCompare(b.expiresAt);
  return { mine: mine.sort(byExpiry), sharedWithMe: sharedWithMe.sort(byExpiry) };
}
async function listAllShares() {
  const out = [];
  for (const d of await listShareDefs()) out.push(toShare(d, labelRows(await queryTarget(d.target))));
  return out.sort((a, b) => a.expiresAt.localeCompare(b.expiresAt));
}
async function holdersFromRows(rows) {
  const users = /* @__PURE__ */ new Set();
  for (const r of rows) {
    if (isExpired(r)) continue;
    const p = parsePrincipal(r.principal);
    if (p?.kind === "user") users.add(p.userId);
    else if (p?.kind === "group") for (const u of await membersOf(p.groupId)) users.add(u);
  }
  return [...users];
}
async function endShare(def, via) {
  const rows = await queryTarget(def.target);
  const holders = await holdersFromRows(rows);
  const batchId = newBatchId();
  await withAccessDiff(holders, via, () => deleteShareRows(def.shareId, rows), /* @__PURE__ */ new Map([[def.shareId, def.label]]), { batchId });
  await recordEvent({
    category: "access",
    action: "share.stop",
    subject: { kind: "user", id: def.ownerSub, name: def.ownerName },
    target: def.target,
    targetName: def.label,
    details: { via, batchId }
  });
}
async function removeShare(shareId, actor) {
  const def = await getDef(shareId);
  if (def.ownerSub !== actor.sub && !actor.admin) {
    throw new ForbiddenError("Only the owner or an admin can stop this share");
  }
  await endShare(def, actor.sub === def.ownerSub ? "OWNER" : "ADMIN");
  log11("share removed", { shareId, by: actor.sub, owner: def.ownerSub });
}
async function removeSharesOwnedBy(ownerSub) {
  const mine = (await listShareDefs()).filter((d) => d.ownerSub === ownerSub);
  for (const def of mine) await endShare(def, "ADMIN");
  if (mine.length) log11("shares removed with owner", { ownerSub, count: mine.length });
  return mine.length;
}
var import_crypto5, log11, DEFAULT_MAX_ACTIVE_SHARES_PER_OWNER, CONFIG, devSharesConfig, LABEL_MAX, MAX_GRANTEES, TTL_GRACE_S, WRITE_BATCH, ID_RE, ttlOf;
var init_sharesService = __esm({
  "lambdacode/api/services/sharesService.ts"() {
    "use strict";
    import_crypto5 = require("crypto");
    init_access2();
    init_accessNotices();
    init_auditService();
    init_directory();
    init_preferencesService();
    init_groupsService();
    init_httpErrors();
    init_naming();
    log11 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    DEFAULT_MAX_ACTIVE_SHARES_PER_OWNER = 10;
    CONFIG = parseConfig();
    devSharesConfig = () => CONFIG;
    LABEL_MAX = 60;
    MAX_GRANTEES = 50;
    TTL_GRACE_S = 24 * 60 * 60;
    WRITE_BATCH = 25;
    ID_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$/;
    ttlOf = (expiresAt) => Math.floor(Date.parse(expiresAt) / 1e3) + TTL_GRACE_S;
  }
});

// lambdacode/api/services/tokenScopes.ts
function adminScopeAllows(scopes, method) {
  if (scopes.includes("admin.write.all")) return true;
  return scopes.includes("admin.read.all") && READ_METHODS.has(method.toUpperCase());
}
function tokenRouteAllowed(scopes, method, rawPath) {
  const path = normalize(rawPath);
  const verb = method.toUpperCase() === "HEAD" ? "GET" : method.toUpperCase();
  const listed = ROUTES.filter((r) => r.method === verb && r.path.test(path));
  if (listed.some((r) => r.scope === "any")) return true;
  if (TOKEN_MANAGEMENT.test(path)) return false;
  if (scopes.includes("api")) return true;
  if (ADMIN_ROUTES.test(path)) return adminScopeAllows(scopes, verb);
  return listed.some((r) => scopes.includes(r.scope));
}
function parseScopes(raw, allowed) {
  if (!Array.isArray(raw) || !raw.length) throw new ValidationError(`scopes must list at least one of: ${allowed.join(", ")}`);
  const out = /* @__PURE__ */ new Set();
  for (const s of raw) {
    if (!allowed.includes(s)) throw new ValidationError(`Unknown scope "${String(s)}" \u2014 use one of: ${allowed.join(", ")}`);
    out.add(s);
  }
  return allowed.filter((s) => out.has(s));
}
var SEG, route, ROUTES, TOKEN_MANAGEMENT, ADMIN_ROUTES, READ_METHODS, normalize, TOKEN_SCOPE_CODE;
var init_tokenScopes = __esm({
  "lambdacode/api/services/tokenScopes.ts"() {
    "use strict";
    init_httpErrors();
    SEG = "[^/]+";
    route = (scope, method, path) => ({
      scope,
      method,
      path: new RegExp(`^${path}$`, "i")
    });
    ROUTES = [
      route("any", "GET", "/tokens/current"),
      route("aws", "GET", "/accounts"),
      route("aws", "POST", "/credentials"),
      route("aws", "POST", `/accounts/${SEG}/roles/${SEG}/console`),
      route("network", "GET", "/network"),
      route("network", "POST", "/network/device-key"),
      route("network", "GET", "/network/devices"),
      route("network", "DELETE", `/network/devices/${SEG}/${SEG}`),
      route("shares", "GET", "/network"),
      route("shares", "GET", "/network/shares"),
      route("shares", "POST", "/network/shares"),
      route("shares", "DELETE", `/network/shares/${SEG}`),
      route("shares", "GET", "/network/shares/directory")
    ];
    TOKEN_MANAGEMENT = /^\/(admin\/)?tokens(\/|$)/i;
    ADMIN_ROUTES = /^\/admin(\/|$)/i;
    READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
    normalize = (path) => {
      const collapsed = path.replace(/\/{2,}/g, "/");
      return collapsed.length > 1 ? collapsed.replace(/\/$/, "") : collapsed;
    };
    TOKEN_SCOPE_CODE = "TOKEN_SCOPE";
  }
});

// lambdacode/api/services/verificationError.ts
var TokenVerificationError, PERSONAL_TOKEN_PREFIX;
var init_verificationError = __esm({
  "lambdacode/api/services/verificationError.ts"() {
    "use strict";
    TokenVerificationError = class extends Error {
      constructor(reason, message3) {
        super(message3);
        this.reason = reason;
        this.name = "TokenVerificationError";
      }
    };
    PERSONAL_TOKEN_PREFIX = "icpat_";
  }
});

// lambdacode/api/services/personalTokens.ts
function personalTokensConfig() {
  const off = { enabled: false, maxLifetimeDays: DEFAULT_MAX_LIFETIME_DAYS };
  const raw = process.env.PERSONAL_ACCESS_TOKENS;
  if (!raw) return off;
  try {
    const parsed = JSON.parse(raw);
    const max = Number(parsed.maxLifetimeDays);
    return {
      enabled: parsed.enabled === true,
      maxLifetimeDays: Number.isInteger(max) && max >= 1 && max <= 365 ? max : DEFAULT_MAX_LIFETIME_DAYS
    };
  } catch {
    return off;
  }
}
function base62(length) {
  let out = "";
  while (out.length < length) {
    for (const b of (0, import_crypto6.randomBytes)(length * 2)) {
      if (b < 248 && out.length < length) out += BASE62[b % 62];
    }
  }
  return out;
}
function parseToken(token) {
  if (!isPersonalToken(token)) return null;
  const rest = token.slice(TOKEN_PREFIX.length);
  const sep = rest.indexOf("_");
  if (sep < 0) return null;
  const tokenId = rest.slice(0, sep);
  const secret = rest.slice(sep + 1);
  return TOKEN_ID_RE.test(tokenId) && SECRET_RE.test(secret) ? { tokenId, secret } : null;
}
function secretMatches(secret, storedHash) {
  const actual = Buffer.from(hashSecret(secret), "hex");
  const expected = Buffer.from(storedHash ?? "", "hex");
  return expected.length === actual.length && (0, import_crypto6.timingSafeEqual)(actual, expected);
}
async function getTokenRow(tokenId) {
  const out = await ddb10.send(new import_lib_dynamodb10.GetCommand({ TableName: tokensTableName(), Key: { tokenId }, ConsistentRead: true }));
  return out.Item;
}
async function ownerStatus(sub) {
  const hit = ownerCache.get(sub);
  if (hit && Date.now() - hit.at < OWNER_TTL_MS) return hit.status;
  let status;
  try {
    const user = await cognito2.send(new import_client_cognito_identity_provider2.AdminGetUserCommand({ UserPoolId: process.env.USER_POOL_ID, Username: sub }));
    status = {
      exists: true,
      enabled: user.Enabled !== false,
      email: user.UserAttributes?.find((a) => a.Name === "email")?.Value
    };
  } catch (err) {
    if (err.name !== "UserNotFoundException") throw err;
    status = { exists: false, enabled: false };
  }
  ownerCache.set(sub, { at: Date.now(), status });
  return status;
}
async function touchToken(row, now = Date.now()) {
  const last = row.lastUsedAt ? Date.parse(row.lastUsedAt) : NaN;
  if (!Number.isNaN(last) && now - last < TOUCH_EVERY_MS) return;
  try {
    await ddb10.send(
      new import_lib_dynamodb10.UpdateCommand({
        TableName: tokensTableName(),
        Key: { tokenId: row.tokenId },
        UpdateExpression: "SET lastUsedAt = :t",
        ConditionExpression: "attribute_exists(tokenId)",
        ExpressionAttributeValues: { ":t": new Date(now).toISOString() }
      })
    );
  } catch (err) {
    if (err.name !== "ConditionalCheckFailedException") {
      console.log(JSON.stringify({ msg: "WARN: token lastUsedAt stamp failed", error: err.message }));
    }
  }
}
async function verifyPersonalToken(token) {
  if (!tokensTableName() || !personalTokensConfig().enabled) {
    throw new TokenVerificationError("invalid", "personal access tokens are not accepted here");
  }
  const parsed = parseToken(token);
  if (!parsed) throw new TokenVerificationError("invalid", "malformed personal access token");
  let row;
  try {
    row = await getTokenRow(parsed.tokenId);
  } catch (err) {
    throw new TokenVerificationError("dependency", `token table unavailable: ${message(err)}`);
  }
  if (!row || !secretMatches(parsed.secret, row.secretHash)) {
    throw new TokenVerificationError("invalid", `unknown or revoked personal access token ${parsed.tokenId}`);
  }
  if (!(Date.parse(row.expiresAt) > Date.now())) {
    throw new TokenVerificationError("invalid", `personal access token ${row.tokenId} expired`);
  }
  let owner;
  try {
    owner = await ownerStatus(row.ownerId);
  } catch (err) {
    throw new TokenVerificationError("dependency", `directory unavailable: ${message(err)}`);
  }
  if (!owner.exists || !owner.enabled) {
    throw new TokenVerificationError("invalid", `owner of personal access token ${row.tokenId} is disabled or gone`);
  }
  return {
    kind: "token",
    subject: row.ownerId,
    email: owner.email ?? row.ownerEmail,
    token: {
      id: row.tokenId,
      name: row.name,
      scopes: row.scopes ?? [],
      ...row.roles?.length ? { roles: row.roles } : {},
      expiresAt: row.expiresAt,
      ...row.lastUsedAt ? { lastUsedAt: row.lastUsedAt } : {}
    }
  };
}
var import_crypto6, import_client_dynamodb10, import_lib_dynamodb10, import_client_cognito_identity_provider2, ddb10, cognito2, TOKEN_PREFIX, TOKEN_SCOPES, SERVICE_USER_SCOPES, DEFAULT_MAX_LIFETIME_DAYS, tokensTableName, TOKEN_ID_RE, SECRET_RE, BASE62, newTokenId, newSecret, formatToken, hashSecret, isPersonalToken, OWNER_TTL_MS, ownerCache, TOUCH_EVERY_MS, message;
var init_personalTokens = __esm({
  "lambdacode/api/services/personalTokens.ts"() {
    "use strict";
    import_crypto6 = require("crypto");
    import_client_dynamodb10 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb10 = require("@aws-sdk/lib-dynamodb");
    import_client_cognito_identity_provider2 = require("@aws-sdk/client-cognito-identity-provider");
    init_verificationError();
    ddb10 = import_lib_dynamodb10.DynamoDBDocumentClient.from(new import_client_dynamodb10.DynamoDBClient({}));
    cognito2 = new import_client_cognito_identity_provider2.CognitoIdentityProviderClient({});
    TOKEN_PREFIX = PERSONAL_TOKEN_PREFIX;
    TOKEN_SCOPES = ["api", "aws", "network", "shares"];
    SERVICE_USER_SCOPES = ["aws", "network", "shares", "admin.read.all", "admin.write.all"];
    DEFAULT_MAX_LIFETIME_DAYS = 90;
    tokensTableName = () => process.env.TOKENS_TABLE_NAME ?? "";
    TOKEN_ID_RE = /^[a-f0-9]{16}$/;
    SECRET_RE = /^[A-Za-z0-9]{40}$/;
    BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    newTokenId = () => (0, import_crypto6.randomBytes)(8).toString("hex");
    newSecret = () => base62(40);
    formatToken = (tokenId, secret) => `${TOKEN_PREFIX}${tokenId}_${secret}`;
    hashSecret = (secret) => (0, import_crypto6.createHash)("sha256").update(secret, "utf8").digest("hex");
    isPersonalToken = (token) => token.startsWith(TOKEN_PREFIX);
    OWNER_TTL_MS = 6e4;
    ownerCache = /* @__PURE__ */ new Map();
    TOUCH_EVERY_MS = 5 * 6e4;
    message = (err) => err instanceof Error ? err.message : String(err);
  }
});

// lambdacode/api/services/tokensService.ts
function summary(row) {
  return {
    tokenId: row.tokenId,
    name: row.name,
    ...row.description ? { description: row.description } : {},
    scopes: row.scopes,
    ...row.roles?.length ? { roles: row.roles } : {},
    createdAt: row.createdAt,
    expiresAt: row.expiresAt,
    ...row.lastUsedAt ? { lastUsedAt: row.lastUsedAt } : {}
  };
}
async function ownRows(ownerId) {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb11.send(
      new import_lib_dynamodb11.QueryCommand({
        TableName: tokensTableName(),
        IndexName: "byOwner",
        KeyConditionExpression: "ownerId = :o",
        ExpressionAttributeValues: { ":o": ownerId },
        ExclusiveStartKey
      })
    );
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
function parseRoles(raw) {
  if (raw === void 0 || raw === null) return [];
  if (!Array.isArray(raw)) throw new ValidationError("roles must be a list of {accountNumber, roleName}");
  if (raw.length > MAX_ROLES_PER_TOKEN) throw new ValidationError(`at most ${MAX_ROLES_PER_TOKEN} roles per token`);
  const seen = /* @__PURE__ */ new Map();
  for (const r of raw) {
    const accountNumber = r?.accountNumber;
    const roleName = r?.roleName;
    if (typeof accountNumber !== "string" || !/^\d{12}$/.test(accountNumber) || typeof roleName !== "string" || !roleName || roleName.length > 128 || /[#/]/.test(roleName)) {
      throw new ValidationError("roles must be a list of {accountNumber (12 digits), roleName}");
    }
    seen.set(roleTarget(accountNumber, roleName), { accountNumber, roleName });
  }
  return [...seen.values()];
}
async function createToken(ownerId, ownerEmail, input, cfg = personalTokensConfig()) {
  const name = typeof input.name === "string" ? input.name.trim() : "";
  if (!name || name.length > NAME_MAX2) throw new ValidationError(`name is required (at most ${NAME_MAX2} characters)`);
  const description = typeof input.description === "string" ? input.description.trim() : "";
  if (input.description !== void 0 && typeof input.description !== "string") throw new ValidationError("description must be text");
  if (description.length > DESCRIPTION_MAX2) throw new ValidationError(`description must be at most ${DESCRIPTION_MAX2} characters`);
  const scopes = parseScopes(input.scopes, TOKEN_SCOPES);
  const days = input.expiresInDays;
  if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > cfg.maxLifetimeDays) {
    throw new ValidationError(`expiresInDays must be a whole number between 1 and ${cfg.maxLifetimeDays}`);
  }
  const roles = parseRoles(input.roles);
  if (roles.length && !scopes.some((s) => s === "aws" || s === "api")) {
    throw new ValidationError("a role limit needs the aws or api scope");
  }
  if (roles.length) {
    const held = await effectiveForMany(ownerId, roles.map((r) => roleTarget(r.accountNumber, r.roleName)));
    const missing = roles.filter((r) => !held.get(roleTarget(r.accountNumber, r.roleName))?.active);
    if (missing.length) {
      throw new ValidationError(`You do not hold ${missing.map((r) => `${r.roleName} in ${r.accountNumber}`).join(", ")}`);
    }
  }
  const mine = (await ownRows(ownerId)).filter((r) => live(r));
  if (mine.length >= MAX_TOKENS_PER_USER) {
    throw new ConflictError(`at most ${MAX_TOKENS_PER_USER} active tokens \u2014 revoke one first`);
  }
  const tokenId = newTokenId();
  const secret = newSecret();
  const now = /* @__PURE__ */ new Date();
  const expiresAt = new Date(now.getTime() + days * 24 * 60 * 60 * 1e3).toISOString();
  const row = {
    tokenId,
    ownerId,
    ...ownerEmail ? { ownerEmail } : {},
    name,
    ...description ? { description } : {},
    scopes,
    ...roles.length ? { roles } : {},
    secretHash: hashSecret(secret),
    createdAt: now.toISOString(),
    expiresAt,
    ttl: Math.floor(Date.parse(expiresAt) / 1e3) + TTL_GRACE_S2
  };
  await ddb11.send(
    new import_lib_dynamodb11.PutCommand({ TableName: tokensTableName(), Item: row, ConditionExpression: "attribute_not_exists(tokenId)" })
  );
  const after = (await ownRows(ownerId)).filter((r) => live(r));
  if (after.length > MAX_TOKENS_PER_USER) {
    await deleteRow2(tokenId, ownerId);
    throw new ConflictError(`at most ${MAX_TOKENS_PER_USER} active tokens \u2014 revoke one first`);
  }
  await recordEvent({
    category: "auth",
    action: "token.create",
    subject: { kind: "user", id: ownerId, name: ownerEmail },
    target: tokenTarget(tokenId),
    targetName: name,
    details: { expiresAt, scopes, ...roles.length ? { roles: roles.length } : {} }
  });
  log12("token created", { tokenId, ownerId, scopes, days, roles: roles.length });
  return { token: summary(row), secret: formatToken(tokenId, secret) };
}
async function listTokens(ownerId) {
  return (await ownRows(ownerId)).sort(newestFirst).map(summary);
}
async function listAllTokens() {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb11.send(new import_lib_dynamodb11.ScanCommand({ TableName: tokensTableName(), ExclusiveStartKey }));
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows.sort(newestFirst).map(adminSummary);
}
async function deleteRow2(tokenId, ownerId) {
  try {
    const out = await ddb11.send(
      new import_lib_dynamodb11.DeleteCommand({
        TableName: tokensTableName(),
        Key: { tokenId },
        ConditionExpression: ownerId ? "ownerId = :o" : "attribute_exists(tokenId)",
        ...ownerId ? { ExpressionAttributeValues: { ":o": ownerId } } : {},
        ReturnValues: "ALL_OLD"
      })
    );
    return out.Attributes;
  } catch (err) {
    if (err.name === "ConditionalCheckFailedException") return void 0;
    throw err;
  }
}
async function revokeToken(tokenId, ownerId) {
  const row = TOKEN_ID_RE.test(tokenId) ? await deleteRow2(tokenId, ownerId) : void 0;
  if (!row) throw new NotFoundError(`No token ${tokenId}`);
  await recordEvent({
    category: "auth",
    action: "token.revoke",
    subject: { kind: "user", id: row.ownerId, name: row.ownerEmail },
    target: tokenTarget(row.tokenId),
    targetName: row.name,
    details: { via: ownerId ? "OWNER" : "ADMIN" }
  });
  log12("token revoked", { tokenId, ownerId: row.ownerId, by: ownerId ? "owner" : "admin" });
}
async function deleteTokensOwnedBy(ownerId) {
  if (!tokensTableName()) return 0;
  const rows = await ownRows(ownerId);
  for (const r of rows) await deleteRow2(r.tokenId);
  if (rows.length) log12("tokens removed with owner", { ownerId, count: rows.length });
  return rows.length;
}
async function listTokenExpiryNotices(ownerId) {
  const rows = await ownRows(ownerId);
  const byId = new Map(rows.map((r) => [r.tokenId, r]));
  return expiryPhases(
    rows.map((r) => ({ target: r.tokenId, grantedAt: r.createdAt, expiresAt: r.expiresAt, expiringSeen: r.expiringSeen, expiredSeen: r.expiredSeen })),
    (tokenId) => ({ tokenId, name: byId.get(tokenId)?.name ?? tokenId })
  );
}
async function markTokenExpiryNoticesSeen(ownerId) {
  const phases = await listTokenExpiryNotices(ownerId);
  const unseen = [
    ...phases.expiring.filter((n) => !n.seen).map((n) => ({ n, flag: "expiringSeen" })),
    ...phases.expired.filter((n) => !n.seen).map((n) => ({ n, flag: "expiredSeen" }))
  ];
  let cleared = 0;
  for (const { n, flag } of unseen) {
    try {
      await ddb11.send(
        new import_lib_dynamodb11.UpdateCommand({
          TableName: tokensTableName(),
          Key: { tokenId: n.tokenId },
          UpdateExpression: "SET #f = :t",
          ConditionExpression: "ownerId = :o",
          ExpressionAttributeNames: { "#f": flag },
          ExpressionAttributeValues: { ":t": true, ":o": ownerId }
        })
      );
      cleared++;
    } catch (err) {
      if (err.name !== "ConditionalCheckFailedException") throw err;
    }
  }
  return cleared;
}
var import_client_dynamodb11, import_lib_dynamodb11, ddb11, log12, NAME_MAX2, DESCRIPTION_MAX2, MAX_TOKENS_PER_USER, MAX_ROLES_PER_TOKEN, TTL_GRACE_S2, tokenTarget, adminSummary, live, newestFirst;
var init_tokensService = __esm({
  "lambdacode/api/services/tokensService.ts"() {
    "use strict";
    import_client_dynamodb11 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb11 = require("@aws-sdk/lib-dynamodb");
    init_access2();
    init_auditService();
    init_grantsService();
    init_httpErrors();
    init_tokenScopes();
    init_personalTokens();
    ddb11 = import_lib_dynamodb11.DynamoDBDocumentClient.from(new import_client_dynamodb11.DynamoDBClient({}));
    log12 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    NAME_MAX2 = 60;
    DESCRIPTION_MAX2 = 200;
    MAX_TOKENS_PER_USER = 25;
    MAX_ROLES_PER_TOKEN = 50;
    TTL_GRACE_S2 = 8 * 24 * 60 * 60;
    tokenTarget = (tokenId) => `token#${tokenId}`;
    adminSummary = (row) => ({
      ...summary(row),
      ownerId: row.ownerId,
      ...row.ownerEmail ? { ownerEmail: row.ownerEmail } : {}
    });
    live = (row, now = Date.now()) => Date.parse(row.expiresAt) > now;
    newestFirst = (a, b) => b.createdAt.localeCompare(a.createdAt);
  }
});

// lambdacode/api/services/serviceUserRegistry.ts
async function getServiceUser(clientId) {
  const out = await ddb12.send(
    new import_lib_dynamodb12.GetCommand({ TableName: SERVICE_USERS_TABLE_NAME, Key: { clientId }, ConsistentRead: true })
  );
  const row = out.Item;
  if (!row?.name) return void 0;
  return { name: row.name, scopes: row.scopes ?? [...LEGACY_SERVICE_USER_SCOPES] };
}
var import_client_dynamodb12, import_lib_dynamodb12, ddb12, SERVICE_USERS_TABLE_NAME, SERVICE_SCOPE, LEGACY_SERVICE_USER_SCOPES;
var init_serviceUserRegistry = __esm({
  "lambdacode/api/services/serviceUserRegistry.ts"() {
    "use strict";
    import_client_dynamodb12 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb12 = require("@aws-sdk/lib-dynamodb");
    ddb12 = import_lib_dynamodb12.DynamoDBDocumentClient.from(new import_client_dynamodb12.DynamoDBClient({}));
    SERVICE_USERS_TABLE_NAME = process.env.SERVICE_USERS_TABLE_NAME;
    SERVICE_SCOPE = "api/invoke";
    LEGACY_SERVICE_USER_SCOPES = ["aws", "network", "shares", "admin.write.all"];
  }
});

// lambdacode/api/services/tempPassword.ts
function tempPassword(len = 24) {
  const all = TEMP_PW_SETS.join("");
  const chars = TEMP_PW_SETS.map((s) => s[(0, import_crypto7.randomInt)(s.length)]);
  while (chars.length < len) chars.push(all[(0, import_crypto7.randomInt)(all.length)]);
  for (let i = chars.length - 1; i > 0; i--) {
    const j = (0, import_crypto7.randomInt)(i + 1);
    [chars[i], chars[j]] = [chars[j], chars[i]];
  }
  return chars.join("");
}
var import_crypto7, TEMP_PW_SETS;
var init_tempPassword = __esm({
  "lambdacode/api/services/tempPassword.ts"() {
    "use strict";
    import_crypto7 = require("crypto");
    TEMP_PW_SETS = [
      "ABCDEFGHJKMNPQRSTUVWXYZ",
      "abcdefghjkmnpqrstuvwxyz",
      "23456789",
      "!$*._~-"
    ];
  }
});

// lambdacode/api/services/usersService.ts
var usersService_exports = {};
__export(usersService_exports, {
  ADMIN_GROUP: () => ADMIN_GROUP,
  LIST_CAP: () => LIST_CAP,
  assertUserExists: () => assertUserExists,
  capLists: () => capLists,
  createUser: () => createUser,
  createUsers: () => createUsers,
  deleteUser: () => deleteUser,
  deleteUsers: () => deleteUsers,
  getUser: () => getUser,
  listAdminSubs: () => listAdminSubs,
  listUsers: () => listUsers,
  mintSignupLink: () => mintSignupLink,
  normalizeEmail: () => normalizeEmail,
  resendInvite: () => resendInvite,
  resetUserMfa: () => resetUserMfa,
  signupLink: () => signupLink,
  updateUser: () => updateUser
});
async function listUsers() {
  const [directory, adminSubs, graph, resourceMeta, groups] = await Promise.all([
    listDirectory(),
    listAdminSubs(),
    snapshot(),
    scanResourceMeta(),
    listGroups()
  ]);
  const groupName = new Map(groups.map((g) => [g.groupId, g.name]));
  const users = directory.map((u) => {
    const { roles, resources } = accessLists(graph.users.get(u.userId)?.values() ?? [], groupName, resourceMeta);
    return {
      userId: u.userId,
      email: u.email,
      admin: adminSubs.has(u.userId),
      // A federated sign-in never runs the set-password step, so a user who only ever signs in
      // that way stays FORCE_CHANGE_PASSWORD in Cognito; being seen by the API proves they got in.
      pendingInvite: u.pendingInvite && !graph.presence.has(u.userId),
      lastSeenAt: graph.presence.get(u.userId),
      ...u.claims ? { claims: u.claims } : {},
      roles,
      roleCount: roles.length,
      resources,
      resourceCount: resources.length
    };
  });
  log13("listed users", { count: users.length });
  return users;
}
function capLists(u) {
  const roleNames = [...new Set(u.roles.map((r) => r.roleName))].sort();
  const groupNames = [.../* @__PURE__ */ new Set([...u.roles.flatMap((r) => r.groups), ...u.resources.flatMap((r) => r.groups)])].sort();
  return { ...u, roles: u.roles.slice(0, LIST_CAP), resources: u.resources.slice(0, LIST_CAP), roleNames, groupNames };
}
function accessLists(entries, groupName, resourceMeta) {
  const roles = [];
  const resources = [];
  for (const e of entries) {
    if (!e.active) continue;
    const p = parseTarget(e.target);
    const teams = e.groups.map((g) => groupName.get(g) ?? g).sort();
    const direct = Boolean(e.direct && !isExpired(e.direct));
    if (p?.kind === "role") {
      roles.push({ accountNumber: p.accountNumber, roleName: p.roleName, direct, groups: teams });
    } else if (p?.kind === "resource") {
      const meta = resourceMeta.get(p.resourceId);
      resources.push({
        resourceId: p.resourceId,
        name: meta?.name ?? "(deleted resource)",
        accountNumber: meta?.accountNumber,
        direct,
        groups: teams
      });
    }
  }
  roles.sort((a, b) => a.accountNumber.localeCompare(b.accountNumber) || a.roleName.localeCompare(b.roleName));
  resources.sort((a, b) => a.name.localeCompare(b.name));
  return { roles, resources };
}
async function assertUserExists(userId) {
  if (await getServiceUser(userId)) return;
  try {
    await cognito3.send(new import_client_cognito_identity_provider3.AdminGetUserCommand({ UserPoolId: USER_POOL_ID2, Username: userId }));
  } catch (err) {
    if (err.name === "UserNotFoundException") throw new NotFoundError(`User ${userId} not found`);
    throw err;
  }
}
async function getUser(userId) {
  let found;
  try {
    found = await cognito3.send(new import_client_cognito_identity_provider3.AdminGetUserCommand({ UserPoolId: USER_POOL_ID2, Username: userId }));
  } catch (err) {
    if (err.name === "UserNotFoundException") throw new NotFoundError(`User ${userId} not found`);
    throw err;
  }
  const attrs = Object.fromEntries((found.UserAttributes ?? []).map((a) => [a.Name ?? "", a.Value]));
  const [adminSubs, entries, resourceMeta, index, presence] = await Promise.all([
    listAdminSubs(),
    effectiveAccess(userId),
    scanResourceMeta(),
    catalog(),
    getRow(userPrincipal(userId), PRESENCE_TARGET)
  ]);
  const { roles, resources } = accessLists(entries.values(), index.groupName, resourceMeta);
  const claims = customClaims(attrs);
  const lastSeenAt = typeof presence?.lastSeenAt === "string" ? presence.lastSeenAt : void 0;
  return {
    userId,
    email: attrs.email ?? "",
    admin: adminSubs.has(userId),
    pendingInvite: found.UserStatus === "FORCE_CHANGE_PASSWORD" && !lastSeenAt,
    lastSeenAt,
    ...Object.keys(claims).length ? { claims } : {},
    roles,
    roleCount: roles.length,
    resources,
    resourceCount: resources.length
  };
}
async function listAdminSubs() {
  const subs = /* @__PURE__ */ new Set();
  let NextToken;
  do {
    const page = await cognito3.send(
      new import_client_cognito_identity_provider3.ListUsersInGroupCommand({
        UserPoolId: USER_POOL_ID2,
        GroupName: ADMIN_GROUP,
        NextToken
      })
    );
    for (const u of page?.Users ?? []) {
      const sub = (u.Attributes ?? []).find((a) => a.Name === "sub")?.Value;
      if (sub) subs.add(sub);
    }
    NextToken = page?.NextToken;
  } while (NextToken);
  return subs;
}
async function scanResourceMeta() {
  const meta = /* @__PURE__ */ new Map();
  let ExclusiveStartKey;
  do {
    const page = await ddb13.send(
      new import_lib_dynamodb13.ScanCommand({
        TableName: RESOURCES_TABLE_NAME5,
        ProjectionExpression: "resourceId, #n, accountNumber",
        ExpressionAttributeNames: { "#n": "name" },
        // reserved word
        ExclusiveStartKey
      })
    );
    for (const it of page.Items ?? []) {
      if (isSentinelRow(it.resourceId)) continue;
      meta.set(it.resourceId, {
        name: it.name,
        accountNumber: it.accountNumber
      });
    }
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return meta;
}
async function createUser(rawEmail, admin, sendEmail = true) {
  const user = await invite(rawEmail, admin, sendEmail);
  await recordEvent(inviteRow(user, sendEmail ? "email" : "link"));
  return sendEmail ? withoutLink(user) : user;
}
async function invite(rawEmail, admin, sendEmail) {
  const email = normalizeEmail(rawEmail);
  const temp = tempPassword();
  try {
    const res = await cognito3.send(
      new import_client_cognito_identity_provider3.AdminCreateUserCommand({
        UserPoolId: USER_POOL_ID2,
        Username: email,
        UserAttributes: [
          { Name: "email", Value: email },
          { Name: "email_verified", Value: "true" }
        ],
        TemporaryPassword: temp,
        DesiredDeliveryMediums: ["EMAIL"],
        ...sendEmail ? {} : { MessageAction: "SUPPRESS" }
      })
    );
    const userId = res.User?.Attributes?.find((a) => a.Name === SUB_ATTR)?.Value ?? "";
    const username = res.User?.Username ?? email;
    if (admin) {
      await cognito3.send(
        new import_client_cognito_identity_provider3.AdminAddUserToGroupCommand({
          UserPoolId: USER_POOL_ID2,
          Username: userId || email,
          GroupName: ADMIN_GROUP
        })
      );
    }
    await linkFederatedProviders(username, email);
    log13("created user", { userId, email, admin, sendEmail });
    return { userId, email, admin, pendingInvite: true, roles: [], roleCount: 0, resources: [], resourceCount: 0, signupLink: signupLink(username, temp) };
  } catch (err) {
    throw translateCognitoError(err);
  }
}
async function federatedProviders() {
  if (providersCache && Date.now() - providersCache.at < PROVIDERS_TTL_MS) return providersCache.value;
  const value = (async () => {
    const names = [];
    let NextToken;
    do {
      const page = await cognito3.send(
        new import_client_cognito_identity_provider3.ListIdentityProvidersCommand({ UserPoolId: USER_POOL_ID2, MaxResults: 60, NextToken })
      );
      for (const p of page.Providers ?? []) if (p.ProviderName && p.ProviderType === "OIDC") names.push(p.ProviderName);
      NextToken = page.NextToken;
    } while (NextToken);
    return names;
  })();
  providersCache = { at: Date.now(), value };
  value.catch(() => providersCache = void 0);
  return value;
}
async function linkFederatedProviders(username, email) {
  let providers;
  try {
    providers = await federatedProviders();
  } catch (err) {
    log13("WARN: could not list federated providers (trigger links at first sign-in)", {
      error: err.message
    });
    return;
  }
  await Promise.all(
    providers.map(
      (provider) => cognito3.send(
        new import_client_cognito_identity_provider3.AdminLinkProviderForUserCommand({
          UserPoolId: USER_POOL_ID2,
          DestinationUser: { ProviderName: "Cognito", ProviderAttributeValue: username },
          SourceUser: { ProviderName: provider, ProviderAttributeName: LINK_ATTRIBUTE, ProviderAttributeValue: email }
        })
      ).catch(
        (err) => log13("WARN: federated link failed (trigger links at first sign-in)", {
          provider,
          email,
          error: err.message
        })
      )
    )
  );
}
async function unlinkFederatedProviders(email) {
  let providers;
  try {
    providers = await federatedProviders();
  } catch (err) {
    log13("WARN: could not list federated providers (old email link kept)", { error: err.message });
    return;
  }
  await Promise.all(
    providers.map(
      (provider) => cognito3.send(
        new import_client_cognito_identity_provider3.AdminDisableProviderForUserCommand({
          UserPoolId: USER_POOL_ID2,
          User: { ProviderName: provider, ProviderAttributeName: LINK_ATTRIBUTE, ProviderAttributeValue: email }
        })
      ).catch(
        (err) => log13("WARN: could not drop old federated link", { provider, email, error: err.message })
      )
    )
  );
}
async function createUsers(emails, admin, sendEmail = true) {
  const results = [];
  const seen = /* @__PURE__ */ new Set();
  const batchId = newBatchId();
  const rows = [];
  for (const raw of emails) {
    const email = typeof raw === "string" ? raw.trim() : "";
    const key = email.toLowerCase();
    if (seen.has(key)) continue;
    seen.add(key);
    if (!BULK_EMAIL_RE.test(email)) {
      const message3 = "Not a valid email address";
      results.push({ email: email || String(raw), status: "FAILED", message: message3 });
      rows.push(failedInviteRow(email || String(raw), admin, message3, batchId));
      continue;
    }
    try {
      const user = await invite(email, admin, sendEmail);
      results.push({ email, status: "CREATED", userId: user.userId, ...sendEmail ? {} : { signupLink: user.signupLink } });
      rows.push(inviteRow(user, sendEmail ? "email" : "link", batchId));
    } catch (err) {
      const message3 = err.message || "Could not create the user";
      results.push({ email, status: "FAILED", message: message3 });
      rows.push(failedInviteRow(email, admin, message3, batchId));
    }
  }
  await recordEvents(rows);
  const created = results.filter((r) => r.status === "CREATED").length;
  log13("bulk created users", { requested: emails.length, created, admin, sendEmail });
  return results;
}
async function identityBySub(userId) {
  try {
    const user = await cognito3.send(new import_client_cognito_identity_provider3.AdminGetUserCommand({ UserPoolId: USER_POOL_ID2, Username: userId }));
    const email = user.UserAttributes?.find((a) => a.Name === "email")?.Value;
    if (!email) return void 0;
    return { email, username: user.Username ?? email, status: user.UserStatus };
  } catch (err) {
    if (err.name === "UserNotFoundException") return void 0;
    throw err;
  }
}
async function mintSignupLink(userId) {
  const who = await identityBySub(userId);
  if (!who) throw new NotFoundError("User not found");
  if (who.status && who.status !== "FORCE_CHANGE_PASSWORD") {
    throw new ConflictError("This user has already set a password");
  }
  const temp = tempPassword();
  try {
    await cognito3.send(
      new import_client_cognito_identity_provider3.AdminSetUserPasswordCommand({ UserPoolId: USER_POOL_ID2, Username: who.username, Password: temp, Permanent: false })
    );
  } catch (err) {
    throw translateCognitoError(err);
  }
  await recordEvent({
    category: "users",
    action: "user.reinvite",
    subject: { kind: "user", id: userId, name: who.email },
    target: userTarget(userId),
    details: { delivery: "link" }
  });
  log13("minted sign-up link", { userId });
  return signupLink(who.username, temp);
}
async function resendInvite(userId) {
  const email = await emailBySub(userId);
  if (!email) {
    throw new NotFoundError("User not found");
  }
  try {
    await cognito3.send(
      new import_client_cognito_identity_provider3.AdminCreateUserCommand({
        UserPoolId: USER_POOL_ID2,
        Username: email,
        MessageAction: "RESEND",
        // Without this, RESEND regenerates with Cognito's own alphabet,
        // which isn't URL-fragment-safe (see tempPassword).
        TemporaryPassword: tempPassword(),
        DesiredDeliveryMediums: ["EMAIL"]
      })
    );
  } catch (err) {
    throw translateCognitoError(err);
  }
  await recordEvent({
    category: "users",
    action: "user.reinvite",
    subject: { kind: "user", id: userId, name: email },
    target: userTarget(userId),
    details: { delivery: "email" }
  });
  log13("resent invite", { userId, email });
}
async function resetUserMfa(userId) {
  const email = await emailBySub(userId);
  if (!email) {
    throw new NotFoundError("User not found");
  }
  await cognito3.send(
    new import_client_cognito_identity_provider3.AdminSetUserMFAPreferenceCommand({
      UserPoolId: USER_POOL_ID2,
      Username: email,
      SoftwareTokenMfaSettings: { Enabled: false, PreferredMfa: false }
    })
  );
  await recordEvent({
    category: "users",
    action: "user.mfa.reset",
    subject: { kind: "user", id: userId, name: email },
    target: userTarget(userId)
  });
  log13("reset MFA", { userId, email });
}
async function signOutEverywhere(userId) {
  try {
    await cognito3.send(new import_client_cognito_identity_provider3.AdminUserGlobalSignOutCommand({ UserPoolId: USER_POOL_ID2, Username: userId }));
  } catch (err) {
    if (err.name !== "UserNotFoundException") throw err;
  }
}
async function assertNotLastAdmin(userId, admins) {
  admins ??= await listAdminSubs();
  if (admins.has(userId) && admins.size <= 1) {
    throw new ConflictError(
      "That would remove the last admin \u2014 make another user an admin first"
    );
  }
}
async function updateUser(userId, changes) {
  const admins = changes.admin === void 0 ? void 0 : await listAdminSubs();
  if (changes.admin === false) await assertNotLastAdmin(userId, admins);
  const rows = [];
  try {
    if (changes.email !== void 0) {
      const email = normalizeEmail(changes.email);
      const previous = await emailBySub(userId).catch(() => void 0);
      await cognito3.send(
        new import_client_cognito_identity_provider3.AdminUpdateUserAttributesCommand({
          UserPoolId: USER_POOL_ID2,
          Username: userId,
          UserAttributes: [
            { Name: "email", Value: email },
            { Name: "email_verified", Value: "true" }
          ]
        })
      );
      if (previous && previous !== email) await unlinkFederatedProviders(previous);
      await linkFederatedProviders(userId, email);
      if (previous !== email) {
        rows.push({
          category: "users",
          action: "user.email.change",
          subject: { kind: "user", id: userId, name: email },
          target: userTarget(userId),
          details: { changed: { email: { from: previous, to: email } } }
        });
      }
    }
    if (changes.admin !== void 0) {
      const cmd = changes.admin ? new import_client_cognito_identity_provider3.AdminAddUserToGroupCommand({
        UserPoolId: USER_POOL_ID2,
        Username: userId,
        GroupName: ADMIN_GROUP
      }) : new import_client_cognito_identity_provider3.AdminRemoveUserFromGroupCommand({
        UserPoolId: USER_POOL_ID2,
        Username: userId,
        GroupName: ADMIN_GROUP
      });
      await cognito3.send(cmd);
      if (!changes.admin && admins.has(userId)) {
        await signOutEverywhere(userId).catch(
          (err) => log13("WARN: could not end the demoted admin's sessions", { userId, error: err.message })
        );
      }
      if (changes.admin !== admins.has(userId)) {
        rows.push({
          category: "users",
          action: changes.admin ? "user.admin.grant" : "user.admin.revoke",
          subject: { kind: "user", id: userId },
          target: userTarget(userId)
        });
      }
    }
  } catch (err) {
    throw translateCognitoError(err);
  }
  await recordEvents(rows);
  log13("updated user", { userId, ...changes });
}
async function deleteUser(userId) {
  await assertNotLastAdmin(userId);
  await removeSharesOwnedBy(userId);
  await deleteTokensOwnedBy(userId);
  const email = await emailBySub(userId).catch(() => void 0);
  let alreadyGone = false;
  try {
    await signOutEverywhere(userId);
    await cognito3.send(
      new import_client_cognito_identity_provider3.AdminDeleteUserCommand({
        UserPoolId: USER_POOL_ID2,
        Username: userId
      })
    );
  } catch (err) {
    const translated = translateCognitoError(err);
    if (!(translated instanceof NotFoundError)) throw translated;
    alreadyGone = true;
  }
  await revokeAllForUser(userId);
  await revokeAllResourcesForUser(userId);
  await deleteRequestsForUser(userId);
  await removeUserFromAllGroups(userId);
  await recordEvent({
    category: "users",
    action: "user.delete",
    subject: { kind: "user", id: userId, name: email },
    target: userTarget(userId),
    targetName: email
  });
  if (alreadyGone) {
    log13("re-swept deleted user", { userId });
    throw new NotFoundError(`User ${userId} not found`);
  }
  log13("deleted user", { userId });
}
async function deleteUsers(userIds, actingUserId) {
  const results = [];
  for (const userId of [...new Set(userIds)].filter(Boolean)) {
    if (userId === actingUserId) {
      results.push({
        userId,
        status: "FAILED",
        message: "You can't delete your own account"
      });
      continue;
    }
    try {
      await deleteUser(userId);
      results.push({ userId, status: "DELETED" });
    } catch (err) {
      results.push({
        userId,
        status: "FAILED",
        message: err.message || "Could not delete the user"
      });
    }
  }
  const deleted = results.filter((r) => r.status === "DELETED").length;
  log13("bulk deleted users", { requested: userIds.length, deleted });
  return results;
}
function emailLimitMessage(err) {
  if (err.name !== "LimitExceededException" || !/email/i.test(err.message)) return null;
  return process.env.EMAIL_CONFIGURED === "1" ? "The email service has reached its daily sending limit, so this invite was not sent and the user was not created. Check the SES sending quota in the AWS console (a sandboxed SES also delivers only to verified addresses) and try again tomorrow." : "Cognito's built-in email sender has reached its daily limit \u2014 about 50 messages per AWS account, shared by invites, sign-in codes and password resets \u2014 so this invite was not sent and the user was not created. Try again tomorrow, or set the `email` block in the deployment config so mail goes through SES from your own domain (see the Email deliverability runbook).";
}
function translateCognitoError(err) {
  const name = err.name;
  switch (name) {
    case "LimitExceededException": {
      const friendly = emailLimitMessage(err);
      return friendly ? new ValidationError(friendly) : err;
    }
    case "UsernameExistsException":
      return new ConflictError("A user with that email already exists");
    case "UserNotFoundException":
      return new NotFoundError("User not found");
    case "AliasExistsException":
      return new ConflictError("That email is already in use by another user");
    case "UnsupportedUserStateException":
      return new ConflictError("User has already completed account setup");
    case "InvalidParameterException":
    case "InvalidPasswordException":
    case "CodeDeliveryFailureException":
      return new ValidationError(err.message);
    default:
      return err;
  }
}
var import_client_dynamodb13, import_lib_dynamodb13, import_client_cognito_identity_provider3, ddb13, cognito3, RESOURCES_TABLE_NAME5, USER_POOL_ID2, APP_URL, ADMIN_GROUP, log13, listDirectory, LIST_CAP, SUB_ATTR, normalizeEmail, userTarget, inviteRow, signupLink, failedInviteRow, withoutLink, PROVIDERS_TTL_MS, providersCache, LINK_ATTRIBUTE, BULK_EMAIL_RE, emailBySub;
var init_usersService = __esm({
  "lambdacode/api/services/usersService.ts"() {
    "use strict";
    import_client_dynamodb13 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb13 = require("@aws-sdk/lib-dynamodb");
    import_client_cognito_identity_provider3 = require("@aws-sdk/client-cognito-identity-provider");
    init_grantsService();
    init_directory();
    init_sharesService();
    init_tokensService();
    init_access2();
    init_catalogIndex();
    init_claims();
    init_resourceGrantsService();
    init_groupsService();
    init_requestsService();
    init_serviceUserRegistry();
    init_auditService();
    init_httpErrors();
    init_tempPassword();
    init_resourcesService();
    ddb13 = import_lib_dynamodb13.DynamoDBDocumentClient.from(new import_client_dynamodb13.DynamoDBClient({}));
    cognito3 = new import_client_cognito_identity_provider3.CognitoIdentityProviderClient({});
    RESOURCES_TABLE_NAME5 = process.env.RESOURCES_TABLE_NAME;
    USER_POOL_ID2 = process.env.USER_POOL_ID;
    APP_URL = process.env.APP_URL ?? "";
    ADMIN_GROUP = "admins";
    log13 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    listDirectory = listDirectoryUsers;
    LIST_CAP = 50;
    SUB_ATTR = "sub";
    normalizeEmail = (email) => email.trim();
    userTarget = (userId) => `user#${userId}`;
    inviteRow = (user, delivery, batchId) => ({
      category: "users",
      action: "user.invite",
      subject: { kind: "user", id: user.userId, name: user.email },
      target: userTarget(user.userId),
      details: { admin: user.admin, batchId, delivery }
    });
    signupLink = (username, temp) => `${APP_URL}/login#inv=${username}:${temp}`;
    failedInviteRow = (email, admin, reason, batchId) => ({
      category: "users",
      action: "user.invite",
      outcome: "FAILED",
      reason,
      subject: { kind: "user", id: email, name: email },
      details: { admin, batchId }
    });
    withoutLink = ({ signupLink: _link, ...user }) => user;
    PROVIDERS_TTL_MS = 5 * 60 * 1e3;
    LINK_ATTRIBUTE = "email";
    BULK_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    emailBySub = async (userId) => (await identityBySub(userId))?.email;
  }
});

// lambdacode/api/services/requestsService.ts
var requestsService_exports = {};
__export(requestsService_exports, {
  ADMIN_REVIEW_REASON: () => ADMIN_REVIEW_REASON,
  DURATION_PRESET_HOURS: () => DURATION_PRESET_HOURS,
  GROUP_REVIEW_REASON: () => GROUP_REVIEW_REASON,
  REAPPROVAL_GRACE_DAYS: () => REAPPROVAL_GRACE_DAYS,
  REAPPROVAL_INTERVAL_MONTHS: () => REAPPROVAL_INTERVAL_MONTHS,
  REAPPROVAL_REASON: () => REAPPROVAL_REASON,
  SERVICE_USER_REVIEW_REASON: () => SERVICE_USER_REVIEW_REASON,
  approveRequest: () => approveRequest,
  closePendingRequestsFor: () => closePendingRequestsFor,
  createPluginReapprovalRequest: () => createPluginReapprovalRequest,
  createReapprovalRequest: () => createReapprovalRequest,
  createRequest: () => createRequest,
  createResourceReapprovalRequest: () => createResourceReapprovalRequest,
  createResourceRequest: () => createResourceRequest,
  createReviewRequest: () => createReviewRequest,
  deleteRequestsForUser: () => deleteRequestsForUser,
  denyRequest: () => denyRequest,
  groupTargetOf: () => groupTargetOf,
  isDurationPreset: () => isDurationPreset,
  listMyRequests: () => listMyRequests,
  listRequestableResources: () => listRequestableResources,
  listRequestableRoles: () => listRequestableRoles,
  listRequests: () => listRequests,
  markRequestsSeen: () => markRequestsSeen,
  targetOfRequest: () => targetOfRequest
});
function isDurationPreset(hours) {
  return DURATION_PRESET_HOURS.includes(hours);
}
async function listRequestableRoles(userId) {
  const [index, held, pending] = await Promise.all([
    catalog(),
    listHeldAccountRoles(userId),
    listPendingAccountRoles(userId)
  ]);
  const byAccount = /* @__PURE__ */ new Map();
  for (const role of index.roleByKey.values()) {
    const key = `${role.accountNumber}#${role.roleName}`;
    const grant = held.get(key);
    if (grant && !isExpired(grant) || pending.has(key)) continue;
    const account = index.byNumber.get(role.accountNumber);
    const entry = byAccount.get(role.accountNumber) ?? {
      accountNumber: role.accountNumber,
      name: account?.name,
      ...account?.dims ? { dims: account.dims } : {},
      roles: []
    };
    entry.roles.push({
      roleName: role.roleName,
      displayName: role.displayName,
      description: role.description
    });
    byAccount.set(role.accountNumber, entry);
  }
  const accounts = [...byAccount.values()].sort(
    (a, b) => (a.name ?? a.accountNumber).localeCompare(b.name ?? b.accountNumber)
  );
  for (const a of accounts) {
    a.roles.sort((x, y) => x.roleName.localeCompare(y.roleName));
  }
  log14("listed requestable roles", { userId, accountCount: accounts.length });
  return accounts;
}
async function createRequest(userId, accountNumber, roleName, reason, requestedDurationHours) {
  const role = await ddb14.send(
    new import_lib_dynamodb14.GetCommand({
      TableName: ROLES_TABLE_NAME3,
      Key: { accountNumber, roleName }
    })
  );
  if (!role.Item) {
    throw new NotFoundError(
      `Role ${roleName} not found in account ${accountNumber}`
    );
  }
  if (requestedDurationHours !== void 0 && !isDurationPreset(requestedDurationHours)) {
    throw new ValidationError(
      `duration must be one of ${DURATION_PRESET_HOURS.join(", ")} hours`
    );
  }
  const key = `${accountNumber}#${roleName}`;
  const [held, pending] = await Promise.all([
    listHeldAccountRoles(userId),
    listPendingAccountRoles(userId)
  ]);
  const heldGrant = held.get(key);
  if (heldGrant && !heldGrant.expiresAt) {
    throw new ConflictError(`You already have ${roleName} in ${accountNumber}`);
  }
  if (pending.has(key)) {
    throw new ConflictError(
      `You already have a pending request for ${roleName} in ${accountNumber}`
    );
  }
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId,
    accountNumber,
    roleName,
    reason: reason?.trim() || void 0,
    ...requestedDurationHours !== void 0 ? { requestedDurationHours } : {},
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(
    new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request })
  );
  await recordEvent({
    category: "request",
    action: "request.create",
    ...auditShape(request),
    details: { requestId: request.requestId, requestedDurationHours, note: request.reason }
  });
  log14("created request", {
    requestId: request.requestId,
    userId,
    key,
    requestedDurationHours
  });
  return request;
}
async function listRequestableResources(userId) {
  const [resources, index, held, pending] = await Promise.all([
    listResources(),
    catalog(),
    listUserResourceGrants(userId),
    listPendingResourceIds(userId)
  ]);
  const accountNames = new Map([...index.byNumber.values()].filter((a) => a.name).map((a) => [a.accountNumber, a.name]));
  const heldById = new Map(held.map((g) => [g.resourceId, g]));
  const out = [];
  for (const r of resources) {
    const grant = heldById.get(r.resourceId);
    if (grant && !isExpired(grant) || pending.has(r.resourceId)) continue;
    out.push({
      resourceId: r.resourceId,
      name: r.name,
      type: r.type,
      description: r.description,
      accountNumber: r.accountNumber,
      accountName: accountNames.get(r.accountNumber)
    });
  }
  log14("listed requestable resources", { userId, count: out.length });
  return out;
}
async function createResourceRequest(userId, resourceId, reason, requestedDurationHours) {
  const resource = await getResource(resourceId);
  if (requestedDurationHours !== void 0 && !isDurationPreset(requestedDurationHours)) {
    throw new ValidationError(
      `duration must be one of ${DURATION_PRESET_HOURS.join(", ")} hours`
    );
  }
  const [held, pending] = await Promise.all([
    listUserResourceGrants(userId),
    listPendingResourceIds(userId)
  ]);
  const heldGrant = held.find((g) => g.resourceId === resourceId);
  if (heldGrant && !heldGrant.expiresAt) {
    throw new ConflictError(`You already have access to ${resource.name}`);
  }
  if (pending.has(resourceId)) {
    throw new ConflictError(
      `You already have a pending request for ${resource.name}`
    );
  }
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId,
    kind: "RESOURCE",
    resourceId,
    reason: reason?.trim() || void 0,
    ...requestedDurationHours !== void 0 ? { requestedDurationHours } : {},
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(
    new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request })
  );
  await recordEvent({
    category: "request",
    action: "request.create",
    ...auditShape(request),
    targetName: resource.name,
    accountNumber: resource.accountNumber,
    details: { requestId: request.requestId, requestedDurationHours, note: request.reason }
  });
  log14("created resource request", {
    requestId: request.requestId,
    userId,
    resourceId,
    requestedDurationHours
  });
  return request;
}
async function createResourceReapprovalRequest(userId, resourceId) {
  let resource;
  try {
    resource = await getResource(resourceId);
  } catch (err) {
    if (err instanceof NotFoundError) return null;
    throw err;
  }
  const pending = await listPendingResourceIds(userId);
  if (pending.has(resourceId)) return null;
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId,
    kind: "RESOURCE",
    resourceId,
    type: "REAPPROVAL",
    reason: REAPPROVAL_REASON,
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(
    new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request })
  );
  await recordReviewRaised(request, { targetName: resource.name, accountNumber: resource.accountNumber });
  log14("created resource reapproval request", {
    requestId: request.requestId,
    userId,
    resourceId
  });
  return request;
}
async function createPluginReapprovalRequest(userId, pluginId, accountNumber, permission) {
  const pending = await listPendingRows(userId);
  const dup = pending.some(
    (it) => it.kind === "PLUGIN" && it.pluginId === pluginId && it.accountNumber === accountNumber && it.permission === permission
  );
  if (dup) return null;
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId,
    kind: "PLUGIN",
    pluginId,
    accountNumber,
    permission,
    type: "REAPPROVAL",
    reason: REAPPROVAL_REASON,
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request }));
  await recordReviewRaised(request);
  log14("created plugin reapproval request", { requestId: request.requestId, userId, pluginId, accountNumber, permission });
  return request;
}
async function createReapprovalRequest(userId, accountNumber, roleName) {
  const key = `${accountNumber}#${roleName}`;
  const pending = await listPendingAccountRoles(userId);
  if (pending.has(key)) return null;
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId,
    accountNumber,
    roleName,
    type: "REAPPROVAL",
    reason: REAPPROVAL_REASON,
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(
    new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request })
  );
  await recordReviewRaised(request);
  log14("created reapproval request", { requestId: request.requestId, userId, key });
  return request;
}
async function createReviewRequest(subjectId, kind) {
  const pending = await listPendingRows(subjectId);
  if (pending.some((it) => it.kind === kind)) return null;
  const request = {
    requestId: (0, import_crypto8.randomUUID)(),
    userId: subjectId,
    kind,
    // A GROUP review is the whole bundle at once (one question per group, however many roles it holds).
    ...kind === "GROUP" ? { groupId: subjectId } : {},
    type: "REAPPROVAL",
    reason: kind === "ADMIN" ? ADMIN_REVIEW_REASON : kind === "SERVICE_USER" ? SERVICE_USER_REVIEW_REASON : GROUP_REVIEW_REASON,
    status: "PENDING",
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  await ddb14.send(
    new import_lib_dynamodb14.PutCommand({ TableName: REQUESTS_TABLE_NAME, Item: request })
  );
  await recordReviewRaised(request);
  log14("created review request", {
    requestId: request.requestId,
    subjectId,
    kind
  });
  return request;
}
async function listMyRequests(userId) {
  const items = await queryAll({
    TableName: REQUESTS_TABLE_NAME,
    IndexName: "byUser",
    KeyConditionExpression: "userId = :u",
    ExpressionAttributeValues: { ":u": userId },
    ScanIndexForward: false
    // newest first
  });
  log14("listed my requests", { userId, count: items.length });
  return items;
}
async function markRequestsSeen(userId) {
  const mine = await listMyRequests(userId);
  const unseen = mine.filter((r) => r.status !== "PENDING" && !r.seen);
  for (const r of unseen) {
    try {
      await ddb14.send(
        new import_lib_dynamodb14.UpdateCommand({
          TableName: REQUESTS_TABLE_NAME,
          Key: { requestId: r.requestId },
          UpdateExpression: "SET seen = :true",
          // The condition means a mismatched id can never touch someone else's row.
          ConditionExpression: "userId = :u",
          ExpressionAttributeValues: { ":true": true, ":u": userId }
        })
      );
    } catch (err) {
      if (err.name !== CONDITION_FAILED4) throw err;
    }
  }
  if (unseen.length) log14("marked requests seen", { userId, count: unseen.length });
  return unseen.length;
}
async function listRequests(status) {
  if (!status) {
    const all = await scanAll3({ TableName: REQUESTS_TABLE_NAME });
    return all.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
  }
  const items = await queryAll({
    TableName: REQUESTS_TABLE_NAME,
    IndexName: "byStatus",
    KeyConditionExpression: "#s = :s",
    ExpressionAttributeNames: STATUS_ALIAS,
    ExpressionAttributeValues: { ":s": status },
    ScanIndexForward: true
    // oldest first — longest wait at the top
  });
  log14("listed requests", { status, count: items.length });
  return items;
}
async function approveRequest(requestId, adminUserId, note, durationHours) {
  if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
    throw new ValidationError(
      `duration must be one of ${DURATION_PRESET_HOURS.join(", ")} hours`
    );
  }
  if (durationHours !== void 0) {
    const current = await ddb14.send(
      new import_lib_dynamodb14.GetCommand({ TableName: REQUESTS_TABLE_NAME, Key: { requestId } })
    );
    if (current.Item?.type === "REAPPROVAL") {
      throw new ValidationError("A reapproval renews the existing grant as it is \u2014 a duration does not apply");
    }
  }
  const claimed = await decide(
    requestId,
    "APPROVED",
    adminUserId,
    note,
    durationHours
  );
  const expiresAt = durationHours !== void 0 && claimed.decidedAt ? new Date(
    Date.parse(claimed.decidedAt) + durationHours * 60 * 60 * 1e3
  ).toISOString() : void 0;
  try {
    if (claimed.kind === "GROUP") {
      await markGroupReviewed(claimed.userId, adminUserId);
    } else if (claimed.kind === "ADMIN") {
      await upsertPref(claimed.userId, ADMIN_REVIEW_TARGET, {
        reviewedAt: (/* @__PURE__ */ new Date()).toISOString()
      });
    } else if (claimed.kind === "SERVICE_USER") {
      await markReviewed(claimed.userId);
    } else if (claimed.groupId) {
      if (claimed.kind === "PLUGIN") await assertPluginAssignable(pluginKeyOf(claimed));
      await restampGroupTarget(claimed.groupId, groupTargetOf(claimed), adminUserId);
    } else if (claimed.kind === "PLUGIN") {
      if (claimed.type === "REAPPROVAL") await assertStillHeld(claimed);
      await assignPlugin({ ...pluginKeyOf(claimed), principal: { kind: "user", userId: claimed.userId }, grantedBy: adminUserId, fromRequestId: requestId });
    } else if (claimed.type === "REAPPROVAL" && claimed.kind === "RESOURCE") {
      await renewResourceGrant(claimed.resourceId, claimed.userId, adminUserId, { fromRequestId: requestId });
    } else if (claimed.type === "REAPPROVAL") {
      await renewRole(claimed.accountNumber, claimed.roleName, claimed.userId, adminUserId, { fromRequestId: requestId });
    } else if (claimed.kind === "RESOURCE") {
      await assignResource(
        claimed.resourceId,
        claimed.userId,
        adminUserId,
        expiresAt,
        { fromRequestId: requestId }
      );
    } else {
      await assignRole(
        claimed.accountNumber,
        claimed.roleName,
        claimed.userId,
        adminUserId,
        expiresAt,
        { fromRequestId: requestId }
      );
    }
  } catch (err) {
    await releaseClaim(requestId);
    log14("ERROR: approve failed, request returned to pending", {
      requestId,
      error: err.message
    });
    throw err;
  }
  await recordEvent({
    category: "request",
    action: "request.approve",
    ...auditShape(claimed),
    details: { requestId, durationHours, note, expiresAt, ...reviewFlag(claimed) }
  });
  log14("approved request", {
    requestId,
    userId: claimed.userId,
    accountNumber: claimed.accountNumber,
    roleName: claimed.roleName,
    adminUserId
  });
  return claimed;
}
async function denyRequest(requestId, adminUserId, note) {
  const decided = await decide(requestId, "DENIED", adminUserId, note);
  if (decided.type === "REAPPROVAL") {
    if (decided.kind === "ADMIN" || decided.kind === "SERVICE_USER" || decided.kind === "GROUP") {
      try {
        if (decided.kind === "ADMIN") {
          await lazyUsers().updateUser(decided.userId, { admin: false });
        } else if (decided.kind === "GROUP") {
          await deleteGroup(decided.userId);
        } else {
          await deleteServiceUser(decided.userId);
        }
      } catch (err) {
        if (!(err instanceof NotFoundError)) {
          await releaseClaim(requestId);
          throw err;
        }
      }
    } else {
      try {
        if (decided.groupId) {
          await revokeGroupTarget(decided.groupId, groupTargetOf(decided));
        } else if (decided.kind === "PLUGIN") {
          await revokePlugin({ ...pluginKeyOf(decided), principal: { kind: "user", userId: decided.userId }, via: "REAPPROVAL" });
        } else if (decided.kind === "RESOURCE") {
          await revokeResourceGrant(
            decided.resourceId,
            decided.userId,
            "REAPPROVAL"
          );
        } else {
          await revokeRole(
            decided.accountNumber,
            decided.roleName,
            decided.userId,
            "REAPPROVAL"
          );
        }
      } catch (err) {
        if (!(err instanceof NotFoundError) && !(err instanceof ConflictError)) {
          await releaseClaim(requestId);
          throw err;
        }
      }
    }
  }
  await recordEvent({
    category: "request",
    action: "request.deny",
    reason: note || void 0,
    ...auditShape(decided),
    details: { requestId, note: note || void 0, ...reviewFlag(decided) }
  });
  log14("denied request", {
    requestId,
    userId: decided.userId,
    adminUserId,
    type: decided.type ?? "ACCESS"
  });
  return decided;
}
function groupTargetOf(req) {
  if (req.kind === "RESOURCE") return resourceTarget(req.resourceId);
  if (req.kind === "PLUGIN") return pluginTarget(req.pluginId, req.accountNumber, req.permission);
  return roleTarget(req.accountNumber, req.roleName);
}
function auditShape(req) {
  const subject = req.groupId ? { kind: "group", id: req.groupId } : { kind: req.kind === "SERVICE_USER" ? "serviceUser" : "user", id: req.userId };
  const hasTarget = req.kind === "RESOURCE" ? Boolean(req.resourceId) : req.kind === "PLUGIN" ? Boolean(req.pluginId && req.accountNumber && req.permission) : req.kind !== "ADMIN" && req.kind !== "SERVICE_USER" && req.kind !== "GROUP" && Boolean(req.accountNumber && req.roleName);
  return hasTarget ? { subject, target: groupTargetOf(req), targetName: req.roleName } : { subject };
}
async function recordReviewRaised(request, snapshot2 = {}) {
  await recordEvent({
    category: "request",
    action: "review.raise",
    ...auditShape(request),
    ...snapshot2,
    details: { requestId: request.requestId }
  });
}
async function decide(requestId, status, adminUserId, note, grantedDurationHours) {
  const current = await ddb14.send(
    new import_lib_dynamodb14.GetCommand({ TableName: REQUESTS_TABLE_NAME, Key: { requestId } })
  );
  const pending = current.Item;
  if (pending?.kind === "ADMIN" && pending.userId === adminUserId) {
    const admins = await lazyUsers().listAdminSubs();
    if (admins.size > 1) {
      throw new ConflictError(
        "This is your own admin review \u2014 another admin must decide it."
      );
    }
  }
  try {
    const res = await ddb14.send(
      new import_lib_dynamodb14.UpdateCommand({
        TableName: REQUESTS_TABLE_NAME,
        Key: { requestId },
        UpdateExpression: "SET #s = :next, decidedAt = :at, decidedBy = :by, seen = :false" + (note ? ", decisionNote = :note" : "") + (grantedDurationHours !== void 0 ? ", grantedDurationHours = :dur" : ""),
        ConditionExpression: "attribute_exists(requestId) AND #s = :pending",
        ExpressionAttributeNames: STATUS_ALIAS,
        ExpressionAttributeValues: {
          ":next": status,
          ":pending": "PENDING",
          ":at": (/* @__PURE__ */ new Date()).toISOString(),
          ":by": adminUserId,
          ":false": false,
          ...note ? { ":note": note } : {},
          ...grantedDurationHours !== void 0 ? { ":dur": grantedDurationHours } : {}
        },
        ReturnValues: "ALL_NEW"
      })
    );
    return res.Attributes;
  } catch (err) {
    if (err.name === CONDITION_FAILED4) {
      const current2 = await ddb14.send(
        new import_lib_dynamodb14.GetCommand({
          TableName: REQUESTS_TABLE_NAME,
          Key: { requestId }
        })
      );
      if (!current2.Item) {
        throw new NotFoundError(`Request ${requestId} not found`);
      }
      throw new ConflictError(
        `Request was already ${String(current2.Item.status).toLowerCase()}`
      );
    }
    throw err;
  }
}
async function releaseClaim(requestId) {
  try {
    await ddb14.send(
      new import_lib_dynamodb14.UpdateCommand({
        TableName: REQUESTS_TABLE_NAME,
        Key: { requestId },
        UpdateExpression: "SET #s = :pending REMOVE decidedAt, decidedBy, seen, decisionNote, grantedDurationHours",
        ConditionExpression: "attribute_exists(requestId)",
        ExpressionAttributeNames: STATUS_ALIAS,
        ExpressionAttributeValues: { ":pending": "PENDING" }
      })
    );
  } catch (err) {
    if (err.name !== CONDITION_FAILED4) {
      log14("ERROR: could not roll back request claim", {
        requestId,
        error: err.message
      });
    }
  }
}
async function deleteRequestsForUser(userId, opts = {}) {
  const targets = opts.targets ? new Set(opts.targets) : void 0;
  const except = new Set(opts.exceptKinds ?? []);
  const rows = await queryAll({
    TableName: REQUESTS_TABLE_NAME,
    IndexName: "byUser",
    KeyConditionExpression: "userId = :u",
    ExpressionAttributeValues: { ":u": userId },
    ProjectionExpression: "requestId, #s, #t, #k, accountNumber, roleName, resourceId, pluginId, #p",
    ExpressionAttributeNames: { ...STATUS_ALIAS, "#t": "type", "#k": "kind", "#p": "permission" }
  });
  const mine = rows.filter(
    (r) => (!opts.onlyPending || r.status === "PENDING") && (!opts.onlyReviews || r.type === "REAPPROVAL") && !(r.kind && except.has(r.kind)) && (!opts.target || targetOfRequest(r) === opts.target) && (!targets || targets.has(targetOfRequest(r) ?? ""))
  );
  for (const r of mine) {
    await ddb14.send(
      new import_lib_dynamodb14.DeleteCommand({
        TableName: REQUESTS_TABLE_NAME,
        Key: { requestId: r.requestId }
      })
    );
  }
  if (mine.length) {
    log14("deleted requests", { userId, removed: mine.length, ...opts });
  }
  return mine.length;
}
async function closePendingRequestsFor(targets, note) {
  const wanted = new Set(Array.isArray(targets) ? targets : [targets]);
  if (!wanted.size) return 0;
  const pending = (await listRequests("PENDING")).filter((r) => {
    const t = targetOfRequest(r);
    return t !== void 0 && wanted.has(t);
  });
  const by = currentActor()?.id ?? "system:catalog";
  let closed = 0;
  for (const r of pending) {
    const reason = typeof note === "function" ? note(targetOfRequest(r)) : note;
    try {
      const decided = await decide(r.requestId, "DENIED", by, reason);
      await recordEvent({
        category: "request",
        action: "request.deny",
        reason,
        ...auditShape(decided),
        details: { requestId: r.requestId, note: reason, ...reviewFlag(decided), catalogCascade: true }
      });
      closed++;
    } catch (err) {
      if (!(err instanceof ConflictError) && !(err instanceof NotFoundError)) throw err;
    }
  }
  if (closed) log14("closed pending requests for removed targets", { targets: [...wanted], closed });
  return closed;
}
function targetOfRequest(r) {
  if (r.kind === "ADMIN" || r.kind === "SERVICE_USER" || r.kind === "GROUP") return void 0;
  if (r.kind === "RESOURCE") return r.resourceId ? resourceTarget(r.resourceId) : void 0;
  if (r.kind === "PLUGIN") {
    return r.pluginId && r.accountNumber && r.permission ? pluginTarget(r.pluginId, r.accountNumber, r.permission) : void 0;
  }
  return r.accountNumber && r.roleName ? roleTarget(r.accountNumber, r.roleName) : void 0;
}
async function assertStillHeld(req) {
  const target = targetOfRequest(req);
  if (!target || !await getRow(userPrincipal(req.userId), target)) {
    throw new ConflictError("This review's access was already revoked \u2014 there is nothing to renew");
  }
}
async function listHeldAccountRoles(userId) {
  const grants = await listUserGrants(userId);
  return new Map(
    grants.map((g) => [`${g.accountNumber}#${g.roleName}`, { expiresAt: g.expiresAt }])
  );
}
async function listPendingAccountRoles(userId) {
  const items = await listPendingRows(userId);
  return new Set(
    items.filter((it) => it.kind !== "RESOURCE" && it.kind !== "PLUGIN" && it.accountNumber).map((it) => `${it.accountNumber}#${it.roleName}`)
  );
}
async function listPendingResourceIds(userId) {
  const items = await listPendingRows(userId);
  return new Set(
    items.filter((it) => it.kind === "RESOURCE").map((it) => it.resourceId)
  );
}
async function listPendingRows(userId) {
  return queryAll({
    TableName: REQUESTS_TABLE_NAME,
    IndexName: "byUser",
    KeyConditionExpression: "userId = :u",
    FilterExpression: "#s = :pending",
    ExpressionAttributeNames: STATUS_ALIAS,
    ExpressionAttributeValues: { ":u": userId, ":pending": "PENDING" }
  });
}
async function queryAll(input) {
  const all = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb14.send(
      new import_lib_dynamodb14.QueryCommand({ ...input, ExclusiveStartKey })
    );
    all.push(...page.Items ?? []);
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return all;
}
async function scanAll3(input) {
  const all = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb14.send(
      new import_lib_dynamodb14.ScanCommand({ ...input, ExclusiveStartKey })
    );
    all.push(...page.Items ?? []);
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return all;
}
var import_crypto8, import_client_dynamodb14, import_lib_dynamodb14, lazyUsers, ddb14, REQUESTS_TABLE_NAME, ROLES_TABLE_NAME3, log14, CONDITION_FAILED4, STATUS_ALIAS, REAPPROVAL_INTERVAL_MONTHS, REAPPROVAL_GRACE_DAYS, REAPPROVAL_REASON, DURATION_PRESET_HOURS, ADMIN_REVIEW_REASON, SERVICE_USER_REVIEW_REASON, GROUP_REVIEW_REASON, pluginKeyOf, reviewFlag;
var init_requestsService = __esm({
  "lambdacode/api/services/requestsService.ts"() {
    "use strict";
    import_crypto8 = require("crypto");
    import_client_dynamodb14 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb14 = require("@aws-sdk/lib-dynamodb");
    init_grantsService();
    init_resourceGrantsService();
    init_resourcesService();
    init_access2();
    init_pluginGrantsService();
    init_groupsService();
    init_serviceUsersService();
    init_auditService();
    init_actorContext();
    init_httpErrors();
    init_catalogIndex();
    lazyUsers = () => (init_usersService(), __toCommonJS(usersService_exports));
    ddb14 = import_lib_dynamodb14.DynamoDBDocumentClient.from(new import_client_dynamodb14.DynamoDBClient({}));
    REQUESTS_TABLE_NAME = process.env.REQUESTS_TABLE_NAME;
    ROLES_TABLE_NAME3 = process.env.ROLES_TABLE_NAME;
    log14 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    CONDITION_FAILED4 = "ConditionalCheckFailedException";
    STATUS_ALIAS = { "#s": "status" };
    REAPPROVAL_INTERVAL_MONTHS = 12;
    REAPPROVAL_GRACE_DAYS = 14;
    REAPPROVAL_REASON = "12-month reapproval \u2014 standing access is due for periodic review.";
    DURATION_PRESET_HOURS = [1, 12, 24, 72, 168, 720];
    ADMIN_REVIEW_REASON = "12-month review \u2014 should this user remain an admin?";
    SERVICE_USER_REVIEW_REASON = "12-month review \u2014 is this automation still needed?";
    GROUP_REVIEW_REASON = "12-month review \u2014 is this group's standing access still needed?";
    pluginKeyOf = (req) => ({ pluginId: req.pluginId, accountNumber: req.accountNumber, permission: req.permission });
    reviewFlag = (req) => req.type === "REAPPROVAL" ? { review: true } : {};
  }
});

// lambdacode/api/services/grantsService.ts
async function revokeDirectRow(userId, target, via, row, resourceNames) {
  let stillHeld = false;
  const removed = await withAccessDiff([userId], via, () => deleteRow(userPrincipal(userId), target), resourceNames, {
    derived: false,
    // No loss means something else still covers the target (a group; for plugins an admin row) — or the row
    // had already expired; the diff's after-set tells them apart so the flag never claims access that isn't there.
    onDiff: (changes) => {
      stillHeld = changes.some((c) => c.userId === userId && c.after.has(target));
    }
  });
  if (!removed) return false;
  if (via !== "REAPPROVAL") await clearPendingReviews(userId, target);
  const groups = stillHeld ? (await effectiveAccess(userId)).get(target)?.groups ?? [] : [];
  const stillHeldVia = stillHeld ? groups.length ? groups : true : void 0;
  await recordEvent({
    category: "access",
    ...row,
    subject: { kind: "user", id: userId },
    target,
    details: { via, ...stillHeldVia ? { stillHeldVia } : {} }
  });
  return true;
}
async function clearPendingReviews(userId, target, targets) {
  const { deleteRequestsForUser: deleteRequestsForUser2 } = (init_requestsService(), __toCommonJS(requestsService_exports));
  await deleteRequestsForUser2(userId, { onlyPending: true, onlyReviews: true, target, targets });
}
async function assertRoleExists(accountNumber, roleName) {
  const role = await ddb15.send(
    new import_lib_dynamodb15.GetCommand({ TableName: ROLES_TABLE_NAME4, Key: { accountNumber, roleName } })
  );
  if (!role.Item) {
    throw new NotFoundError(`Role ${roleName} not found in account ${accountNumber}`);
  }
}
async function assignRole(accountNumber, roleName, userId, grantedBy, expiresAt, opts) {
  await assertRoleExists(accountNumber, roleName);
  const target = roleTarget(accountNumber, roleName);
  if (expiresAt) {
    const existing = await getRow(userPrincipal(userId), target);
    if (existing && !existing.expiresAt) {
      log15("kept long-term grant (no downgrade)", { userId, accountNumber, roleName, requestedExpiresAt: expiresAt });
      return { userId, accountNumber, roleName };
    }
  }
  await withAccessDiff(
    [userId],
    "ADMIN",
    () => putRow({
      principal: userPrincipal(userId),
      target,
      grantedBy,
      grantedAt: (/* @__PURE__ */ new Date()).toISOString(),
      ...expiresAt ? { expiresAt } : {}
    }),
    void 0,
    { derived: false, gainNotices: !opts?.fromRequestId }
  );
  await recordEvent({
    category: "access",
    action: "role.grant",
    subject: { kind: "user", id: userId },
    target,
    targetName: roleName,
    details: { expiresAt, requestId: opts?.fromRequestId }
  });
  log15("assigned role", { userId, accountNumber, roleName, grantedBy, expiresAt });
  return { userId, accountNumber, roleName, expiresAt };
}
async function renewRole(accountNumber, roleName, userId, grantedBy, opts) {
  const target = roleTarget(accountNumber, roleName);
  const renewed = await updateExisting(userPrincipal(userId), target, {
    grantedBy,
    grantedAt: (/* @__PURE__ */ new Date()).toISOString()
  });
  if (!renewed) {
    throw new ConflictError(`${userId} no longer holds ${roleName} in ${accountNumber} \u2014 there is nothing to renew`);
  }
  await recordEvent({
    category: "access",
    action: "role.grant",
    subject: { kind: "user", id: userId },
    target,
    targetName: roleName,
    details: { requestId: opts?.fromRequestId, renewed: true }
  });
  log15("renewed role", { userId, accountNumber, roleName, grantedBy });
}
async function revokeRole(accountNumber, roleName, userId, via = "ADMIN") {
  const target = roleTarget(accountNumber, roleName);
  const removed = await revokeDirectRow(userId, target, via, { action: "role.revoke", targetName: roleName });
  if (!removed) {
    throw new NotFoundError(`No grant for user ${userId} on ${roleName} in ${accountNumber}`);
  }
  log15("revoked role", { userId, accountNumber, roleName });
}
async function listGrantees(accountNumber, roleName) {
  const holders = await holdersOf(roleTarget(accountNumber, roleName));
  return holders.map((h) => ({
    userId: h.userId,
    grantedBy: h.direct?.grantedBy,
    grantedAt: h.direct?.grantedAt,
    expiresAt: h.direct?.expiresAt,
    direct: Boolean(h.direct),
    viaGroup: h.direct ? void 0 : h.groups[0],
    viaGroups: h.groups
  }));
}
async function listUserGrants(userId) {
  const out = [];
  for (const [t, e] of await effectiveAccess(userId)) {
    const p = parseTarget(t);
    if (p?.kind !== "role") continue;
    out.push({
      accountNumber: p.accountNumber,
      roleName: p.roleName,
      grantedBy: e.direct?.grantedBy,
      grantedAt: e.direct?.grantedAt,
      // Effective expiry: a temporary direct grant with a group behind it is
      // long-term in practice, so no expiry is reported.
      expiresAt: e.groups.length ? void 0 : e.direct?.expiresAt,
      viaGroup: e.direct ? void 0 : e.groups[0],
      viaGroups: e.groups
    });
  }
  return out;
}
async function assignRolesToUsers(roles, userIds, grantedBy, expiresAt) {
  const results = [];
  const events = [];
  const uniqueUsers = [...new Set(userIds)].filter(Boolean);
  const seenRoles = /* @__PURE__ */ new Set();
  const batchId = newBatchId();
  await withAccessDiff(
    uniqueUsers,
    "ADMIN",
    async () => {
      for (const { accountNumber, roleName } of roles) {
        const target = roleTarget(accountNumber, roleName);
        if (seenRoles.has(target)) continue;
        seenRoles.add(target);
        const failed = (userId, message3) => {
          results.push({ userId, accountNumber, roleName, status: "FAILED", message: message3 });
          events.push(pairEvent("role.grant", userId, target, roleName, { batchId }, message3));
        };
        const role = await ddb15.send(
          new import_lib_dynamodb15.GetCommand({ TableName: ROLES_TABLE_NAME4, Key: { accountNumber, roleName } })
        );
        if (!role.Item) {
          for (const userId of uniqueUsers) failed(userId, `Role ${roleName} not found in account ${accountNumber}`);
          continue;
        }
        for (const userId of uniqueUsers) {
          const base = { userId, accountNumber, roleName };
          try {
            const existing = await getRow(userPrincipal(userId), target);
            if (existing && !existing.expiresAt) {
              results.push({ ...base, status: "ALREADY_HAD", message: "Already assigned" });
              continue;
            }
            const replacedTemporary = Boolean(existing && !isExpired(existing));
            await putRow({
              principal: userPrincipal(userId),
              target,
              grantedBy,
              grantedAt: (/* @__PURE__ */ new Date()).toISOString(),
              ...expiresAt ? { expiresAt } : {}
            });
            results.push({
              ...base,
              status: "GRANTED",
              ...replacedTemporary ? { message: "Replaced a temporary grant" } : {}
            });
            events.push(pairEvent("role.grant", userId, target, roleName, { batchId, expiresAt, ...replacedTemporary ? { replacedTemporary } : {} }));
          } catch (err) {
            failed(userId, err.message || "Could not write the grant");
          }
        }
      }
    },
    void 0,
    { batchId, derived: false }
  );
  await recordEvents(events);
  const granted = results.filter((r) => r.status === "GRANTED").length;
  log15("bulk assigned roles", { users: uniqueUsers.length, roles: seenRoles.size, granted, grantedBy, expiresAt });
  return results;
}
async function revokeRolesFromUsers(roles, userIds) {
  const results = [];
  const events = [];
  const uniqueUsers = [...new Set(userIds)].filter(Boolean);
  const seenRoles = /* @__PURE__ */ new Set();
  const batchId = newBatchId();
  await withAccessDiff(
    uniqueUsers,
    "ADMIN",
    async () => {
      for (const { accountNumber, roleName } of roles) {
        const target = roleTarget(accountNumber, roleName);
        if (seenRoles.has(target)) continue;
        seenRoles.add(target);
        for (const userId of uniqueUsers) {
          const base = { userId, accountNumber, roleName };
          try {
            const removed = await deleteRow(userPrincipal(userId), target);
            results.push(
              removed ? { ...base, status: "REVOKED" } : { ...base, status: "SKIPPED", message: "No direct grant to revoke" }
            );
            if (removed) {
              events.push(pairEvent("role.revoke", userId, target, roleName, { via: "ADMIN", batchId }));
              await clearPendingReviews(userId, target);
            }
          } catch (err) {
            const message3 = err.message || "Could not revoke the grant";
            results.push({ ...base, status: "FAILED", message: message3 });
            events.push(pairEvent("role.revoke", userId, target, roleName, { via: "ADMIN", batchId }, message3));
          }
        }
      }
    },
    void 0,
    { batchId, derived: false }
  );
  await recordEvents(events);
  log15("bulk revoked roles", { users: uniqueUsers.length, roles: seenRoles.size, revoked: results.filter((r) => r.status === "REVOKED").length });
  return results;
}
function expiringThresholdMs(grant) {
  const end = Date.parse(grant.expiresAt);
  const start = grant.grantedAt ? Date.parse(grant.grantedAt) : NaN;
  const half = Number.isNaN(start) ? EXPIRING_WINDOW_MS : (end - start) / 2;
  return Math.min(EXPIRING_WINDOW_MS, half);
}
function expiryPhases(rows, toNotice, now = Date.now()) {
  const expiring = [];
  const expired = [];
  for (const it of rows) {
    if (!it.expiresAt) continue;
    const base = toNotice(it.target);
    if (!base) continue;
    const end = Date.parse(it.expiresAt);
    if (end <= now) {
      if (now - end <= EXPIRED_NOTICE_DAYS * 24 * 60 * 60 * 1e3) {
        expired.push({ ...base, expiresAt: it.expiresAt, seen: Boolean(it.expiredSeen) });
      }
    } else if (end - now <= expiringThresholdMs({ grantedAt: it.grantedAt, expiresAt: it.expiresAt })) {
      expiring.push({ ...base, expiresAt: it.expiresAt, seen: Boolean(it.expiringSeen) });
    }
  }
  const soonestFirst = (a, b) => a.expiresAt.localeCompare(b.expiresAt);
  expiring.sort(soonestFirst);
  expired.sort((a, b) => soonestFirst(b, a));
  return { expiring, expired };
}
async function listExpiryNotices(userId) {
  const rows = await queryPrincipal(userPrincipal(userId), "role#");
  return expiryPhases(rows, (t) => {
    const p = parseTarget(t);
    return p?.kind === "role" ? { accountNumber: p.accountNumber, roleName: p.roleName } : null;
  });
}
async function markExpiryPhasesSeen(userId, phases, toTarget) {
  const unseen = [
    ...phases.expiring.filter((n) => !n.seen).map((n) => ({ n, flag: "expiringSeen" })),
    ...phases.expired.filter((n) => !n.seen).map((n) => ({ n, flag: "expiredSeen" }))
  ];
  for (const { n, flag } of unseen) {
    await updateExisting(userPrincipal(userId), toTarget(n), { [flag]: true });
  }
  return unseen.length;
}
async function markExpiryNoticesSeen(userId) {
  const count = await markExpiryPhasesSeen(userId, await listExpiryNotices(userId), (n) => roleTarget(n.accountNumber, n.roleName));
  if (count) log15("marked expiry notices seen", { userId, count });
  return count;
}
async function revokeAllAccessForUser(userId) {
  const rows = (await queryPrincipal(userPrincipal(userId))).filter(
    (r) => isGrantTarget(r.target) || r.target.startsWith("member#")
  );
  const batchId = newBatchId();
  await withAccessDiff(
    [userId],
    "ADMIN",
    async () => {
      for (const r of rows) await deleteRow(r.principal, r.target);
    },
    void 0,
    { batchId }
  );
  if (rows.length) {
    await clearPendingReviews(userId, void 0, rows.filter((r) => isGrantTarget(r.target)).map((r) => r.target));
    await recordEvent({
      category: "access",
      action: "user.revoke_all",
      subject: { kind: "user", id: userId },
      details: { removed: rows.length, batchId }
    });
    log15("revoked all access for user", { userId, removed: rows.length });
  }
  return rows.length;
}
async function revokeAllForUser(userId) {
  const rows = await queryPrincipal(userPrincipal(userId));
  for (const r of rows) await deleteRow(r.principal, r.target);
  if (rows.length) log15("removed all access rows for deleted user", { userId, removed: rows.length });
  return rows.length;
}
async function revokeAllForRole(accountNumber, roleName, batchId, onDiff) {
  const target = roleTarget(accountNumber, roleName);
  const holders = await holdersOf(target);
  const rows = await queryTarget(target);
  await withAccessDiff(
    holders.map((h) => h.userId),
    "CASCADE",
    async () => {
      for (const r of rows) await deleteRow(r.principal, r.target);
    },
    void 0,
    { batchId, onDiff, targets: [target] }
  );
  if (rows.length) log15("revoked grants for deleted role", { accountNumber, roleName, removed: rows.length });
  return rows.length;
}
var import_client_dynamodb15, import_lib_dynamodb15, ddb15, ROLES_TABLE_NAME4, log15, pairEvent, EXPIRING_WINDOW_MS, EXPIRED_NOTICE_DAYS;
var init_grantsService = __esm({
  "lambdacode/api/services/grantsService.ts"() {
    "use strict";
    import_client_dynamodb15 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb15 = require("@aws-sdk/lib-dynamodb");
    init_httpErrors();
    init_access2();
    init_accessNotices();
    init_auditService();
    ddb15 = import_lib_dynamodb15.DynamoDBDocumentClient.from(new import_client_dynamodb15.DynamoDBClient({}));
    ROLES_TABLE_NAME4 = process.env.ROLES_TABLE_NAME;
    log15 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    pairEvent = (action, userId, target, roleName, details, reason) => ({
      category: "access",
      action,
      ...reason ? { outcome: "FAILED", reason } : {},
      subject: { kind: "user", id: userId },
      target,
      targetName: roleName,
      details
    });
    EXPIRING_WINDOW_MS = 24 * 60 * 60 * 1e3;
    EXPIRED_NOTICE_DAYS = 7;
  }
});

// lambdacode/api/services/serviceUsersService.ts
function assertValidName(name) {
  if (typeof name !== "string" || !NAME_RE.test(name)) {
    throw new ValidationError(
      "name must be 2-63 characters of lowercase letters, digits, and hyphens (like a hostname)"
    );
  }
}
async function scanRegistry() {
  const rows = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb16.send(
      new import_lib_dynamodb16.ScanCommand({ TableName: SERVICE_USERS_TABLE_NAME2, ExclusiveStartKey })
    );
    rows.push(...page?.Items ?? []);
    ExclusiveStartKey = page?.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return rows;
}
async function getRow2(clientId) {
  const res = await ddb16.send(
    new import_lib_dynamodb16.GetCommand({ TableName: SERVICE_USERS_TABLE_NAME2, Key: { clientId } })
  );
  return res.Item;
}
async function getCurrentRow(clientId) {
  const row = await getRow2(clientId);
  if (!row || row.retiredInto) {
    throw new NotFoundError(`Service user ${clientId} not found`);
  }
  return row;
}
async function createAppClient(name) {
  const res = await cognito4.send(
    new import_client_cognito_identity_provider4.CreateUserPoolClientCommand({
      UserPoolId: USER_POOL_ID3,
      ClientName: name,
      GenerateSecret: true,
      AllowedOAuthFlows: ["client_credentials"],
      AllowedOAuthFlowsUserPoolClient: true,
      AllowedOAuthScopes: [SERVICE_SCOPE],
      // Machines re-fetch tokens automatically, so keep them short — this is also the exposure window
      // after DeleteUserPoolClient (an already-issued token verifies until it expires).
      AccessTokenValidity: 60,
      TokenValidityUnits: { AccessToken: "minutes" },
      // client_credentials issues no refresh token; allowing only the refresh
      // flow keeps every password/SRP path off this client.
      ExplicitAuthFlows: ["ALLOW_REFRESH_TOKEN_AUTH"]
    })
  );
  const clientId = res.UserPoolClient?.ClientId;
  const clientSecret = res.UserPoolClient?.ClientSecret;
  if (!clientId || !clientSecret) {
    throw new Error("Cognito returned no client id/secret");
  }
  return { clientId, clientSecret };
}
async function deleteAppClient(clientId) {
  try {
    await cognito4.send(
      new import_client_cognito_identity_provider4.DeleteUserPoolClientCommand({ UserPoolId: USER_POOL_ID3, ClientId: clientId })
    );
  } catch (err) {
    if (err.name !== "ResourceNotFoundException") throw err;
    log16("app client already gone", { clientId });
  }
}
function toView(row, roles, previous) {
  return {
    clientId: row.clientId,
    name: row.name,
    createdAt: row.createdAt,
    createdBy: row.createdBy,
    lastUsedAt: row.lastUsedAt,
    secretCreatedAt: row.secretCreatedAt,
    reviewedAt: row.reviewedAt,
    scopes: row.scopes ?? [...LEGACY_SERVICE_USER_SCOPES],
    roles,
    ...row.previousClientId ? {
      previous: {
        clientId: row.previousClientId,
        rotatedAt: row.rotatedAt,
        lastUsedAt: previous?.lastUsedAt
      }
    } : {}
  };
}
async function listServiceUsers() {
  const rows = await scanRegistry();
  const byId = new Map(rows.map((r) => [r.clientId, r]));
  const current = rows.filter((r) => !r.retiredInto).sort((a, b) => a.name.localeCompare(b.name) || a.clientId.localeCompare(b.clientId));
  const out = [];
  for (const row of current) {
    out.push(
      toView(
        row,
        await listUserGrants(row.clientId),
        row.previousClientId ? byId.get(row.previousClientId) : void 0
      )
    );
  }
  log16("listed service users", { count: out.length });
  return out;
}
async function createServiceUser(name, createdBy, rawScopes) {
  assertValidName(name);
  const scopes = parseScopes(rawScopes, SERVICE_USER_SCOPES);
  const taken = (await scanRegistry()).some((r) => !r.retiredInto && r.name === name);
  if (taken) {
    throw new ConflictError(`A service user named ${name} already exists`);
  }
  const { clientId, clientSecret } = await createAppClient(name);
  const now = (/* @__PURE__ */ new Date()).toISOString();
  const row = {
    clientId,
    name,
    createdAt: now,
    createdBy,
    secretCreatedAt: now,
    scopes
  };
  await ddb16.send(
    new import_lib_dynamodb16.PutCommand({
      TableName: SERVICE_USERS_TABLE_NAME2,
      Item: row,
      ConditionExpression: "attribute_not_exists(clientId)"
    })
  );
  await recordServiceUserEvent("serviceuser.create", clientId, name, { scopes });
  log16("created service user", { clientId, name, createdBy, scopes });
  return { serviceUser: toView(row, []), clientSecret };
}
async function rotateServiceUser(clientId, actingUserId) {
  const row = await getCurrentRow(clientId);
  if (row.previousClientId) {
    throw new ConflictError(
      "A previous secret is still active \u2014 remove it before rotating again"
    );
  }
  const replacement = await createAppClient(row.name);
  const grants = (await queryPrincipal(userPrincipal(clientId))).filter(
    (r) => isGrantTarget(r.target)
  );
  for (const g of grants) {
    await putRow({ ...g, principal: userPrincipal(replacement.clientId) });
  }
  const now = (/* @__PURE__ */ new Date()).toISOString();
  const newRow = {
    clientId: replacement.clientId,
    name: row.name,
    createdAt: row.createdAt,
    createdBy: row.createdBy,
    secretCreatedAt: now,
    ...row.reviewedAt ? { reviewedAt: row.reviewedAt } : {},
    scopes: row.scopes ?? [...LEGACY_SERVICE_USER_SCOPES],
    previousClientId: clientId,
    rotatedAt: now
  };
  await ddb16.send(
    new import_lib_dynamodb16.PutCommand({ TableName: SERVICE_USERS_TABLE_NAME2, Item: newRow })
  );
  await ddb16.send(
    new import_lib_dynamodb16.UpdateCommand({
      TableName: SERVICE_USERS_TABLE_NAME2,
      Key: { clientId },
      UpdateExpression: "SET retiredInto = :n",
      ExpressionAttributeValues: { ":n": replacement.clientId }
    })
  );
  await recordServiceUserEvent("serviceuser.rotate", clientId, row.name, { replacementClientId: replacement.clientId });
  log16("rotated service user", {
    name: row.name,
    newClientId: replacement.clientId,
    previousClientId: clientId,
    grantsCopied: grants.length,
    by: actingUserId
  });
  return {
    serviceUser: toView(newRow, await listUserGrants(replacement.clientId), row),
    clientSecret: replacement.clientSecret
  };
}
async function updateServiceUserScopes(clientId, rawScopes) {
  const scopes = parseScopes(rawScopes, SERVICE_USER_SCOPES);
  const row = await getCurrentRow(clientId);
  const from = row.scopes ?? [...LEGACY_SERVICE_USER_SCOPES];
  for (const id of [clientId, row.previousClientId].filter(Boolean)) {
    try {
      await ddb16.send(
        new import_lib_dynamodb16.UpdateCommand({
          TableName: SERVICE_USERS_TABLE_NAME2,
          Key: { clientId: id },
          UpdateExpression: "SET scopes = :s",
          ConditionExpression: "attribute_exists(clientId)",
          ExpressionAttributeValues: { ":s": scopes }
        })
      );
    } catch (err) {
      if (id === clientId || err.name !== "ConditionalCheckFailedException") throw err;
    }
  }
  if (from.join(" ") !== scopes.join(" ")) {
    await recordServiceUserEvent("serviceuser.scopes", clientId, row.name, { changed: { scopes: { from, to: scopes } } });
  }
  log16("updated service user scopes", { clientId, name: row.name, from, to: scopes });
  const updated = { ...row, scopes };
  return toView(updated, await listUserGrants(clientId), row.previousClientId ? await getRow2(row.previousClientId) : void 0);
}
async function removePreviousSecret(clientId) {
  const row = await getCurrentRow(clientId);
  const previous = row.previousClientId;
  if (!previous) {
    throw new NotFoundError("No previous secret to remove");
  }
  await deleteAppClient(previous);
  await revokeAllForUser(previous);
  await ddb16.send(
    new import_lib_dynamodb16.DeleteCommand({ TableName: SERVICE_USERS_TABLE_NAME2, Key: { clientId: previous } })
  );
  await ddb16.send(
    new import_lib_dynamodb16.UpdateCommand({
      TableName: SERVICE_USERS_TABLE_NAME2,
      Key: { clientId },
      UpdateExpression: "REMOVE previousClientId, rotatedAt"
    })
  );
  await recordServiceUserEvent("serviceuser.rotate.finish", clientId, row.name, { previousClientId: previous });
  log16("removed previous secret", { clientId, previousClientId: previous });
}
async function markReviewed(clientId) {
  try {
    await ddb16.send(
      new import_lib_dynamodb16.UpdateCommand({
        TableName: SERVICE_USERS_TABLE_NAME2,
        Key: { clientId },
        UpdateExpression: "SET reviewedAt = :t",
        ConditionExpression: "attribute_exists(clientId)",
        ExpressionAttributeValues: { ":t": (/* @__PURE__ */ new Date()).toISOString() }
      })
    );
  } catch (err) {
    if (err.name === "ConditionalCheckFailedException") {
      throw new NotFoundError(`Service user ${clientId} not found`);
    }
    throw err;
  }
  log16("marked service user reviewed", { clientId });
}
async function deleteServiceUser(clientId) {
  const row = await getCurrentRow(clientId);
  const { deleteRequestsForUser: deleteRequestsForUser2 } = (init_requestsService(), __toCommonJS(requestsService_exports));
  for (const id of [row.previousClientId, clientId].filter(Boolean)) {
    await deleteAppClient(id);
    await revokeAllForUser(id);
    await deleteRequestsForUser2(id, { onlyPending: true });
    await ddb16.send(
      new import_lib_dynamodb16.DeleteCommand({ TableName: SERVICE_USERS_TABLE_NAME2, Key: { clientId: id } })
    );
  }
  await recordServiceUserEvent("serviceuser.delete", clientId, row.name);
  log16("deleted service user", { clientId, name: row.name });
}
async function serviceUserNames() {
  return new Map((await scanRegistry()).map((r) => [r.clientId, r.name]));
}
async function serviceUserAdmins() {
  const admin = (scopes) => scopes.includes("admin.write.all") || scopes.includes("admin.read.all");
  return new Set(
    (await scanRegistry()).filter((r) => admin(r.scopes ?? LEGACY_SERVICE_USER_SCOPES)).map((r) => r.clientId)
  );
}
async function touchServiceUser(clientId) {
  try {
    const out = await ddb16.send(
      new import_lib_dynamodb16.UpdateCommand({
        TableName: SERVICE_USERS_TABLE_NAME2,
        Key: { clientId },
        UpdateExpression: "SET lastUsedAt = :t",
        ConditionExpression: "attribute_exists(clientId)",
        ExpressionAttributeValues: { ":t": (/* @__PURE__ */ new Date()).toISOString() },
        ReturnValues: "ALL_NEW"
      })
    );
    return out.Attributes?.name;
  } catch (err) {
    if (err.name !== "ConditionalCheckFailedException") {
      log16("WARN: could not stamp service-user lastUsedAt", {
        clientId,
        error: err.message
      });
    }
    return void 0;
  }
}
var import_client_dynamodb16, import_lib_dynamodb16, import_client_cognito_identity_provider4, ddb16, cognito4, SERVICE_USERS_TABLE_NAME2, USER_POOL_ID3, log16, recordServiceUserEvent, NAME_RE;
var init_serviceUsersService = __esm({
  "lambdacode/api/services/serviceUsersService.ts"() {
    "use strict";
    import_client_dynamodb16 = require("@aws-sdk/client-dynamodb");
    import_lib_dynamodb16 = require("@aws-sdk/lib-dynamodb");
    import_client_cognito_identity_provider4 = require("@aws-sdk/client-cognito-identity-provider");
    init_httpErrors();
    init_access2();
    init_grantsService();
    init_auditService();
    init_serviceUserRegistry();
    init_serviceUserRegistry();
    init_personalTokens();
    init_tokenScopes();
    ddb16 = import_lib_dynamodb16.DynamoDBDocumentClient.from(new import_client_dynamodb16.DynamoDBClient({}));
    cognito4 = new import_client_cognito_identity_provider4.CognitoIdentityProviderClient({});
    SERVICE_USERS_TABLE_NAME2 = process.env.SERVICE_USERS_TABLE_NAME;
    USER_POOL_ID3 = process.env.USER_POOL_ID;
    log16 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    recordServiceUserEvent = (action, clientId, name, details) => recordEvent({
      category: "users",
      action,
      subject: { kind: "serviceUser", id: clientId, name },
      target: `serviceuser#${clientId}`,
      targetName: name,
      details
    });
    NAME_RE = /^[a-z0-9][a-z0-9-]{1,62}$/;
  }
});

// lambdacode/api/services/nameDirectory.ts
async function build2() {
  const [users, machines, machineAdmins, groups, resources] = await Promise.all([
    listUsers(),
    serviceUserNames(),
    optional(async () => [...await serviceUserAdmins()]),
    optional(listGroups),
    optional(listResources)
  ]);
  const adminMachines = new Set(machineAdmins);
  const email = new Map(users.map((u) => [u.userId, u.email]));
  const admin = new Map(users.map((u) => [u.userId, Boolean(u.admin)]));
  const groupName = new Map(groups.map((g) => [g.groupId, g.name]));
  const resourceName = new Map(resources.map((r) => [r.resourceId, r.name]));
  const resourceAccount = new Map(resources.map((r) => [r.resourceId, r.accountNumber]));
  const who = (id) => email.get(id) ?? machines.get(id) ?? groupName.get(id);
  return {
    email: (id) => email.get(id),
    isAdmin: (id) => Boolean(admin.get(id)) || adminMachines.has(id),
    isMachine: (id) => machines.has(id),
    machineName: (id) => machines.get(id),
    groupName: (id) => groupName.get(id),
    resourceName: (id) => resourceName.get(id),
    resourceAccount: (id) => resourceAccount.get(id),
    who,
    targetName: (target) => {
      const p = parseTarget(target);
      if (p?.kind === "role") return p.roleName;
      if (p?.kind === "resource") return resourceName.get(p.resourceId);
      if (p?.kind === "plugin") return `${p.pluginId} (${p.permission})`;
      if (p?.kind === "share") return p.shareId;
      if (target.startsWith("group#")) return groupName.get(target.slice("group#".length));
      if (target.startsWith("user#")) return email.get(target.slice("user#".length));
      if (target.startsWith("serviceuser#")) return machines.get(target.slice("serviceuser#".length));
      return void 0;
    }
  };
}
function loadNameDirectory(opts = {}) {
  const now = Date.now();
  if (opts.maxAgeMs !== void 0 && cached2 && now - cached2.at < opts.maxAgeMs) return cached2.directory;
  const directory = build2();
  const entry = { at: now, directory };
  cached2 = entry;
  directory.catch(() => {
    if (cached2 === entry) cached2 = void 0;
  });
  return directory;
}
var cached2, optional;
var init_nameDirectory = __esm({
  "lambdacode/api/services/nameDirectory.ts"() {
    "use strict";
    init_access2();
    init_usersService();
    init_groupsService();
    init_resourcesService();
    init_serviceUsersService();
    optional = (load) => Promise.resolve().then(load).then((v) => v ?? []).catch(() => []);
  }
});

// lambdacode/api/services/accessReportService.ts
async function buildAccessReport() {
  const [graph, names] = await Promise.all([snapshot(), loadNameDirectory()]);
  const who = (id) => names.who(id) ?? id;
  const rows = [];
  for (const [userId, targets] of graph.users) {
    const machine = names.isMachine(userId);
    for (const e of targets.values()) {
      if (!e.active) continue;
      const p = parseTarget(e.target);
      if (!p || p.kind !== "role" && p.kind !== "resource" && p.kind !== "plugin" && p.kind !== "share") continue;
      const via = [...e.direct ? ["direct"] : [], ...e.groups.map((g) => `group:${names.groupName(g) ?? g}`)].join("; ");
      rows.push({
        email: who(userId),
        userId,
        principalKind: machine ? "serviceUser" : "user",
        admin: names.isAdmin(userId),
        targetKind: p.kind,
        targetName: names.targetName(e.target) ?? (p.kind === "resource" ? p.resourceId : e.target),
        accountNumber: p.kind === "role" || p.kind === "plugin" ? p.accountNumber : p.kind === "resource" ? names.resourceAccount(p.resourceId) ?? "" : "",
        via,
        grantedBy: e.direct?.grantedBy ? who(e.direct.grantedBy) : "",
        grantedAt: e.direct?.grantedAt ?? "",
        expiresAt: e.expiresAt ?? "",
        lastSeenAt: graph.presence.get(userId) ?? ""
      });
    }
  }
  rows.sort((a, b) => a.email.localeCompare(b.email) || a.targetKind.localeCompare(b.targetKind) || a.targetName.localeCompare(b.targetName));
  return rows;
}
function csvCell(value) {
  const s = String(value ?? "");
  const safe = /^[=+\-@]/.test(s) ? `'${s}` : s;
  return `"${safe.replace(/"/g, '""')}"`;
}
function accessReportCsv(rows) {
  const lines = [ACCESS_REPORT_COLUMNS.map(csvCell).join(",")];
  for (const r of rows) lines.push(ACCESS_REPORT_COLUMNS.map((c) => csvCell(r[c])).join(","));
  return "\uFEFF" + lines.join("\r\n") + "\r\n";
}
var ACCESS_REPORT_COLUMNS;
var init_accessReportService = __esm({
  "lambdacode/api/services/accessReportService.ts"() {
    "use strict";
    init_access2();
    init_nameDirectory();
    ACCESS_REPORT_COLUMNS = [
      "email",
      "userId",
      "principalKind",
      "admin",
      "targetKind",
      "targetName",
      "accountNumber",
      "via",
      "grantedBy",
      "grantedAt",
      "expiresAt",
      "lastSeenAt"
    ];
  }
});

// lambdacode/api/services/reportJobs.ts
var reportJobs_exports = {};
__export(reportJobs_exports, {
  getAccessReportJob: () => getAccessReportJob,
  runAccessReportJob: () => runAccessReportJob,
  startAccessReportJob: () => startAccessReportJob
});
async function writeJob(job) {
  await s32.send(new import_client_s32.PutObjectCommand({ Bucket: BUCKET2, Key: statusKey(job.jobId), Body: JSON.stringify(job), ContentType: "application/json" }));
}
async function readJob(jobId) {
  try {
    const res = await s32.send(new import_client_s32.GetObjectCommand({ Bucket: BUCKET2, Key: statusKey(jobId) }));
    return JSON.parse(await res.Body.transformToString() || "{}");
  } catch (err) {
    if (err.name === "NoSuchKey") return void 0;
    throw err;
  }
}
async function startAccessReportJob(requestedBy) {
  const job = { jobId: (0, import_crypto9.randomUUID)(), kind: "accessReport", status: "running", requestedBy, startedAt: (/* @__PURE__ */ new Date()).toISOString() };
  await writeJob(job);
  await lambda3.send(
    new import_client_lambda3.InvokeCommand({
      FunctionName: JOB_FUNCTION,
      InvocationType: "Event",
      Payload: Buffer.from(JSON.stringify({ job: "accessReport", jobId: job.jobId }))
    })
  );
  log26("access report job started", { jobId: job.jobId, requestedBy });
  return job;
}
async function runAccessReportJob(jobId) {
  const job = await readJob(jobId);
  if (!job) {
    log26("ERROR: report job unknown", { jobId });
    return;
  }
  try {
    const rows = await buildAccessReport();
    await s32.send(
      new import_client_s32.PutObjectCommand({
        Bucket: BUCKET2,
        Key: reportKey(jobId),
        Body: accessReportCsv(rows),
        ContentType: "text/csv; charset=utf-8",
        ContentDisposition: `attachment; filename="access-report-${job.startedAt.slice(0, 10)}.csv"`
      })
    );
    await writeJob({ ...job, status: "done", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), rows: rows.length });
    log26("access report job done", { jobId, rows: rows.length });
  } catch (err) {
    await writeJob({ ...job, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: "The report could not be built" });
    log26("ERROR: access report job failed", { jobId, error: err.message });
  }
}
async function getAccessReportJob(jobId, requestedBy) {
  const job = await readJob(jobId);
  if (!job || job.requestedBy !== requestedBy) throw new NotFoundError(`Report job ${jobId} not found`);
  if (job.status !== "done") return job;
  const url = await (0, import_s3_request_presigner.getSignedUrl)(s32, new import_client_s32.GetObjectCommand({ Bucket: BUCKET2, Key: reportKey(jobId) }), { expiresIn: DOWNLOAD_TTL_SECONDS });
  return { ...job, url };
}
var import_crypto9, import_client_s32, import_s3_request_presigner, import_client_lambda3, s32, lambda3, BUCKET2, JOB_FUNCTION, DOWNLOAD_TTL_SECONDS, log26, statusKey, reportKey;
var init_reportJobs = __esm({
  "lambdacode/api/services/reportJobs.ts"() {
    "use strict";
    import_crypto9 = require("crypto");
    import_client_s32 = require("@aws-sdk/client-s3");
    import_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
    import_client_lambda3 = require("@aws-sdk/client-lambda");
    init_accessReportService();
    init_httpErrors();
    s32 = new import_client_s32.S3Client({});
    lambda3 = new import_client_lambda3.LambdaClient({});
    BUCKET2 = process.env.REPORTS_BUCKET;
    JOB_FUNCTION = process.env.REPORT_JOB_FUNCTION;
    DOWNLOAD_TTL_SECONDS = 15 * 60;
    log26 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
    statusKey = (jobId) => `jobs/${jobId}.json`;
    reportKey = (jobId) => `reports/${jobId}.csv`;
  }
});

// lambdacode/api/app.ts
var app_exports = {};
__export(app_exports, {
  MOUNTS: () => MOUNTS,
  app: () => app,
  handler: () => handler,
  reportJob: () => reportJob
});
module.exports = __toCommonJS(app_exports);
var import_express11 = __toESM(require("express"));
var import_serverless_http = __toESM(require("serverless-http"));

// lambdacode/api/routes/accounts.ts
var import_express = require("express");

// lambdacode/api/auth.ts
init_serviceUsersService();
init_usersService();
init_preferencesService();

// lambdacode/api/services/tokenVerifier.ts
var import_aws_jwt_verify = require("aws-jwt-verify");
var import_error = require("aws-jwt-verify/error");
init_claims();
init_serviceUserRegistry();
init_verificationError();
var idVerifier = import_aws_jwt_verify.CognitoJwtVerifier.create({
  userPoolId: process.env.USER_POOL_ID,
  tokenUse: "id",
  clientId: null
});
var accessVerifier = import_aws_jwt_verify.CognitoJwtVerifier.create({
  userPoolId: process.env.USER_POOL_ID,
  tokenUse: "access",
  clientId: null
});
function bearerToken(header) {
  const value = header ?? "";
  return value.startsWith("Bearer ") ? value.slice(7) : value;
}
var message2 = (err) => err instanceof Error ? err.message : String(err);
async function verifyBearerToken(token, personalTokens) {
  if (!token) throw new TokenVerificationError("invalid", "missing bearer token");
  if (token.startsWith(PERSONAL_TOKEN_PREFIX)) {
    if (!personalTokens) throw new TokenVerificationError("invalid", "personal access tokens are not accepted here");
    return personalTokens(token);
  }
  let idFailure;
  let keysUnavailable = false;
  try {
    const payload2 = await idVerifier.verify(token);
    return {
      kind: "user",
      subject: payload2.sub,
      email: typeof payload2.email === "string" ? payload2.email : void 0,
      claims: customClaims(payload2),
      groups: payload2["cognito:groups"] ?? []
    };
  } catch (err) {
    idFailure = err;
    keysUnavailable = err instanceof import_error.FetchError;
  }
  let payload;
  try {
    payload = await accessVerifier.verify(token);
  } catch (err) {
    if (err instanceof import_error.FetchError || keysUnavailable) {
      throw new TokenVerificationError("dependency", `signing keys unavailable: ${message2(keysUnavailable ? idFailure : err)}`);
    }
    throw new TokenVerificationError("invalid", `not an ID token (${message2(idFailure)}) nor an access token (${message2(err)})`);
  }
  const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
  if (!scopes.includes(SERVICE_SCOPE)) throw new TokenVerificationError("invalid", `access token without the ${SERVICE_SCOPE} scope`);
  let registered;
  try {
    registered = await getServiceUser(payload.sub);
  } catch (err) {
    throw new TokenVerificationError("dependency", `service-user registry unavailable: ${message2(err)}`);
  }
  if (!registered) throw new TokenVerificationError("invalid", `no registry row for service client ${payload.sub}`);
  return { kind: "service", subject: payload.sub, name: registered.name, scopes: registered.scopes };
}

// lambdacode/api/auth.ts
init_actorContext();
init_auditService();
init_personalTokens();
init_tokenScopes();
var log17 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
async function requireAuth(req, res, next) {
  const token = bearerToken(req.header("authorization"));
  log17("requireAuth", { hasToken: Boolean(token) });
  if (!token) {
    res.status(401).json({ message: "Missing bearer token" });
    return;
  }
  let principal;
  try {
    principal = await verifyBearerToken(token, verifyPersonalToken);
  } catch (err) {
    log17("requireAuth: verify failed", { error: err.message });
    res.status(401).json({ message: "Invalid or expired token" });
    return;
  }
  req.userId = principal.subject;
  if (principal.kind === "token") {
    const t = principal.token;
    const path = `${req.baseUrl}${req.path}`;
    if (!tokenRouteAllowed(t.scopes, req.method, path)) {
      log17("requireAuth: token scope refused", { tokenId: t.id, method: req.method, path });
      res.status(403).json({ message: `This access token's scopes do not allow ${req.method} ${path}`, code: TOKEN_SCOPE_CODE });
      return;
    }
    req.token = { id: t.id, name: t.name, scopes: t.scopes, ...t.roles ? { roles: t.roles } : {}, expiresAt: t.expiresAt };
    req.userName = principal.email;
    req.claims = {};
    req.groups = t.scopes.includes("api") && await liveAdmin(principal.subject) ? [ADMIN_GROUP] : [];
    await touchToken({ tokenId: t.id, lastUsedAt: t.lastUsedAt });
  } else if (principal.kind === "user") {
    req.userName = principal.email;
    req.claims = principal.claims;
    req.groups = principal.groups;
    await touchPresence(principal.subject);
  } else {
    const path = `${req.baseUrl}${req.path}`;
    if (!tokenRouteAllowed(principal.scopes, req.method, path)) {
      log17("requireAuth: service-user scope refused", { clientId: principal.subject, method: req.method, path });
      res.status(403).json({ message: `This service user's scopes do not allow ${req.method} ${path}`, code: TOKEN_SCOPE_CODE });
      return;
    }
    req.groups = [];
    req.serviceClient = true;
    req.serviceScopes = principal.scopes;
    req.userName = principal.name;
    await touchServiceUser(principal.subject);
  }
  runAsActor(
    {
      kind: principal.kind === "service" ? "service" : "user",
      id: principal.subject,
      name: req.userName,
      ...principal.kind === "user" && principal.claims && Object.keys(principal.claims).length ? { claims: principal.claims } : {},
      ...req.token ? { token: { id: req.token.id, name: req.token.name, ...req.token.roles ? { roles: req.token.roles } : {} } } : {}
    },
    () => next()
  );
}
var isAdmin = (req) => Boolean(
  req.serviceClient && req.serviceScopes && adminScopeAllows(req.serviceScopes, req.method ?? "GET") || req.groups?.includes(ADMIN_GROUP)
);
var ADMIN_LIVENESS_TTL_MS = 6e4;
var ADMIN_LIVENESS_RETRY_MS = 5e3;
var liveAdminCache = null;
async function refreshLiveAdmins() {
  try {
    liveAdminCache = { at: Date.now(), subs: await listAdminSubs() };
  } catch (err) {
    log17("WARN: admin liveness check unavailable, trusting the token", { error: err.message });
  }
}
async function stillAdmin(sub) {
  if (!liveAdminCache || Date.now() - liveAdminCache.at >= ADMIN_LIVENESS_TTL_MS) await refreshLiveAdmins();
  if (!liveAdminCache) return true;
  if (liveAdminCache.subs.has(sub)) return true;
  if (Date.now() - liveAdminCache.at >= ADMIN_LIVENESS_RETRY_MS) {
    await refreshLiveAdmins();
    if (liveAdminCache.subs.has(sub)) return true;
  }
  return false;
}
async function liveAdmin(sub) {
  if (!liveAdminCache || Date.now() - liveAdminCache.at >= ADMIN_LIVENESS_TTL_MS) await refreshLiveAdmins();
  if (!liveAdminCache) return false;
  return stillAdmin(sub);
}
function requireHumanSession(req, res, next) {
  if (req.token || req.serviceClient) {
    res.status(403).json({ message: "Token management needs a signed-in session, not an access token", code: TOKEN_SCOPE_CODE });
    return;
  }
  next();
}
async function requireAdmin(req, res, next) {
  const reason = !isAdmin(req) ? "Admin access required" : !req.serviceClient && !await stillAdmin(req.userId) ? "Admin access was removed" : null;
  if (reason) {
    log17("requireAdmin: denied", { userId: req.userId, groups: req.groups, reason });
    await recordEvent({
      category: "auth",
      action: "admin.access",
      outcome: "DENIED",
      reason,
      target: `route#${req.method} ${req.baseUrl}${req.path}`,
      targetName: `${req.method} ${req.baseUrl}${req.path}`
    });
    res.status(403).json({ message: reason });
    return;
  }
  next();
}

// lambdacode/api/services/accountsService.ts
init_access2();
init_actorContext();

// lambdacode/api/services/profileNames.ts
function defaultProfileName(accountNumber, roleName) {
  return `${accountNumber}-${roleName}`.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
}
function resolveProfileName(input) {
  let suggested;
  let source;
  if (input.accountProfileName && input.rolesInAccount === 1) {
    suggested = input.accountProfileName;
    source = "account";
  } else if (input.roleProfileName) {
    suggested = input.roleProfileName;
    source = "role";
  } else {
    suggested = defaultProfileName(input.accountNumber, input.roleName);
    source = "default";
  }
  if (input.override && input.override !== suggested) {
    return { name: input.override, source: "override", suggested };
  }
  return { name: suggested, source, suggested };
}
var PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
var isValidProfileName = (p) => p === void 0 || p === "" || typeof p === "string" && PROFILE_NAME_RE.test(p);
var PROFILE_NAME_MESSAGE = "profileName must be 1\u201364 characters: letters, digits, '.', '_' or '-' (empty string clears it)";

// lambdacode/api/services/accountsService.ts
init_accountOrder();
init_catalogIndex();
init_preferencesService();

// lambdacode/api/services/dashboardLayout.ts
var DASHBOARD_LAYOUT_MODES = ["auto", "sections", "plain"];
function isDashboardLayoutMode(v) {
  return typeof v === "string" && DASHBOARD_LAYOUT_MODES.includes(v);
}
function dashboardLayout() {
  const mode = process.env.DASHBOARD_LAYOUT;
  return isDashboardLayoutMode(mode) ? mode : "auto";
}

// lambdacode/api/services/credentialsService.ts
var import_client_dynamodb17 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb17 = require("@aws-sdk/lib-dynamodb");
var import_client_sts = require("@aws-sdk/client-sts");
var import_client_kms = require("@aws-sdk/client-kms");
init_access2();
init_actorContext();
var ddb17 = import_lib_dynamodb17.DynamoDBDocumentClient.from(new import_client_dynamodb17.DynamoDBClient({}));
var UPSTREAM_TIMEOUT_MS = 4e3;
var sts = new import_client_sts.STSClient({ requestHandler: { requestTimeout: UPSTREAM_TIMEOUT_MS } });
var kms = new import_client_kms.KMSClient({ requestHandler: { requestTimeout: UPSTREAM_TIMEOUT_MS } });
var ROLES_TABLE_NAME5 = process.env.ROLES_TABLE_NAME;
var KMS_KEY_ID = process.env.KMS_KEY_ID;
var ISSUER_URL = (process.env.ISSUER_URL ?? "").replace(/\/$/, "");
var AUDIENCE = process.env.AUDIENCE ?? "sts.amazonaws.com";
var log18 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var b64url = (input) => Buffer.from(input).toString("base64url");
var PermissionError = class extends Error {
  constructor(message3, reason = "NO_GRANT") {
    super(message3);
    this.reason = reason;
  }
};
var VendError = class extends Error {
};
var fmtDuration = (seconds) => seconds % 3600 === 0 ? `${seconds / 3600} h` : `${Math.round(seconds / 60)} min`;
var isDurationRejection = (err) => err?.name === "ValidationError" && /DurationSeconds|MaxSessionDuration/i.test(err.message ?? "");
async function mintWebIdentityToken(userId, accountNumber, role) {
  const now = Math.floor(Date.now() / 1e3);
  const header = { alg: "RS256", typ: "JWT", kid: KMS_KEY_ID };
  const payload = {
    iss: ISSUER_URL,
    sub: `${accountNumber}/${role}/${userId}`,
    aud: AUDIENCE,
    iat: now,
    exp: now + 600
  };
  const signingInput = `${b64url(JSON.stringify(header))}.${b64url(
    JSON.stringify(payload)
  )}`;
  const { Signature } = await kms.send(
    new import_client_kms.SignCommand({
      KeyId: KMS_KEY_ID,
      Message: Buffer.from(signingInput),
      MessageType: "RAW",
      // KMS hashes the message with SHA-256 for us
      SigningAlgorithm: "RSASSA_PKCS1_V1_5_SHA_256"
      // == JWT RS256
    })
  );
  return `${signingInput}.${b64url(Buffer.from(Signature))}`;
}
function roleSessionName(prefix, userId, callerName) {
  const fallback = `${prefix}-${userId}`.slice(0, 64);
  if (process.env.ROLE_SESSION_NAME !== "email" || !callerName) return fallback;
  const name = callerName.replace(/[^\w+=,.@-]/g, "_");
  return name.length >= 2 && name.length <= 64 ? name : fallback;
}
async function vendCredentials(userId, accountNumber, role, callerName) {
  log18("credentials requested", { userId, accountNumber, role });
  const accountRole = `${accountNumber}#${role}`;
  const entry = await effectiveFor(userId, roleTarget(accountNumber, role), { consistent: true, roleLimit: callerRoleLimit(userId) });
  if (!entry) {
    log18("DENIED: no access row", { userId, accountRole });
    throw new PermissionError(
      `User not permitted to assume ${role} in ${accountNumber}`
    );
  }
  if (!entry.active) {
    const expiresAt = entry.direct?.expiresAt;
    log18("DENIED: grant expired", { userId, accountRole, expiresAt });
    throw new PermissionError(
      `Access to ${role} in ${accountNumber} expired on ${expiresAt}. Request it again if you still need it.`,
      "EXPIRED"
    );
  }
  const roleRow = await ddb17.send(
    new import_lib_dynamodb17.GetCommand({
      TableName: ROLES_TABLE_NAME5,
      Key: { accountNumber, roleName: role }
    })
  );
  if (!roleRow.Item?.roleArn) {
    log18("DENIED: role not in catalog", { userId, accountRole });
    throw new PermissionError(
      `${role} in ${accountNumber} is no longer registered. Ask an admin to register it again if you still need it.`,
      "NO_ROLE"
    );
  }
  const roleArn = roleRow.Item.roleArn;
  const durationSeconds = clampDuration(roleRow.Item?.sessionDurationSeconds);
  log18("ALLOWED, minting web-identity token", {
    userId,
    roleArn,
    catalogued: Boolean(roleRow.Item),
    durationSeconds
  });
  const webIdentityToken = await mintWebIdentityToken(userId, accountNumber, role);
  log18("token signed by KMS, calling AssumeRoleWithWebIdentity", { roleArn });
  let assumed;
  try {
    assumed = await sts.send(
      new import_client_sts.AssumeRoleWithWebIdentityCommand({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName("creds", userId, callerName),
        WebIdentityToken: webIdentityToken,
        DurationSeconds: durationSeconds
      })
    );
  } catch (err) {
    if (isDurationRejection(err)) {
      log18("ERROR: session length exceeds the IAM role's MaxSessionDuration", {
        userId,
        roleArn,
        durationSeconds
      });
      throw new VendError(
        `This role is configured for ${fmtDuration(durationSeconds)} sessions, but AWS caps it lower (the IAM role's maximum session duration). Ask an admin to pick a shorter session length for this role, or raise the cap on the IAM role and try again.`
      );
    }
    throw err;
  }
  const c = assumed.Credentials;
  if (!c) {
    log18("ERROR: STS returned no credentials", { userId, roleArn });
    throw new Error("STS did not return credentials");
  }
  log18("SUCCESS: credentials issued", {
    userId,
    roleArn,
    accessKeyId: c.AccessKeyId,
    // safe to log (an ID, not a secret)
    expiration: c.Expiration
  });
  return {
    accessKeyId: c.AccessKeyId,
    secretKey: c.SecretAccessKey,
    sessionToken: c.SessionToken,
    expiration: c.Expiration ?? new Date(Date.now() + durationSeconds * 1e3)
  };
}
var MIN_SESSION_SECONDS = 900;
var MAX_SESSION_SECONDS = 43200;
var DEFAULT_SESSION_SECONDS = 3600;
function clampDuration(v) {
  const n = typeof v === "number" && Number.isFinite(v) ? Math.floor(v) : DEFAULT_SESSION_SECONDS;
  return Math.min(MAX_SESSION_SECONDS, Math.max(MIN_SESSION_SECONDS, n));
}
async function testAssume(adminUserId, accountNumber, role, durationSeconds, adminName) {
  const roleRow = await ddb17.send(
    new import_lib_dynamodb17.GetCommand({ TableName: ROLES_TABLE_NAME5, Key: { accountNumber, roleName: role } })
  );
  const roleArn = roleRow.Item?.roleArn ?? `arn:aws:iam::${accountNumber}:role/${role}`;
  const webIdentityToken = await mintWebIdentityToken(adminUserId, accountNumber, role);
  try {
    const assumed = await sts.send(
      new import_client_sts.AssumeRoleWithWebIdentityCommand({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName("test", adminUserId, adminName),
        WebIdentityToken: webIdentityToken,
        DurationSeconds: clampDuration(durationSeconds)
      })
    );
    log18("session-length test ok", { adminUserId, roleArn, durationSeconds });
    return { ok: true, expiration: assumed.Credentials?.Expiration };
  } catch (err) {
    const message3 = err.message || String(err);
    log18("session-length test failed", { adminUserId, roleArn, durationSeconds, message: message3 });
    return { ok: false, message: message3 };
  }
}
var FEDERATION_ENDPOINT = "https://signin.aws.amazon.com/federation";
var CONSOLE_HOME = "https://console.aws.amazon.com/";
async function vendConsoleUrl(userId, accountNumber, role, destination = CONSOLE_HOME, callerName) {
  const creds = await vendCredentials(userId, accountNumber, role, callerName);
  const session = JSON.stringify({
    sessionId: creds.accessKeyId,
    sessionKey: creds.secretKey,
    sessionToken: creds.sessionToken
  });
  const tokenUrl = `${FEDERATION_ENDPOINT}?Action=getSigninToken&Session=${encodeURIComponent(
    session
  )}`;
  let resp;
  try {
    resp = await fetch(tokenUrl, { signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
  } catch (err) {
    log18("ERROR: getSigninToken unreachable", { userId, error: err.name });
    throw new VendError(
      'AWS console federation did not answer in time. The credentials vended fine \u2014 try again in a moment, or use "Get credentials" instead.'
    );
  }
  if (!resp.ok) {
    const body = await resp.text().catch(() => "");
    log18("ERROR: getSigninToken failed", { userId, status: resp.status, body: body.slice(0, 500) });
    throw new VendError(
      `AWS console federation rejected the sign-in request (HTTP ${resp.status}). The credentials vended fine \u2014 try again in a moment, or use "Get credentials" instead.`
    );
  }
  const { SigninToken } = await resp.json();
  const params = new URLSearchParams({
    Action: "login",
    Issuer: ISSUER_URL || "infra-client",
    Destination: destination,
    SigninToken
  });
  const url = `${FEDERATION_ENDPOINT}?${params.toString()}`;
  log18("console sign-in URL issued", { userId, accountNumber, role });
  return { url, expiration: creds.expiration };
}

// lambdacode/api/services/accountsService.ts
var log19 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
async function homeAccess(userId) {
  const [held, index, favoriteNumbers, recentNumbers] = await Promise.all([listAccess(userId), catalog(), listFavorites(userId), listRecent(userId)]);
  const layout = dashboardLayout();
  const byNumber = new Map(held.map((a) => [a.accountNumber, a]));
  const isMain = (accountNumber) => index.byNumber.get(accountNumber)?.main !== false;
  const main = held.filter((a) => isMain(a.accountNumber));
  const favorites = favoriteNumbers.map((n) => byNumber.get(n)).filter((a) => Boolean(a)).sort(compareAccounts);
  const recent = recentNumbers.map((n) => byNumber.get(n)).filter((a) => Boolean(a));
  return {
    // The deployment's configured choice wins; "auto" means sections once a held account is not main.
    // Holding nothing is never sectioned: the plain empty state ("Request a role") is the only sensible dashboard.
    sectioned: held.length === 0 ? false : layout === "sections" ? true : layout === "plain" ? false : main.length < held.length,
    layout,
    heldTotal: held.length,
    main,
    favorites,
    recent,
    favoriteNumbers
  };
}
async function listAccountNames() {
  const out = {};
  for (const a of (await catalog()).accounts) if (a.registered && a.name) out[a.accountNumber] = a.name;
  return out;
}
async function listAccess(userId) {
  const pointers = [];
  for (const [t, e] of await effectiveAccess(userId, { roleLimit: callerRoleLimit(userId) })) {
    if (!e.active) continue;
    const p = parseTarget(t);
    if (p?.kind !== "role") continue;
    pointers.push({ accountNumber: p.accountNumber, role: p.roleName, expiresAt: e.expiresAt });
  }
  if (pointers.length === 0) {
    log19("listed access", { userId, accountCount: 0 });
    return [];
  }
  const [index, prefs] = await Promise.all([catalog(), queryPrincipal(userPrincipal(userId), "pref#")]);
  const overrideByKey = /* @__PURE__ */ new Map();
  for (const row of prefs) {
    const p = parseTarget(row.target);
    if (p?.kind === "pref" && typeof row.profileName === "string" && row.profileName) {
      overrideByKey.set(prefTarget(p.accountNumber, p.roleName), row.profileName);
    }
  }
  const rolesPerAccount = /* @__PURE__ */ new Map();
  for (const p of pointers) rolesPerAccount.set(p.accountNumber, (rolesPerAccount.get(p.accountNumber) ?? 0) + 1);
  const byAccount = /* @__PURE__ */ new Map();
  for (const { accountNumber, role, expiresAt } of pointers) {
    const resolved = index.roleByKey.get(roleKey(accountNumber, role));
    const account = index.byNumber.get(accountNumber);
    const roleArn = resolved?.roleArn ?? `arn:aws:iam::${accountNumber}:role/${role}`;
    const entry = byAccount.get(accountNumber) ?? {
      accountNumber,
      name: account?.name,
      environment: account?.environment,
      ...account?.dims ? { dims: account.dims } : {},
      ...account?.main === false ? { main: false } : {},
      sortOrder: account?.sortOrder,
      position: 0,
      roles: []
    };
    const profile = resolveProfileName({
      accountNumber,
      roleName: role,
      override: overrideByKey.get(prefTarget(accountNumber, role)),
      accountProfileName: account?.profileName,
      roleProfileName: resolved?.profileName,
      rolesInAccount: rolesPerAccount.get(accountNumber) ?? 1
    });
    entry.roles.push({
      role,
      roleArn,
      displayName: resolved?.displayName,
      description: resolved?.description,
      icon: resolved?.icon,
      expiresAt,
      sessionDurationSeconds: clampDuration(resolved?.sessionDurationSeconds),
      profileName: profile.name,
      profileSource: profile.source,
      suggestedProfileName: profile.suggested
    });
    byAccount.set(accountNumber, entry);
  }
  for (const entry of byAccount.values()) {
    const key = (r) => ({
      roleName: r.role,
      displayName: r.displayName,
      sortOrder: index.roleByKey.get(roleKey(entry.accountNumber, r.role))?.sortOrder
    });
    entry.roles.sort((x, y) => compareRoles(key(x), key(y)));
  }
  log19("listed access", { userId, accountCount: byAccount.size });
  const accounts = [...byAccount.values()].sort(compareAccounts);
  accounts.forEach((a, i) => a.position = i);
  return accounts;
}

// lambdacode/api/routes/accounts.ts
init_preferencesService();
init_grantsService();
init_auditService();

// lambdacode/api/services/listing.ts
init_httpErrors();
var MAX_LIMIT = 200;
var asString = (v) => typeof v === "string" ? v : Array.isArray(v) && typeof v[0] === "string" ? v[0] : void 0;
function parseListQuery(query, opts) {
  const rawLimit = asString(query.limit);
  if (rawLimit === void 0) return void 0;
  const limit = Number(rawLimit);
  if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
    throw new ValidationError(`limit must be an integer from 1 to ${MAX_LIMIT}`);
  }
  let sort = asString(query.sort) ?? opts.sorts[0];
  const desc = sort.startsWith("-");
  if (desc) sort = sort.slice(1);
  if (!opts.sorts.includes(sort)) throw new ValidationError(`sort must be one of: ${opts.sorts.join(", ")}`);
  const filters = {};
  const raw = query.filter;
  if (raw !== void 0) {
    if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
      throw new ValidationError("filters are written filter[key]=value");
    }
    for (const [key, value] of Object.entries(raw)) {
      if (!opts.facets?.includes(key)) throw new ValidationError(`unknown filter: ${key}`);
      const values = (Array.isArray(value) ? value : [value]).flatMap((v) => typeof v === "string" ? v.split(",") : []).map((v) => v.trim()).filter(Boolean);
      if (values.length) filters[key] = values;
    }
  }
  return {
    q: (asString(query.q) ?? "").trim(),
    filters,
    sort,
    desc,
    limit,
    cursor: asString(query.cursor) || void 0
  };
}
function hashQuery(query) {
  const s = JSON.stringify([query.q, query.filters, query.sort, query.desc]);
  let h = 5381;
  for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) | 0;
  return (h >>> 0).toString(16);
}
var encodeCursor = (c) => Buffer.from(JSON.stringify(c)).toString("base64url");
function decodeCursor(raw, hash) {
  let c;
  try {
    c = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
  } catch {
    throw new ValidationError("cursor is not valid");
  }
  if (typeof c !== "object" || c === null || typeof c.i !== "string" || typeof c.k !== "string" && typeof c.k !== "number") {
    throw new ValidationError("cursor is not valid");
  }
  if (c.h !== hash) throw new ValidationError("cursor belongs to a different query \u2014 start again without it");
  return c;
}
function paginate(all, query, spec) {
  const tokens = query.q.toLowerCase().split(/\s+/).filter(Boolean);
  const matchesText = (item) => {
    if (!tokens.length) return true;
    const text2 = spec.text(item).toLowerCase();
    return tokens.every((t) => text2.includes(t));
  };
  const facetKeys = Object.keys(spec.facets ?? {});
  for (const key of Object.keys(query.filters)) {
    if (!facetKeys.includes(key)) throw new ValidationError(`unknown filter: ${key}`);
  }
  const matchesFacets = (item, except) => Object.entries(query.filters).every(([key, values]) => {
    if (key === except) return true;
    const v = spec.facets[key](item);
    return v !== void 0 && values.includes(v);
  });
  const textMatched = all.filter(matchesText);
  const facets = {};
  for (const key of facetKeys) {
    const counts = {};
    for (const item of textMatched) {
      if (!matchesFacets(item, key)) continue;
      const v = spec.facets[key](item);
      if (v !== void 0) counts[v] = (counts[v] ?? 0) + 1;
    }
    facets[key] = counts;
  }
  const sortKey = spec.sorts[query.sort];
  const dir = query.desc ? -1 : 1;
  const compare = (a, b) => {
    const ka = sortKey(a);
    const kb = sortKey(b);
    const c = typeof ka === "number" && typeof kb === "number" ? ka - kb : String(ka).localeCompare(String(kb));
    return (c || spec.id(a).localeCompare(spec.id(b))) * dir;
  };
  const matched = textMatched.filter((item) => matchesFacets(item)).sort(compare);
  let start = 0;
  if (query.cursor) {
    const c = decodeCursor(query.cursor, hashQuery(query));
    const after = (item) => {
      const k = sortKey(item);
      const cmp = typeof k === "number" && typeof c.k === "number" ? k - c.k : String(k).localeCompare(String(c.k));
      return (cmp || spec.id(item).localeCompare(c.i)) * dir > 0;
    };
    start = matched.findIndex(after);
    if (start < 0) start = matched.length;
  }
  const items = matched.slice(start, start + query.limit);
  const last = items[items.length - 1];
  const nextCursor = last !== void 0 && start + items.length < matched.length ? encodeCursor({ h: hashQuery(query), k: sortKey(last), i: spec.id(last) }) : void 0;
  return { items, total: matched.length, facets, ...nextCursor ? { nextCursor } : {} };
}

// lambdacode/api/routes/accounts.ts
init_dimensions();

// lambdacode/api/routes/errors.ts
init_httpErrors();
var log20 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
function sendError(res, err, action) {
  if (err instanceof NotFoundError) {
    res.status(404).json({ message: err.message });
    return;
  }
  if (err instanceof ConflictError) {
    res.status(409).json({ message: err.message });
    return;
  }
  if (err instanceof ForbiddenError) {
    res.status(403).json({ message: err.message });
    return;
  }
  if (err instanceof ValidationError) {
    res.status(400).json({ message: err.message });
    return;
  }
  log20(`ERROR: ${action} failed`, { error: err.message });
  res.status(502).json({ message: `Failed to ${action}` });
}

// lambdacode/api/routes/accounts.ts
var accessListSpec = (favorites) => ({
  text: (a) => [a.accountNumber, a.name ?? "", a.dims?.tenant ?? "", a.dims?.project ?? "", a.dims?.stage ?? "", ...a.roles.map((r) => `${r.role} ${r.displayName ?? ""}`)].join(" "),
  id: (a) => a.accountNumber,
  sorts: {
    // listAccess already returns the admin-chosen order; its index IS the position key.
    position: (a) => a.position,
    name: (a) => a.name ?? a.accountNumber,
    number: (a) => a.accountNumber
  },
  facets: {
    environment: (a) => a.environment,
    main: (a) => a.main === false ? "false" : "true",
    favorite: (a) => favorites.has(a.accountNumber) ? "true" : "false",
    ...dimensionFacets()
  }
});
var CONSOLE_FAILED = "Failed to create console sign-in URL";
var log21 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var accountsRouter = (0, import_express.Router)();
var CONSOLE_URL = /^https:\/\/([a-z0-9-]+\.)*console\.aws\.amazon\.com\//;
accountsRouter.get("/", requireAuth, async (req, res) => {
  try {
    const spec = accessListSpec(new Set(await listFavorites(req.userId)));
    const page = parseListQuery(req.query, { sorts: Object.keys(spec.sorts), facets: Object.keys(spec.facets ?? {}) });
    const accounts = await listAccess(req.userId);
    if (!page) {
      res.json({ accounts });
      return;
    }
    res.json(paginate(accounts, page, spec));
  } catch (err) {
    sendError(res, err, "list accounts");
  }
});
accountsRouter.get("/home", requireAuth, async (req, res) => {
  try {
    res.json(await homeAccess(req.userId));
  } catch (err) {
    sendError(res, err, "load dashboard");
  }
});
accountsRouter.get("/names", requireAuth, async (_req, res) => {
  try {
    res.json({ names: await listAccountNames() });
  } catch (err) {
    sendError(res, err, "list account names");
  }
});
accountsRouter.get("/expiry", requireAuth, async (req, res) => {
  try {
    const notices = await listExpiryNotices(req.userId);
    res.json(notices);
  } catch (err) {
    log21("ERROR: listExpiryNotices failed", { error: err.message });
    res.status(502).json({ message: "Failed to list expiry notices" });
  }
});
accountsRouter.post(
  "/expiry/seen",
  requireAuth,
  async (req, res) => {
    try {
      const cleared = await markExpiryNoticesSeen(req.userId);
      res.json({ cleared });
    } catch (err) {
      log21("ERROR: markExpiryNoticesSeen failed", { error: err.message });
      res.status(502).json({ message: "Failed to mark expiry notices seen" });
    }
  }
);
accountsRouter.post(
  "/:accountNumber/roles/:roleName/console",
  requireAuth,
  async (req, res) => {
    const { destination } = req.body ?? {};
    if (destination && !CONSOLE_URL.test(destination)) {
      res.status(400).json({ message: "destination must be an AWS console URL" });
      return;
    }
    const audit = vendAuditor({
      userId: req.userId,
      userName: req.userName,
      claims: req.claims,
      serviceUser: req.serviceClient,
      accountNumber: req.params.accountNumber,
      roleName: req.params.roleName,
      action: "CONSOLE"
    });
    try {
      const signin = await vendConsoleUrl(
        req.userId,
        req.params.accountNumber,
        req.params.roleName,
        destination,
        req.userName
      );
      await audit("VENDED");
      await touchRecent(req.userId, req.params.accountNumber);
      res.json(signin);
    } catch (err) {
      if (err instanceof PermissionError) {
        await audit("DENIED", { deniedReason: err.reason });
        res.status(403).json({ message: err.message });
        return;
      }
      if (err instanceof VendError) {
        await audit("FAILED", { failureReason: err.message });
        res.status(502).json({ message: err.message });
        return;
      }
      log21("ERROR: vendConsoleUrl failed", { error: err.message });
      await audit("FAILED", { failureReason: CONSOLE_FAILED });
      res.status(502).json({ message: CONSOLE_FAILED });
    }
  }
);

// lambdacode/api/routes/credentials.ts
var import_express2 = require("express");
init_auditService();
init_preferencesService();
var log22 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var ASSUME_FAILED = "Failed to assume role";
var credentialsRouter = (0, import_express2.Router)();
credentialsRouter.post("/", requireAuth, async (req, res) => {
  const { accountNumber, role } = req.body ?? {};
  if (typeof accountNumber !== "string" || !/^\d{12}$/.test(accountNumber) || typeof role !== "string" || !role || role.length > 128 || role.includes("#") || // the Access target delimiter (role#<acct>#<name>)
  role.includes("/")) {
    res.status(400).json({ message: "accountNumber (12 digits) and role are required" });
    return;
  }
  const audit = vendAuditor({
    userId: req.userId,
    userName: req.userName,
    claims: req.claims,
    serviceUser: req.serviceClient,
    accountNumber,
    roleName: role,
    action: "CREDENTIALS"
  });
  try {
    const creds = await vendCredentials(req.userId, accountNumber, role, req.userName);
    await audit("VENDED");
    if (req.body?.background !== true) await touchRecent(req.userId, accountNumber);
    res.json(creds);
  } catch (err) {
    if (err instanceof PermissionError) {
      await audit("DENIED", { deniedReason: err.reason });
      res.status(403).json({ message: err.message });
      return;
    }
    if (err instanceof VendError) {
      await audit("FAILED", { failureReason: err.message });
      res.status(502).json({ message: err.message });
      return;
    }
    log22("ERROR: vendCredentials failed", { error: err.message });
    await audit("FAILED", { failureReason: ASSUME_FAILED });
    res.status(502).json({ message: ASSUME_FAILED });
  }
});

// lambdacode/api/routes/requests.ts
var import_express3 = require("express");
init_dimensions();
init_requestsService();
init_resourcesService();
var requestsRouter = (0, import_express3.Router)();
requestsRouter.use(requireAuth);
requestsRouter.get("/catalog", async (req, res) => {
  try {
    const spec = {
      text: (a) => [a.accountNumber, a.name ?? "", ...a.roles.map((r) => `${r.roleName} ${r.displayName ?? ""}`)].join(" "),
      id: (a) => a.accountNumber,
      sorts: { name: (a) => a.name ?? a.accountNumber, number: (a) => a.accountNumber },
      facets: dimensionFacets()
    };
    const page = parseListQuery(req.query, { sorts: Object.keys(spec.sorts), facets: Object.keys(spec.facets ?? {}) });
    const accounts = await listRequestableRoles(req.userId);
    if (!page) {
      res.json({ accounts });
      return;
    }
    res.json(paginate(accounts, page, spec));
  } catch (err) {
    sendError(res, err, "list requestable roles");
  }
});
requestsRouter.get("/resource-catalog", async (req, res) => {
  try {
    const resources = await listRequestableResources(req.userId);
    res.json({ resources });
  } catch (err) {
    sendError(res, err, "list requestable resources");
  }
});
requestsRouter.get("/", async (req, res) => {
  try {
    const requests = await listMyRequests(req.userId);
    if (requests.some((r) => r.kind === "RESOURCE")) {
      const nameById = new Map(
        (await listResources()).map((r) => [r.resourceId, r.name])
      );
      res.json({
        requests: requests.map(
          (r) => r.kind === "RESOURCE" ? {
            ...r,
            resourceName: nameById.get(r.resourceId ?? "") ?? "(deleted resource)"
          } : r
        )
      });
      return;
    }
    res.json({ requests });
  } catch (err) {
    sendError(res, err, "list requests");
  }
});
var REASON_MAX2 = 500;
requestsRouter.post("/", async (req, res) => {
  const { accountNumber, roleName, reason, durationHours } = req.body ?? {};
  if (!/^\d{12}$/.test(accountNumber ?? "")) {
    res.status(400).json({ message: "accountNumber must be a 12-digit AWS account id" });
    return;
  }
  if (!roleName || typeof roleName !== "string") {
    res.status(400).json({ message: "roleName is required" });
    return;
  }
  if (reason !== void 0 && typeof reason !== "string") {
    res.status(400).json({ message: "reason must be a string" });
    return;
  }
  if (typeof reason === "string" && reason.length > REASON_MAX2) {
    res.status(400).json({ message: `reason must be ${REASON_MAX2} characters or fewer` });
    return;
  }
  if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
    res.status(400).json({
      message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
    });
    return;
  }
  try {
    const request = await createRequest(
      req.userId,
      accountNumber,
      roleName,
      reason,
      durationHours
    );
    res.status(201).json({ request });
  } catch (err) {
    sendError(res, err, "create request");
  }
});
requestsRouter.post("/resource", async (req, res) => {
  const { resourceId, reason, durationHours } = req.body ?? {};
  if (!resourceId || typeof resourceId !== "string") {
    res.status(400).json({ message: "resourceId is required" });
    return;
  }
  if (reason !== void 0 && typeof reason !== "string") {
    res.status(400).json({ message: "reason must be a string" });
    return;
  }
  if (typeof reason === "string" && reason.length > REASON_MAX2) {
    res.status(400).json({ message: `reason must be ${REASON_MAX2} characters or fewer` });
    return;
  }
  if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
    res.status(400).json({
      message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
    });
    return;
  }
  try {
    const request = await createResourceRequest(
      req.userId,
      resourceId,
      reason,
      durationHours
    );
    res.status(201).json({ request });
  } catch (err) {
    sendError(res, err, "create resource request");
  }
});
requestsRouter.post("/seen", async (req, res) => {
  try {
    const cleared = await markRequestsSeen(req.userId);
    res.json({ cleared });
  } catch (err) {
    sendError(res, err, "mark requests seen");
  }
});

// lambdacode/api/routes/admin.ts
var import_express6 = require("express");
init_tokensService();

// lambdacode/api/services/adminService.ts
var import_client_dynamodb18 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb18 = require("@aws-sdk/lib-dynamodb");
init_httpErrors();
init_dimensions();
init_grantsService();
init_pluginGrantsService();
init_access2();
init_groupsService();
init_resourcesService();
init_auditService();
init_accountOrder();
init_catalogIndex();
init_accessNotices();
var ddb18 = import_lib_dynamodb18.DynamoDBDocumentClient.from(new import_client_dynamodb18.DynamoDBClient({}));
var ACCOUNTS_TABLE_NAME3 = process.env.ACCOUNTS_TABLE_NAME;
var ROLES_TABLE_NAME6 = process.env.ROLES_TABLE_NAME;
var log23 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
async function listAllAccounts() {
  const [index, granteeCounts] = await Promise.all([catalog(), countGranteesByRole()]);
  const accounts = index.accounts.map((a, position) => ({
    accountNumber: a.accountNumber,
    name: a.name,
    environment: a.environment,
    status: a.status,
    profileName: a.profileName,
    sortOrder: a.sortOrder,
    main: a.main,
    ...a.dims ? { dims: a.dims } : {},
    position,
    roles: a.roles.map((r) => ({
      roleName: r.roleName,
      roleArn: r.roleArn,
      policyTier: r.policyTier,
      displayName: r.displayName,
      description: r.description,
      color: r.color,
      icon: r.icon,
      profileName: r.profileName,
      sessionDurationSeconds: r.sessionDurationSeconds,
      sortOrder: r.sortOrder,
      grantees: granteeCounts.get(`${a.accountNumber}#${r.roleName}`) ?? 0
    }))
  }));
  log23("listed all accounts (admin)", { accountCount: accounts.length, roleCount: index.roleByKey.size });
  return accounts;
}
async function getAccount(accountNumber) {
  const acct = await ddb18.send(
    new import_lib_dynamodb18.GetCommand({ TableName: ACCOUNTS_TABLE_NAME3, Key: { accountNumber } })
  );
  if (!acct.Item) {
    throw new NotFoundError(`Account ${accountNumber} not found`);
  }
  const roles = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb18.send(
      new import_lib_dynamodb18.QueryCommand({
        TableName: ROLES_TABLE_NAME6,
        KeyConditionExpression: "accountNumber = :a",
        ExpressionAttributeValues: { ":a": accountNumber },
        ExclusiveStartKey
      })
    );
    for (const r of page.Items ?? []) {
      roles.push({
        roleName: r.roleName,
        roleArn: r.roleArn ?? `arn:aws:iam::${accountNumber}:role/${r.roleName}`,
        policyTier: r.policyTier,
        displayName: r.displayName,
        description: r.description,
        color: r.color,
        icon: r.icon,
        profileName: r.profileName,
        sessionDurationSeconds: r.sessionDurationSeconds,
        sortOrder: r.sortOrder
      });
    }
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  roles.sort(compareRoles);
  const a = acct.Item;
  const dims = cleanDims(a.dims);
  return {
    accountNumber,
    name: a.name,
    environment: a.environment,
    status: a.status,
    ...dims ? { dims } : {},
    roles
  };
}
async function countGranteesByRole() {
  const graph = await snapshot();
  const counts = /* @__PURE__ */ new Map();
  for (const entries of graph.users.values()) {
    for (const e of entries.values()) {
      if (!e.active) continue;
      const p = parseTarget(e.target);
      if (p?.kind !== "role") continue;
      const key = `${p.accountNumber}#${p.roleName}`;
      counts.set(key, (counts.get(key) ?? 0) + 1);
    }
  }
  return counts;
}
async function getAccountNames() {
  return new Map(Object.entries(await listAccountNames()));
}
async function scanAll4(TableName) {
  const items = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb18.send(new import_lib_dynamodb18.ScanCommand({ TableName, ExclusiveStartKey }));
    items.push(...page.Items ?? []);
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return items;
}
var CONDITION_FAILED5 = "ConditionalCheckFailedException";
var compact3 = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
var accountTarget = (accountNumber) => `account#${accountNumber}`;
function changedFields2(current, fields) {
  const changed = {};
  for (const [k, to] of Object.entries(fields)) {
    const from = current?.[k];
    if (JSON.stringify(from ?? null) !== JSON.stringify(to ?? null)) changed[k] = { from, to };
  }
  return changed;
}
function differingField(stored, provided) {
  return Object.keys(provided).find((k) => JSON.stringify(stored[k] ?? null) !== JSON.stringify(provided[k] ?? null));
}
async function createAccount(input) {
  if (input.profileName) await assertProfileNameFree(input.profileName, { account: input.accountNumber });
  const dims = dimensionsSettings().enabled ? cleanDims(input.dims) ?? parseAccountName(input.name) : void 0;
  const item = compact3({
    accountNumber: input.accountNumber,
    name: input.name,
    environment: input.environment,
    status: input.status,
    profileName: input.profileName || void 0,
    notMain: input.main === false ? true : void 0,
    dims
  });
  try {
    await ddb18.send(
      new import_lib_dynamodb18.PutCommand({
        TableName: ACCOUNTS_TABLE_NAME3,
        Item: item,
        ConditionExpression: "attribute_not_exists(accountNumber)"
      })
    );
  } catch (err) {
    if (err.name !== CONDITION_FAILED5) throw err;
    const stored = (await ddb18.send(new import_lib_dynamodb18.GetCommand({ TableName: ACCOUNTS_TABLE_NAME3, Key: { accountNumber: input.accountNumber } }))).Item ?? {};
    const asked = { ...item };
    delete asked.dims;
    const compared = { ...asked, ...input.dims ? { dims: cleanDims(input.dims) } : {}, ...input.main === true ? { notMain: void 0 } : {} };
    const differs = differingField(stored, compared);
    if (differs) throw new ConflictError(`Account ${input.accountNumber} already exists with a different ${differs}`);
    log23("account already registered", { accountNumber: input.accountNumber });
    return { ...await getAccount(input.accountNumber), existing: true };
  }
  await bumpCatalogVersion();
  await recordEvent({
    category: "catalog",
    action: "account.create",
    target: accountTarget(input.accountNumber),
    targetName: input.name
  });
  log23("created account", { accountNumber: input.accountNumber });
  return { ...input, roles: [] };
}
var lazyRequests = () => (init_requestsService(), __toCommonJS(requestsService_exports));
async function cascadeRole(accountNumber, roleName, batchId, collect) {
  const target = roleTarget(accountNumber, roleName);
  const bundling = await groupsBundling(target);
  const removedRows = await revokeAllForRole(accountNumber, roleName, batchId, collect);
  await removeRoleFromAllGroups(accountNumber, roleName);
  return { removedRows, emptiedGroups: bundling };
}
var roleRemovedNote = (target) => `Role ${target.split("#")[2]} in ${target.split("#")[1]} was removed`;
async function deleteAccount(accountNumber) {
  const account = await ddb18.send(
    new import_lib_dynamodb18.GetCommand({ TableName: ACCOUNTS_TABLE_NAME3, Key: { accountNumber } })
  );
  if (!account.Item) {
    throw new NotFoundError(`Account ${accountNumber} not found`);
  }
  const resources = (await listResources()).filter((r) => r.accountNumber === accountNumber);
  if (resources.length) {
    throw new ConflictError(
      `Account ${accountNumber} still has ${resources.length} network resource${resources.length === 1 ? "" : "s"} \u2014 remove them first`
    );
  }
  const batchId = newBatchId();
  const roleNames = await listRoleNames(accountNumber);
  const changes = [];
  const collect = (c) => changes.push(...c);
  const bundlingGroups = [];
  for (const roleName of roleNames) {
    const { emptiedGroups } = await cascadeRole(accountNumber, roleName, batchId, collect);
    bundlingGroups.push(...emptiedGroups);
    await ddb18.send(
      new import_lib_dynamodb18.DeleteCommand({
        TableName: ROLES_TABLE_NAME6,
        Key: { accountNumber, roleName }
      })
    );
  }
  const plugins = await revokeAllPluginGrantsForAccount(accountNumber, void 0, batchId, collect);
  const removedPluginGrants = plugins.removedRows;
  await deleteGroupsLeftEmpty([...bundlingGroups, ...plugins.bundlingGroups]);
  const closedRequests = await lazyRequests().closePendingRequestsFor(
    [...roleNames.map((roleName) => roleTarget(accountNumber, roleName)), ...plugins.targets],
    (target) => parseTarget(target)?.kind === "plugin" ? `Account ${accountNumber} was removed` : roleRemovedNote(target)
  );
  await ddb18.send(
    new import_lib_dynamodb18.DeleteCommand({
      TableName: ACCOUNTS_TABLE_NAME3,
      Key: { accountNumber }
    })
  );
  await bumpCatalogVersion();
  await recordEvent({
    category: "catalog",
    action: "account.delete",
    target: accountTarget(accountNumber),
    targetName: account.Item.name,
    details: { removedRoles: roleNames.length, removedPluginGrants, closedRequests, batchId, affected: affectedOf(changes, { change: "lost" }), unchanged: unchangedOf(changes, { change: "lost" }) }
  });
  log23("deleted account", { accountNumber, removedRoles: roleNames.length, removedPluginGrants });
}
async function listRoleNames(accountNumber) {
  const names = [];
  let ExclusiveStartKey;
  do {
    const page = await ddb18.send(
      new import_lib_dynamodb18.QueryCommand({
        TableName: ROLES_TABLE_NAME6,
        KeyConditionExpression: "accountNumber = :a",
        ExpressionAttributeValues: { ":a": accountNumber },
        ProjectionExpression: "roleName",
        ExclusiveStartKey
      })
    );
    for (const it of page.Items ?? []) names.push(it.roleName);
    ExclusiveStartKey = page.LastEvaluatedKey;
  } while (ExclusiveStartKey);
  return names;
}
async function createRole(accountNumber, input) {
  const wanted = input.roleName.toLowerCase();
  if (input.profileName) {
    await assertProfileNameFree(input.profileName, { role: { accountNumber, roleName: input.roleName } });
  }
  let scanKey;
  do {
    const page = await ddb18.send(
      new import_lib_dynamodb18.QueryCommand({
        TableName: ROLES_TABLE_NAME6,
        KeyConditionExpression: "accountNumber = :a",
        ExpressionAttributeValues: { ":a": accountNumber },
        ExclusiveStartKey: scanKey
      })
    );
    for (const r of page?.Items ?? []) {
      if (String(r.roleName).toLowerCase() !== wanted) continue;
      if (r.roleName === input.roleName) {
        const stored = { ...r, roleArn: r.roleArn ?? `arn:aws:iam::${accountNumber}:role/${input.roleName}` };
        const differs = differingField(stored, compact3({ ...input, profileName: input.profileName || void 0 }));
        if (differs) throw new ConflictError(`Role ${input.roleName} already exists in account ${accountNumber} with a different ${differs}`);
        log23("role already registered", { accountNumber, roleName: input.roleName });
        return { ...r, existing: true };
      }
      throw new ConflictError(
        `A role named "${input.roleName}" already exists in account ${accountNumber} \u2014 role names must be unique, ignoring case.`
      );
    }
    scanKey = page?.LastEvaluatedKey;
  } while (scanKey);
  try {
    await ddb18.send(
      new import_lib_dynamodb18.PutCommand({
        TableName: ACCOUNTS_TABLE_NAME3,
        Item: { accountNumber },
        ConditionExpression: "attribute_not_exists(accountNumber)"
      })
    );
    log23("auto-registered account for new role", { accountNumber });
  } catch (err) {
    if (err.name !== CONDITION_FAILED5) throw err;
  }
  const fields = compact3({
    displayName: input.displayName,
    roleArn: input.roleArn,
    policyTier: input.policyTier,
    description: input.description,
    color: input.color,
    icon: input.icon,
    profileName: input.profileName || void 0,
    sessionDurationSeconds: input.sessionDurationSeconds
  });
  try {
    await ddb18.send(
      new import_lib_dynamodb18.PutCommand({
        TableName: ROLES_TABLE_NAME6,
        Item: { accountNumber, roleName: input.roleName, ...fields },
        ConditionExpression: "attribute_not_exists(roleName)"
      })
    );
  } catch (err) {
    if (err.name === CONDITION_FAILED5) {
      throw new ConflictError(
        `Role ${input.roleName} already exists in account ${accountNumber}`
      );
    }
    throw err;
  }
  await bumpCatalogVersion();
  await recordEvent({
    category: "catalog",
    action: "role.create",
    target: roleTarget(accountNumber, input.roleName),
    targetName: input.roleName,
    details: fields
  });
  log23("created role", { accountNumber, roleName: input.roleName });
  return input;
}
async function deleteRole(accountNumber, roleName) {
  const existing = await ddb18.send(
    new import_lib_dynamodb18.GetCommand({ TableName: ROLES_TABLE_NAME6, Key: { accountNumber, roleName } })
  );
  const batchId = newBatchId();
  let changes = [];
  const target = roleTarget(accountNumber, roleName);
  const { removedRows, emptiedGroups } = await cascadeRole(accountNumber, roleName, batchId, (c) => changes = c);
  await deleteGroupsLeftEmpty(emptiedGroups);
  const closedRequests = await lazyRequests().closePendingRequestsFor(target, roleRemovedNote(target));
  if (!existing.Item) {
    if (removedRows || closedRequests) log23("re-swept deleted role", { accountNumber, roleName, removedRows, closedRequests });
    throw new NotFoundError(`Role ${roleName} not found in account ${accountNumber}`);
  }
  try {
    await ddb18.send(
      new import_lib_dynamodb18.DeleteCommand({
        TableName: ROLES_TABLE_NAME6,
        Key: { accountNumber, roleName },
        ConditionExpression: "attribute_exists(roleName)"
      })
    );
  } catch (err) {
    if (err.name !== CONDITION_FAILED5) throw err;
    log23("role deleted concurrently", { accountNumber, roleName });
    throw new NotFoundError(`Role ${roleName} not found in account ${accountNumber}`);
  }
  await bumpCatalogVersion();
  await recordEvent({
    category: "catalog",
    action: "role.delete",
    target: roleTarget(accountNumber, roleName),
    targetName: roleName,
    details: { batchId, removedRows, closedRequests, affected: affectedOf(changes, { change: "lost" }), unchanged: unchangedOf(changes, { change: "lost" }) }
  });
  log23("deleted role", { accountNumber, roleName });
}
async function assertProfileNameFree(profileName, self) {
  const wanted = profileName.toLowerCase();
  const index = await catalog();
  for (const a of index.accounts) {
    if (self.account && a.accountNumber === self.account) continue;
    if ((a.profileName ?? "").toLowerCase() === wanted) {
      throw new ConflictError(`Profile name "${profileName}" is already used by account ${a.name || a.accountNumber}`);
    }
  }
  for (const r of index.roleByKey.values()) {
    if (self.role && r.accountNumber === self.role.accountNumber && r.roleName === self.role.roleName) continue;
    if ((r.profileName ?? "").toLowerCase() === wanted) {
      throw new ConflictError(`Profile name "${profileName}" is already used by role ${r.roleName} in ${r.accountNumber}`);
    }
  }
}
function buildUpdate2(fields, remove = []) {
  const names = {};
  const values = {};
  const sets = [];
  for (const [k, v] of Object.entries(fields)) {
    names[`#${k}`] = k;
    values[`:${k}`] = v;
    sets.push(`#${k} = :${k}`);
  }
  for (const k of remove) names[`#${k}`] = k;
  const parts = [sets.length ? `SET ${sets.join(", ")}` : "", remove.length ? `REMOVE ${remove.map((k) => `#${k}`).join(", ")}` : ""].filter(Boolean);
  return {
    UpdateExpression: parts.join(" "),
    ExpressionAttributeNames: names,
    ...sets.length ? { ExpressionAttributeValues: values } : {}
  };
}
async function reorderAccounts(order2) {
  const [accountItems, roleItems] = await Promise.all([scanAll4(ACCOUNTS_TABLE_NAME3), scanAll4(ROLES_TABLE_NAME6)]);
  const accountPos = new Map(accountItems.map((a) => [a.accountNumber, a.sortOrder]));
  const rolesOf = /* @__PURE__ */ new Map();
  for (const r of roleItems) {
    const list = rolesOf.get(r.accountNumber) ?? [];
    list.push({ roleName: r.roleName, sortOrder: r.sortOrder });
    rolesOf.set(r.accountNumber, list);
  }
  for (const { accountNumber, roles } of order2) {
    if (!accountPos.has(accountNumber)) throw new NotFoundError(`Account ${accountNumber} is not registered`);
    const known = new Set((rolesOf.get(accountNumber) ?? []).map((r) => r.roleName));
    for (const roleName of roles ?? []) {
      if (!known.has(roleName)) throw new NotFoundError(`Role ${roleName} is not registered in account ${accountNumber}`);
    }
  }
  const position = (TableName, Key, at) => ({
    Update: {
      TableName,
      Key,
      ...at === null ? { UpdateExpression: "REMOVE sortOrder" } : { UpdateExpression: "SET sortOrder = :o", ExpressionAttributeValues: { ":o": at } },
      ConditionExpression: `attribute_exists(${"roleName" in Key ? "roleName" : "accountNumber"})`
    }
  });
  const writes = [];
  order2.forEach(({ accountNumber, roles }, i) => {
    writes.push(position(ACCOUNTS_TABLE_NAME3, { accountNumber }, i));
    if (!roles) return;
    roles.forEach((roleName, j) => writes.push(position(ROLES_TABLE_NAME6, { accountNumber, roleName }, j)));
    for (const r of rolesOf.get(accountNumber) ?? []) {
      if (r.sortOrder !== void 0 && !roles.includes(r.roleName)) {
        writes.push(position(ROLES_TABLE_NAME6, { accountNumber, roleName: r.roleName }, null));
      }
    }
  });
  const listed = new Set(order2.map((o) => o.accountNumber));
  for (const [accountNumber, sortOrder] of accountPos) {
    if (sortOrder !== void 0 && !listed.has(accountNumber)) writes.push(position(ACCOUNTS_TABLE_NAME3, { accountNumber }, null));
  }
  for (let i = 0; i < writes.length; i += 100) {
    try {
      await ddb18.send(new import_lib_dynamodb18.TransactWriteCommand({ TransactItems: writes.slice(i, i + 100) }));
    } catch (err) {
      if (err.name === "TransactionCanceledException") {
        throw new NotFoundError("One of the accounts or roles is no longer registered");
      }
      throw err;
    }
  }
  const rolesOrderedFor = order2.filter((o) => o.roles).map((o) => o.accountNumber);
  await bumpCatalogVersion();
  await recordEvent({
    category: "catalog",
    action: "account.reorder",
    details: { order: order2.map((o) => o.accountNumber), ...rolesOrderedFor.length ? { rolesOrderedFor } : {} }
  });
  log23("reordered accounts", { count: order2.length, roleLists: rolesOrderedFor.length, writes: writes.length });
}
async function updateAccount(accountNumber, patch) {
  if (patch.profileName) await assertProfileNameFree(patch.profileName, { account: accountNumber });
  const fields = compact3({
    name: patch.name,
    environment: patch.environment,
    status: patch.status,
    profileName: patch.profileName,
    notMain: patch.main === false ? true : void 0,
    dims: patch.dims ? cleanDims(patch.dims) : void 0
  });
  if (patch.dims && !fields.dims) throw new ValidationError("dims needs at least tenant and stage");
  const remove = [...patch.main === true ? ["notMain"] : [], ...patch.dims === null ? ["dims"] : []];
  const current = (await ddb18.send(new import_lib_dynamodb18.GetCommand({ TableName: ACCOUNTS_TABLE_NAME3, Key: { accountNumber } }))).Item;
  try {
    const res = await ddb18.send(
      new import_lib_dynamodb18.UpdateCommand({
        TableName: ACCOUNTS_TABLE_NAME3,
        Key: { accountNumber },
        ...buildUpdate2(fields, remove),
        ConditionExpression: "attribute_exists(accountNumber)",
        ReturnValues: "ALL_NEW"
      })
    );
    const changed = changedFields2(current, { ...fields, ...patch.main === true ? { notMain: void 0 } : {}, ...patch.dims === null ? { dims: void 0 } : {} });
    if (Object.keys(changed).length) {
      await bumpCatalogVersion();
      await recordEvent({
        category: "catalog",
        action: "account.update",
        target: accountTarget(accountNumber),
        targetName: res.Attributes?.name,
        details: { changed }
      });
    }
    log23("updated account", { accountNumber });
    return res.Attributes;
  } catch (err) {
    if (err.name === CONDITION_FAILED5) {
      throw new NotFoundError(`Account ${accountNumber} not found`);
    }
    throw err;
  }
}
async function updateRole(accountNumber, roleName, patch) {
  if (patch.profileName) await assertProfileNameFree(patch.profileName, { role: { accountNumber, roleName } });
  const fields = compact3({
    displayName: patch.displayName,
    roleArn: patch.roleArn,
    policyTier: patch.policyTier,
    description: patch.description,
    color: patch.color,
    icon: patch.icon,
    profileName: patch.profileName,
    sessionDurationSeconds: patch.sessionDurationSeconds
  });
  const current = (await ddb18.send(new import_lib_dynamodb18.GetCommand({ TableName: ROLES_TABLE_NAME6, Key: { accountNumber, roleName } }))).Item;
  try {
    const res = await ddb18.send(
      new import_lib_dynamodb18.UpdateCommand({
        TableName: ROLES_TABLE_NAME6,
        Key: { accountNumber, roleName },
        ...buildUpdate2(fields),
        ConditionExpression: "attribute_exists(roleName)",
        ReturnValues: "ALL_NEW"
      })
    );
    const changed = changedFields2(current, fields);
    if (Object.keys(changed).length) {
      await bumpCatalogVersion();
      await recordEvent({
        category: "catalog",
        action: "role.update",
        target: roleTarget(accountNumber, roleName),
        targetName: roleName,
        details: { changed }
      });
    }
    log23("updated role", { accountNumber, roleName });
    return res.Attributes;
  } catch (err) {
    if (err.name === CONDITION_FAILED5) {
      throw new NotFoundError(
        `Role ${roleName} not found in account ${accountNumber}`
      );
    }
    throw err;
  }
}

// lambdacode/api/routes/admin.ts
init_grantsService();
init_usersService();
init_requestsService();
init_resourcesService();

// lambdacode/api/services/networkStatusService.ts
var import_client_dynamodb19 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb19 = require("@aws-sdk/lib-dynamodb");
var ddb19 = import_lib_dynamodb19.DynamoDBDocumentClient.from(new import_client_dynamodb19.DynamoDBClient({}));
var RESOURCES_TABLE_NAME6 = process.env.RESOURCES_TABLE_NAME;
var RECONCILER_STATUS_KEY = "__reconciler-status__";
var EMPTY = {
  at: null,
  resources: {},
  staleConnectors: [],
  resourcesLive: 0,
  rules: 0,
  shares: {},
  sharesLive: 0,
  connectors: [],
  devices: {}
};
function siteIdsFromEnv() {
  try {
    const sites = JSON.parse(process.env.NETWORK_SITES ?? "[]");
    return sites.map((s) => s.id);
  } catch {
    return [];
  }
}
async function getReconcilerStatus() {
  const keys = [
    RECONCILER_STATUS_KEY,
    ...siteIdsFromEnv().map((id) => `${RECONCILER_STATUS_KEY}${id}`)
  ];
  const rows = (await Promise.all(
    keys.map(
      (k) => ddb19.send(
        new import_lib_dynamodb19.GetCommand({
          TableName: RESOURCES_TABLE_NAME6,
          Key: { resourceId: k }
        })
      )
    )
  )).map((r) => r.Item).filter((i) => Boolean(i));
  if (!rows.length) return EMPTY;
  const merged = {
    ...EMPTY,
    resources: {},
    staleConnectors: [],
    shares: {},
    connectors: [],
    devices: {}
  };
  const sites = {};
  for (const item of rows) {
    const at = item.at ?? null;
    if (at && (!merged.at || at < merged.at)) merged.at = at;
    Object.assign(
      merged.resources,
      item.statuses ?? {}
    );
    merged.staleConnectors.push(...item.staleConnectors ?? []);
    merged.resourcesLive += item.resourcesLive ?? 0;
    merged.rules += item.rules ?? 0;
    Object.assign(merged.shares, item.shares ?? {});
    merged.sharesLive += item.sharesLive ?? 0;
    const siteId = typeof item.siteId === "string" ? item.siteId : "";
    const topo = item.topology;
    for (const c of topo?.connectors ?? []) {
      merged.connectors.push({ ...c, siteId });
    }
    for (const [sub, d] of Object.entries(topo?.devices ?? {})) {
      const prev = merged.devices[sub];
      merged.devices[sub] = {
        count: (prev?.count ?? 0) + d.count,
        online: Boolean(prev?.online) || d.online,
        lastSeen: prev?.lastSeen && (!d.lastSeen || prev.lastSeen > d.lastSeen) ? prev.lastSeen : d.lastSeen,
        sites: [...prev?.sites ?? [], ...siteId ? [siteId] : []]
      };
    }
    if (typeof item.siteId === "string") {
      sites[item.siteId] = {
        at,
        staleConnectors: item.staleConnectors ?? [],
        resourcesLive: item.resourcesLive ?? 0,
        rules: item.rules ?? 0,
        sharesLive: item.sharesLive ?? 0
      };
    }
  }
  merged.staleConnectors = [...new Set(merged.staleConnectors)];
  if (Object.keys(sites).length) merged.sites = sites;
  return merged;
}

// lambdacode/api/routes/network.ts
var import_express4 = require("express");
var import_client_lambda2 = require("@aws-sdk/client-lambda");
init_auditService();

// lambdacode/api/services/reconcilerKick.ts
var import_client_lambda = require("@aws-sdk/client-lambda");
var lambda = new import_client_lambda.LambdaClient({});
async function invokeReconciler() {
  const fn = process.env.NETWORK_RECONCILER_FN_NAME ?? "";
  if (!fn) return false;
  await lambda.send(new import_client_lambda.InvokeCommand({ FunctionName: fn, InvocationType: "Event", Payload: "{}" }));
  return true;
}

// lambdacode/api/routes/network.ts
init_sharesService();
init_naming();
var log24 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var KEYMINTER_FN = process.env.NETWORK_KEYMINTER_FN_NAME ?? "";
function sitesFromEnv() {
  try {
    const sites = JSON.parse(process.env.NETWORK_SITES ?? "[]");
    if (sites.length) return sites;
  } catch {
  }
  const legacy = process.env.NETWORK_CONTROL_URL ?? "";
  return legacy ? [{ id: "default", controlUrl: legacy, accounts: [] }] : [];
}
var lambda2 = new import_client_lambda2.LambdaClient({});
var networkRouter = (0, import_express4.Router)();
var enabled = () => Boolean(KEYMINTER_FN && sitesFromEnv().length);
function requireNetwork(_req, res, next) {
  if (enabled()) next();
  else res.status(501).json({ message: "Private network access is not enabled" });
}
function requireShares(_req, res, next) {
  if (enabled() && devSharesConfig().enabled) next();
  else res.status(501).json({ message: "Dev shares are not enabled" });
}
networkRouter.get("/", requireAuth, (_req, res) => {
  const sites = sitesFromEnv();
  const shares = devSharesConfig();
  res.json({
    enabled: enabled(),
    // Legacy field older app bundles read — always the first site.
    controlUrl: sites[0]?.controlUrl ?? null,
    sites: sites.map(({ splitDns: _d, connectorVpcs: _v, ...pub }) => pub),
    devShares: {
      enabled: enabled() && shares.enabled,
      maxDurationHours: shares.maxDurationHours,
      maxActiveSharesPerOwner: shares.maxActiveSharesPerOwner
    }
  });
});
var kickReconciler = () => invokeReconciler().catch((err) => log24("WARN: reconciler kick failed", { error: err.message }));
var SHARE_ID_RE = /^[a-f0-9]{12}$/;
networkRouter.get("/shares", requireAuth, requireNetwork, async (req, res) => {
  try {
    res.json(await listShares(req.userId));
  } catch (err) {
    sendError(res, err, "list shares");
  }
});
networkRouter.get("/shares/directory", requireAuth, requireShares, async (_req, res) => {
  try {
    res.json(await listShareDirectory());
  } catch (err) {
    sendError(res, err, "list share directory");
  }
});
networkRouter.post("/shares", requireAuth, requireShares, async (req, res) => {
  try {
    const body = req.body ?? {};
    const share = await createShare(
      req.userId,
      req.userName ?? req.userId,
      {
        port: body.port,
        label: body.label,
        siteId: String(body.siteId ?? sitesFromEnv()[0]?.id ?? ""),
        durationHours: body.durationHours,
        hostname: body.hostname,
        ip: body.ip,
        device: body.device,
        grantees: body.grantees
      },
      sitesFromEnv().map((s) => s.id)
    );
    await kickReconciler();
    res.status(201).json({ share });
  } catch (err) {
    sendError(res, err, "create share");
  }
});
networkRouter.delete("/shares/:shareId", requireAuth, requireNetwork, async (req, res) => {
  const shareId = String(req.params.shareId ?? "");
  if (!SHARE_ID_RE.test(shareId)) {
    res.status(404).json({ message: `No share ${shareId}` });
    return;
  }
  try {
    await removeShare(shareId, { sub: req.userId, admin: isAdmin(req) });
    await kickReconciler();
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "stop share");
  }
});
async function invokeMinter(payload, req) {
  const out = await lambda2.send(
    new import_client_lambda2.InvokeCommand({
      FunctionName: KEYMINTER_FN,
      Payload: JSON.stringify({ keyType: "device", ...payload, userName: req.userId })
    })
  );
  const text2 = Buffer.from(out.Payload ?? []).toString("utf8");
  if (out.FunctionError) throw new Error(`keyminter ${String(payload.op ?? "mint")} failed: ${text2.slice(0, 500)}`);
  return JSON.parse(text2);
}
networkRouter.get("/devices", requireAuth, requireNetwork, async (req, res) => {
  try {
    const { devices = [], unreachable = [] } = await invokeMinter({ op: "list" }, req);
    res.json({ devices, unreachable });
  } catch (err) {
    log24("ERROR: device list", { error: err.message });
    res.status(502).json({ message: "Could not list your devices" });
  }
});
networkRouter.delete("/devices/:siteId/:name", requireAuth, requireNetwork, async (req, res) => {
  const siteId = String(req.params.siteId ?? "");
  const name = String(req.params.name ?? "").toLowerCase();
  const site = sitesFromEnv().find((s) => s.id === siteId);
  if (!site || !NODE_NAME_RE.test(name)) {
    res.status(404).json({ message: `No device ${name} on ${siteId}` });
    return;
  }
  try {
    const { deleted = 0 } = await invokeMinter({ op: "delete", siteId, name }, req);
    if (!deleted) {
      res.status(404).json({ message: `No device ${name} on ${siteId}` });
      return;
    }
    await recordEvent({
      category: "network",
      action: "device.delete",
      subject: { kind: "user", id: req.userId, name: req.userName },
      target: `site#${siteId}`,
      targetName: name,
      details: { siteId, count: deleted }
    });
    await kickReconciler();
    res.status(204).end();
  } catch (err) {
    log24("ERROR: device delete", { error: err.message, siteId });
    res.status(502).json({ message: "Could not remove the device" });
  }
});
networkRouter.post("/device-key", requireAuth, async (req, res) => {
  if (!enabled()) {
    res.status(501).json({ message: "Private network access is not enabled" });
    return;
  }
  const ephemeral = req.body?.ephemeral;
  if (ephemeral !== void 0 && typeof ephemeral !== "boolean") {
    res.status(400).json({ message: "ephemeral must be true or false" });
    return;
  }
  const sites = sitesFromEnv();
  const siteId = req.body?.siteId ?? sites[0].id;
  const site = sites.find((s) => s.id === siteId);
  if (!site) {
    res.status(400).json({ message: `Unknown site "${siteId}"` });
    return;
  }
  const audit = vendAuditor({
    userId: req.userId,
    userName: req.userName,
    claims: req.claims,
    serviceUser: req.serviceClient,
    accountNumber: "-",
    // enrollment is not account-scoped
    roleName: "tailnet-device",
    action: "NETWORK_KEY"
  });
  const MINT_FAILED = "Could not mint a network key";
  try {
    const { key, expiresAt } = await invokeMinter({ op: "mint", siteId: site.id, ephemeral: ephemeral === true }, req);
    await audit("VENDED");
    log24("device key minted", { siteId: site.id, ephemeral: ephemeral === true });
    res.json({ key, expiresAt, controlUrl: site.controlUrl, siteId: site.id });
  } catch (err) {
    log24("ERROR: keyminter invoke", { error: err.message });
    await audit("FAILED", { failureReason: MINT_FAILED });
    res.status(502).json({ message: MINT_FAILED });
  }
});

// lambdacode/api/routes/admin.ts
init_sharesService();

// lambdacode/api/routes/plugins.ts
var import_express5 = require("express");

// lambdacode/api/services/pluginDiscoveryService.ts
init_backend();
init_pluginAccess();
function discoveryRefreshSeconds() {
  const raw = Number(process.env.PLUGIN_DISCOVERY_REFRESH_SECONDS);
  if (!Number.isFinite(raw)) return PLUGIN_DISCOVERY_DEFAULT_REFRESH_SECONDS;
  return Math.min(Math.max(Math.round(raw), PLUGIN_DISCOVERY_MIN_REFRESH_SECONDS), PLUGIN_DISCOVERY_MAX_REFRESH_SECONDS);
}
var regionsOf = (record, accountNumber) => record.manifest.accounts.find((a) => a.accountNumber === accountNumber)?.regions;
function accountEntry(record, accountNumber, permissions, ctx) {
  const regions = regionsOf(record, accountNumber);
  return {
    accountNumber,
    // The Accounts catalog names accounts, not IAM grants: a caller who holds only a plugin grant still
    // sees the account's name.
    displayName: ctx.accountNames.get(accountNumber) ?? accountNumber,
    ...regions?.length ? { regions } : {},
    permissions
  };
}
function entryFor(pluginId, capabilities, ctx) {
  const record = ctx.catalog.get(pluginId);
  if (!record) return null;
  const byAccount = /* @__PURE__ */ new Map();
  for (const c of capabilities) {
    const held = byAccount.get(c.accountNumber) ?? [];
    held.push(c.permission);
    byAccount.set(c.accountNumber, held);
  }
  if (!byAccount.size) return null;
  const accounts = [...byAccount.entries()].sort(([a], [b]) => a.localeCompare(b)).map(
    ([accountNumber, held]) => accountEntry(record, accountNumber, PLUGIN_PERMISSIONS.filter((p) => held.includes(p)), ctx)
  );
  const ui = {};
  for (const permission of PLUGIN_PERMISSIONS) {
    const entry = record.ui?.[permission];
    if (entry && accounts.some((a) => a.permissions.includes(permission))) ui[permission] = entry;
  }
  return {
    id: record.pluginId,
    displayName: record.manifest.displayName,
    ...record.manifest.description ? { description: record.manifest.description } : {},
    version: record.manifest.version,
    revision: record.revision,
    apiBaseUrl: pluginApiBaseUrl(record.pluginId),
    ui,
    accounts
  };
}
async function callerDiscovery(userId, ctx) {
  const context = ctx ?? await loadPluginContext();
  const byPlugin = /* @__PURE__ */ new Map();
  for (const capability of await pluginCapabilitiesFor(userId, context)) {
    if (!capability.available) continue;
    const held = byPlugin.get(capability.pluginId) ?? [];
    held.push(capability);
    byPlugin.set(capability.pluginId, held);
  }
  const plugins = [...byPlugin.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([pluginId, capabilities]) => entryFor(pluginId, capabilities, context)).filter((e) => e !== null);
  return { schemaVersion: 1, refreshAfterSeconds: discoveryRefreshSeconds(), plugins };
}
function adminEntry(record, ctx) {
  const declared = record.manifest.permissions.map((p) => p.id);
  return {
    id: record.pluginId,
    displayName: record.manifest.displayName,
    ...record.manifest.description ? { description: record.manifest.description } : {},
    version: record.manifest.version,
    revision: record.revision,
    schemaVersion: record.schemaVersion,
    hostApiVersion: record.manifest.hostApiVersion,
    status: pluginCatalogStatus(record),
    enabled: record.manifest.enabled,
    installed: record.installed,
    permissions: record.manifest.permissions.map((p) => ({
      id: p.id,
      label: p.label,
      ...p.description ? { description: p.description } : {},
      // The shared rule is reflexive (it answers "what does holding this give?"); the editor wants the
      // extras only, so self is projected off here rather than by a second rule.
      implies: pluginPermissionsImpliedBy(p.id, declared).filter((implied) => implied !== p.id)
    })),
    accounts: record.manifest.accounts.map((a) => {
      const registered = ctx.registeredAccounts.has(a.accountNumber);
      const displayName = ctx.accountNames.get(a.accountNumber);
      return {
        accountNumber: a.accountNumber,
        ...displayName ? { displayName } : {},
        ...a.regions?.length ? { regions: a.regions } : {},
        available: registered,
        ...registered ? {} : { reason: "unregistered" }
      };
    }),
    ui: {
      ...record.ui?.user ? { user: stripUrl(record.ui.user) } : {},
      ...record.ui?.admin ? { admin: stripUrl(record.ui.admin) } : {}
    },
    routes: record.routes.map(({ id, method, path, permission }) => ({ id, method, path, permission })),
    updatedAt: record.updatedAt
  };
}
var stripUrl = ({ url: _url, ...rest }) => rest;
async function adminCatalog(ctx) {
  const context = ctx ?? await loadPluginContext();
  const plugins = [...context.catalog.values()].sort((a, b) => a.manifest.displayName.localeCompare(b.manifest.displayName) || a.pluginId.localeCompare(b.pluginId)).map((record) => adminEntry(record, context));
  return { schemaVersion: 1, plugins };
}

// lambdacode/api/routes/plugins.ts
init_pluginGrantsService();
var pluginsRouter = (0, import_express5.Router)();
var noStore = (_req, res, next) => {
  res.set("Cache-Control", "no-store");
  next();
};
pluginsRouter.use(noStore, requireAuth);
pluginsRouter.get("/", async (req, res) => {
  try {
    res.json(await callerDiscovery(req.userId));
  } catch (err) {
    sendError(res, err, "list plugins");
  }
});
pluginsRouter.get("/expiry", async (req, res) => {
  try {
    res.json(await listPluginExpiryFeed(req.userId));
  } catch (err) {
    sendError(res, err, "list plugin expiry");
  }
});
pluginsRouter.post("/expiry/seen", async (req, res) => {
  try {
    res.json({ cleared: await markPluginExpiryNoticesSeen(req.userId) });
  } catch (err) {
    sendError(res, err, "mark plugin expiry seen");
  }
});

// lambdacode/api/routes/admin.ts
init_resourceGrantsService();
init_auditService();
init_accessReportService();
init_nameDirectory();
init_directory();
init_usersService();
init_access2();

// lambdacode/api/services/brandingService.ts
var import_client_s3 = require("@aws-sdk/client-s3");
init_httpErrors();

// lambdacode/api/services/brandingShapes.ts
var HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
var LOGO_MAX = 64e3;
var LOGO_URL_RE = /^(https:\/\/|data:image\/)/;
function isBrandColor(key, value) {
  return HEX_RE.test(value) || key === "primaryColor" && value === "mono";
}

// lambdacode/api/services/brandingService.ts
init_auditService();
var s3 = new import_client_s3.S3Client({});
var BUCKET = process.env.WEB_BUCKET_NAME;
var KEY = "branding.json";
var log25 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var GRAY_TONES = ["slate", "neutral", "warm", "mauve", "sage", "olive", "sand"];
var RADII = ["none", "sm", "md", "lg"];
var ICON_SETS = ["outline", "bold", "solid"];
var NAME_MAX3 = 60;
var KNOWN_KEYS = [
  "projectName",
  "logoUrl",
  "primaryColor",
  "primaryHoverColor",
  "accentColor",
  "grayTone",
  "radius",
  "iconSet",
  "panelStrength",
  "accentDepth",
  "borderStrength",
  "gradientStrength"
];
var PERCENT_KEYS = [
  "panelStrength",
  "accentDepth",
  "borderStrength",
  "gradientStrength"
];
function validate(b) {
  for (const key of Object.keys(b)) {
    if (!KNOWN_KEYS.includes(key)) {
      throw new ValidationError(`Unknown branding field: ${key}`);
    }
  }
  for (const key of ["primaryColor", "primaryHoverColor", "accentColor"]) {
    const v = b[key];
    if (v !== void 0 && !isBrandColor(key, v)) {
      throw new ValidationError(`${key} must be a #rgb or #rrggbb hex color`);
    }
  }
  if (b.grayTone !== void 0 && !GRAY_TONES.includes(b.grayTone)) {
    throw new ValidationError(`grayTone must be one of: ${GRAY_TONES.join(", ")}`);
  }
  if (b.radius !== void 0 && !RADII.includes(b.radius)) {
    throw new ValidationError(`radius must be one of: ${RADII.join(", ")}`);
  }
  if (b.iconSet !== void 0 && !ICON_SETS.includes(b.iconSet)) {
    throw new ValidationError(`iconSet must be one of: ${ICON_SETS.join(", ")}`);
  }
  for (const key of PERCENT_KEYS) {
    const v = b[key];
    if (v !== void 0 && (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 100)) {
      throw new ValidationError(`${key} must be a number from 0 to 100`);
    }
  }
  if (b.projectName !== void 0) {
    const name = b.projectName.trim();
    if (!name || name.length > NAME_MAX3) {
      throw new ValidationError(`projectName must be 1-${NAME_MAX3} characters`);
    }
  }
  if (b.logoUrl !== void 0 && b.logoUrl !== "") {
    if (b.logoUrl.length > LOGO_MAX) {
      throw new ValidationError(`logoUrl must be at most ${LOGO_MAX} characters`);
    }
    if (!LOGO_URL_RE.test(b.logoUrl)) {
      throw new ValidationError("logoUrl must be an https:// URL or a data:image/* URI");
    }
  }
}
function requireBucket() {
  if (!BUCKET) throw new ValidationError("BRANDING_NOT_DEPLOYED");
  return BUCKET;
}
async function readCurrent(bucket) {
  try {
    const res = await s3.send(new import_client_s3.GetObjectCommand({ Bucket: bucket, Key: KEY }));
    return JSON.parse(await res.Body.transformToString() || "{}");
  } catch (err) {
    if (err instanceof import_client_s3.NoSuchKey || err.name === "NoSuchKey") return null;
    throw err;
  }
}
async function saveBranding(updatedBy, changes) {
  const bucket = requireBucket();
  if (changes.branding === void 0 && changes.dismissed === void 0) {
    throw new ValidationError("provide at least one of: branding, dismissed");
  }
  if (changes.branding !== void 0) validate(changes.branding);
  const current = await readCurrent(bucket);
  const next = {
    version: 1,
    updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    updatedBy,
    dismissed: changes.dismissed ?? current?.dismissed,
    branding: changes.branding ?? current?.branding
  };
  if (next.dismissed === void 0) delete next.dismissed;
  if (next.branding === void 0) delete next.branding;
  await s3.send(
    new import_client_s3.PutObjectCommand({
      Bucket: bucket,
      Key: KEY,
      Body: JSON.stringify(next),
      ContentType: "application/json",
      // Belt and braces with the CloudFront CACHING_DISABLED behavior.
      CacheControl: "no-cache"
    })
  );
  const summary2 = { dismissed: next.dismissed ?? false, hasTheme: next.branding !== void 0 };
  const changed = brandingChanges(current, next);
  if (Object.keys(changed).length) {
    await recordEvent({
      category: "catalog",
      action: "branding.update",
      details: { ...summary2, changed }
    });
  }
  log25("branding saved", { updatedBy, ...summary2 });
}
function brandingChanges(before, after) {
  const changed = {};
  const short = (key, v) => v === void 0 ? null : key === "logoUrl" && typeof v === "string" ? v ? "(image)" : null : v;
  const was = before?.branding ?? {};
  const now = after.branding ?? {};
  for (const key of /* @__PURE__ */ new Set([...Object.keys(was), ...Object.keys(now)])) {
    if (was[key] !== now[key]) changed[key] = { from: short(key, was[key]), to: short(key, now[key]) };
  }
  if ((before?.dismissed ?? false) !== (after.dismissed ?? false)) {
    changed.dismissed = { from: before?.dismissed ?? false, to: after.dismissed ?? false };
  }
  return changed;
}

// lambdacode/api/services/setupService.ts
var import_client_dynamodb20 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb20 = require("@aws-sdk/lib-dynamodb");
init_catalogIndex();
var import_client_cognito_identity_provider5 = require("@aws-sdk/client-cognito-identity-provider");
var ddb20 = import_lib_dynamodb20.DynamoDBDocumentClient.from(new import_client_dynamodb20.DynamoDBClient({}));
var cognito5 = new import_client_cognito_identity_provider5.CognitoIdentityProviderClient({});
var AUDIT_TABLE_NAME = process.env.AUDIT_TABLE_NAME;
var USER_POOL_ID4 = process.env.USER_POOL_ID;
var ISSUER_URL2 = (process.env.ISSUER_URL ?? "").replace(/\/$/, "");
var EMAIL_CONFIGURED = process.env.EMAIL_CONFIGURED === "1";
var EMAIL_FROM = process.env.EMAIL_FROM || void 0;
function configAccountsFromEnv() {
  const raw = process.env.CONFIG_ACCOUNTS;
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(
      (a) => typeof a?.accountNumber === "string" && Array.isArray(a?.roles)
    );
  } catch {
    return [];
  }
}
async function registeredAccountIds() {
  return (await catalog()).accounts.filter((a) => a.registered).map((a) => a.accountNumber);
}
async function countRoles() {
  return (await catalog()).roleByKey.size;
}
async function anyVendSucceeded() {
  let key;
  for (let page = 0; page < 4; page++) {
    const res = await ddb20.send(
      new import_lib_dynamodb20.ScanCommand({
        TableName: AUDIT_TABLE_NAME,
        // Both row generations: the vend-only log (VENDED / CREDENTIALS) and the activity log (OK / credentials.vend).
        FilterExpression: "#o IN (:vended, :ok) AND #a IN (:cred, :console, :credV2, :consoleV2)",
        ExpressionAttributeNames: { "#o": "outcome", "#a": "action" },
        ExpressionAttributeValues: {
          ":vended": "VENDED",
          ":ok": "OK",
          ":cred": "CREDENTIALS",
          ":console": "CONSOLE",
          ":credV2": "credentials.vend",
          ":consoleV2": "console.open"
        },
        ProjectionExpression: "eventId",
        Limit: 50,
        ExclusiveStartKey: key
      })
    );
    if ((res.Items ?? []).length > 0) return true;
    key = res.LastEvaluatedKey;
    if (!key) return false;
  }
  return false;
}
async function userCounts(callerId) {
  let total = 0;
  let invitedActive = false;
  let token;
  do {
    const page = await cognito5.send(
      new import_client_cognito_identity_provider5.ListUsersCommand({
        UserPoolId: USER_POOL_ID4,
        Limit: 60,
        PaginationToken: token
      })
    );
    for (const u of page.Users ?? []) {
      total++;
      const sub = u.Attributes?.find((a) => a.Name === "sub")?.Value;
      if (u.UserStatus === "CONFIRMED" && u.Enabled !== false && sub !== callerId) {
        invitedActive = true;
      }
    }
    token = page.PaginationToken;
  } while (token);
  return { total, invitedActive };
}
async function getSetupStatus(callerId) {
  const [accountIds, roles, users, vended] = await Promise.all([
    registeredAccountIds(),
    countRoles(),
    userCounts(callerId),
    anyVendSucceeded()
  ]);
  const registered = new Set(accountIds);
  return {
    issuerUrl: ISSUER_URL2,
    region: process.env.AWS_REGION ?? "",
    emailConfigured: EMAIL_CONFIGURED,
    emailFrom: EMAIL_CONFIGURED ? EMAIL_FROM : void 0,
    accounts: accountIds.length,
    roles,
    usersTotal: users.total,
    invitedActive: users.invitedActive,
    vended,
    configAccounts: configAccountsFromEnv().map((a) => ({
      ...a,
      registered: registered.has(a.accountNumber)
    }))
  };
}

// lambdacode/api/routes/admin.ts
init_pluginGrantsService();
init_groupsService();
init_dimensions();
init_catalogIndex();
init_reportJobs();
init_groupsService();
init_serviceUsersService();
init_httpErrors();
var log27 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var isOptionalText = (v, max) => v === void 0 || typeof v === "string" && v.length <= max;
var textMessage = (field, max) => `${field} must be a string of ${max} characters or fewer`;
var ACCOUNT_TEXT_FIELDS = [["name", 128], ["environment", 64], ["status", 32]];
var DIMS_MESSAGE = "dims must be { tenant, stage, project? } of non-empty strings";
var ORDER_MAX = 5e3;
var BULK_MAX = 500;
var ROLE_TEXT_FIELDS = [["policyTier", 64], ["description", 500]];
var firstBadText = (body, fields) => {
  for (const [field, max] of fields) if (!isOptionalText(body[field], max)) return textMessage(field, max);
  return void 0;
};
var isValidSessionDuration = (v) => v === void 0 || typeof v === "number" && Number.isInteger(v) && v >= 900 && v <= 43200;
var SESSION_DURATION_MESSAGE = "sessionDurationSeconds must be a whole number between 900 and 43200";
var isValidChipColor = (color) => color === void 0 || color === "" || typeof color === "string" && /^#[0-9a-fA-F]{6}$/.test(color);
var CHIP_COLOR_MESSAGE = 'color must be a hex color like "#3e63dd" (empty string clears it)';
var ROLE_ICONS = ["view", "admin", "operate", "deploy", "data", "billing", "analytics", "access"];
var isValidRoleIcon = (icon) => icon === void 0 || icon === "" || typeof icon === "string" && ROLE_ICONS.includes(icon);
var ROLE_ICON_MESSAGE = `icon must be one of: ${ROLE_ICONS.join(", ")} (empty string clears it)`;
var PRINCIPAL_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;
var isPrincipalId = (v) => typeof v === "string" && PRINCIPAL_ID_RE.test(v);
var PRINCIPAL_ID_MESSAGE = "userId must be a Cognito sub or a service-user client id";
var adminRouter = (0, import_express6.Router)();
adminRouter.use(["/plugins", "/users/:userId/plugin-grants", "/groups/:groupId/plugin-grants"], noStore);
adminRouter.use(requireAuth, requireAdmin);
adminRouter.param("userId", (_req, res, next, value) => {
  if (!isPrincipalId(value)) {
    res.status(400).json({ message: PRINCIPAL_ID_MESSAGE });
    return;
  }
  next();
});
adminRouter.get("/setup", async (req, res) => {
  try {
    res.json(await getSetupStatus(req.userId));
  } catch (err) {
    sendError(res, err, "load setup status");
  }
});
adminRouter.get("/accounts", async (req, res) => {
  try {
    const spec = {
      text: (a) => [a.accountNumber, a.name ?? "", a.dims?.tenant ?? "", a.dims?.project ?? "", a.dims?.stage ?? "", ...a.roles.map((r) => `${r.roleName} ${r.displayName ?? ""} ${r.roleArn ?? ""}`)].join(" "),
      id: (a) => a.accountNumber,
      sorts: { position: (a) => a.position ?? 0, name: (a) => a.name ?? a.accountNumber, number: (a) => a.accountNumber },
      facets: {
        environment: (a) => a.environment,
        status: (a) => a.status,
        // Arrange mode fetches only the main accounts (`filter[main]=true`).
        main: (a) => a.main === false ? "false" : "true",
        ...dimensionFacets()
      }
    };
    const page = parseListQuery(req.query, { sorts: Object.keys(spec.sorts), facets: Object.keys(spec.facets ?? {}) });
    const accounts = await listAllAccounts();
    if (!page) {
      res.json({ accounts });
      return;
    }
    res.json(paginate(accounts, page, spec));
  } catch (err) {
    sendError(res, err, "list accounts");
  }
});
adminRouter.get("/accounts/:accountNumber", async (req, res) => {
  try {
    const account = await getAccount(req.params.accountNumber);
    res.json({ account });
  } catch (err) {
    sendError(res, err, "get account");
  }
});
adminRouter.post("/accounts", async (req, res) => {
  const { accountNumber, name, environment, status, profileName, main, dims } = req.body ?? {};
  if (!/^\d{12}$/.test(accountNumber ?? "")) {
    res.status(400).json({ message: "accountNumber must be a 12-digit AWS account id" });
    return;
  }
  if (dims !== void 0 && !cleanDims(dims)) {
    res.status(400).json({ message: DIMS_MESSAGE });
    return;
  }
  if (main !== void 0 && typeof main !== "boolean") {
    res.status(400).json({ message: "main must be a boolean" });
    return;
  }
  if (!isValidProfileName(profileName)) {
    res.status(400).json({ message: PROFILE_NAME_MESSAGE });
    return;
  }
  const badText = firstBadText(req.body ?? {}, ACCOUNT_TEXT_FIELDS);
  if (badText) {
    res.status(400).json({ message: badText });
    return;
  }
  try {
    const { existing, ...account } = await createAccount({ accountNumber, name, environment, status, profileName, main, dims });
    res.status(existing ? 200 : 201).json({ account });
  } catch (err) {
    sendError(res, err, "create account");
  }
});
adminRouter.put("/accounts/order", async (req, res) => {
  const { accounts } = req.body ?? {};
  const validRoles = (roles) => roles === void 0 || Array.isArray(roles) && roles.length <= 200 && roles.every((r) => typeof r === "string" && r.length > 0 && r.length <= 64) && new Set(roles).size === roles.length;
  const valid = Array.isArray(accounts) && accounts.length > 0 && accounts.length <= ORDER_MAX && accounts.every(
    (a) => !!a && typeof a === "object" && typeof a.accountNumber === "string" && /^\d{12}$/.test(a.accountNumber) && validRoles(a.roles)
  ) && new Set(accounts.map((a) => a.accountNumber)).size === accounts.length;
  if (!valid) {
    res.status(400).json({
      message: "accounts must be a non-empty list of distinct 12-digit account ids, each with an optional distinct list of its role names"
    });
    return;
  }
  try {
    await reorderAccounts(
      accounts.map((a) => ({ accountNumber: a.accountNumber, roles: a.roles }))
    );
    const ordered = new Set(accounts.map((a) => a.accountNumber));
    res.json({ accounts: (await listAllAccounts()).filter((a) => ordered.has(a.accountNumber)) });
  } catch (err) {
    sendError(res, err, "reorder accounts");
  }
});
adminRouter.patch("/accounts/:accountNumber", async (req, res) => {
  const { name, environment, status, profileName, main, dims } = req.body ?? {};
  if (name === void 0 && environment === void 0 && status === void 0 && profileName === void 0 && main === void 0 && dims === void 0) {
    res.status(400).json({ message: "provide at least one of: name, environment, status, profileName, main, dims" });
    return;
  }
  if (main !== void 0 && typeof main !== "boolean") {
    res.status(400).json({ message: "main must be a boolean" });
    return;
  }
  if (dims !== void 0 && dims !== null && !cleanDims(dims)) {
    res.status(400).json({ message: DIMS_MESSAGE });
    return;
  }
  if (!isValidProfileName(profileName)) {
    res.status(400).json({ message: PROFILE_NAME_MESSAGE });
    return;
  }
  const badText = firstBadText(req.body ?? {}, ACCOUNT_TEXT_FIELDS);
  if (badText) {
    res.status(400).json({ message: badText });
    return;
  }
  try {
    const account = await updateAccount(req.params.accountNumber, {
      name,
      environment,
      status,
      profileName,
      main,
      dims
    });
    res.json({ account });
  } catch (err) {
    sendError(res, err, "update account");
  }
});
adminRouter.delete("/accounts/:accountNumber", async (req, res) => {
  try {
    await deleteAccount(req.params.accountNumber);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "delete account");
  }
});
adminRouter.post(
  "/accounts/:accountNumber/roles",
  async (req, res) => {
    const { roleName, displayName, roleArn, policyTier, description, color, icon, profileName, sessionDurationSeconds } = req.body ?? {};
    if (!roleName || !roleArn) {
      res.status(400).json({ message: "roleName and roleArn are required" });
      return;
    }
    if (!isValidProfileName(profileName)) {
      res.status(400).json({ message: PROFILE_NAME_MESSAGE });
      return;
    }
    if (!isValidSessionDuration(sessionDurationSeconds)) {
      res.status(400).json({ message: SESSION_DURATION_MESSAGE });
      return;
    }
    if (!isValidChipColor(color)) {
      res.status(400).json({ message: CHIP_COLOR_MESSAGE });
      return;
    }
    if (!isValidRoleIcon(icon)) {
      res.status(400).json({ message: ROLE_ICON_MESSAGE });
      return;
    }
    if (!/^\d{12}$/.test(req.params.accountNumber)) {
      res.status(400).json({ message: "accountNumber must be 12 digits" });
      return;
    }
    if (typeof roleName !== "string" || roleName.includes("#") || roleName.includes("/")) {
      res.status(400).json({ message: 'roleName must not contain "#" or "/"' });
      return;
    }
    if (displayName !== void 0 && (typeof displayName !== "string" || displayName.length > 128)) {
      res.status(400).json({ message: "displayName must be a string of 128 characters or fewer" });
      return;
    }
    const badText = firstBadText(req.body ?? {}, ROLE_TEXT_FIELDS);
    if (badText) {
      res.status(400).json({ message: badText });
      return;
    }
    if (!/^arn:aws:iam::\d{12}:role\/.+/.test(roleArn)) {
      res.status(400).json({ message: "roleArn must be a valid IAM role ARN" });
      return;
    }
    if (roleArn.split(":")[4] !== req.params.accountNumber) {
      res.status(400).json({
        message: "roleArn's account id must match the accountNumber in the path"
      });
      return;
    }
    try {
      const role = await createRole(req.params.accountNumber, {
        roleName,
        displayName,
        roleArn,
        policyTier,
        description,
        color,
        icon,
        profileName,
        sessionDurationSeconds
      });
      const { existing, ...created } = role;
      res.status(existing ? 200 : 201).json({ role: created });
    } catch (err) {
      sendError(res, err, "create role");
    }
  }
);
adminRouter.patch(
  "/accounts/:accountNumber/roles/:roleName",
  async (req, res) => {
    const { displayName, roleArn, policyTier, description, color, icon, profileName, sessionDurationSeconds } = req.body ?? {};
    if (displayName === void 0 && roleArn === void 0 && policyTier === void 0 && description === void 0 && color === void 0 && icon === void 0 && profileName === void 0 && sessionDurationSeconds === void 0) {
      res.status(400).json({
        message: "provide at least one of: displayName, roleArn, policyTier, description, color, icon, profileName, sessionDurationSeconds"
      });
      return;
    }
    if (!isValidProfileName(profileName)) {
      res.status(400).json({ message: PROFILE_NAME_MESSAGE });
      return;
    }
    if (!isValidSessionDuration(sessionDurationSeconds)) {
      res.status(400).json({ message: SESSION_DURATION_MESSAGE });
      return;
    }
    if (!isValidChipColor(color)) {
      res.status(400).json({ message: CHIP_COLOR_MESSAGE });
      return;
    }
    if (!isValidRoleIcon(icon)) {
      res.status(400).json({ message: ROLE_ICON_MESSAGE });
      return;
    }
    if (displayName !== void 0 && (typeof displayName !== "string" || displayName.length > 128)) {
      res.status(400).json({ message: "displayName must be a string of 128 characters or fewer" });
      return;
    }
    const badText = firstBadText(req.body ?? {}, ROLE_TEXT_FIELDS);
    if (badText) {
      res.status(400).json({ message: badText });
      return;
    }
    if (roleArn !== void 0 && !/^arn:aws:iam::\d{12}:role\/.+/.test(roleArn)) {
      res.status(400).json({ message: "roleArn must be a valid IAM role ARN" });
      return;
    }
    if (roleArn !== void 0 && roleArn.split(":")[4] !== req.params.accountNumber) {
      res.status(400).json({
        message: "roleArn's account id must match the accountNumber in the path"
      });
      return;
    }
    try {
      const role = await updateRole(req.params.accountNumber, req.params.roleName, {
        displayName,
        roleArn,
        policyTier,
        description,
        color,
        icon,
        profileName,
        sessionDurationSeconds
      });
      res.json({ role });
    } catch (err) {
      sendError(res, err, "update role");
    }
  }
);
adminRouter.delete(
  "/accounts/:accountNumber/roles/:roleName",
  async (req, res) => {
    try {
      await deleteRole(req.params.accountNumber, req.params.roleName);
      res.status(204).end();
    } catch (err) {
      sendError(res, err, "delete role");
    }
  }
);
adminRouter.get(
  "/accounts/:accountNumber/roles/:roleName/grants",
  async (req, res) => {
    try {
      const grantees = await listGrantees(
        req.params.accountNumber,
        req.params.roleName
      );
      res.json({ grantees });
    } catch (err) {
      sendError(res, err, "list grantees");
    }
  }
);
adminRouter.put(
  "/accounts/:accountNumber/roles/:roleName/grants/:userId",
  async (req, res) => {
    const { durationHours } = req.body ?? {};
    if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
      res.status(400).json({
        message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
      });
      return;
    }
    try {
      const grant = await assignRole(
        req.params.accountNumber,
        req.params.roleName,
        req.params.userId,
        req.userId,
        durationHours !== void 0 ? new Date(Date.now() + durationHours * 60 * 60 * 1e3).toISOString() : void 0
      );
      res.status(200).json({ grant });
    } catch (err) {
      sendError(res, err, "assign role");
    }
  }
);
adminRouter.delete(
  "/accounts/:accountNumber/roles/:roleName/grants/:userId",
  async (req, res) => {
    try {
      await revokeRole(
        req.params.accountNumber,
        req.params.roleName,
        req.params.userId
      );
      res.status(204).end();
    } catch (err) {
      sendError(res, err, "revoke role");
    }
  }
);
adminRouter.get("/resources", async (_req, res) => {
  try {
    const resources = await listResources();
    res.json({ resources });
  } catch (err) {
    sendError(res, err, "list resources");
  }
});
adminRouter.get("/resources/status", async (_req, res) => {
  try {
    res.json(await getReconcilerStatus());
  } catch (err) {
    sendError(res, err, "read reconciler status");
  }
});
adminRouter.get("/network", async (_req, res) => {
  try {
    res.json({ sites: sitesFromEnv(), status: await getReconcilerStatus() });
  } catch (err) {
    sendError(res, err, "read network topology");
  }
});
adminRouter.post("/network/sync", async (req, res) => {
  if (!process.env.NETWORK_RECONCILER_FN_NAME) {
    res.status(501).json({ message: "Private network access is not enabled" });
    return;
  }
  try {
    await invokeReconciler();
    log27("network sync requested", { by: req.userId });
    res.status(202).json({ message: "Sync requested" });
  } catch (err) {
    sendError(res, err, "request network sync");
  }
});
adminRouter.get("/network/shares", async (_req, res) => {
  if (!process.env.NETWORK_SITES) {
    res.status(501).json({ message: "Private network access is not enabled" });
    return;
  }
  try {
    res.json({ shares: await listAllShares() });
  } catch (err) {
    sendError(res, err, "list shares");
  }
});
adminRouter.post(
  "/accounts/:accountNumber/roles/:roleName/test-session",
  async (req, res) => {
    const { durationSeconds } = req.body ?? {};
    if (!isValidSessionDuration(durationSeconds) || durationSeconds === void 0) {
      res.status(400).json({ message: SESSION_DURATION_MESSAGE.replace("sessionDurationSeconds", "durationSeconds") });
      return;
    }
    const { accountNumber, roleName } = req.params;
    try {
      const result = await testAssume(req.userId, accountNumber, roleName, durationSeconds, req.userName);
      await recordEvent({
        category: "vend",
        action: "role.test",
        outcome: result.ok ? "OK" : "FAILED",
        reason: result.ok ? void 0 : result.message,
        subject: { kind: req.serviceClient ? "serviceUser" : "user", id: req.userId, name: req.userName },
        target: roleTarget(accountNumber, roleName),
        targetName: roleName,
        details: { durationSeconds }
      });
      res.json(result);
    } catch (err) {
      sendError(res, err, "test session length");
    }
  }
);
adminRouter.post("/users/:userId/revoke-all", async (req, res) => {
  try {
    const removed = await revokeAllAccessForUser(req.params.userId);
    res.json({ removed });
  } catch (err) {
    sendError(res, err, "revoke all access");
  }
});
adminRouter.post("/resources", async (req, res) => {
  if (!process.env.NETWORK_SITES) {
    res.status(501).json({ message: "Private network access is not enabled" });
    return;
  }
  const {
    accountNumber,
    name,
    type,
    cidr,
    ports,
    dnsName,
    sshUser,
    securityGroupId,
    description
  } = req.body ?? {};
  if (!/^\d{12}$/.test(accountNumber ?? "")) {
    res.status(400).json({ message: "accountNumber must be a 12-digit AWS account id" });
    return;
  }
  try {
    const resource = await createResource(
      {
        accountNumber,
        name,
        type,
        cidr,
        ports,
        dnsName,
        sshUser,
        securityGroupId,
        description
      },
      req.userId
    );
    res.status(201).json({ resource });
  } catch (err) {
    sendError(res, err, "create resource");
  }
});
adminRouter.patch("/resources/:resourceId", async (req, res) => {
  const { name, type, cidr, ports, dnsName, sshUser, securityGroupId, description } = req.body ?? {};
  if (name === void 0 && type === void 0 && cidr === void 0 && ports === void 0 && dnsName === void 0 && sshUser === void 0 && securityGroupId === void 0 && description === void 0) {
    res.status(400).json({
      message: "provide at least one of: name, type, cidr, ports, dnsName, sshUser, securityGroupId, description"
    });
    return;
  }
  try {
    const resource = await updateResource(req.params.resourceId, {
      name,
      type,
      cidr,
      ports,
      dnsName,
      sshUser,
      securityGroupId,
      description
    });
    res.json({ resource });
  } catch (err) {
    sendError(res, err, "update resource");
  }
});
adminRouter.delete("/resources/:resourceId", async (req, res) => {
  try {
    await deleteResource(req.params.resourceId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "delete resource");
  }
});
adminRouter.get(
  "/resources/:resourceId/grants",
  async (req, res) => {
    try {
      const [grantees, users] = await Promise.all([
        listResourceGrantees(req.params.resourceId),
        listUsers()
      ]);
      const emailBySub2 = new Map(users.map((u) => [u.userId, u.email]));
      res.json({
        grantees: grantees.map((g) => ({
          ...g,
          email: emailBySub2.get(g.userId) ?? ""
        }))
      });
    } catch (err) {
      sendError(res, err, "list resource grantees");
    }
  }
);
adminRouter.put(
  "/resources/:resourceId/grants/:userId",
  async (req, res) => {
    if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(req.params.userId)) {
      res.status(400).json({ message: "userId must be a Cognito sub" });
      return;
    }
    const { durationHours } = req.body ?? {};
    if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
      res.status(400).json({
        message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
      });
      return;
    }
    try {
      const grant = await assignResource(
        req.params.resourceId,
        req.params.userId,
        req.userId,
        durationHours !== void 0 ? new Date(Date.now() + durationHours * 60 * 60 * 1e3).toISOString() : void 0
      );
      res.status(200).json({ grant });
    } catch (err) {
      sendError(res, err, "assign resource");
    }
  }
);
adminRouter.delete(
  "/resources/:resourceId/grants/:userId",
  async (req, res) => {
    try {
      await revokeResourceGrant(req.params.resourceId, req.params.userId);
      res.status(204).end();
    } catch (err) {
      sendError(res, err, "revoke resource grant");
    }
  }
);
adminRouter.get(
  "/users/:userId/resource-grants",
  async (req, res) => {
    try {
      const [grants, resources] = await Promise.all([
        listUserResourceGrants(req.params.userId),
        listResources()
      ]);
      const nameById = new Map(resources.map((r) => [r.resourceId, r.name]));
      res.json({
        grants: grants.map((g) => ({
          ...g,
          resourceName: nameById.get(g.resourceId) ?? "(deleted resource)"
        }))
      });
    } catch (err) {
      sendError(res, err, "list user resource grants");
    }
  }
);
adminRouter.get("/users", async (req, res) => {
  try {
    const page = parseListQuery(req.query, { sorts: ["email", "lastSeen"], facets: ["admin", "status"] });
    const users = await listUsers();
    if (!page) {
      res.json({ users: users.map(capLists) });
      return;
    }
    const result = paginate(users, page, {
      text: (u) => [u.email, u.userId, ...u.roles.map((r) => `${r.accountNumber} ${r.roleName}`)].join(" "),
      id: (u) => u.userId,
      sorts: { email: (u) => u.email, lastSeen: (u) => u.lastSeenAt ?? "" },
      facets: {
        admin: (u) => u.admin ? "admin" : "member",
        status: (u) => u.pendingInvite ? "invited" : "active"
      }
    });
    res.json({ ...result, items: result.items.map(capLists) });
  } catch (err) {
    sendError(res, err, "list users");
  }
});
var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
adminRouter.post("/users", async (req, res) => {
  const { email, admin, sendEmail } = req.body ?? {};
  if (typeof email !== "string" || !EMAIL_RE.test(email)) {
    res.status(400).json({ message: "a valid email is required" });
    return;
  }
  if (admin !== void 0 && typeof admin !== "boolean") {
    res.status(400).json({ message: "admin must be true or false" });
    return;
  }
  try {
    const { signupLink: signupLink2, ...user } = await createUser(email, admin === true, sendEmail !== false);
    res.status(201).json({ user, signupLink: signupLink2 });
  } catch (err) {
    sendError(res, err, "create user");
  }
});
var BULK_CREATE_MAX = 50;
adminRouter.post("/users/bulk", async (req, res) => {
  const { emails, admin, sendEmail } = req.body ?? {};
  if (!Array.isArray(emails) || emails.length === 0 || !emails.every((e) => typeof e === "string")) {
    res.status(400).json({ message: "emails must be a non-empty string array" });
    return;
  }
  if (emails.length > BULK_CREATE_MAX) {
    res.status(400).json({
      message: `at most ${BULK_CREATE_MAX} emails per request`
    });
    return;
  }
  try {
    const results = await createUsers(emails, admin === true, sendEmail !== false);
    res.json({ results });
  } catch (err) {
    sendError(res, err, "bulk create users");
  }
});
adminRouter.get("/users/:userId", async (req, res) => {
  try {
    res.json({ user: await getUser(req.params.userId) });
  } catch (err) {
    sendError(res, err, "load user");
  }
});
adminRouter.patch("/users/:userId", async (req, res) => {
  const { email, admin } = req.body ?? {};
  if (email === void 0 && admin === void 0) {
    res.status(400).json({ message: "provide at least one of: email, admin" });
    return;
  }
  if (email !== void 0 && (typeof email !== "string" || !EMAIL_RE.test(email))) {
    res.status(400).json({ message: "email must be a valid email address" });
    return;
  }
  if (admin !== void 0 && typeof admin !== "boolean") {
    res.status(400).json({ message: "admin must be true or false" });
    return;
  }
  try {
    await updateUser(req.params.userId, { email, admin });
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "update user");
  }
});
adminRouter.post("/users/:userId/resend-invite", async (req, res) => {
  try {
    await resendInvite(req.params.userId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "resend invite");
  }
});
adminRouter.post("/users/:userId/signup-link", async (req, res) => {
  try {
    res.json({ signupLink: await mintSignupLink(req.params.userId) });
  } catch (err) {
    sendError(res, err, "mint sign-up link");
  }
});
adminRouter.post("/users/:userId/reset-mfa", async (req, res) => {
  try {
    await resetUserMfa(req.params.userId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "reset MFA");
  }
});
adminRouter.delete("/users/:userId", async (req, res) => {
  try {
    await deleteUser(req.params.userId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "delete user");
  }
});
adminRouter.get("/users/:userId/grants", async (req, res) => {
  try {
    const grants = await listUserGrants(req.params.userId);
    res.json({ grants });
  } catch (err) {
    sendError(res, err, "list user grants");
  }
});
var BULK_ASSIGN_MAX_USERS = 50;
var BULK_ASSIGN_MAX_ROLES = 20;
adminRouter.post("/grants/bulk", async (req, res) => {
  const { userIds, roles, durationHours } = req.body ?? {};
  if (!Array.isArray(userIds) || userIds.length === 0 || userIds.length > BULK_ASSIGN_MAX_USERS || !userIds.every(isPrincipalId)) {
    res.status(400).json({
      message: `userIds must be 1-${BULK_ASSIGN_MAX_USERS} user ids`
    });
    return;
  }
  if (!Array.isArray(roles) || roles.length === 0 || roles.length > BULK_ASSIGN_MAX_ROLES || !roles.every(
    (r) => typeof r?.accountNumber === "string" && r.accountNumber && typeof r?.roleName === "string" && r.roleName
  )) {
    res.status(400).json({
      message: `roles must be 1-${BULK_ASSIGN_MAX_ROLES} { accountNumber, roleName } pairs`
    });
    return;
  }
  if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
    res.status(400).json({
      message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
    });
    return;
  }
  try {
    const results = await assignRolesToUsers(
      roles,
      userIds,
      req.userId,
      durationHours !== void 0 ? new Date(Date.now() + durationHours * 60 * 60 * 1e3).toISOString() : void 0
    );
    res.json({ results });
  } catch (err) {
    sendError(res, err, "bulk assign roles");
  }
});
adminRouter.post("/grants/bulk-revoke", async (req, res) => {
  const { userIds, roles } = req.body ?? {};
  if (!Array.isArray(userIds) || userIds.length === 0 || userIds.length > BULK_ASSIGN_MAX_USERS || !userIds.every(isPrincipalId)) {
    res.status(400).json({
      message: `userIds must be 1-${BULK_ASSIGN_MAX_USERS} user ids`
    });
    return;
  }
  if (!Array.isArray(roles) || roles.length === 0 || roles.length > BULK_ASSIGN_MAX_ROLES || !roles.every(
    (r) => typeof r?.accountNumber === "string" && r.accountNumber && typeof r?.roleName === "string" && r.roleName
  )) {
    res.status(400).json({
      message: `roles must be 1-${BULK_ASSIGN_MAX_ROLES} { accountNumber, roleName } pairs`
    });
    return;
  }
  try {
    const results = await revokeRolesFromUsers(roles, userIds);
    res.json({ results });
  } catch (err) {
    sendError(res, err, "bulk revoke roles");
  }
});
adminRouter.post("/users/bulk-delete", async (req, res) => {
  const userIds = readUserIds(req.body);
  if (!userIds || userIds.length > BULK_CREATE_MAX) {
    res.status(400).json({
      message: `userIds must be 1-${BULK_CREATE_MAX} user ids`
    });
    return;
  }
  try {
    const results = await deleteUsers(userIds, req.userId);
    res.json({ results });
  } catch (err) {
    sendError(res, err, "bulk delete users");
  }
});
adminRouter.get("/tokens", requireHumanSession, async (_req, res) => {
  try {
    res.json({ tokens: await listAllTokens() });
  } catch (err) {
    sendError(res, err, "list tokens");
  }
});
adminRouter.delete("/tokens/:tokenId", requireHumanSession, async (req, res) => {
  try {
    await revokeToken(String(req.params.tokenId));
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "revoke token");
  }
});
var CLIENT_ID_RE = /^[a-z0-9]{1,128}$/;
adminRouter.get("/service-users", async (_req, res) => {
  try {
    const serviceUsers = await listServiceUsers();
    res.json({ serviceUsers });
  } catch (err) {
    sendError(res, err, "list service users");
  }
});
adminRouter.post("/service-users", async (req, res) => {
  try {
    const created = await createServiceUser(req.body?.name, req.userId, req.body?.scopes);
    res.status(201).json(created);
  } catch (err) {
    sendError(res, err, "create service user");
  }
});
adminRouter.put("/service-users/:clientId/scopes", async (req, res) => {
  if (!CLIENT_ID_RE.test(req.params.clientId)) {
    res.status(400).json({ message: "clientId must be a Cognito app client id" });
    return;
  }
  try {
    const serviceUser = await updateServiceUserScopes(req.params.clientId, req.body?.scopes);
    res.json({ serviceUser });
  } catch (err) {
    sendError(res, err, "update service user scopes");
  }
});
adminRouter.post(
  "/service-users/:clientId/rotate",
  async (req, res) => {
    if (!CLIENT_ID_RE.test(req.params.clientId)) {
      res.status(400).json({ message: "clientId must be a Cognito app client id" });
      return;
    }
    try {
      const rotated = await rotateServiceUser(req.params.clientId, req.userId);
      res.json(rotated);
    } catch (err) {
      sendError(res, err, "rotate service user secret");
    }
  }
);
adminRouter.delete(
  "/service-users/:clientId/previous",
  async (req, res) => {
    if (!CLIENT_ID_RE.test(req.params.clientId)) {
      res.status(400).json({ message: "clientId must be a Cognito app client id" });
      return;
    }
    try {
      await removePreviousSecret(req.params.clientId);
      res.status(204).end();
    } catch (err) {
      sendError(res, err, "remove previous secret");
    }
  }
);
adminRouter.delete(
  "/service-users/:clientId",
  async (req, res) => {
    if (!CLIENT_ID_RE.test(req.params.clientId)) {
      res.status(400).json({ message: "clientId must be a Cognito app client id" });
      return;
    }
    try {
      await deleteServiceUser(req.params.clientId);
      res.status(204).end();
    } catch (err) {
      sendError(res, err, "delete service user");
    }
  }
);
adminRouter.get("/groups", async (_req, res) => {
  try {
    const [groups, users, resources] = await Promise.all([
      listGroups(),
      listUsers(),
      listResources()
    ]);
    const emailBySub2 = new Map(users.map((u) => [u.userId, u.email]));
    const resourceNameById = new Map(
      resources.map((r) => [r.resourceId, r.name])
    );
    res.json({
      groups: groups.map((g) => ({
        ...g,
        roles: g.roles.slice(0, GROUP_ROLE_CAP),
        roleCount: g.roles.length,
        members: g.members.map((userId) => ({
          userId,
          email: emailBySub2.get(userId) ?? ""
        })),
        resources: g.resources.map((resourceId) => ({
          resourceId,
          name: resourceNameById.get(resourceId) ?? "(deleted resource)"
        }))
      }))
    });
  } catch (err) {
    sendError(res, err, "list groups");
  }
});
var GROUP_ROLE_CAP = 50;
adminRouter.get("/groups/suggest", async (req, res) => {
  const { accountNumber, roleName } = req.query;
  if (typeof accountNumber !== "string" || !/^\d{12}$/.test(accountNumber) || typeof roleName !== "string" || !roleName) {
    res.status(400).json({ message: "provide accountNumber (12 digits) and roleName" });
    return;
  }
  try {
    res.json({ suggestions: await suggestGroupsForRole(accountNumber, roleName) });
  } catch (err) {
    sendError(res, err, "suggest groups");
  }
});
adminRouter.get("/groups/:groupId", async (req, res) => {
  try {
    const [group, users, resources] = await Promise.all([getGroup(req.params.groupId), listDirectoryUsers(), listResources()]);
    const emailBySub2 = new Map(users.map((u) => [u.userId, u.email]));
    const resourceNameById = new Map(resources.map((r) => [r.resourceId, r.name]));
    res.json({
      group: {
        ...group,
        roleCount: group.roles.length,
        members: group.members.map((userId) => ({ userId, email: emailBySub2.get(userId) ?? "" })),
        resources: group.resources.map((resourceId) => ({ resourceId, name: resourceNameById.get(resourceId) ?? "(deleted resource)" }))
      }
    });
  } catch (err) {
    sendError(res, err, "load group");
  }
});
adminRouter.get("/groups/:groupId/roles", async (req, res) => {
  try {
    const page = parseListQuery(req.query, { sorts: ["account", "role"] }) ?? { q: "", filters: {}, sort: "account", desc: false, limit: 50 };
    const [group, index] = await Promise.all([getGroup(req.params.groupId), catalog()]);
    const rows = group.roles.map((r) => ({ ...r, accountName: index.byNumber.get(r.accountNumber)?.name, displayName: index.roleByKey.get(`${r.accountNumber}#${r.roleName}`)?.displayName }));
    res.json(
      paginate(rows, page, {
        text: (r) => `${r.accountNumber} ${r.accountName ?? ""} ${r.roleName} ${r.displayName ?? ""}`,
        id: (r) => `${r.accountNumber}#${r.roleName}`,
        sorts: { account: (r) => `${r.accountName ?? r.accountNumber}#${r.roleName}`, role: (r) => `${r.roleName}#${r.accountNumber}` }
      })
    );
  } catch (err) {
    sendError(res, err, "list group roles");
  }
});
adminRouter.post("/groups", async (req, res) => {
  const { name, description, roles, resources } = req.body ?? {};
  try {
    const group = await createGroup(
      name,
      roles,
      req.userId,
      description,
      resources
    );
    res.status(201).json({ group });
  } catch (err) {
    sendError(res, err, "create group");
  }
});
adminRouter.patch("/groups/:groupId", async (req, res) => {
  const { name, description, roles, resources } = req.body ?? {};
  if (name === void 0 && description === void 0 && roles === void 0 && resources === void 0) {
    res.status(400).json({
      message: "provide at least one of: name, description, roles, resources"
    });
    return;
  }
  try {
    const group = await updateGroup(
      req.params.groupId,
      { name, description, roles, resources },
      req.userId
    );
    res.json({ group });
  } catch (err) {
    sendError(res, err, "update group");
  }
});
adminRouter.post("/groups/:groupId/roles", async (req, res) => {
  const { accountNumber, roleName } = req.body ?? {};
  if (typeof accountNumber !== "string" || !/^\d{12}$/.test(accountNumber) || typeof roleName !== "string" || !roleName) {
    res.status(400).json({ message: "provide accountNumber (12 digits) and roleName" });
    return;
  }
  try {
    const change = await addGroupRole(req.params.groupId, { accountNumber, roleName }, req.userId);
    res.status(change.added ? 201 : 200).json(change);
  } catch (err) {
    sendError(res, err, "add role to group");
  }
});
adminRouter.post("/groups/:groupId/roles/bulk", async (req, res) => {
  const { roleName, filter, q, dryRun } = req.body ?? {};
  const dims = parseDimsFilter(filter ?? {});
  if (typeof roleName !== "string" || !roleName || !dims || q !== void 0 && typeof q !== "string") {
    res.status(400).json({ message: "provide roleName, an optional filter { tenant?, project?, stage? } of value lists, and an optional q" });
    return;
  }
  try {
    const index = await catalog();
    const tokens = (q ?? "").toLowerCase().split(/\s+/).filter(Boolean);
    const roles = index.accounts.filter((a) => a.registered && matchesDims(a.dims, dims)).filter((a) => !tokens.length || tokens.every((t) => `${a.accountNumber} ${a.name ?? ""}`.toLowerCase().includes(t))).filter((a) => a.roles.some((r) => r.roleName === roleName)).map((a) => ({ accountNumber: a.accountNumber, roleName }));
    if (dryRun === true) {
      await assertGroupExists(req.params.groupId);
      res.json({ matched: roles.length });
      return;
    }
    const group = await getGroup(req.params.groupId);
    const have = new Set(group.roles.map((r) => `${r.accountNumber}#${r.roleName}`));
    const missing = roles.filter((r) => !have.has(`${r.accountNumber}#${r.roleName}`));
    const batch = missing.slice(0, BULK_MAX);
    const result = batch.length ? await addGroupRoles(req.params.groupId, batch, req.userId) : { group, added: 0, skipped: 0 };
    res.status(result.added ? 201 : 200).json({
      matched: roles.length,
      added: result.added,
      skipped: roles.length - missing.length + result.skipped,
      remaining: missing.length - batch.length,
      group: result.group
    });
  } catch (err) {
    sendError(res, err, "add roles to group by dimension");
  }
});
adminRouter.delete("/groups/:groupId/roles/:accountNumber/:roleName", async (req, res) => {
  try {
    await removeGroupRole(req.params.groupId, { accountNumber: req.params.accountNumber, roleName: req.params.roleName });
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "remove role from group");
  }
});
adminRouter.delete("/groups/:groupId", async (req, res) => {
  try {
    await deleteGroup(req.params.groupId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "delete group");
  }
});
function readUserIds(body) {
  const userIds = body?.userIds;
  if (!Array.isArray(userIds) || userIds.length === 0 || !userIds.every(isPrincipalId)) {
    return null;
  }
  return userIds;
}
adminRouter.post("/groups/:groupId/members", async (req, res) => {
  const userIds = readUserIds(req.body);
  if (!userIds) {
    res.status(400).json({ message: "userIds must be a non-empty list of user ids" });
    return;
  }
  try {
    const added = await addMembers(req.params.groupId, userIds, req.userId);
    res.json({ added });
  } catch (err) {
    sendError(res, err, "add group members");
  }
});
adminRouter.post(
  "/groups/:groupId/members/remove",
  async (req, res) => {
    const userIds = readUserIds(req.body);
    if (!userIds) {
      res.status(400).json({ message: "userIds must be a non-empty list of user ids" });
      return;
    }
    try {
      const removed = await removeMembers(req.params.groupId, userIds);
      res.json({ removed });
    } catch (err) {
      sendError(res, err, "remove group members");
    }
  }
);
function readList(raw, allowed, label) {
  if (raw === void 0) return void 0;
  const values = String(raw).split(",").map((v) => v.trim()).filter(Boolean);
  for (const v of values) {
    if (!allowed.includes(v)) throw new ValidationError(`${label} must be one of ${allowed.join(", ")}`);
  }
  return values;
}
var NAMES_MAX_AGE_MS = 3e4;
var readString = (raw) => typeof raw === "string" && raw.trim() ? raw.trim() : void 0;
var readRepeated = (raw) => {
  const list = (Array.isArray(raw) ? raw : [raw]).filter((v) => typeof v === "string" && v.trim() !== "").map((v) => v.trim());
  return list.length ? list : void 0;
};
adminRouter.get("/audit", async (req, res) => {
  const days = readPositiveInt(req.query.days);
  const limit = readPositiveInt(req.query.limit);
  if (days === null || limit === null) {
    res.status(400).json({ message: "days and limit must be positive integers" });
    return;
  }
  let query;
  try {
    const before = readString(req.query.before);
    const to = readString(req.query.to);
    const csv = (raw) => {
      const list = typeof raw === "string" ? raw.split(",").map((t) => t.trim()).filter(Boolean) : [];
      return list.length ? list : void 0;
    };
    query = {
      from: readString(req.query.from),
      days,
      to,
      before,
      limit,
      user: csv(req.query.user) ?? csv(req.query.userId),
      actor: csv(req.query.actor),
      account: csv(req.query.account),
      group: csv(req.query.group),
      category: readList(req.query.category, AUDIT_CATEGORIES, "category"),
      outcome: readList(req.query.outcome, AUDIT_OUTCOMES, "outcome"),
      // Repeated, never split: a role name may contain a comma.
      target: readRepeated(req.query.target),
      skip: typeof req.query.skip === "string" ? req.query.skip.split(",").map((t) => t.trim()).filter(Boolean).slice(0, 200) : void 0,
      derived: req.query.derived === "true" || req.query.derived === "1"
    };
  } catch (err) {
    sendError(res, err, "read activity filters");
    return;
  }
  try {
    const [page, names] = await Promise.all([listAuditEvents(query), loadNameDirectory({ maxAgeMs: NAMES_MAX_AGE_MS })]);
    const person = (p, machineKind) => {
      const live2 = names.who(p.id);
      if (live2) return { ...p, name: live2, ...p.kind === "user" && names.isMachine(p.id) ? { kind: machineKind } : {} };
      return p.kind === "system" ? p : { ...p, deleted: true };
    };
    res.json({
      ...page,
      events: page.events.map((e) => ({
        ...e,
        actor: person(e.actor, "service"),
        ...e.subject ? { subject: person(e.subject, "serviceUser") } : {},
        targetName: e.targetName ?? (e.target ? names.targetName(e.target) : void 0),
        ...e.details?.affected || e.details?.unchanged || Array.isArray(e.details?.stillHeldVia) ? {
          details: {
            ...e.details,
            ...e.details.affected ? { affected: e.details.affected.map((a) => ({ ...a, name: names.who(a.userId) ?? a.name })) } : {},
            ...e.details.unchanged ? { unchanged: e.details.unchanged.map((u) => ({ ...u, name: names.who(u.userId) ?? u.name })) } : {},
            ...Array.isArray(e.details.stillHeldVia) ? { stillHeldViaNames: e.details.stillHeldVia.map((g) => names.groupName(g) ?? g) } : {}
          }
        } : {}
      }))
    });
  } catch (err) {
    if (err instanceof AuditQueryError) {
      res.status(400).json({ message: err.message });
      return;
    }
    sendError(res, err, "list audit events");
  }
});
adminRouter.post("/access-report/jobs", async (req, res) => {
  try {
    res.status(202).json({ job: await startAccessReportJob(req.userId) });
  } catch (err) {
    sendError(res, err, "start the access report");
  }
});
adminRouter.get("/access-report/jobs/:jobId", async (req, res) => {
  if (!/^[0-9a-f-]{36}$/.test(req.params.jobId)) {
    res.status(400).json({ message: "jobId must be a job id" });
    return;
  }
  try {
    res.set("Cache-Control", "no-store").json({ job: await getAccessReportJob(req.params.jobId, req.userId) });
  } catch (err) {
    sendError(res, err, "load the access report job");
  }
});
adminRouter.get("/access-report", async (_req, res) => {
  try {
    const rows = await buildAccessReport();
    res.status(200).set("Content-Type", "text/csv; charset=utf-8").set("Content-Disposition", `attachment; filename="access-report-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv"`).send(accessReportCsv(rows));
  } catch (err) {
    sendError(res, err, "build access report");
  }
});
function readPositiveInt(raw) {
  if (raw === void 0) return void 0;
  if (typeof raw !== "string" || !/^\d+$/.test(raw) || Number(raw) < 1) return null;
  return Number(raw);
}
var STATUSES = ["PENDING", "APPROVED", "DENIED"];
var NOTE_MAX2 = 500;
adminRouter.get("/requests", async (req, res) => {
  const raw = req.query.status;
  const status = typeof raw === "string" ? raw.toUpperCase() : void 0;
  if (status !== void 0 && !STATUSES.includes(status)) {
    res.status(400).json({ message: `status must be one of: ${STATUSES.join(", ")}` });
    return;
  }
  try {
    const [requests, users, resources, machineNames, index] = await Promise.all([
      listRequests(status),
      listDirectoryUsers(),
      listResources(),
      serviceUserNames(),
      catalog()
    ]);
    const emailBySub2 = new Map(users.map((u) => [u.userId, u.email]));
    const resourceNameById = new Map(
      resources.map((r) => [r.resourceId, r.name])
    );
    const groupNameById = index.groupName;
    const withUsage = req.query.usage === "1";
    const usageOf = async (r) => {
      if (!withUsage || r.status !== "PENDING") return {};
      if (r.type !== "REAPPROVAL" || r.groupId) return {};
      if (!r.accountNumber || !r.roleName) return {};
      try {
        return { usage: await countRoleUsage(r.userId, r.accountNumber, r.roleName) };
      } catch {
        return {};
      }
    };
    const rows = await Promise.all(
      requests.map(async (r) => ({
        ...r,
        email: emailBySub2.get(r.userId) ?? "",
        ...machineNames.has(r.userId) ? { serviceUser: machineNames.get(r.userId) } : {},
        ...r.groupId ? { group: groupNameById.get(r.groupId) ?? "(deleted group)" } : {},
        ...r.kind === "RESOURCE" ? {
          resourceName: resourceNameById.get(r.resourceId ?? "") ?? "(deleted resource)"
        } : {},
        ...await usageOf(r)
      }))
    );
    res.json({ requests: rows });
  } catch (err) {
    sendError(res, err, "list requests");
  }
});
function readNote(body) {
  const note = body?.note;
  if (note === void 0 || note === null) return void 0;
  if (typeof note !== "string" || note.length > NOTE_MAX2) return null;
  return note.trim() || void 0;
}
adminRouter.post("/requests/:requestId/approve", async (req, res) => {
  const note = readNote(req.body);
  if (note === null) {
    res.status(400).json({ message: `note must be ${NOTE_MAX2} characters or fewer` });
    return;
  }
  const { durationHours } = req.body ?? {};
  if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
    res.status(400).json({
      message: `durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`
    });
    return;
  }
  try {
    const request = await approveRequest(
      req.params.requestId,
      req.userId,
      note,
      durationHours
    );
    res.json({ request });
  } catch (err) {
    sendError(res, err, "approve request");
  }
});
adminRouter.post("/requests/:requestId/deny", async (req, res) => {
  const note = readNote(req.body);
  if (note === null) {
    res.status(400).json({ message: `note must be ${NOTE_MAX2} characters or fewer` });
    return;
  }
  try {
    const request = await denyRequest(req.params.requestId, req.userId, note);
    res.json({ request });
  } catch (err) {
    sendError(res, err, "deny request");
  }
});
adminRouter.put("/branding", async (req, res) => {
  const { branding, dismissed } = req.body ?? {};
  try {
    await saveBranding(req.userId, {
      branding,
      dismissed: dismissed === void 0 ? void 0 : dismissed === true
    });
    res.status(204).end();
  } catch (err) {
    if (err instanceof ValidationError && err.message === "BRANDING_NOT_DEPLOYED") {
      res.status(501).json({ message: "Branding storage is not deployed yet." });
      return;
    }
    sendError(res, err, "save branding");
  }
});
adminRouter.get("/plugins", async (_req, res) => {
  try {
    const catalog2 = await adminCatalog();
    res.json(catalog2);
  } catch (err) {
    sendError(res, err, "list the plugin catalog");
  }
});
adminRouter.get("/users/:userId/plugin-grants", async (req, res) => {
  try {
    const access = await listUserPluginAccess(req.params.userId);
    res.json(access);
  } catch (err) {
    sendError(res, err, "list user plugin grants");
  }
});
adminRouter.get("/groups/:groupId/plugin-grants", async (req, res) => {
  try {
    await assertGroupExists(req.params.groupId);
    const assignments = await listGroupPluginAssignments(req.params.groupId);
    res.json({ assignments });
  } catch (err) {
    sendError(res, err, "list group plugin grants");
  }
});
async function readPrincipal(body, opts = {}) {
  const principal = body?.principal;
  if (principal?.kind === "user") {
    if (typeof principal.userId !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/.test(principal.userId)) {
      throw new ValidationError("principal.userId must be a Cognito sub");
    }
    if (opts.userMustExist) await assertUserExists(principal.userId);
    return { kind: "user", userId: principal.userId };
  }
  if (principal?.kind === "group") {
    if (typeof principal.groupId !== "string" || !principal.groupId) throw new ValidationError("principal.groupId is required");
    await assertGroupExists(principal.groupId);
    return { kind: "group", groupId: principal.groupId };
  }
  throw new ValidationError('principal must be { kind: "user", userId } or { kind: "group", groupId }');
}
var pluginKeyOf2 = (req, permission) => {
  if (permission !== "user" && permission !== "admin") throw new ValidationError('permission must be "user" or "admin"');
  const key = {
    pluginId: req.params.pluginId,
    accountNumber: req.params.accountNumber,
    permission
  };
  validatePluginGrantKey(key);
  return key;
};
adminRouter.get("/plugins/:pluginId/accounts/:accountNumber/grants", async (req, res) => {
  try {
    const [grants, users] = await Promise.all([
      listPluginGrants(req.params.pluginId, req.params.accountNumber),
      listUsers()
    ]);
    const emailBySub2 = new Map(users.map((u) => [u.userId, u.email]));
    res.json({
      assignments: grants.assignments,
      holders: grants.holders.map((h) => ({ ...h, email: emailBySub2.get(h.userId) ?? "" }))
    });
  } catch (err) {
    sendError(res, err, "list plugin grants");
  }
});
adminRouter.put("/plugins/:pluginId/accounts/:accountNumber/grants", async (req, res) => {
  try {
    const { permission, durationHours } = req.body ?? {};
    const key = pluginKeyOf2(req, permission);
    if (durationHours !== void 0 && !isDurationPreset(durationHours)) {
      throw new ValidationError(`durationHours must be one of: ${DURATION_PRESET_HOURS.join(", ")}`);
    }
    const assignment = await assignPlugin({
      ...key,
      principal: await readPrincipal(req.body, { userMustExist: true }),
      grantedBy: req.userId,
      ...durationHours === void 0 ? {} : { expiresAt: new Date(Date.now() + durationHours * 60 * 60 * 1e3).toISOString() }
    });
    res.status(200).json({ assignment });
  } catch (err) {
    sendError(res, err, "assign plugin access");
  }
});
adminRouter.delete("/plugins/:pluginId/accounts/:accountNumber/grants", async (req, res) => {
  try {
    const principal = await readPrincipal(req.body);
    const key = pluginKeyOf2(req, (req.body ?? {}).permission);
    try {
      await revokePlugin({ ...key, principal });
    } catch (err) {
      if (!(err instanceof NotFoundError)) throw err;
    }
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "revoke plugin access");
  }
});

// lambdacode/api/routes/preferences.ts
var import_express7 = require("express");
init_preferencesService();
init_preferencesService();
var log28 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var preferencesRouter = (0, import_express7.Router)();
preferencesRouter.use(requireAuth);
var ROLE_LABEL_MAX = 64;
function badTarget(accountNumber, role) {
  if (!/^\d{12}$/.test(accountNumber)) {
    return "accountNumber must be a 12-digit AWS account id";
  }
  if (!role) return "role is required";
  return null;
}
preferencesRouter.get("/", async (req, res) => {
  try {
    res.json({ preferences: await listPreferences(req.userId) });
  } catch (err) {
    log28("ERROR: listPreferences failed", { error: err.message });
    res.status(502).json({ message: "Failed to read preferences" });
  }
});
preferencesRouter.put(
  "/auto-vend/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    const on = req.body?.autoVend;
    if (typeof on !== "boolean") {
      res.status(400).json({ message: "autoVend must be a boolean" });
      return;
    }
    try {
      await setAutoVend(req.userId, accountNumber, role, on);
      res.json({ autoVend: on });
    } catch (err) {
      log28("ERROR: setAutoVend failed", { error: err.message });
      res.status(502).json({ message: "Failed to save preference" });
    }
  }
);
preferencesRouter.put("/favorites/:accountNumber", async (req, res) => {
  const { accountNumber } = req.params;
  if (!/^\d{12}$/.test(accountNumber)) {
    res.status(400).json({ message: "accountNumber must be a 12-digit AWS account id" });
    return;
  }
  const on = req.body?.favorite;
  if (typeof on !== "boolean") {
    res.status(400).json({ message: "favorite must be a boolean" });
    return;
  }
  try {
    await setFavorite(req.userId, accountNumber, on);
    res.json({ favorite: on });
  } catch (err) {
    sendError(res, err, "save favorite");
  }
});
preferencesRouter.get("/network", async (req, res) => {
  try {
    res.json(await getNetworkPrefs(req.userId));
  } catch (err) {
    log28("ERROR: getNetworkPrefs failed", { error: err.message });
    res.status(502).json({ message: "Failed to read preference" });
  }
});
preferencesRouter.get("/notifications", async (req, res) => {
  try {
    res.json(await getNotificationPrefs(req.userId));
  } catch (err) {
    log28("ERROR: getNotificationPrefs failed", { error: err.message });
    res.status(502).json({ message: "Failed to read preference" });
  }
});
preferencesRouter.put("/notifications", async (req, res) => {
  const { enabled: enabled2, kinds } = req.body ?? {};
  if (enabled2 !== void 0 && typeof enabled2 !== "boolean") {
    res.status(400).json({ message: "enabled must be a boolean" });
    return;
  }
  if (kinds !== void 0) {
    const bad = typeof kinds !== "object" || kinds === null || Object.entries(kinds).some(
      ([k, v]) => !NOTIFICATION_KINDS.includes(k) || typeof v !== "boolean"
    );
    if (bad) {
      res.status(400).json({ message: `kinds must map ${NOTIFICATION_KINDS.join(", ")} to booleans` });
      return;
    }
  }
  if (enabled2 === void 0 && kinds === void 0) {
    res.status(400).json({ message: "nothing to update" });
    return;
  }
  try {
    res.json(await setNotificationPrefs(req.userId, { enabled: enabled2, kinds }));
  } catch (err) {
    log28("ERROR: setNotificationPrefs failed", { error: err.message });
    res.status(502).json({ message: "Failed to save preference" });
  }
});
var SITE_ID_MAX = 64;
preferencesRouter.put("/network", async (req, res) => {
  const { autoReconnect, lastSiteId } = req.body ?? {};
  if (autoReconnect !== void 0 && typeof autoReconnect !== "boolean") {
    res.status(400).json({ message: "autoReconnect must be a boolean" });
    return;
  }
  if (lastSiteId !== void 0 && (typeof lastSiteId !== "string" || !lastSiteId || lastSiteId.length > SITE_ID_MAX)) {
    res.status(400).json({
      message: `lastSiteId must be a non-empty string of ${SITE_ID_MAX} characters or fewer`
    });
    return;
  }
  if (autoReconnect === void 0 && lastSiteId === void 0) {
    res.status(400).json({ message: "nothing to update" });
    return;
  }
  try {
    await setNetworkPrefs(req.userId, { autoReconnect, lastSiteId });
    res.json(await getNetworkPrefs(req.userId));
  } catch (err) {
    log28("ERROR: setNetworkPrefs failed", { error: err.message });
    res.status(502).json({ message: "Failed to save preference" });
  }
});
preferencesRouter.get(
  "/profile-name/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    try {
      const profileName = await getProfileName(req.userId, accountNumber, role);
      res.json({ profileName });
    } catch (err) {
      log28("ERROR: getProfileName failed", { error: err.message });
      res.status(502).json({ message: "Failed to read preference" });
    }
  }
);
preferencesRouter.put(
  "/profile-name/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    const profileName = req.body?.profileName;
    if (profileName !== void 0 && typeof profileName !== "string") {
      res.status(400).json({ message: "profileName must be a string" });
      return;
    }
    const trimmed = (profileName ?? "").trim();
    if (!isValidProfileName(trimmed)) {
      res.status(400).json({ message: PROFILE_NAME_MESSAGE });
      return;
    }
    try {
      if (trimmed === "") {
        await clearProfileName(req.userId, accountNumber, role);
        res.json({ profileName: null });
        return;
      }
      await setProfileName(req.userId, accountNumber, role, trimmed);
      res.json({ profileName: trimmed });
    } catch (err) {
      log28("ERROR: setProfileName failed", { error: err.message });
      res.status(502).json({ message: "Failed to save preference" });
    }
  }
);
preferencesRouter.put(
  "/role-label/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    const roleLabel = req.body?.roleLabel;
    if (roleLabel !== void 0 && typeof roleLabel !== "string") {
      res.status(400).json({ message: "roleLabel must be a string" });
      return;
    }
    const trimmed = (roleLabel ?? "").trim();
    if (trimmed.length > ROLE_LABEL_MAX) {
      res.status(400).json({
        message: `roleLabel must be ${ROLE_LABEL_MAX} characters or fewer`
      });
      return;
    }
    try {
      if (trimmed === "") {
        await clearRoleLabel(req.userId, accountNumber, role);
        res.json({ roleLabel: null });
        return;
      }
      await setRoleLabel(req.userId, accountNumber, role, trimmed);
      res.json({ roleLabel: trimmed });
    } catch (err) {
      log28("ERROR: setRoleLabel failed", { error: err.message });
      res.status(502).json({ message: "Failed to save preference" });
    }
  }
);
preferencesRouter.delete(
  "/role-label/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    try {
      await clearRoleLabel(req.userId, accountNumber, role);
      res.status(204).end();
    } catch (err) {
      log28("ERROR: clearRoleLabel failed", { error: err.message });
      res.status(502).json({ message: "Failed to clear preference" });
    }
  }
);
preferencesRouter.delete(
  "/profile-name/:accountNumber/:role",
  async (req, res) => {
    const { accountNumber, role } = req.params;
    const bad = badTarget(accountNumber, role);
    if (bad) {
      res.status(400).json({ message: bad });
      return;
    }
    try {
      await clearProfileName(req.userId, accountNumber, role);
      res.status(204).end();
    } catch (err) {
      log28("ERROR: clearProfileName failed", { error: err.message });
      res.status(502).json({ message: "Failed to clear preference" });
    }
  }
);

// lambdacode/api/routes/resources.ts
var import_express8 = require("express");
init_resourceGrantsService();
init_resourcesService();
var log29 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var resourcesRouter = (0, import_express8.Router)();
resourcesRouter.use(requireAuth);
resourcesRouter.get("/", async (req, res) => {
  try {
    const [grants, catalog2, accountNames] = await Promise.all([
      listUserResourceGrants(req.userId),
      listResources(),
      getAccountNames()
    ]);
    const byId = new Map(catalog2.map((r) => [r.resourceId, r]));
    const resources = [];
    for (const g of grants) {
      if (isExpired(g)) continue;
      const r = byId.get(g.resourceId);
      if (!r) continue;
      resources.push({
        resourceId: r.resourceId,
        name: r.name,
        type: r.type,
        cidr: r.cidr,
        ports: r.ports,
        dnsName: r.dnsName,
        sshUser: r.sshUser,
        description: r.description,
        accountNumber: r.accountNumber,
        accountName: accountNames.get(r.accountNumber),
        expiresAt: g.expiresAt
      });
    }
    resources.sort((a, b) => a.name.localeCompare(b.name));
    res.json({ resources });
  } catch (err) {
    log29("ERROR: list reachable resources failed", {
      error: err.message
    });
    res.status(502).json({ message: "Failed to list resources" });
  }
});
resourcesRouter.get("/expiry", async (req, res) => {
  try {
    const [{ expiring, expired }, catalog2] = await Promise.all([
      listResourceExpiryNotices(req.userId),
      listResources()
    ]);
    const nameById = new Map(catalog2.map((r) => [r.resourceId, r.name]));
    const named = (n) => ({
      ...n,
      name: nameById.get(n.resourceId) ?? "(deleted resource)"
    });
    res.json({ expiring: expiring.map(named), expired: expired.map(named) });
  } catch (err) {
    log29("ERROR: list resource expiry failed", { error: err.message });
    res.status(502).json({ message: "Failed to list resource expiry" });
  }
});
resourcesRouter.post(
  "/expiry/seen",
  async (req, res) => {
    try {
      const cleared = await markResourceExpiryNoticesSeen(req.userId);
      res.json({ cleared });
    } catch (err) {
      log29("ERROR: mark resource expiry seen failed", {
        error: err.message
      });
      res.status(502).json({ message: "Failed to mark resource expiry seen" });
    }
  }
);

// lambdacode/api/routes/notifications.ts
var import_express9 = require("express");
init_revocationsService();
init_resourcesService();
var log30 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var notificationsRouter = (0, import_express9.Router)();
notificationsRouter.use(requireAuth);
notificationsRouter.get(
  "/revocations",
  async (req, res) => {
    try {
      const notices = await listRevocationNotices(req.userId);
      const needNames = notices.some(
        (n) => n.kind === "RESOURCE" && n.resourceId
      );
      const nameById = needNames ? new Map((await listResources()).map((r) => [r.resourceId, r.name])) : /* @__PURE__ */ new Map();
      res.json({
        notices: notices.map(
          (n) => n.kind === "RESOURCE" ? {
            ...n,
            resourceName: n.resourceId && nameById.get(n.resourceId) || n.resourceName || "(deleted resource)"
          } : n
        )
      });
    } catch (err) {
      log30("ERROR: list revocations failed", { error: err.message });
      res.status(502).json({ message: "Failed to list revocations" });
    }
  }
);
notificationsRouter.post(
  "/revocations/seen",
  async (req, res) => {
    try {
      const cleared = await markRevocationNoticesSeen(req.userId);
      res.json({ cleared });
    } catch (err) {
      log30("ERROR: mark revocations seen failed", {
        error: err.message
      });
      res.status(502).json({ message: "Failed to mark revocations seen" });
    }
  }
);

// lambdacode/api/routes/tokens.ts
var import_express10 = require("express");
init_personalTokens();
init_tokensService();
var tokensRouter = (0, import_express10.Router)();
tokensRouter.use(requireAuth);
function requireTokensEnabled(_req, res, next) {
  if (personalTokensConfig().enabled) next();
  else res.status(501).json({ message: "Personal access tokens are not enabled" });
}
tokensRouter.get("/current", (req, res) => {
  if (!req.token) {
    res.status(400).json({ message: "Not signed in with a personal access token" });
    return;
  }
  res.json({
    tokenId: req.token.id,
    name: req.token.name,
    scopes: req.token.scopes,
    ...req.token.roles ? { roles: req.token.roles } : {},
    expiresAt: req.token.expiresAt,
    user: { userId: req.userId, email: req.userName }
  });
});
tokensRouter.use(requireHumanSession);
tokensRouter.get("/", async (req, res) => {
  try {
    res.json({ tokens: await listTokens(req.userId) });
  } catch (err) {
    sendError(res, err, "list tokens");
  }
});
tokensRouter.post("/", requireTokensEnabled, async (req, res) => {
  try {
    res.status(201).json(await createToken(req.userId, req.userName, req.body ?? {}));
  } catch (err) {
    sendError(res, err, "create token");
  }
});
tokensRouter.get("/expiry", async (req, res) => {
  try {
    res.json(await listTokenExpiryNotices(req.userId));
  } catch (err) {
    sendError(res, err, "list token expiry notices");
  }
});
tokensRouter.post("/expiry/seen", async (req, res) => {
  try {
    res.json({ cleared: await markTokenExpiryNoticesSeen(req.userId) });
  } catch (err) {
    sendError(res, err, "mark token expiry notices seen");
  }
});
tokensRouter.delete("/:tokenId", async (req, res) => {
  try {
    await revokeToken(String(req.params.tokenId), req.userId);
    res.status(204).end();
  } catch (err) {
    sendError(res, err, "revoke token");
  }
});

// lambdacode/api/app.ts
init_personalTokens();
var log31 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var app = (0, import_express11.default)();
app.use((req, _res, next) => {
  if (req.url === "/api" || req.url.startsWith("/api/")) {
    req.url = req.url.slice(4) || "/";
  }
  next();
});
app.use(import_express11.default.json({ limit: "1mb" }));
app.use((req, _res, next) => {
  log31("request", { method: req.method, path: req.path });
  next();
});
var publicRouter = (0, import_express11.Router)();
publicRouter.get("/health", (_req, res) => {
  res.json({ ok: true });
});
publicRouter.get("/.well-known/infra-client", (_req, res) => {
  res.json({
    // No name fallback: the template's own name must never leak into a
    // client's UI (the desktop falls back to the backend hostname).
    projectName: process.env.PROJECT_NAME ?? "",
    cognito: {
      userPoolId: process.env.USER_POOL_ID ?? "",
      clientId: process.env.USER_POOL_CLIENT_ID ?? "",
      region: process.env.AWS_REGION ?? ""
    },
    issuer: process.env.ISSUER_URL ?? "",
    personalAccessTokens: { enabled: personalTokensConfig().enabled },
    // The desktop shell pins THESE controlUrls for its tailscale calls, so a page can never redirect the
    // VPN at some other control plane. The single `controlUrl` (first site) stays for already-shipped shells.
    network: process.env.NETWORK_CONTROL_URL ? {
      controlUrl: process.env.NETWORK_CONTROL_URL,
      sites: (() => {
        try {
          const sites = JSON.parse(process.env.NETWORK_SITES ?? "[]");
          return sites.map(({ id, displayName, controlUrl }) => ({
            id,
            displayName: displayName ?? id,
            controlUrl
          }));
        } catch {
          return [];
        }
      })()
    } : null
  });
});
var MOUNTS = {
  "/": publicRouter,
  "/accounts": accountsRouter,
  "/credentials": credentialsRouter,
  "/requests": requestsRouter,
  "/admin": adminRouter,
  "/preferences": preferencesRouter,
  "/network": networkRouter,
  "/resources": resourcesRouter,
  "/notifications": notificationsRouter,
  "/plugins": pluginsRouter,
  "/tokens": tokensRouter
};
for (const [prefix, router] of Object.entries(MOUNTS)) app.use(prefix, router);
app.use((req, res) => {
  res.status(404).json({ message: `Not found: ${req.method} ${req.path}` });
});
app.use(
  (err, _req, res, _next) => {
    const status = err.status ?? err.statusCode ?? 500;
    if (status >= 500) log31("ERROR: unhandled", { error: err.message });
    res.status(status).json({ message: status < 500 ? err.message : "Internal error" });
  }
);
var handler = (0, import_serverless_http.default)(app);
var reportJob = async (event) => {
  if (event?.job === "accessReport" && typeof event.jobId === "string") {
    const { runAccessReportJob: runAccessReportJob2 } = await Promise.resolve().then(() => (init_reportJobs(), reportJobs_exports));
    await runAccessReportJob2(event.jobId);
    return;
  }
  log31("ERROR: unknown job event", { event });
};
if (require.main === module) {
  const port = Number(process.env.PORT ?? 3e3);
  app.listen(
    port,
    () => console.log(`credentials API listening on http://localhost:${port}`)
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MOUNTS,
  app,
  handler,
  reportJob
});