@sshkeda/check 4.0.1 → 4.2.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.
@@ -25,4 +25,5 @@ export default lintConfig({
25
25
  - `trustsUnverifiedTypes`: Allows trusting a value's type without checking it, through `Schema.declare`.
26
26
  - `handlesEveryFailure`: Allows catching every error, through `Effect.catch`, `Effect.exit`, a forked fiber or `Effect.runPromise`.
27
27
  - `fallsBackToFixedValues`: Allows answering every failure, or a whole library error such as `PlatformError`, with a fixed value that never reads the failure.
28
+ - `replacesTheConsole`: Allows `Console` from `node:console`, and reading, calling and assigning these members of the global `console` by name: `log`, `warn`, `error`, `info`, `debug`, `dir`, `dirxml`, `table`, `trace`, `assert`, `clear`, `count`, `countReset`, `group`, `groupCollapsed`, `groupEnd`, `time`, `timeEnd` and `timeLog`.
28
29
  - `isGeneratedByATool`: Check skips this path, so it can't have any other permission.
@@ -10,7 +10,10 @@ Check may not catch every violation of these principles. Review your code agains
10
10
  - Move the code that needs a grant into its own small file and grant that file. A grant covers the whole file, so Check stops reporting that ban for everything else in it.
11
11
  - Design for the current requirement as if you were starting fresh. Delete code the new design doesn't need.
12
12
  - Handle a forked effect's failure before the fork, or keep the fiber and join it.
13
+ - Read a fact from where a tool states it, such as an error's fields, a command's exit code or its JSON output. Text written for people changes between releases, and code that searches it breaks quietly when it does.
13
14
  - Return a fixed value only for the one failure you expect, such as a file that isn't there. Let every other failure fail.
15
+ - Write a job that moves through stages as an explicit state machine, with one tagged case per stage in one union, so the job is always in exactly one stage.
16
+ - Give each status its own struct holding the fields that status always has, and join them in a union.
14
17
  - Grant `isGeneratedByATool` only to a file a tool generates.
15
18
 
16
19
  ## Make the code explain itself
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sshkeda/check",
3
- "version": "4.0.1",
3
+ "version": "4.2.0",
4
4
  "homepage": "https://github.com/sshkeda/check#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/sshkeda/check/issues"
@@ -5,10 +5,24 @@ import {
5
5
  NODE_BUILTIN_RULES,
6
6
  nodeBuiltinNameOf,
7
7
  } from "../shared/lint-rule-messages-and-patterns.ts";
8
- import { importsOnlyTypes, staticKeyName } from "./resolve-what-an-expression-imports.ts";
8
+ import {
9
+ importsOnlyTypes,
10
+ moduleExportName,
11
+ staticKeyName,
12
+ } from "./resolve-what-an-expression-imports.ts";
9
13
 
10
14
  export const nodeBuiltinRule = (ruleName: keyof typeof NODE_BUILTIN_RULES) => {
11
15
  const bannedModules: ReadonlySet<string> = new Set(NODE_BUILTIN_RULES[ruleName].modules);
16
+ const allowedImports: ReadonlySet<string> = new Set(NODE_BUILTIN_RULES[ruleName].allowedImports);
17
+ const isErasedOrAllowed = (specifier: ESTree.ImportSpecifier) => {
18
+ const isErased = specifier.importKind === "type";
19
+ return isErased || allowedImports.has(moduleExportName(specifier.imported));
20
+ };
21
+ const importsOnlyAllowedNames = (node: ESTree.ImportDeclaration) =>
22
+ node.specifiers.length > 0 &&
23
+ node.specifiers.every(
24
+ (specifier) => specifier.type === "ImportSpecifier" && isErasedOrAllowed(specifier),
25
+ );
12
26
  return defineRule({
13
27
  meta: {
14
28
  type: "problem",
@@ -23,7 +37,9 @@ export const nodeBuiltinRule = (ruleName: keyof typeof NODE_BUILTIN_RULES) => {
23
37
 
24
38
  return {
25
39
  ImportDeclaration(node) {
26
- if (!importsOnlyTypes(node, context.sourceCode)) {
40
+ const isAllowed =
41
+ importsOnlyTypes(node, context.sourceCode) || importsOnlyAllowedNames(node);
42
+ if (!isAllowed) {
27
43
  check(node.source, node.source.value);
28
44
  }
29
45
  },
@@ -0,0 +1,77 @@
1
+ import type { Context, CreateRule, ESTree } from "@oxlint/plugins";
2
+ import { Schema } from "effect";
3
+
4
+ import {
5
+ equivalentModuleSpecifiers,
6
+ REPLACES_THE_CONSOLE,
7
+ } from "../shared/bans-each-permission-lifts.ts";
8
+ import { CONSOLE_REPLACED } from "../shared/record-and-grant-permissions-by-path.ts";
9
+ import { decodeRuleOptions, ruleOptionsJsonSchema } from "./describe-and-decode-rule-options.ts";
10
+ import {
11
+ importsOnlyTypes,
12
+ moduleExportName,
13
+ staticKeyName,
14
+ } from "./resolve-what-an-expression-imports.ts";
15
+
16
+ const NODE_CONSOLE = "node:console";
17
+ const CONSOLE_EXPORT = "Console";
18
+ const NODE_CONSOLE_SPECIFIERS: ReadonlySet<string> = new Set(
19
+ equivalentModuleSpecifiers(NODE_CONSOLE),
20
+ );
21
+
22
+ const NODE_CONSOLE_OPTIONS = Schema.Struct({
23
+ console: Schema.optionalKey(Schema.Literal(CONSOLE_REPLACED)),
24
+ });
25
+
26
+ const isTheConsoleExport = (specifier: ESTree.ImportDeclaration["specifiers"][number]) =>
27
+ specifier.type === "ImportSpecifier" && moduleExportName(specifier.imported) === CONSOLE_EXPORT;
28
+
29
+ export const noNodeConsole = {
30
+ meta: {
31
+ type: "problem",
32
+ messages: {
33
+ outsideTheGrant: `${CONSOLE_EXPORT} from {{module}} is used outside a file allowed ${REPLACES_THE_CONSOLE}`,
34
+ forbiddenForm: `{{module}} is imported in a way no file may. A file allowed ${REPLACES_THE_CONSOLE} may import only ${CONSOLE_EXPORT} from ${NODE_CONSOLE}`,
35
+ },
36
+ schema: ruleOptionsJsonSchema(NODE_CONSOLE_OPTIONS),
37
+ },
38
+ create(context: Pick<Context, "options" | "report" | "sourceCode">) {
39
+ const isGranted =
40
+ decodeRuleOptions(NODE_CONSOLE_OPTIONS, context.options)?.console === CONSOLE_REPLACED;
41
+ const report = (source: ESTree.Node, module: string, isTheConsoleOnly: boolean) => {
42
+ if (!isTheConsoleOnly) {
43
+ context.report({ node: source, messageId: "forbiddenForm", data: { module } });
44
+ return;
45
+ }
46
+ if (!isGranted) {
47
+ context.report({ node: source, messageId: "outsideTheGrant", data: { module } });
48
+ }
49
+ };
50
+ return {
51
+ ImportDeclaration(node: ESTree.ImportDeclaration) {
52
+ const isNodeConsoleWithValues =
53
+ NODE_CONSOLE_SPECIFIERS.has(node.source.value) &&
54
+ !importsOnlyTypes(node, context.sourceCode);
55
+ if (!isNodeConsoleWithValues) {
56
+ return;
57
+ }
58
+ const valueSpecifiers = node.specifiers.filter(
59
+ (specifier) => specifier.type !== "ImportSpecifier" || specifier.importKind !== "type",
60
+ );
61
+ report(
62
+ node.source,
63
+ node.source.value,
64
+ valueSpecifiers.length > 0 &&
65
+ valueSpecifiers.every((specifier) => isTheConsoleExport(specifier)),
66
+ );
67
+ },
68
+ ImportExpression(node: ESTree.ImportExpression) {
69
+ const module = staticKeyName(node.source);
70
+ const loadsNodeConsole = module !== undefined && NODE_CONSOLE_SPECIFIERS.has(module);
71
+ if (loadsNodeConsole) {
72
+ report(node.source, module, false);
73
+ }
74
+ },
75
+ };
76
+ },
77
+ } satisfies CreateRule;
@@ -2,6 +2,7 @@ import { eslintCompatPlugin } from "@oxlint/plugins";
2
2
  import { Record } from "effect";
3
3
 
4
4
  import {
5
+ CONSOLE,
5
6
  everyBanOf,
6
7
  IMPORT_META,
7
8
  moduleSpecifiersOfGlobalObject,
@@ -18,6 +19,7 @@ import {
18
19
  permissionBanRuleId,
19
20
  FAILURES_AS_RESULTS_RULE,
20
21
  FIXED_FALLBACKS_RULE,
22
+ NODE_CONSOLE_RULE,
21
23
  STDIO_SERVICE_RULE,
22
24
  TEST_TIMEOUTS_RULE,
23
25
  TYPE_PREDICATES_RULE,
@@ -60,6 +62,7 @@ import { noVagueFileNames } from "./ban-vague-file-names.ts";
60
62
  import { permissionBanRule } from "./ban-what-a-file-is-not-granted.ts";
61
63
  import { noWhile } from "./ban-while-do-while-and-for-loops.ts";
62
64
  import { noSharedHolders } from "./ban-writing-captured-objects-inside-effect-callbacks.ts";
65
+ import { noNodeConsole } from "./confine-node-console-to-its-console-export.ts";
63
66
  import {
64
67
  noServiceDeclarations,
65
68
  noUnusedServiceGrants,
@@ -105,8 +108,6 @@ export const RESTRICTED_IMPORT_PATHS = RESTRICTED_PROPERTIES.flatMap(({ object,
105
108
  })),
106
109
  );
107
110
 
108
- const CONSOLE = "console";
109
-
110
111
  const GLOBALS_WHOSE_MEMBERS_OTHER_RULES_BAN = ["Atomics", "Intl", "Number"] as const;
111
112
 
112
113
  const GLOBALS_WHOSE_MEMBERS_PERMISSIONS_BAN = Object.values(PERMISSION_BANS)
@@ -147,6 +148,7 @@ const NAMED_RULES = {
147
148
  "no-declared-values": noDeclaredValues,
148
149
  [TYPE_PREDICATES_RULE]: noTypePredicates,
149
150
  [STDIO_SERVICE_RULE]: noStdioService,
151
+ [NODE_CONSOLE_RULE]: noNodeConsole,
150
152
  [FAILURES_AS_RESULTS_RULE]: noFailuresAsResults,
151
153
  "no-overloads": noOverloads,
152
154
  "no-re-exports": noReExports,
@@ -2,6 +2,7 @@ import type { Context, CreateRule, Visitor } from "@oxlint/plugins";
2
2
  import { Schema } from "effect";
3
3
 
4
4
  import {
5
+ CONSOLE,
5
6
  HANDLES_EVERY_FAILURE,
6
7
  PERMISSION_BANS,
7
8
  RULES_EACH_PERMISSION_LIFTS,
@@ -14,6 +15,8 @@ import {
14
15
  CODE_GRANTS,
15
16
  FAILURES_AS_RESULTS_RULE,
16
17
  INSIDE_THE_TEST_HOME,
18
+ NO_CONSOLE_RULE,
19
+ NODE_CONSOLE_RULE,
17
20
  rulesACodeGrantChanges,
18
21
  SCHEDULES_RULE,
19
22
  SLEEP_RULE,
@@ -30,17 +33,41 @@ import { noClockReadsAndSleeps } from "./ban-reading-the-clock-and-sleeping-outs
30
33
  import { noSchedules } from "./ban-timer-schedules-without-deadlines.ts";
31
34
  import { noTypePredicates } from "./ban-type-predicates.ts";
32
35
  import { mergedVisitors, permissionBanRule } from "./ban-what-a-file-is-not-granted.ts";
36
+ import { noNodeConsole } from "./confine-node-console-to-its-console-export.ts";
33
37
  import { decodeRuleOptions, ruleOptionsJsonSchema } from "./describe-and-decode-rule-options.ts";
38
+ import { isGlobalReference, memberName } from "./resolve-what-an-expression-imports.ts";
34
39
 
35
- const RULES_CODE_GRANTS_CHANGE: ReadonlyMap<
40
+ const NO_CONSOLE_OPTIONS = Schema.Struct({
41
+ allow: Schema.optionalKey(Schema.Array(Schema.String)),
42
+ });
43
+
44
+ const consoleMembersNoConsoleReports = {
45
+ create(context: Pick<Context, "options" | "report" | "sourceCode">) {
46
+ const allowed = new Set(decodeRuleOptions(NO_CONSOLE_OPTIONS, context.options)?.allow);
47
+ return {
48
+ MemberExpression(node) {
49
+ const name = memberName(node);
50
+ const isReported =
51
+ isGlobalReference(node.object, context.sourceCode, CONSOLE) &&
52
+ (name === undefined || !allowed.has(name));
53
+ if (isReported) {
54
+ context.report({ node, message: name ?? CONSOLE });
55
+ }
56
+ },
57
+ } satisfies Visitor;
58
+ },
59
+ };
60
+
61
+ const RULES_CODE_GRANTS_CHANGE = new Map<
36
62
  string,
37
63
  {
38
64
  readonly create: (context: Pick<Context, "options" | "report" | "sourceCode">) => Visitor;
39
65
  }
40
- > = new Map(
41
- Object.entries({
66
+ >([
67
+ ...Object.entries({
42
68
  [PERMISSION_BANS[HANDLES_EVERY_FAILURE].ruleName]: permissionBanRule(HANDLES_EVERY_FAILURE),
43
69
  [PERMISSION_BANS[TRUSTS_UNVERIFIED_TYPES].ruleName]: permissionBanRule(TRUSTS_UNVERIFIED_TYPES),
70
+ [NODE_CONSOLE_RULE]: noNodeConsole,
44
71
  [FAILURES_AS_RESULTS_RULE]: noFailuresAsResults,
45
72
  [UNNAMED_FALLBACKS_RULE]: noUnnamedFallbacks,
46
73
  [SLEEP_RULE]: effectOperationRule(SLEEP_RULE),
@@ -50,7 +77,8 @@ const RULES_CODE_GRANTS_CHANGE: ReadonlyMap<
50
77
  [RULES_EACH_PERMISSION_LIFTS[SHORT_NAMES]]: noAbbreviations,
51
78
  [TYPE_PREDICATES_RULE]: noTypePredicates,
52
79
  }).map(([name, rule]) => [`sshkeda/${name}`, rule] as const),
53
- );
80
+ [NO_CONSOLE_RULE, consoleMembersNoConsoleReports],
81
+ ]);
54
82
 
55
83
  const UNUSED_CODE_GRANT_OPTIONS = Schema.Struct({
56
84
  permissions: Schema.optionalKey(Schema.Array(Schema.Literals(CODE_GRANTS))),
@@ -1,19 +1,31 @@
1
- import { Effect, Path } from "effect";
2
- import type { Node, SourceFile } from "typescript/unstable/ast";
1
+ import { Effect, Path, Schema } from "effect";
2
+ import { SyntaxKind } from "typescript/unstable/ast";
3
+ import type { ImportDeclaration, Node, SourceFile } from "typescript/unstable/ast";
3
4
  import {
4
5
  isBindingElement,
5
6
  isComputedPropertyName,
6
7
  isElementAccessExpression,
8
+ isExpressionWithTypeArguments,
7
9
  isIdentifier,
10
+ isImportDeclaration,
11
+ isNamedImports,
12
+ isNamespaceImport,
8
13
  isNoSubstitutionTemplateLiteral,
9
14
  isNumericLiteral,
10
15
  isObjectBindingPattern,
11
16
  isPropertyAccessExpression,
12
17
  isStringLiteral,
18
+ isTypeAliasDeclaration,
19
+ isTypeNode,
13
20
  } from "typescript/unstable/ast/is";
14
21
  import { isStringLiteralType, isTypeParameter, isUnionType } from "typescript/unstable/async";
15
22
  import type { Checker, Type } from "typescript/unstable/async";
16
23
 
24
+ import {
25
+ moduleSpecifiersOfGlobalObject,
26
+ READS_CONFIG,
27
+ WRITES_TO_THE_TERMINAL,
28
+ } from "../../../../../shared/bans-each-permission-lifts.ts";
17
29
  import { loadedLintConfigIn } from "../../../shared/load-the-lint-config.ts";
18
30
  import {
19
31
  CONCURRENT_TYPESCRIPT_REQUESTS,
@@ -24,18 +36,36 @@ import {
24
36
  } from "../../../shared/query-the-typescript-project.ts";
25
37
  import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
26
38
  import {
39
+ GrantNothingUses,
27
40
  StdioArgumentsReadWithoutGrant,
28
41
  StdioTerminalWriteWithoutGrant,
42
+ STDIO_PERMISSION,
29
43
  StdioUsesRefused,
30
44
  } from "./stdio-use-errors.ts";
31
45
 
32
46
  const STDIO_TYPE_ID = "~effect/Stdio";
33
47
 
34
- const PERMISSION_OF_STDIO_MEMBER = new Map<string, "readsConfig" | "writesToTheTerminal">([
35
- ["args", "readsConfig"],
36
- ["stdout", "writesToTheTerminal"],
37
- ["stderr", "writesToTheTerminal"],
48
+ const PERMISSION_OF_STDIO_MEMBER = new Map<string, typeof STDIO_PERMISSION.Type>([
49
+ ["args", READS_CONFIG],
50
+ ["stdout", WRITES_TO_THE_TERMINAL],
51
+ ["stderr", WRITES_TO_THE_TERMINAL],
52
+ ]);
53
+
54
+ const PROCESS = "process";
55
+ const PROCESS_MEMBERS_THAT_READ_CONFIG = new Set(["env", "argv"]);
56
+ const EFFECT = "effect";
57
+ const PERMISSION_OF_MODULE = new Map<string, typeof STDIO_PERMISSION.Type>([
58
+ ["effect/Config", READS_CONFIG],
59
+ ...moduleSpecifiersOfGlobalObject(PROCESS).map((specifier) => [specifier, READS_CONFIG] as const),
60
+ ["effect/Stdio", WRITES_TO_THE_TERMINAL],
61
+ ]);
62
+ const PERMISSION_OF_NAME = new Map<string, typeof STDIO_PERMISSION.Type>([
63
+ ["Config", READS_CONFIG],
64
+ ["Stdio", WRITES_TO_THE_TERMINAL],
38
65
  ]);
66
+ const EVERY_STDIO_PERMISSION = [READS_CONFIG, WRITES_TO_THE_TERMINAL] as const;
67
+
68
+ const isStdioPermission = Schema.is(STDIO_PERMISSION);
39
69
 
40
70
  const literalKeyText = (key: Node) => {
41
71
  const isNamedOrLiteralKey =
@@ -97,6 +127,155 @@ const possibleStdioReadsIn = (sourceFile: SourceFile) => {
97
127
  return reads;
98
128
  };
99
129
 
130
+ const processMemberRead = (reference: Node) => {
131
+ const parent = parentOf(reference);
132
+ const isMemberRead =
133
+ parent !== undefined && isPropertyAccessExpression(parent) && parent.expression === reference;
134
+ if (isMemberRead) {
135
+ return parent.name.text;
136
+ }
137
+ const isElementRead =
138
+ parent !== undefined && isElementAccessExpression(parent) && parent.expression === reference;
139
+ if (!isElementRead) {
140
+ return;
141
+ }
142
+ const key = parent.argumentExpression;
143
+ return isIdentifier(key) ? undefined : literalKeyText(key);
144
+ };
145
+
146
+ const readsConfigThroughProcess = (processReference: Node) => {
147
+ const parent = parentOf(processReference);
148
+ const isGlobalMember =
149
+ parent !== undefined && isPropertyAccessExpression(parent) && parent.name === processReference;
150
+ const member = processMemberRead(isGlobalMember ? parent : processReference);
151
+ return member === undefined || PROCESS_MEMBERS_THAT_READ_CONFIG.has(member);
152
+ };
153
+
154
+ const namespacePermissions = (moduleName: string) => {
155
+ if (moduleName === EFFECT) {
156
+ return EVERY_STDIO_PERMISSION;
157
+ }
158
+ const permission = PERMISSION_OF_MODULE.get(moduleName);
159
+ return permission === undefined ? [] : [permission];
160
+ };
161
+
162
+ const importedBindings = (declaration: ImportDeclaration) => {
163
+ const { importClause, moduleSpecifier } = declaration;
164
+ const isNamedModuleImport = importClause !== undefined && isStringLiteral(moduleSpecifier);
165
+ if (!isNamedModuleImport) {
166
+ return [];
167
+ }
168
+ const moduleName = moduleSpecifier.text;
169
+ const isTypeOnlyClause = importClause.phaseModifier === SyntaxKind.TypeKeyword;
170
+ const modulePermission = PERMISSION_OF_MODULE.get(moduleName);
171
+ const bindings = importClause.namedBindings;
172
+ const isNamespace = bindings !== undefined && isNamespaceImport(bindings);
173
+ if (isNamespace) {
174
+ return namespacePermissions(moduleName).map((permission) => ({
175
+ local: bindings.name.text,
176
+ permission,
177
+ isTypeOnly: isTypeOnlyClause,
178
+ }));
179
+ }
180
+ const isNamed = bindings !== undefined && isNamedImports(bindings);
181
+ const named = (isNamed ? bindings.elements : []).flatMap((specifier) => {
182
+ const imported = literalKeyText(specifier.propertyName ?? specifier.name) ?? "";
183
+ const permission = moduleName === EFFECT ? PERMISSION_OF_NAME.get(imported) : modulePermission;
184
+ const isTypeOnly = isTypeOnlyClause || specifier.isTypeOnly;
185
+ return permission === undefined ? [] : [{ local: specifier.name.text, permission, isTypeOnly }];
186
+ });
187
+ const defaultName = importClause.name;
188
+ const hasPermittingDefault = defaultName !== undefined && modulePermission !== undefined;
189
+ const defaultBinding = hasPermittingDefault
190
+ ? [{ local: defaultName.text, permission: modulePermission, isTypeOnly: isTypeOnlyClause }]
191
+ : [];
192
+ return [...named, ...defaultBinding];
193
+ };
194
+
195
+ const sideEffectImportPermission = (declaration: ImportDeclaration) => {
196
+ const specifier = declaration.moduleSpecifier;
197
+ const isSideEffectImport = declaration.importClause === undefined && isStringLiteral(specifier);
198
+ return isSideEffectImport ? PERMISSION_OF_MODULE.get(specifier.text) : undefined;
199
+ };
200
+
201
+ const permissionOfReference = (
202
+ reference: Node,
203
+ permissionOfLocal: ReadonlyMap<string, typeof STDIO_PERMISSION.Type>,
204
+ ) => {
205
+ if (!isIdentifier(reference)) {
206
+ return;
207
+ }
208
+ if (reference.text !== PROCESS) {
209
+ return permissionOfLocal.get(reference.text);
210
+ }
211
+ return readsConfigThroughProcess(reference) ? READS_CONFIG : undefined;
212
+ };
213
+
214
+ const importDeclarationsIn = (sourceFile: SourceFile) => {
215
+ const declarations: ImportDeclaration[] = [];
216
+ const visit = (node: Node): void => {
217
+ if (isImportDeclaration(node)) {
218
+ declarations.push(node);
219
+ return;
220
+ }
221
+ node.forEachChild(visit);
222
+ };
223
+ sourceFile.forEachChild(visit);
224
+ return declarations;
225
+ };
226
+
227
+ const visitComputedKeysIn = (node: Node, visit: (expression: Node) => void): void => {
228
+ if (isComputedPropertyName(node)) {
229
+ visit(node.expression);
230
+ return;
231
+ }
232
+ node.forEachChild((child) => {
233
+ visitComputedKeysIn(child, visit);
234
+ });
235
+ };
236
+
237
+ const permissionsUsedOutsideStdioReadsIn = (sourceFile: SourceFile) => {
238
+ const used = new Set<typeof STDIO_PERMISSION.Type>();
239
+ const permissionOfLocal = new Map(PERMISSION_OF_NAME);
240
+ for (const declaration of importDeclarationsIn(sourceFile)) {
241
+ const sideEffectPermission = sideEffectImportPermission(declaration);
242
+ if (sideEffectPermission !== undefined) {
243
+ used.add(sideEffectPermission);
244
+ }
245
+ for (const binding of importedBindings(declaration)) {
246
+ if (binding.isTypeOnly) {
247
+ permissionOfLocal.set(binding.local, binding.permission);
248
+ } else {
249
+ used.add(binding.permission);
250
+ }
251
+ }
252
+ }
253
+ const visit = (node: Node): void => {
254
+ if (isImportDeclaration(node)) {
255
+ return;
256
+ }
257
+ if (isExpressionWithTypeArguments(node)) {
258
+ visit(node.expression);
259
+ for (const typeArgument of node.typeArguments ?? []) {
260
+ visitComputedKeysIn(typeArgument, visit);
261
+ }
262
+ return;
263
+ }
264
+ const isErasedType = isTypeNode(node) || isTypeAliasDeclaration(node);
265
+ if (isErasedType) {
266
+ visitComputedKeysIn(node, visit);
267
+ return;
268
+ }
269
+ const permission = permissionOfReference(node, permissionOfLocal);
270
+ if (permission !== undefined) {
271
+ used.add(permission);
272
+ }
273
+ node.forEachChild(visit);
274
+ };
275
+ sourceFile.forEachChild(visit);
276
+ return used;
277
+ };
278
+
100
279
  const unionMembersOf = (type: Type) =>
101
280
  isUnionType(type)
102
281
  ? typeScriptRequest("read the members of a union", () => type.getTypes())
@@ -180,17 +359,39 @@ export const findUngrantedStdioUses = <OpeningError, OpeningRequirement>(
180
359
  Effect.gen(function* () {
181
360
  const path = yield* Path.Path;
182
361
  const grants = yield* loadedLintConfigIn(path.dirname(projectFile));
362
+ const stdioGrants = grants.flatMap((grant) =>
363
+ grant.allow.filter(isStdioPermission).map((permission) => ({ path: grant.path, permission })),
364
+ );
183
365
  const isGranted = (displayName: string, member: string) => {
184
366
  const permission = PERMISSION_OF_STDIO_MEMBER.get(member);
185
- return grants.some(
186
- (grant) =>
187
- grant.path === displayName &&
188
- permission !== undefined &&
189
- grant.allow.some((allowed) => allowed === permission),
367
+ return stdioGrants.some(
368
+ (grant) => grant.path === displayName && grant.permission === permission,
190
369
  );
191
370
  };
371
+ const usedPermissions = new Map<string, Set<typeof STDIO_PERMISSION.Type>>();
372
+ const recordUse = (
373
+ displayName: string,
374
+ permission: typeof STDIO_PERMISSION.Type | undefined,
375
+ ) => {
376
+ if (permission === undefined) {
377
+ return;
378
+ }
379
+ const used = usedPermissions.get(displayName) ?? new Set<typeof STDIO_PERMISSION.Type>();
380
+ used.add(permission);
381
+ usedPermissions.set(displayName, used);
382
+ };
383
+ const checkedFiles = new Set<string>();
192
384
  const violations: StdioUsesRefused["violations"][number][] = [];
193
385
  for (const { checker, sourceFiles } of yield* openedProjects) {
386
+ for (const { sourceFile, displayName } of sourceFiles) {
387
+ checkedFiles.add(displayName);
388
+ const isGrantedFile = stdioGrants.some((grant) => grant.path === displayName);
389
+ if (isGrantedFile) {
390
+ for (const permission of permissionsUsedOutsideStdioReadsIn(sourceFile)) {
391
+ recordUse(displayName, permission);
392
+ }
393
+ }
394
+ }
194
395
  const reads = sourceFiles.flatMap(({ sourceFile, displayName }) =>
195
396
  possibleStdioReadsIn(sourceFile).map((read) => {
196
397
  const location = nodePosition(sourceFile, read.receiver);
@@ -204,15 +405,32 @@ export const findUngrantedStdioUses = <OpeningError, OpeningRequirement>(
204
405
  const found = yield* Effect.forEach(
205
406
  reads,
206
407
  ({ read, displayName, location }) =>
207
- Effect.map(stdioMembersRead(checker, read), (members) =>
208
- members
209
- .filter((member) => !isGranted(displayName, member))
210
- .map((member) => violationOf(member, location)),
211
- ),
408
+ Effect.map(stdioMembersRead(checker, read), (members) => ({
409
+ displayName,
410
+ location,
411
+ members,
412
+ })),
212
413
  { concurrency: CONCURRENT_TYPESCRIPT_REQUESTS },
213
414
  );
214
- violations.push(...found.flat());
415
+ for (const { displayName, location, members } of found) {
416
+ for (const member of members) {
417
+ recordUse(displayName, PERMISSION_OF_STDIO_MEMBER.get(member));
418
+ if (!isGranted(displayName, member)) {
419
+ violations.push(violationOf(member, location));
420
+ }
421
+ }
422
+ }
215
423
  }
424
+ const unusedGrants = stdioGrants.filter(
425
+ ({ path: grantedPath, permission }) =>
426
+ checkedFiles.has(grantedPath) && usedPermissions.get(grantedPath)?.has(permission) !== true,
427
+ );
428
+ violations.push(
429
+ ...unusedGrants.map(
430
+ ({ path: grantedPath, permission }) =>
431
+ new GrantNothingUses({ location: grantedPath, permission }),
432
+ ),
433
+ );
216
434
  if (violations.length > 0) {
217
435
  return yield* new StdioUsesRefused({ violations });
218
436
  }
@@ -1,5 +1,10 @@
1
1
  import { Schema } from "effect";
2
2
 
3
+ import {
4
+ READS_CONFIG,
5
+ unusedGrantMessage,
6
+ WRITES_TO_THE_TERMINAL,
7
+ } from "../../../../../shared/bans-each-permission-lifts.ts";
3
8
  import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
9
 
5
10
  export class StdioArgumentsReadWithoutGrant extends Schema.TaggedError<StdioArgumentsReadWithoutGrant>()(
@@ -20,9 +25,24 @@ export class StdioTerminalWriteWithoutGrant extends Schema.TaggedError<StdioTerm
20
25
  }
21
26
  }
22
27
 
28
+ export const STDIO_PERMISSION = Schema.Literals([READS_CONFIG, WRITES_TO_THE_TERMINAL]);
29
+
30
+ export class GrantNothingUses extends Schema.TaggedError<GrantNothingUses>()("GrantNothingUses", {
31
+ location: Schema.String,
32
+ permission: STDIO_PERMISSION,
33
+ }) {
34
+ public override get message() {
35
+ return unusedGrantMessage(this.permission);
36
+ }
37
+ }
38
+
23
39
  export class StdioUsesRefused extends Schema.TaggedError<StdioUsesRefused>()("StdioUsesRefused", {
24
40
  violations: Schema.Array(
25
- Schema.Union([StdioArgumentsReadWithoutGrant, StdioTerminalWriteWithoutGrant]),
41
+ Schema.Union([
42
+ StdioArgumentsReadWithoutGrant,
43
+ StdioTerminalWriteWithoutGrant,
44
+ GrantNothingUses,
45
+ ]),
26
46
  ),
27
47
  }) {
28
48
  public override get message() {
@@ -109,6 +109,29 @@ export const CREATE_REQUIRE_VALUE_USAGE = "createRequire used other than by a ca
109
109
 
110
110
  export const TRUSTS_UNVERIFIED_TYPES = "trustsUnverifiedTypes";
111
111
  export const WRITES_TO_THE_TERMINAL = "writesToTheTerminal";
112
+ export const REPLACES_THE_CONSOLE = "replacesTheConsole";
113
+ export const CONSOLE = "console";
114
+ export const CONSOLE_METHODS = [
115
+ "log",
116
+ "warn",
117
+ "error",
118
+ "info",
119
+ "debug",
120
+ "dir",
121
+ "dirxml",
122
+ "table",
123
+ "trace",
124
+ "assert",
125
+ "clear",
126
+ "count",
127
+ "countReset",
128
+ "group",
129
+ "groupCollapsed",
130
+ "groupEnd",
131
+ "time",
132
+ "timeEnd",
133
+ "timeLog",
134
+ ] as const;
112
135
  export const READS_CONFIG = "readsConfig";
113
136
  const LOCKS_FILES = "locksFiles";
114
137
  export const HANDLES_EVERY_FAILURE = "handlesEveryFailure";
@@ -344,7 +367,6 @@ const GRANTABLE_BANS = {
344
367
  "{{usage}} writes to the terminal in a way no file may; write through the Effect Stdio service in a file allowed writesToTheTerminal",
345
368
  bans: [
346
369
  effectMembersBan([["Console"]]),
347
- moduleBan(["node:console"]),
348
370
  globalMembersBan("process", ["stdout", "stderr"]),
349
371
  globalMembersBan("Bun", ["stdout", "stderr"]),
350
372
  ],
@@ -47,13 +47,18 @@ export const GLOBAL_RULES = {
47
47
  } as const satisfies Readonly<Record<string, { readonly globals: readonly string[] }>>;
48
48
 
49
49
  export const NODE_BUILTIN_RULES = {
50
- "no-node-path": { modules: ["path", "path/posix", "path/win32"] },
51
- "no-node-crypto": { modules: ["crypto"] },
52
- "no-node-os": { modules: ["os"] },
53
- "no-node-http": { modules: ["http", "https"] },
54
- "no-node-stream": { modules: ["stream"] },
55
- "no-node-timers": { modules: ["timers", "timers/promises", "perf_hooks"] },
56
- } as const satisfies Readonly<Record<string, { readonly modules: readonly string[] }>>;
50
+ "no-node-path": { modules: ["path", "path/posix", "path/win32"], allowedImports: [] },
51
+ "no-node-crypto": { modules: ["crypto"], allowedImports: [] },
52
+ "no-node-os": { modules: ["os"], allowedImports: ["constants"] },
53
+ "no-node-http": { modules: ["http", "https"], allowedImports: [] },
54
+ "no-node-stream": { modules: ["stream"], allowedImports: [] },
55
+ "no-node-timers": { modules: ["timers", "timers/promises", "perf_hooks"], allowedImports: [] },
56
+ } as const satisfies Readonly<
57
+ Record<
58
+ string,
59
+ { readonly modules: readonly string[]; readonly allowedImports: readonly string[] }
60
+ >
61
+ >;
57
62
 
58
63
  export const SCHEDULE_MESSAGES = {
59
64
  polling: "{{usage}} polls on a timer",
@@ -3,10 +3,12 @@ import { Array as Arrays, Result, Schema, SchemaIssue } from "effect";
3
3
  import {
4
4
  BANS_NO_GRANT_LIFTS,
5
5
  bansNoGrantLifts,
6
+ CONSOLE_METHODS,
6
7
  GRANTABLE_BAN_NAMES,
7
8
  HANDLES_EVERY_FAILURE,
8
9
  PERMISSION_BANS,
9
10
  READS_CONFIG,
11
+ REPLACES_THE_CONSOLE,
10
12
  RULES_EACH_PERMISSION_LIFTS,
11
13
  SHORT_NAMES,
12
14
  TRUSTS_UNVERIFIED_TYPES,
@@ -29,6 +31,9 @@ export const UNNAMED_FALLBACKS_RULE = "no-unnamed-fallbacks";
29
31
  export const FIXED_FALLBACKS = "fallsBackToFixedValues";
30
32
  export const FIXED_FALLBACKS_RULE = "no-fixed-fallbacks";
31
33
  export const FIXED_FALLBACKS_GRANTED = "granted";
34
+ export const NO_CONSOLE_RULE = "eslint/no-console";
35
+ export const NODE_CONSOLE_RULE = "no-node-console";
36
+ export const CONSOLE_REPLACED = "replaced";
32
37
  const SCHEDULES = "pollsWithADeadline";
33
38
  const TIMERS = "waitsOnTimers";
34
39
  export const SCHEDULES_RULE = "no-schedules";
@@ -56,6 +61,7 @@ export const PERMISSION_NAMES = [
56
61
  TRUSTS_UNVERIFIED_TYPES,
57
62
  HANDLES_EVERY_FAILURE,
58
63
  FIXED_FALLBACKS,
64
+ REPLACES_THE_CONSOLE,
59
65
  GENERATED,
60
66
  ] as const;
61
67
 
@@ -87,7 +93,7 @@ const severityOnceGranted = (permission: keyof typeof PERMISSION_BANS) =>
87
93
 
88
94
  const ruleSeverities = (
89
95
  severities: Readonly<
90
- Record<string, readonly ["error", Readonly<Record<string, string>>] | "off">
96
+ Record<string, readonly ["error", Readonly<Record<string, string[] | string>>] | "off">
91
97
  >,
92
98
  ) => Object.entries(severities);
93
99
 
@@ -127,6 +133,12 @@ const rulesGrantedBy = (permission: (typeof PERMISSION_NAMES)[number]) => {
127
133
  [`sshkeda/${FIXED_FALLBACKS_RULE}`]: ["error", { fixedFallbacks: FIXED_FALLBACKS_GRANTED }],
128
134
  } as const);
129
135
  }
136
+ if (permission === REPLACES_THE_CONSOLE) {
137
+ return ruleSeverities({
138
+ [`sshkeda/${NODE_CONSOLE_RULE}`]: ["error", { console: CONSOLE_REPLACED }],
139
+ [NO_CONSOLE_RULE]: ["error", { allow: [...CONSOLE_METHODS] }],
140
+ });
141
+ }
130
142
  if (permission === TRUSTS_UNVERIFIED_TYPES) {
131
143
  return ruleSeverities({
132
144
  [permissionBanRuleId(permission)]: "off",
@@ -152,6 +164,7 @@ export const CODE_GRANTS = [
152
164
  SCHEDULES,
153
165
  SHORT_NAMES,
154
166
  TRUSTS_UNVERIFIED_TYPES,
167
+ REPLACES_THE_CONSOLE,
155
168
  ] as const;
156
169
 
157
170
  const isCodeGrant = Schema.is(Schema.Literals(CODE_GRANTS));