Skip to content

The open alternative to Salesforce, designed for AI.

refactor(oxlint-rules): de-duplicate the two guarded-endpoint rules (#24535)

Félix Malfait342422a4977c
diff --git a/packages/twenty-oxlint-rules/rules/graphql-resolvers-should-be-guarded.ts b/packages/twenty-oxlint-rules/rules/graphql-resolvers-should-be-guarded.ts
index 36f88971907..9d268e9577e 100644
--- a/packages/twenty-oxlint-rules/rules/graphql-resolvers-should-be-guarded.ts
+++ b/packages/twenty-oxlint-rules/rules/graphql-resolvers-should-be-guarded.ts
@@ -1,74 +1,12 @@
-import { defineRule } from '@oxlint/plugins';
-
-import { typedTokenHelpers } from '../utils/typedTokenHelpers';
+import { createGuardedEndpointRule } from '../utils/createGuardedEndpointRule';
export const RULE_NAME = 'graphql-resolvers-should-be-guarded';
-export const graphqlResolversShouldBeGuarded = (node: any) => {
- const hasGraphQLResolverDecorator =
- typedTokenHelpers.nodeHasDecoratorsNamed(node, [
- 'Query',
- 'Mutation',
- 'Subscription',
- ]);
-
- const hasAuthGuards = typedTokenHelpers.nodeHasAuthGuards(node);
- const hasPermissionsGuard =
- typedTokenHelpers.nodeHasPermissionsGuard(node);
-
- const findClassDeclaration = (node: any): any | null => {
- if (node.type === 'ClassDeclaration') return node;
- if (node.parent) return findClassDeclaration(node.parent);
- return null;
- };
-
- const classNode = findClassDeclaration(node);
-
- const hasAuthGuardsOnResolver = classNode
- ? typedTokenHelpers.nodeHasAuthGuards(classNode)
- : false;
-
- const hasPermissionsGuardOnResolver = classNode
- ? typedTokenHelpers.nodeHasPermissionsGuard(classNode)
- : false;
-
- const missingAuthGuard =
- hasGraphQLResolverDecorator &&
- !hasAuthGuards &&
- !hasAuthGuardsOnResolver;
-
- const missingPermissionGuard =
- hasGraphQLResolverDecorator &&
- !hasPermissionsGuard &&
- !hasPermissionsGuardOnResolver;
-
- return missingAuthGuard || missingPermissionGuard;
-};
-
-export const rule = defineRule({
- meta: {
- docs: {
- description:
- 'GraphQL root resolvers (Query, Mutation, Subscription) should have authentication guards (UserAuthGuard or WorkspaceAuthGuard) or be explicitly marked as public (PublicEndpointGuard) and permission guards (SettingsPermissionGuard or CustomPermissionGuard) to maintain our security model.',
- },
- messages: {
- graphqlResolversShouldBeGuarded:
- 'All GraphQL resolvers must have authentication guards (@UseGuards(UserAuthGuard/WorkspaceAuthGuard)) and permission guards (@UseGuards(..., SettingsPermissionGuard(PermissionFlagType.XXX)), CustomPermissionGuard for custom logic, or NoPermissionGuard for special cases like onboarding).',
- },
- schema: [],
- hasSuggestions: false,
- type: 'suggestion',
- },
- create: (context) => {
- return {
- MethodDefinition: (node: any): void => {
- if (graphqlResolversShouldBeGuarded(node)) {
- context.report({
- node: node,
- messageId: 'graphqlResolversShouldBeGuarded',
- });
- }
- },
- };
- },
+export const rule = createGuardedEndpointRule({
+ triggerDecorators: ['Query', 'Mutation', 'Subscription'],
+ messageId: 'graphqlResolversShouldBeGuarded',
+ description:
+ 'GraphQL root resolvers (Query, Mutation, Subscription) should have authentication guards (UserAuthGuard or WorkspaceAuthGuard) or be explicitly marked as public (PublicEndpointGuard) and permission guards (SettingsPermissionGuard or CustomPermissionGuard) to maintain our security model.',
+ message:
+ 'All GraphQL resolvers must have authentication guards (@UseGuards(UserAuthGuard/WorkspaceAuthGuard)) and permission guards (@UseGuards(..., SettingsPermissionGuard(PermissionFlagType.XXX)), CustomPermissionGuard for custom logic, or NoPermissionGuard for special cases like onboarding).',
});
diff --git a/packages/twenty-oxlint-rules/rules/mdx-component-newlines.ts b/packages/twenty-oxlint-rules/rules/mdx-component-newlines.ts
deleted file mode 100644
index 994ac71510f..00000000000
--- a/packages/twenty-oxlint-rules/rules/mdx-component-newlines.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { defineRule } from '@oxlint/plugins';
-
-export const RULE_NAME = 'mdx-component-newlines';
-
-export const rule = defineRule({
- meta: {
- type: 'layout',
- docs: {
- description:
- 'Enforce JSX/HTML component tags are on separate lines in MDX files to prevent Crowdin translation issues',
- },
- fixable: 'whitespace',
- messages: {
- tagOnSameLine:
- 'JSX/HTML tag should be on its own line. This prevents Crowdin from merging tags with content during translation.',
- },
- schema: [],
- },
-
- create: (context) => {
- const sourceCode = context.sourceCode || (context as any).getSourceCode();
-
- return {
- JSXOpeningElement: (node: any) => {
- const tokenAfter = sourceCode.getTokenAfter(node as any);
-
- if (!tokenAfter) {
- return;
- }
-
- if (node.loc.end.line === tokenAfter.loc.start.line) {
- const nextNode = (sourceCode as any).getNodeByRangeIndex?.(
- tokenAfter.range[0],
- );
- if (nextNode?.type === 'JSXClosingElement') {
- return;
- }
-
- const textBetween = sourceCode.text.slice(
- node.range[1],
- tokenAfter.range[0],
- );
- if (textBetween.trim() === '') {
- return;
- }
-
- context.report({
- node: node as any,
- messageId: 'tagOnSameLine',
- fix: (fixer) => fixer.insertTextAfter(node as any, '\n'),
- });
- }
- },
-
- JSXClosingElement: (node: any) => {
- const tokenBefore = sourceCode.getTokenBefore(node as any);
-
- if (!tokenBefore) {
- return;
- }
-
- if (node.loc.start.line === tokenBefore.loc.end.line) {
- const prevNode = (sourceCode as any).getNodeByRangeIndex?.(
- tokenBefore.range[0],
- );
- if (prevNode?.type === 'JSXOpeningElement') {
- return;
- }
-
- const textBetween = sourceCode.text.slice(
- tokenBefore.range[1],
- node.range[0],
- );
-
- if (
- textBetween.trim() !== '' ||
- tokenBefore.type === 'Punctuator'
- ) {
- context.report({
- node: node as any,
- messageId: 'tagOnSameLine',
- fix: (fixer) =>
- fixer.insertTextBefore(node as any, '\n'),
- });
- }
- }
- },
- };
- },
-});
diff --git a/packages/twenty-oxlint-rules/rules/no-angle-bracket-placeholders.ts b/packages/twenty-oxlint-rules/rules/no-angle-bracket-placeholders.ts
deleted file mode 100644
index 3b2c43093b9..00000000000
--- a/packages/twenty-oxlint-rules/rules/no-angle-bracket-placeholders.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { defineRule } from '@oxlint/plugins';
-
-export const RULE_NAME = 'no-angle-bracket-placeholders';
-
-const ALLOWED_TAGS = [
- 'img',
- 'div',
- 'span',
- 'p',
- 'a',
- 'b',
- 'strong',
- 'em',
- 'i',
- 'code',
- 'pre',
- 'br',
- 'hr',
- 'ul',
- 'ol',
- 'li',
- 'h1',
- 'h2',
- 'h3',
- 'h4',
- 'h5',
- 'h6',
- 'input',
- 'button',
- 'summary',
- 'details',
- 'Frame',
- 'Warning',
- 'Tip',
- 'Info',
- 'Note',
- 'Card',
- 'Step',
- 'Tab',
- 'Tabs',
- 'ArticleTab',
- 'ArticleTabs',
- 'Accordion',
- 'AccordionGroup',
- 'Router',
- 'BrowserRouter',
-];
-
-export const rule = defineRule({
- meta: {
- type: 'problem',
- docs: {
- description:
- 'Disallow angle bracket placeholders in MDX files to prevent Crowdin translation errors. Use curly braces {placeholder} instead.',
- },
- messages: {
- noAngleBracketPlaceholder:
- 'Avoid angle bracket placeholders like "<{{name}}>" in documentation. Use curly braces "{{{name}}}" instead to prevent Crowdin translation errors.',
- },
- schema: [],
- fixable: 'code',
- },
-
- create: (context) => {
- const sourceCode = context.sourceCode || (context as any).getSourceCode();
- const filename = context.filename || (context as any).getFilename();
-
- if (!filename.endsWith('.mdx')) {
- return {};
- }
-
- const isInsideCodeBlock = (
- position: number,
- text: string,
- ): boolean => {
- const codeBlockRanges: { start: number; end: number }[] = [];
- let searchStart = 0;
-
- while (true) {
- const openIndex = text.indexOf('```', searchStart);
- if (openIndex === -1) {
- break;
- }
-
- const closeIndex = text.indexOf('```', openIndex + 3);
- if (closeIndex === -1) {
- break;
- }
-
- codeBlockRanges.push({
- start: openIndex,
- end: closeIndex + 3,
- });
-
- searchStart = closeIndex + 3;
- }
-
- for (const range of codeBlockRanges) {
- if (position >= range.start && position < range.end) {
- return true;
- }
- }
-
- const beforeText = text.substring(0, position);
- let inlineBacktickCount = 0;
-
- for (let i = 0; i < beforeText.length; i++) {
- let insideFencedBlock = false;
- for (const range of codeBlockRanges) {
- if (i >= range.start && i < range.end) {
- insideFencedBlock = true;
- break;
- }
- }
-
- if (!insideFencedBlock && beforeText[i] === '`') {
- inlineBacktickCount++;
- }
- }
-
- return inlineBacktickCount % 2 !== 0;
- };
-
- return {
- Program: (node: any) => {
- const text = sourceCode.getText();
-
- const urlPlaceholderRegex =
- /(https?:\/\/)<([a-z][a-z0-9_-]+)>/g;
- let urlMatch;
- const foundPositions = new Set();
-
- while (
- (urlMatch = urlPlaceholderRegex.exec(text)) !== null
- ) {
- const tagName = urlMatch[2];
- const startPos =
- urlMatch.index + urlMatch[1].length;
- const endPos = startPos + tagName.length + 2;
-
- foundPositions.add(startPos);
-
- if (isInsideCodeBlock(startPos, text)) {
- continue;
- }
-
- context.report({
- node: node as any,
- loc: {
- start: sourceCode.getLocFromIndex(startPos),
- end: sourceCode.getLocFromIndex(endPos),
- },
- messageId: 'noAngleBracketPlaceholder',
- data: {
- name: tagName,
- },
- });
- }
-
- const placeholderRegex = /<([a-z][a-z0-9_-]+)>/g;
- let match;
-
- while ((match = placeholderRegex.exec(text)) !== null) {
- const tagName = match[1];
- const startPos = match.index;
-
- if (foundPositions.has(startPos)) {
- continue;
- }
-
- if (ALLOWED_TAGS.includes(tagName)) {
- continue;
- }
-
- const beforeMatch = text.charAt(match.index - 1);
- if (beforeMatch === '/') {
- continue;
- }
-
- const endPos = startPos + match[0].length;
-
- if (isInsideCodeBlock(startPos, text)) {
- continue;
- }
-
- context.report({
- node: node as any,
- loc: {
- start: sourceCode.getLocFromIndex(startPos),
- end: sourceCode.getLocFromIndex(endPos),
- },
- messageId: 'noAngleBracketPlaceholder',
- data: {
- name: tagName,
- },
- });
- }
- },
- };
- },
-});
diff --git a/packages/twenty-oxlint-rules/rules/plugin-registry.spec.ts b/packages/twenty-oxlint-rules/rules/plugin-registry.spec.ts
new file mode 100644
index 00000000000..bc03b4b9339
--- /dev/null
+++ b/packages/twenty-oxlint-rules/rules/plugin-registry.spec.ts
@@ -0,0 +1,33 @@
+import { readdirSync } from 'node:fs';
+import { join } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import plugin from '../oxlint-plugin';
+
+const RULES_DIRECTORY = join(import.meta.dirname, '.');
+
+const getRuleModuleFileNames = () =>
+ readdirSync(RULES_DIRECTORY).filter(
+ (fileName) => fileName.endsWith('.ts') && !fileName.endsWith('.spec.ts'),
+ );
+
+describe('oxlint plugin registry', () => {
+ it('registers every rule module', async () => {
+ const unregistered: string[] = [];
+
+ for (const fileName of getRuleModuleFileNames()) {
+ const module = await import(join(RULES_DIRECTORY, fileName));
+
+ if (module.RULE_NAME === undefined) {
+ continue;
+ }
+
+ if (plugin.rules[module.RULE_NAME] === undefined) {
+ unregistered.push(`${fileName} (${module.RULE_NAME})`);
+ }
+ }
+
+ expect(unregistered).toEqual([]);
+ });
+});
diff --git a/packages/twenty-oxlint-rules/rules/rest-api-methods-should-be-guarded.ts b/packages/twenty-oxlint-rules/rules/rest-api-methods-should-be-guarded.ts
index 2b98255879e..7e88ded30a7 100644
--- a/packages/twenty-oxlint-rules/rules/rest-api-methods-should-be-guarded.ts
+++ b/packages/twenty-oxlint-rules/rules/rest-api-methods-should-be-guarded.ts
@@ -1,79 +1,21 @@
-import { defineRule } from '@oxlint/plugins';
-
-import { typedTokenHelpers } from '../utils/typedTokenHelpers';
+import { createGuardedEndpointRule } from '../utils/createGuardedEndpointRule';
export const RULE_NAME = 'rest-api-methods-should-be-guarded';
-export const restApiMethodsShouldBeGuarded = (node: any) => {
- const hasRestApiMethodDecorator =
- typedTokenHelpers.nodeHasDecoratorsNamed(node, [
- 'Get',
- 'Post',
- 'Put',
- 'Delete',
- 'Patch',
- 'Options',
- 'Head',
- 'All',
- ]);
-
- const hasAuthGuards = typedTokenHelpers.nodeHasAuthGuards(node);
- const hasPermissionsGuard =
- typedTokenHelpers.nodeHasPermissionsGuard(node);
-
- const findClassDeclaration = (node: any): any | null => {
- if (node.type === 'ClassDeclaration') return node;
- if (node.parent) return findClassDeclaration(node.parent);
- return null;
- };
-
- const classNode = findClassDeclaration(node);
-
- const hasAuthGuardsOnController = classNode
- ? typedTokenHelpers.nodeHasAuthGuards(classNode)
- : false;
-
- const hasPermissionsGuardOnController = classNode
- ? typedTokenHelpers.nodeHasPermissionsGuard(classNode)
- : false;
-
- const missingAuthGuard =
- hasRestApiMethodDecorator &&
- !hasAuthGuards &&
- !hasAuthGuardsOnController;
-
- const missingPermissionGuard =
- hasRestApiMethodDecorator &&
- !hasPermissionsGuard &&
- !hasPermissionsGuardOnController;
-
- return missingAuthGuard || missingPermissionGuard;
-};
-
-export const rule = defineRule({
- meta: {
- docs: {
- description:
- 'REST API endpoints should have authentication guards (UserAuthGuard, WorkspaceAuthGuard, FilePathGuard, FileByIdGuard, FileUploadTokenGuard) or be explicitly marked as public (PublicEndpointGuard) and permission guards (SettingsPermissionGuard or CustomPermissionGuard) to maintain our security model.',
- },
- messages: {
- restApiMethodsShouldBeGuarded:
- 'All REST API controller endpoints must have authentication guards (@UseGuards(...)) and permission guards (@UseGuards(..., SettingsPermissionGuard(...)), CustomPermissionGuard, or NoPermissionGuard).',
- },
- schema: [],
- hasSuggestions: false,
- type: 'suggestion',
- },
- create: (context) => {
- return {
- MethodDefinition: (node: any): void => {
- if (restApiMethodsShouldBeGuarded(node)) {
- context.report({
- node: node,
- messageId: 'restApiMethodsShouldBeGuarded',
- });
- }
- },
- };
- },
+export const rule = createGuardedEndpointRule({
+ triggerDecorators: [
+ 'Get',
+ 'Post',
+ 'Put',
+ 'Delete',
+ 'Patch',
+ 'Options',
+ 'Head',
+ 'All',
+ ],
+ messageId: 'restApiMethodsShouldBeGuarded',
+ description:
+ 'REST API endpoints should have authentication guards (UserAuthGuard, WorkspaceAuthGuard, FilePathGuard, FileByIdGuard, FileUploadTokenGuard) or be explicitly marked as public (PublicEndpointGuard) and permission guards (SettingsPermissionGuard or CustomPermissionGuard) to maintain our security model.',
+ message:
+ 'All REST API controller endpoints must have authentication guards (@UseGuards(...)) and permission guards (@UseGuards(..., SettingsPermissionGuard(...)), CustomPermissionGuard, or NoPermissionGuard).',
});
diff --git a/packages/twenty-oxlint-rules/utils/createGuardedEndpointRule.ts b/packages/twenty-oxlint-rules/utils/createGuardedEndpointRule.ts
new file mode 100644
index 00000000000..13652085380
--- /dev/null
+++ b/packages/twenty-oxlint-rules/utils/createGuardedEndpointRule.ts
@@ -0,0 +1,63 @@
+import { defineRule } from '@oxlint/plugins';
+
+import { typedTokenHelpers } from './typedTokenHelpers';
+
+type GuardedEndpointRuleOptions = {
+ triggerDecorators: string[];
+ messageId: string;
+ description: string;
+ message: string;
+};
+
+const findClassDeclaration = (node: any): any | null => {
+ if (node.type === 'ClassDeclaration') return node;
+ if (node.parent) return findClassDeclaration(node.parent);
+
+ return null;
+};
+
+const isMissingGuards = (node: any, triggerDecorators: string[]) => {
+ const hasTriggerDecorator = typedTokenHelpers.nodeHasDecoratorsNamed(
+ node,
+ triggerDecorators,
+ );
+
+ const classNode = findClassDeclaration(node);
+
+ const missingAuthGuard =
+ hasTriggerDecorator &&
+ !typedTokenHelpers.nodeHasAuthGuards(node) &&
+ !(classNode ? typedTokenHelpers.nodeHasAuthGuards(classNode) : false);
+
+ const missingPermissionGuard =
+ hasTriggerDecorator &&
+ !typedTokenHelpers.nodeHasPermissionsGuard(node) &&
+ !(classNode ? typedTokenHelpers.nodeHasPermissionsGuard(classNode) : false);
+
+ return missingAuthGuard || missingPermissionGuard;
+};
+
+export const createGuardedEndpointRule = ({
+ triggerDecorators,
+ messageId,
+ description,
+ message,
+}: GuardedEndpointRuleOptions) =>
+ defineRule({
+ meta: {
+ docs: { description },
+ messages: { [messageId]: message },
+ schema: [],
+ hasSuggestions: false,
+ type: 'suggestion',
+ },
+ create: (context) => {
+ return {
+ MethodDefinition: (node: any): void => {
+ if (isMissingGuards(node, triggerDecorators)) {
+ context.report({ node, messageId });
+ }
+ },
+ };
+ },
+ });