@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
898 lines (883 loc) • 38 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lambdacode/plugins/catalog-provider.ts
var catalog_provider_exports = {};
__export(catalog_provider_exports, {
handler: () => handler
});
module.exports = __toCommonJS(catalog_provider_exports);
var import_client_dynamodb5 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb5 = require("@aws-sdk/lib-dynamodb");
// lambdacode/api/services/access.ts
var import_client_dynamodb = require("@aws-sdk/client-dynamodb");
// ../infra-client-plugin-sdk/src/contracts/manifest.ts
var PLUGIN_PERMISSIONS = ["user", "admin"];
var PLUGIN_MANIFEST_SCHEMA_VERSION = 1;
var PLUGIN_HOST_API_VERSION = 1;
var PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
var AWS_ACCOUNT_PATTERN = /^\d{12}$/;
// ../infra-client-plugin-sdk/src/contracts/access.ts
var PLUGIN_TARGET_PREFIX = "plugin#";
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];
}
// ../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";
}
// lambdacode/api/services/access.ts
var import_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
var ddb = import_lib_dynamodb.DynamoDBDocumentClient.from(new import_client_dynamodb.DynamoDBClient({}));
var ACCESS_TABLE_NAME = process.env.ACCESS_TABLE_NAME;
var userPrincipal = (sub) => `user#${sub}`;
var groupPrincipal = (groupId) => `group#${groupId}`;
var roleTarget = (accountNumber, roleName) => `role#${accountNumber}#${roleName}`;
var pluginTarget = (pluginId, accountNumber, permission) => pluginTargetKey({ pluginId, accountNumber, permission });
var SHARE_DEF_PRINCIPAL = "sharedef";
var PRESENCE_TARGET = "pref#presence";
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;
}
var isGrantTarget = (t) => t.startsWith("role#") || t.startsWith("resource#") || t.startsWith("share#") || t.startsWith("plugin#");
var consistentRead = (opts) => opts.consistent ? { ConsistentRead: true } : {};
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 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;
}
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;
}
var BATCH_GET_ATTEMPTS = 5;
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
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;
}
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());
}
// lambdacode/api/services/pluginCatalog.ts
var import_client_dynamodb2 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb2 = require("@aws-sdk/lib-dynamodb");
var ddb2 = import_lib_dynamodb2.DynamoDBDocumentClient.from(new import_client_dynamodb2.DynamoDBClient({}));
var emptyPluginCatalog = {
async list() {
return [];
},
async get() {
return void 0;
}
};
var log = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
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;
}
// 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 catalog = 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(catalog, await registeredAccounts([...bound], opts));
}
function withAccounts(catalog, accounts) {
const accountNames = /* @__PURE__ */ new Map();
for (const [n, meta] of accounts) if (meta.name) accountNames.set(n, meta.name);
return { catalog, 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;
}
var sourceOf = (permission, direct, groups) => ({
permission,
...direct && !isExpired(direct) ? { direct } : {},
groups
});
var byBindingThenPermission = (a, b) => a.pluginId.localeCompare(b.pluginId) || a.accountNumber.localeCompare(b.accountNumber) || PLUGIN_PERMISSIONS.indexOf(a.permission) - PLUGIN_PERMISSIONS.indexOf(b.permission);
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);
}
function availableCapabilityKeys(capabilities) {
return new Set(capabilities.filter((c) => c.available).map((c) => pluginTarget(c.pluginId, c.accountNumber, c.permission)));
}
async function pluginHolderUserIds(pluginId) {
const graph = await snapshot();
const out = [];
for (const [userId, entries] of graph.users) {
for (const e of entries.values()) {
if (!e.active) continue;
const p = parseTarget(e.target);
if (p?.kind === "plugin" && p.pluginId === pluginId) {
out.push(userId);
break;
}
}
}
return out.sort();
}
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;
}
// lambdacode/api/services/revocationsService.ts
var import_crypto = require("crypto");
var import_client_dynamodb3 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb3 = require("@aws-sdk/lib-dynamodb");
var ddb3 = import_lib_dynamodb3.DynamoDBDocumentClient.from(new import_client_dynamodb3.DynamoDBClient({}));
var REVOCATIONS_TABLE_NAME = process.env.REVOCATIONS_TABLE_NAME;
var log2 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var NOTICE_RETENTION_DAYS = 30;
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 });
}
// lambdacode/api/services/auditService.ts
var import_crypto2 = require("crypto");
var import_client_dynamodb4 = require("@aws-sdk/client-dynamodb");
var import_lib_dynamodb4 = require("@aws-sdk/lib-dynamodb");
// lambdacode/api/services/actorContext.ts
var import_async_hooks = require("async_hooks");
var store = new import_async_hooks.AsyncLocalStorage();
function runAsActor(actor, fn) {
return store.run(actor, fn);
}
function currentActor() {
return store.getStore();
}
var systemActor = (job, name) => ({
kind: "system",
id: `system:${job}`,
name: name ?? job
});
// lambdacode/api/services/auditService.ts
var ddb4 = import_lib_dynamodb4.DynamoDBDocumentClient.from(new import_client_dynamodb4.DynamoDBClient({}));
var tableName = () => process.env.AUDIT_TABLE_NAME ?? "";
var log3 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var DEFAULT_RETENTION_DAYS = 400;
var REASON_MAX = 300;
var NOTE_MAX = 500;
var AFFECTED_CAP = 50;
var DAY_MS = 24 * 60 * 60 * 1e3;
function retentionDays() {
const n = Number(process.env.AUDIT_RETENTION_DAYS);
return Number.isInteger(n) && n > 0 ? n : DEFAULT_RETENTION_DAYS;
}
var newBatchId = () => (0, import_crypto2.randomUUID)();
var UNKNOWN_ACTOR = { kind: "system", id: "system:unknown" };
var warnedNoTable = false;
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;
}
var SESSION_ACTIONS = /* @__PURE__ */ new Set(["vpn.connect", "vpn.disconnect"]);
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))] });
}
// 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;
}
var log4 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var memo = (load) => {
let p;
return () => p ??= load();
};
var DIFF_CONCURRENCY = 8;
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;
}
var NARROW_MAX_TARGETS = 100;
var NOTICE_BUNDLE_THRESHOLD = 5;
var BUNDLED_VIAS = /* @__PURE__ */ new Set(["GROUP", "CASCADE"]);
var bundled = (via, targets) => BUNDLED_VIAS.has(via) && targets.length > NOTICE_BUNDLE_THRESHOLD;
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;
}
// lambdacode/plugins/catalog-provider.ts
var ddb5 = import_lib_dynamodb5.DynamoDBDocumentClient.from(new import_client_dynamodb5.DynamoDBClient({}));
var log5 = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var putRecord = (table, record) => ddb5.send(new import_lib_dynamodb5.PutCommand({ TableName: table, Item: record }));
var capabilityShape = (m) => JSON.stringify({
enabled: m.enabled,
permissions: m.permissions.map((p) => p.id).sort(),
accounts: m.accounts.map((a) => a.accountNumber).sort()
});
var sameCapabilities = (a, b) => capabilityShape(a) === capabilityShape(b);
function handler(event) {
return runAsActor(systemActor("deploy"), () => apply(event));
}
async function apply(event) {
const table = process.env.PLUGIN_CATALOG_TABLE_NAME;
if (!table) throw new Error("PLUGIN_CATALOG_TABLE_NAME is not set");
const p = event.ResourceProperties;
const pluginId = p.PluginId;
const PhysicalResourceId = `plugin-catalog:${pluginId}`;
const existing = await dynamoPluginCatalog(table).get(pluginId, { consistent: true });
const now = (/* @__PURE__ */ new Date()).toISOString();
const batchId = newBatchId();
const activity = (action, displayName, revision) => recordEvent({ category: "catalog", action, target: `plugin#${pluginId}`, targetName: displayName, details: { revision, owner: p.Owner, batchId } });
const putNoticing = async (record2) => {
let written = false;
try {
await withAccessDiff(
await pluginHolderUserIds(pluginId),
"CASCADE",
async () => {
await putRecord(table, record2);
written = true;
},
void 0,
{ catalogChanges: true, batchId }
);
} catch (err) {
if (!written) throw err;
log5("ERROR: plugin catalog record written but loss notices failed", { pluginId, error: err.message });
}
};
if (event.RequestType === "Delete") {
if (!existing || existing.owner !== p.Owner) {
log5("plugin catalog delete: nothing of ours to tombstone", { pluginId, owner: p.Owner, existingOwner: existing?.owner });
return { PhysicalResourceId, Data: { Revision: p.Revision, Status: "absent" } };
}
if (existing.ownerResourceId && event.LogicalResourceId && existing.ownerResourceId !== event.LogicalResourceId) {
log5("plugin catalog delete: record now owned by another resource, left alone", { pluginId, resource: event.LogicalResourceId, owner: existing.ownerResourceId });
return { PhysicalResourceId, Data: { Revision: existing.revision, Status: existing.installed ? existing.manifest.enabled ? "active" : "disabled" : "removed" } };
}
if (existing.installed) {
await putNoticing({ ...existing, installed: false, removedAt: now, updatedAt: now });
await activity("plugin.tombstone", existing.manifest.displayName, existing.revision);
log5("plugin catalog record tombstoned", { pluginId, revision: existing.revision });
}
return { PhysicalResourceId, Data: { Revision: existing.revision, Status: "removed" } };
}
if (existing?.installed && existing.owner !== p.Owner) {
throw new Error(`Plugin "${pluginId}" is already installed by ${existing.owner}; a plugin id belongs to one deployment.`);
}
const manifest = JSON.parse(p.Manifest);
const record = {
pluginId,
schemaVersion: manifest.schemaVersion,
manifest,
revision: p.Revision,
...p.AssetPrefix ? { assetPrefix: p.AssetPrefix } : {},
installed: true,
owner: p.Owner,
...event.LogicalResourceId ? { ownerResourceId: event.LogicalResourceId } : {},
ui: JSON.parse(p.Ui || "{}"),
routes: JSON.parse(p.Routes || "[]"),
installedAt: existing?.installed ? existing.installedAt : now,
updatedAt: now
};
if (!isPluginCatalogRecord(record) || record.manifest.id !== pluginId) {
throw new Error(`Plugin "${pluginId}": the registration is not a valid catalog record.`);
}
if (existing?.installed && sameCapabilities(existing.manifest, manifest)) await putRecord(table, record);
else await putNoticing(record);
await activity("plugin.activate", manifest.displayName, p.Revision);
const status = manifest.enabled ? "active" : "disabled";
log5(`plugin catalog record ${existing ? "updated" : "created"}`, { pluginId, revision: p.Revision, status, reinstall: Boolean(existing && !existing.installed) });
return { PhysicalResourceId, Data: { Revision: p.Revision, Status: status } };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
handler
});