@checkstack/dashboards-backend 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ import { createExtensionPoint } from "@checkstack/backend-api";
2
+ import type { PluginMetadata } from "@checkstack/common";
3
+ import {
4
+ checkDataSourceSpec,
5
+ type DashboardDataSourceSpec,
6
+ type DashboardWidgetSpec,
7
+ type DataSourceQuery,
8
+ } from "@checkstack/dashboards-common";
9
+
10
+ /**
11
+ * Lets plugins describe their dashboard building blocks to the backend, so AI
12
+ * agents can discover them (`dashboards.getBuildingBlocks`) and drafted
13
+ * dashboards are validated against them (`dashboards.propose`).
14
+ *
15
+ * The frontend renders the same specs: a data source spec lives in the owning
16
+ * plugin's `*-common` package and is handed to both `defineDashboardDataSource`
17
+ * (frontend) and `registerDataSource` (backend). Registration is buffered, so
18
+ * load order does not matter.
19
+ */
20
+ export interface DashboardBuildingBlocksExtensionPoint {
21
+ registerDataSource<Q extends DataSourceQuery>(
22
+ spec: DashboardDataSourceSpec<Q>,
23
+ pluginMetadata: PluginMetadata,
24
+ ): void;
25
+ registerWidget(spec: DashboardWidgetSpec, pluginMetadata: PluginMetadata): void;
26
+ }
27
+
28
+ export const dashboardBuildingBlocksExtensionPoint =
29
+ createExtensionPoint<DashboardBuildingBlocksExtensionPoint>(
30
+ "dashboards.buildingBlocks",
31
+ );
32
+
33
+ /** The data sources and widgets registered on this instance. */
34
+ export interface BuildingBlocksRegistry {
35
+ registerDataSource(spec: DashboardDataSourceSpec): void;
36
+ registerWidget(spec: DashboardWidgetSpec): void;
37
+ dataSources(): DashboardDataSourceSpec[];
38
+ widgets(): DashboardWidgetSpec[];
39
+ getDataSource(id: string): DashboardDataSourceSpec | undefined;
40
+ getWidget(id: string): DashboardWidgetSpec | undefined;
41
+ }
42
+
43
+ export function createBuildingBlocksRegistry(): BuildingBlocksRegistry {
44
+ const dataSources = new Map<string, DashboardDataSourceSpec>();
45
+ const widgets = new Map<string, DashboardWidgetSpec>();
46
+ return {
47
+ registerDataSource(spec) {
48
+ const problems = checkDataSourceSpec({ spec });
49
+ if (problems.length > 0) {
50
+ throw new Error(
51
+ `Dashboard data source ${spec.dataSourceId} is inconsistent: ${problems.join("; ")}`,
52
+ );
53
+ }
54
+ if (dataSources.has(spec.dataSourceId)) {
55
+ throw new Error(`Dashboard data source ${spec.dataSourceId} is already registered`);
56
+ }
57
+ dataSources.set(spec.dataSourceId, spec);
58
+ },
59
+ registerWidget(spec) {
60
+ if (widgets.has(spec.widgetId)) {
61
+ throw new Error(`Dashboard widget ${spec.widgetId} is already registered`);
62
+ }
63
+ widgets.set(spec.widgetId, spec);
64
+ },
65
+ dataSources: () => [...dataSources.values()],
66
+ widgets: () => [...widgets.values()],
67
+ getDataSource: (id) => dataSources.get(id),
68
+ getWidget: (id) => widgets.get(id),
69
+ };
70
+ }
71
+
72
+ /**
73
+ * The home-page sections of the built-in home layout (rendered by the core
74
+ * `dashboard-frontend` package, which has no backend of its own). Plugins with
75
+ * a backend register their own widgets through the extension point.
76
+ */
77
+ export const CORE_HOME_WIDGETS: DashboardWidgetSpec[] = [
78
+ {
79
+ widgetId: "dashboard.welcome",
80
+ title: "Welcome",
81
+ description:
82
+ "Welcome tip, queue-lag alert and the getting-started checklist. Best as the first, full-width row of a home dashboard.",
83
+ defaultSize: { w: 24, h: 6 },
84
+ },
85
+ {
86
+ widgetId: "dashboard.system-health",
87
+ title: "System health",
88
+ description:
89
+ "Fleet health overview of every system the viewer can see, with the systems that need attention. The core of a home dashboard.",
90
+ defaultSize: { w: 24, h: 14 },
91
+ },
92
+ {
93
+ widgetId: "dashboard.recent-activity",
94
+ title: "Recent activity",
95
+ description: "Live feed of health-check runs as they complete.",
96
+ defaultSize: { w: 24, h: 11 },
97
+ },
98
+ ];
package/src/index.ts ADDED
@@ -0,0 +1,139 @@
1
+ import * as schema from "./schema";
2
+ import {
3
+ coreServices,
4
+ createBackendPlugin,
5
+ type SafeDatabase,
6
+ } from "@checkstack/backend-api";
7
+ import { entityExtensionPoint } from "@checkstack/automation-backend";
8
+ import { CATALOG_SYSTEM_ENTITY_KIND } from "@checkstack/catalog-backend";
9
+ import { registerSearchProvider } from "@checkstack/command-backend";
10
+ import { resolveRoute } from "@checkstack/common";
11
+ import {
12
+ dashboardsAccess,
13
+ dashboardsAccessRules,
14
+ dashboardsContract,
15
+ dashboardsResourceTypes,
16
+ dashboardsRoutes,
17
+ pluginMetadata,
18
+ type DataSourceQuery,
19
+ } from "@checkstack/dashboards-common";
20
+ import type { z } from "zod";
21
+ import { aiGuidanceExtensionPoint, aiToolExtensionPoint } from "@checkstack/ai-backend";
22
+ import { DashboardService } from "./service";
23
+ import {
24
+ CORE_HOME_WIDGETS,
25
+ createBuildingBlocksRegistry,
26
+ dashboardBuildingBlocksExtensionPoint,
27
+ } from "./building-blocks";
28
+ import { createGetBuildingBlocksTool } from "./ai/building-blocks-tool";
29
+ import { createDashboardsProposeTool } from "./ai/propose-tool";
30
+ import { createInspectDashboardTool } from "./ai/inspect-tool";
31
+ import { appBaseUrl } from "./ai/view-links";
32
+ import { buildDashboardsGuidance } from "./ai/guidance";
33
+ import { createRouter } from "./router";
34
+
35
+ export default createBackendPlugin({
36
+ metadata: pluginMetadata,
37
+ register(env) {
38
+ env.registerAccessRules(dashboardsAccessRules);
39
+ const { onEntityChanged } = env.getExtensionPoint(entityExtensionPoint);
40
+
41
+ // Data sources and widgets, contributed by their owning plugins, so AI
42
+ // agents can discover them and drafted dashboards are validated.
43
+ const buildingBlocks = createBuildingBlocksRegistry();
44
+ for (const widget of CORE_HOME_WIDGETS) buildingBlocks.registerWidget(widget);
45
+ env.registerExtensionPoint(dashboardBuildingBlocksExtensionPoint, {
46
+ registerDataSource: (spec) =>
47
+ buildingBlocks.registerDataSource({
48
+ ...spec,
49
+ // Erase the query type: the registry validates any stored query.
50
+ querySchema: spec.querySchema as z.ZodType<DataSourceQuery>,
51
+ requiredFields: [...spec.requiredFields],
52
+ }),
53
+ registerWidget: (spec) => buildingBlocks.registerWidget(spec),
54
+ });
55
+
56
+ const aiToolExt = env.getExtensionPoint(aiToolExtensionPoint);
57
+ aiToolExt.registerTool(
58
+ createGetBuildingBlocksTool({ registry: buildingBlocks }),
59
+ pluginMetadata,
60
+ );
61
+ aiToolExt.registerTool(
62
+ createDashboardsProposeTool({ registry: buildingBlocks }),
63
+ pluginMetadata,
64
+ );
65
+ aiToolExt.registerTool(
66
+ createInspectDashboardTool({ baseUrl: () => appBaseUrl() }),
67
+ pluginMetadata,
68
+ );
69
+ const aiGuidanceExt = env.getExtensionPoint(aiGuidanceExtensionPoint);
70
+ for (const section of buildDashboardsGuidance()) {
71
+ aiGuidanceExt.contribute(section, pluginMetadata);
72
+ }
73
+
74
+ env.registerInit({
75
+ schema,
76
+ deps: {
77
+ logger: coreServices.logger,
78
+ rpc: coreServices.rpc,
79
+ resourceResolverRegistry: coreServices.resourceResolverRegistry,
80
+ },
81
+ init: async ({ logger, database, rpc, resourceResolverRegistry }) => {
82
+ const service = new DashboardService(
83
+ database as SafeDatabase<typeof schema>,
84
+ );
85
+ rpc.registerRouter(createRouter({ service }), dashboardsContract);
86
+
87
+ // Lets the Teams admin UI render/search dashboard grants by title.
88
+ resourceResolverRegistry.register(dashboardsResourceTypes.dashboard, {
89
+ resolveNames: async (ids) => service.resolveNames({ ids }),
90
+ search: async (query, limit) => service.search({ query, limit }),
91
+ });
92
+
93
+ registerSearchProvider({
94
+ pluginMetadata,
95
+ commands: [
96
+ {
97
+ id: "dashboards",
98
+ title: "Dashboards",
99
+ subtitle: "Browse system dashboards",
100
+ iconName: "LayoutDashboard",
101
+ route: resolveRoute(dashboardsRoutes.routes.list),
102
+ requiredAccessRules: [dashboardsAccess.dashboard.read],
103
+ },
104
+ ],
105
+ });
106
+
107
+ logger.debug("✅ Dashboards backend initialized.");
108
+ },
109
+ afterPluginsReady: async ({ database, logger }) => {
110
+ const service = new DashboardService(
111
+ database as SafeDatabase<typeof schema>,
112
+ );
113
+ // A deleted system takes its dashboards with it. `work-queue` delivery
114
+ // runs the cleanup exactly once per cluster, not once per pod.
115
+ onEntityChanged({
116
+ kind: CATALOG_SYSTEM_ENTITY_KIND,
117
+ handler: async (change) => {
118
+ if (change.next !== null) return; // tombstones only
119
+ const removed = await service.deleteForSystem({ systemId: change.id });
120
+ if (removed > 0) {
121
+ logger.debug(
122
+ `Removed ${removed} dashboard(s) of deleted system ${change.id}`,
123
+ );
124
+ }
125
+ },
126
+ delivery: {
127
+ mode: "work-queue",
128
+ workerGroup: "dashboards-system-cleanup",
129
+ },
130
+ });
131
+ },
132
+ });
133
+ },
134
+ });
135
+
136
+ export {
137
+ dashboardBuildingBlocksExtensionPoint,
138
+ type DashboardBuildingBlocksExtensionPoint,
139
+ } from "./building-blocks";
@@ -0,0 +1,182 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { DashboardVisibility } from "@checkstack/dashboards-common";
3
+ import {
4
+ canViewDashboard,
5
+ filterDashboardsForCaller,
6
+ resolveHomeDashboard,
7
+ type DashboardViewer,
8
+ } from "./read-access";
9
+
10
+ const viewer = (over: Partial<DashboardViewer>): DashboardViewer => ({
11
+ kind: "user",
12
+ hasReadRule: true,
13
+ hasManageRule: false,
14
+ hasPublishedRule: true,
15
+ roles: [],
16
+ ...over,
17
+ });
18
+ const dash = (visibility: DashboardVisibility, visibleRoleIds: string[] = []) => ({
19
+ visibility,
20
+ visibleRoleIds,
21
+ });
22
+
23
+ describe("canViewDashboard", () => {
24
+ const reader = viewer({});
25
+ const anonymous = viewer({ kind: "anonymous", hasReadRule: false });
26
+ const noRule = viewer({ hasReadRule: false });
27
+
28
+ it("team grants and the global manage rule always see it", () => {
29
+ for (const v of ["team", "authenticated", "roles", "public"] as const) {
30
+ expect(canViewDashboard({ viewer: noRule, dashboard: dash(v), hasTeamGrant: true })).toBe(true);
31
+ expect(
32
+ canViewDashboard({
33
+ viewer: viewer({ hasManageRule: true, hasReadRule: false }),
34
+ dashboard: dash(v),
35
+ hasTeamGrant: false,
36
+ }),
37
+ ).toBe(true);
38
+ }
39
+ });
40
+
41
+ it("service callers see everything", () => {
42
+ expect(
43
+ canViewDashboard({ viewer: viewer({ kind: "service" }), dashboard: dash("team"), hasTeamGrant: false }),
44
+ ).toBe(true);
45
+ });
46
+
47
+ it("team: private to the granted teams", () => {
48
+ expect(canViewDashboard({ viewer: reader, dashboard: dash("team"), hasTeamGrant: false })).toBe(false);
49
+ });
50
+
51
+ it("authenticated: any signed-in reader, not anonymous, not without the rule", () => {
52
+ expect(canViewDashboard({ viewer: reader, dashboard: dash("authenticated"), hasTeamGrant: false })).toBe(true);
53
+ expect(
54
+ canViewDashboard({ viewer: viewer({ kind: "application" }), dashboard: dash("authenticated"), hasTeamGrant: false }),
55
+ ).toBe(true);
56
+ expect(canViewDashboard({ viewer: noRule, dashboard: dash("authenticated"), hasTeamGrant: false })).toBe(false);
57
+ expect(canViewDashboard({ viewer: anonymous, dashboard: dash("authenticated"), hasTeamGrant: false })).toBe(false);
58
+ });
59
+
60
+ it("roles: only users holding one of the roles", () => {
61
+ const d = dash("roles", ["ops", "sre"]);
62
+ expect(canViewDashboard({ viewer: viewer({ roles: ["sre"] }), dashboard: d, hasTeamGrant: false })).toBe(true);
63
+ expect(canViewDashboard({ viewer: viewer({ roles: ["dev"] }), dashboard: d, hasTeamGrant: false })).toBe(false);
64
+ expect(
65
+ canViewDashboard({ viewer: viewer({ roles: ["sre"], hasReadRule: false }), dashboard: d, hasTeamGrant: false }),
66
+ ).toBe(false);
67
+ expect(
68
+ canViewDashboard({ viewer: viewer({ kind: "application", roles: ["sre"] }), dashboard: d, hasTeamGrant: false }),
69
+ ).toBe(false);
70
+ });
71
+
72
+ it("public: signed-in readers and anonymous visitors with the published rule", () => {
73
+ expect(canViewDashboard({ viewer: reader, dashboard: dash("public"), hasTeamGrant: false })).toBe(true);
74
+ expect(canViewDashboard({ viewer: anonymous, dashboard: dash("public"), hasTeamGrant: false })).toBe(true);
75
+ expect(
76
+ canViewDashboard({
77
+ viewer: viewer({ kind: "anonymous", hasReadRule: false, hasPublishedRule: false }),
78
+ dashboard: dash("public"),
79
+ hasTeamGrant: false,
80
+ }),
81
+ ).toBe(false);
82
+ });
83
+
84
+ it("anonymous callers never pass through a (spoofed) grant or manage flag", () => {
85
+ expect(
86
+ canViewDashboard({
87
+ viewer: viewer({ kind: "anonymous", hasManageRule: true }),
88
+ dashboard: dash("team"),
89
+ hasTeamGrant: true,
90
+ }),
91
+ ).toBe(false);
92
+ });
93
+ });
94
+
95
+ /** Fake auth: `granted` = dashboard ids with a team grant, `systems` = readable system ids. */
96
+ function makeAuth({
97
+ granted = [] as string[],
98
+ systems = [] as string[],
99
+ anonymousRules = ["dashboards.published.read"],
100
+ } = {}) {
101
+ return {
102
+ getAnonymousAccessRules: async () => anonymousRules,
103
+ filterPublicObjectIds: async ({ objectIds }: { objectIds: string[] }) =>
104
+ objectIds.filter((id) => systems.includes(id)),
105
+ listAccessibleObjectIds: async ({
106
+ objectType,
107
+ objectIds,
108
+ hasGlobalAccess,
109
+ }: {
110
+ objectType: string;
111
+ objectIds: string[];
112
+ hasGlobalAccess: boolean;
113
+ }) =>
114
+ objectType === "catalog.system"
115
+ ? objectIds.filter((id) => hasGlobalAccess && systems.includes(id))
116
+ : objectIds.filter((id) => granted.includes(id)),
117
+ };
118
+ }
119
+
120
+ const rows = [
121
+ { id: "d-auth", systemId: "s-pub", visibility: "authenticated" as const, visibleRoleIds: [] },
122
+ { id: "d-team", systemId: "s-pub", visibility: "team" as const, visibleRoleIds: [] },
123
+ { id: "d-priv-system", systemId: "s-priv", visibility: "authenticated" as const, visibleRoleIds: [] },
124
+ { id: "g-public", systemId: null, visibility: "public" as const, visibleRoleIds: [] },
125
+ ];
126
+
127
+ const run = (
128
+ user: Parameters<typeof filterDashboardsForCaller>[0]["user"],
129
+ auth: ReturnType<typeof makeAuth>,
130
+ ) => filterDashboardsForCaller({ user, auth, rows }).then((r) => r.map((x) => x.id));
131
+
132
+ const globalReader = {
133
+ type: "user" as const,
134
+ id: "g",
135
+ accessRules: ["catalog.system.read", "dashboards.dashboard.read"],
136
+ };
137
+
138
+ describe("filterDashboardsForCaller", () => {
139
+ it("a reader sees non-team dashboards on readable systems and global ones", async () => {
140
+ expect(await run(globalReader, makeAuth({ systems: ["s-pub"] }))).toEqual(["d-auth", "g-public"]);
141
+ });
142
+
143
+ it("a team grant reveals a team-only dashboard, but never on an unreadable system", async () => {
144
+ const auth = makeAuth({ systems: ["s-pub"], granted: ["d-team", "d-priv-system"] });
145
+ expect(await run(globalReader, auth)).toEqual(["d-auth", "d-team", "g-public"]);
146
+ });
147
+
148
+ it("anonymous visitors only see public dashboards", async () => {
149
+ expect(await run(undefined, makeAuth({ systems: ["s-pub"] }))).toEqual(["g-public"]);
150
+ expect(await run(undefined, makeAuth({ anonymousRules: [] }))).toEqual([]);
151
+ });
152
+
153
+ it("service: everything", async () => {
154
+ expect(await run({ type: "service" }, makeAuth())).toHaveLength(4);
155
+ });
156
+ });
157
+
158
+ describe("resolveHomeDashboard", () => {
159
+ const mine = { id: "mine" };
160
+ const org = { id: "org" };
161
+
162
+ it("prefers the caller's own viewable choice", () => {
163
+ expect(
164
+ resolveHomeDashboard({ userChoiceId: "mine", globalChoiceId: "org", readable: [mine, org] }),
165
+ ).toEqual({ source: "user", dashboard: mine });
166
+ });
167
+
168
+ it("falls back to the organization home when the own choice is not viewable", () => {
169
+ expect(
170
+ resolveHomeDashboard({ userChoiceId: "mine", globalChoiceId: "org", readable: [org] }),
171
+ ).toEqual({ source: "global", dashboard: org });
172
+ });
173
+
174
+ it("falls back to the built-in default when nothing is viewable", () => {
175
+ expect(
176
+ resolveHomeDashboard({ userChoiceId: "mine", globalChoiceId: "org", readable: [] }),
177
+ ).toEqual({ source: "default", dashboard: null });
178
+ expect(
179
+ resolveHomeDashboard({ userChoiceId: null, globalChoiceId: null, readable: [] }),
180
+ ).toEqual({ source: "default", dashboard: null });
181
+ });
182
+ });
@@ -0,0 +1,204 @@
1
+ import {
2
+ filterCatalogIdsForCaller,
3
+ type CatalogAccessAuth,
4
+ type CatalogAccessCaller,
5
+ } from "@checkstack/catalog-common";
6
+ import { qualifyAccessRuleId } from "@checkstack/common";
7
+ import {
8
+ dashboardsAccess,
9
+ dashboardsResourceTypes,
10
+ pluginMetadata,
11
+ type DashboardVisibility,
12
+ } from "@checkstack/dashboards-common";
13
+
14
+ /** The caller facts a visibility decision needs. */
15
+ export interface DashboardViewer {
16
+ kind: "service" | "user" | "application" | "anonymous";
17
+ /** Holds `dashboards.dashboard.read` (or `*`). */
18
+ hasReadRule: boolean;
19
+ /** Holds `dashboards.dashboard.manage` (or `*`): sees every dashboard. */
20
+ hasManageRule: boolean;
21
+ /** Holds `dashboards.published.read` (anonymous public viewing). */
22
+ hasPublishedRule: boolean;
23
+ /** Role ids of a signed-in user. */
24
+ roles: readonly string[];
25
+ }
26
+
27
+ /**
28
+ * The single visibility decision for one dashboard, pinned by
29
+ * `read-access.test.ts`. Teams with a grant (viewer/editor/owner) and holders
30
+ * of the global manage rule always see it; everyone else is decided by the
31
+ * dashboard's `visibility`:
32
+ *
33
+ * - `team`: nobody else.
34
+ * - `authenticated`: signed-in users and applications with the read rule.
35
+ * - `roles`: signed-in users with the read rule and one of `visibleRoleIds`.
36
+ * - `public`: the above plus anonymous visitors with the published rule.
37
+ *
38
+ * The catalog-system check (when the dashboard has a system) is applied on top
39
+ * by {@link filterDashboardsForCaller}.
40
+ */
41
+ export function canViewDashboard({
42
+ viewer,
43
+ dashboard,
44
+ hasTeamGrant,
45
+ }: {
46
+ viewer: DashboardViewer;
47
+ dashboard: { visibility: DashboardVisibility; visibleRoleIds: readonly string[] };
48
+ hasTeamGrant: boolean;
49
+ }): boolean {
50
+ if (viewer.kind === "service") return true;
51
+ if (viewer.kind !== "anonymous" && (viewer.hasManageRule || hasTeamGrant)) {
52
+ return true;
53
+ }
54
+ const signedInReader = viewer.kind !== "anonymous" && viewer.hasReadRule;
55
+ switch (dashboard.visibility) {
56
+ case "team": {
57
+ return false;
58
+ }
59
+ case "authenticated": {
60
+ return signedInReader;
61
+ }
62
+ case "roles": {
63
+ return (
64
+ signedInReader &&
65
+ viewer.kind === "user" &&
66
+ dashboard.visibleRoleIds.some((role) => viewer.roles.includes(role))
67
+ );
68
+ }
69
+ case "public": {
70
+ return signedInReader || (viewer.kind === "anonymous" && viewer.hasPublishedRule);
71
+ }
72
+ }
73
+ }
74
+
75
+ /** A signed-in caller's role ids (the catalog caller type does not declare them). */
76
+ function rolesOf(user: object): string[] {
77
+ const roles: unknown = "roles" in user ? user.roles : undefined;
78
+ return Array.isArray(roles) ? roles.filter((r): r is string => typeof r === "string") : [];
79
+ }
80
+
81
+ /** Derive the {@link DashboardViewer} facts of an RPC caller. */
82
+ export async function toDashboardViewer({
83
+ user,
84
+ auth,
85
+ }: {
86
+ user: CatalogAccessCaller;
87
+ auth: CatalogAccessAuth;
88
+ }): Promise<DashboardViewer> {
89
+ const readRule = qualifyAccessRuleId(pluginMetadata, dashboardsAccess.dashboard.read);
90
+ const manageRule = qualifyAccessRuleId(pluginMetadata, dashboardsAccess.dashboard.manage);
91
+ const publishedRule = qualifyAccessRuleId(pluginMetadata, dashboardsAccess.published);
92
+ if (user?.type === "service") {
93
+ return { kind: "service", hasReadRule: true, hasManageRule: true, hasPublishedRule: true, roles: [] };
94
+ }
95
+ if (!user) {
96
+ const anon = await auth.getAnonymousAccessRules().catch(() => [] as string[]);
97
+ return {
98
+ kind: "anonymous",
99
+ hasReadRule: false,
100
+ hasManageRule: false,
101
+ hasPublishedRule: anon.includes("*") || anon.includes(publishedRule),
102
+ roles: [],
103
+ };
104
+ }
105
+ const rules = user.accessRules ?? [];
106
+ const has = (rule: string) => rules.includes("*") || rules.includes(rule);
107
+ return {
108
+ kind: user.type === "user" ? "user" : "application",
109
+ hasReadRule: has(readRule),
110
+ hasManageRule: has(manageRule),
111
+ hasPublishedRule: has(publishedRule),
112
+ roles: rolesOf(user),
113
+ };
114
+ }
115
+
116
+ /** Ids the caller holds a team grant on (grants only, no global path). */
117
+ async function grantedDashboardIds({
118
+ user,
119
+ auth,
120
+ ids,
121
+ }: {
122
+ user: CatalogAccessCaller;
123
+ auth: CatalogAccessAuth;
124
+ ids: string[];
125
+ }): Promise<Set<string>> {
126
+ if (!user || user.type === "service" || ids.length === 0) return new Set();
127
+ try {
128
+ return new Set(
129
+ await auth.listAccessibleObjectIds({
130
+ userId: user.id,
131
+ userType: user.type,
132
+ objectType: dashboardsResourceTypes.dashboard,
133
+ objectIds: [...new Set(ids)],
134
+ action: "read",
135
+ hasGlobalAccess: false,
136
+ }),
137
+ );
138
+ } catch {
139
+ return new Set();
140
+ }
141
+ }
142
+
143
+ type VisibleRow = {
144
+ id: string;
145
+ systemId: string | null;
146
+ visibility: DashboardVisibility;
147
+ visibleRoleIds: readonly string[];
148
+ };
149
+
150
+ /**
151
+ * Narrow dashboards (or summaries) to those the caller may view: allowed by
152
+ * {@link canViewDashboard} AND, for a system dashboard, on a catalog system the
153
+ * caller can read (so dashboards of team-private systems never leak). Global
154
+ * dashboards need no system check. Fails closed.
155
+ */
156
+ export async function filterDashboardsForCaller<T extends VisibleRow>({
157
+ user,
158
+ auth,
159
+ rows,
160
+ }: {
161
+ user: CatalogAccessCaller;
162
+ auth: CatalogAccessAuth;
163
+ rows: T[];
164
+ }): Promise<T[]> {
165
+ if (rows.length === 0) return rows;
166
+ const [viewer, granted, systems] = await Promise.all([
167
+ toDashboardViewer({ user, auth }),
168
+ grantedDashboardIds({ user, auth, ids: rows.map((r) => r.id) }),
169
+ filterCatalogIdsForCaller({
170
+ user,
171
+ auth,
172
+ kind: "system",
173
+ ids: rows.flatMap((r) => (r.systemId === null ? [] : [r.systemId])),
174
+ }),
175
+ ]);
176
+ return rows.filter(
177
+ (r) =>
178
+ (r.systemId === null || systems.has(r.systemId)) &&
179
+ canViewDashboard({ viewer, dashboard: r, hasTeamGrant: granted.has(r.id) }),
180
+ );
181
+ }
182
+
183
+ /**
184
+ * Pick the caller's home dashboard: their own choice when they can still view
185
+ * it, else the organization-wide one when viewable, else none (the built-in
186
+ * default). `readable` holds the subset of the two choices that passed
187
+ * {@link filterDashboardsForCaller}. Pinned by `read-access.test.ts`.
188
+ */
189
+ export function resolveHomeDashboard<T extends { id: string }>({
190
+ userChoiceId,
191
+ globalChoiceId,
192
+ readable,
193
+ }: {
194
+ userChoiceId: string | null;
195
+ globalChoiceId: string | null;
196
+ readable: T[];
197
+ }): { source: "user" | "global" | "default"; dashboard: T | null } {
198
+ const byId = new Map(readable.map((d) => [d.id, d]));
199
+ const mine = userChoiceId ? byId.get(userChoiceId) : undefined;
200
+ if (mine) return { source: "user", dashboard: mine };
201
+ const org = globalChoiceId ? byId.get(globalChoiceId) : undefined;
202
+ if (org) return { source: "global", dashboard: org };
203
+ return { source: "default", dashboard: null };
204
+ }