Open History to see the last commit
1/**
2 * ManagedPolicy - the administrator's machine-wide policy file, read once at startup. A file this
3 * build cannot fully enforce stops the server instead of leaving it looking managed.
4 *
5 * @module ManagedPolicy
6 */
7import * as NodeModule from "node:module";
8
9import { ManagedPolicyDocument, type ManagedPolicySummary } from "@t3tools/contracts";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14import * as Hex from "effect/encoding/Hex";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import {
21 ManagedPolicyFileError,
22 managedPolicyPath,
23 layerWindowsRegistry,
24 readManagedPolicy,
25 readManagedPolicyFile,
26} from "@t3tools/shared/managedPolicyFile";
27
28import { telemetryChannel } from "../config.ts";
29import * as ManagedLimits from "./managedLimits.ts";
30import * as ManagedProviders from "./managedProviders.ts";
31import * as ManagedSettings from "./managedSettings.ts";
32
33export class ManagedPolicy extends Context.Service<
34 ManagedPolicy,
35 {
36 /** Where the policy is read from, whether or not a file exists there. */
37 readonly path: string;
38 readonly document: ManagedPolicyDocument | undefined;
39 readonly settings: ManagedSettings.ManagedSettings;
40 readonly providers: ManagedProviders.ManagedProviders;
41 /** What clients are told; absent when no policy applies. */
42 readonly summary: ManagedPolicySummary | undefined;
43 }
44>()("t3/policy/ManagedPolicy") {}
45
46type LimitsSummary = NonNullable<ManagedPolicySummary["limits"]>;
47
48const encodeDocumentJson = Schema.encodeEffect(Schema.fromJsonString(ManagedPolicyDocument));
49
50/** What `t3 policy show` compares to tell whether a running server loaded the installed policy. */
51export const loadedPolicy = Effect.fn("ManagedPolicy.loadedPolicy")(function* (
52 policy: Pick<ManagedPolicy["Service"], "path" | "document">,
53) {
54 if (policy.document === undefined) return null;
55 const json = yield* encodeDocumentJson(policy.document).pipe(Effect.orDie);
56 const digest = yield* (yield* Crypto.Crypto)
57 .digest("SHA-256", new TextEncoder().encode(json))
58 .pipe(Effect.orDie);
59 return {
60 source: policy.path,
61 organization: policy.document.organization,
62 fingerprint: Hex.encode(digest).slice(0, 12),
63 };
64});
65
66/**
67 * The organization whose policy switches `capability` off, or undefined when it is allowed.
68 * Only an explicit `false` restricts.
69 */
70export function deniedBy(
71 policy: Pick<ManagedPolicy["Service"], "document">,
72 capability: "webhookTasks" | "telemetry",
73): string | undefined {
74 return policy.document?.limits?.[capability] === false ? policy.document.organization : undefined;
75}
76
77/** Build the service from a decoded document; fails when the document cannot be enforced. */
78export const fromDocument = Effect.fn("ManagedPolicy.fromDocument")(function* (
79 path: string,
80 document: ManagedPolicyDocument | undefined,
81) {
82 if (document === undefined) {
83 return ManagedPolicy.of({
84 path,
85 document: undefined,
86 settings: ManagedSettings.unmanagedSettings,
87 providers: ManagedProviders.unmanagedProviders,
88 summary: undefined,
89 });
90 }
91 const maxRuntimeMode = document.limits?.maxRuntimeMode;
92 const settings = ManagedSettings.makeManagedSettings(document.settings ?? {}, maxRuntimeMode);
93 if (settings._tag === "Invalid") {
94 return yield* new ManagedPolicyFileError({ path, reason: settings.reason });
95 }
96 // A ceiling alone also shapes providers: their launch configuration becomes the administrator's.
97 const providerLimits = document.limits?.providers;
98 const providers =
99 providerLimits === undefined && maxRuntimeMode === undefined
100 ? undefined
101 : ManagedProviders.makeManagedProviders(
102 providerLimits ?? {},
103 maxRuntimeMode,
104 yield* HostProcess.Platform,
105 );
106 if (providers?._tag === "Invalid") {
107 return yield* new ManagedPolicyFileError({ path, reason: providers.reason });
108 }
109 const lockedInstanceFields = providers?.providers.lockedInstanceFields ?? {};
110 return ManagedPolicy.of({
111 path,
112 document,
113 settings: settings.settings,
114 providers: providers?.providers ?? ManagedProviders.unmanagedProviders,
115 summary: {
116 organization: document.organization,
117 ...(document.supportUrl === undefined ? {} : { supportUrl: document.supportUrl }),
118 lockedSettings: settings.settings.lockedPaths,
119 ...(document.limits === undefined
120 ? {}
121 : { limits: summarizeLimits(document, lockedInstanceFields) }),
122 },
123 });
124});
125
126// Copies only what clients may see; other limits can carry values that stay on the server.
127function summarizeLimits(
128 document: ManagedPolicyDocument,
129 lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>,
130): LimitsSummary {
131 const {
132 maxRuntimeMode,
133 clients,
134 webhookTasks,
135 telemetry,
136 browserCookieImport,
137 providers,
138 updates,
139 } = document.limits ?? {};
140 const connect = ManagedLimits.allowsConnect({ document });
141 return {
142 ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
143 ...(clients === undefined ? {} : { clients }),
144 ...(connect ? {} : { connect: false }),
145 ...(webhookTasks === undefined ? {} : { webhookTasks }),
146 ...(telemetry === undefined ? {} : { telemetry }),
147 ...(browserCookieImport === undefined ? {} : { browserCookieImport }),
148 ...(providers?.allowedDrivers === undefined && Object.keys(lockedInstanceFields).length === 0
149 ? {}
150 : {
151 providers: {
152 ...(providers?.allowedDrivers === undefined
153 ? {}
154 : { allowedDrivers: providers.allowedDrivers }),
155 ...(Object.keys(lockedInstanceFields).length === 0 ? {} : { lockedInstanceFields }),
156 },
157 }),
158 ...(updates === undefined
159 ? {}
160 : {
161 updates: {
162 mode: updates.mode,
163 ...(updates.allowNightly === undefined ? {} : { allowNightly: updates.allowNightly }),
164 },
165 }),
166 };
167}
168
169/** Read and validate the policy at `path`; a missing file means no policy. */
170export const load = Effect.fn("ManagedPolicy.load")(function* (path: string) {
171 return yield* fromDocument(path, yield* readManagedPolicyFile(path));
172});
173
174const make = Effect.gen(function* () {
175 // Source builds may read a policy from elsewhere so it can be tried without root. Release
176 // builds never do: any override a user can set is a way around the policy.
177 const devPath =
178 telemetryChannel === "dev"
179 ? yield* Config.option(Config.String("T3CODE_DEV_MANAGED_POLICY_PATH")).pipe(
180 Effect.orElseSucceed(() => Option.none<string>()),
181 )
182 : Option.none<string>();
183 const platform = yield* HostProcess.Platform;
184 const policy = yield* Option.match(devPath, {
185 onSome: load,
186 onNone: () =>
187 readManagedPolicy(platform).pipe(
188 Effect.flatMap((found) =>
189 fromDocument(found?.source ?? managedPolicyPath(platform), found?.document),
190 ),
191 ),
192 });
193 const path = policy.path;
194 if (policy.summary !== undefined) {
195 yield* Effect.logInfo("Managed policy applies.", {
196 path,
197 organization: policy.summary.organization,
198 lockedSettings: policy.summary.lockedSettings,
199 });
200 }
201 return policy;
202});
203
204// A single-executable server resolves packages on disk only through `require`.
205const requireForFfi = NodeModule.createRequire(import.meta.url);
206
207export const layer = Layer.effect(ManagedPolicy, make).pipe(
208 Layer.provide(
209 layerWindowsRegistry(async () => requireForFfi("ffi-rs") as typeof import("ffi-rs")),
210 ),
211);
212
213/** A policy for tests; `undefined` means unmanaged. */
214export const layerTest = (document?: ManagedPolicyDocument) =>
215 Layer.effect(ManagedPolicy, fromDocument("/test/policy.json", document));