1 import * as path from "path"
2 import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils"
3 import { createRule } from "../../create-rule"
4 import { isUnderApiDir } from "../../util/api-route"
5
6 type MessageIds = "noMutation"
7 type Options = [
8 {
9 allowedMutations?: string[]
10 additionalMutationPrefixes?: string[]
11 }?
12 ]
13
14 const HTTP_METHODS = new Set([
15 "GET",
16 "POST",
17 "PUT",
18 "PATCH",
19 "DELETE",
20 "OPTIONS",
21 "HEAD",
22 ])
23
24 const ROUTE_FILE_BASENAMES = new Set(["route.ts", "route.tsx", "route.js"])
25
26 const DEFAULT_MUTATION_PREFIXES = [
27 "create",
28 "update",
29 "delete",
30 "softDelete",
31 "restore",
32 "upsert",
33 "archive",
34 "cancel",
35 "complete",
36 "capture",
37 "refund",
38 "authorize",
39 "void",
40 "add",
41 "remove",
42 "attach",
43 "detach",
44 "set",
45 "reset",
46 "generate",
47 "issue",
48 "revoke",
49 ]
50
51 function buildMutationRegex(prefixes: string[]): RegExp {
52 return new RegExp(`^(?:${prefixes.join("|")})(?:[A-Z_].*)?$`)
53 }
54
55 function isResolveCallee(callee: TSESTree.Node): boolean {
56 return (
57 callee.type === AST_NODE_TYPES.MemberExpression &&
58 !callee.computed &&
59 callee.property.type === AST_NODE_TYPES.Identifier &&
60 callee.property.name === "resolve"
61 )
62 }
63
64 function getHandlerFunctions(
65 node: TSESTree.ExportNamedDeclaration
66 ): TSESTree.Node[] {
67 const out: TSESTree.Node[] = []
68 const decl = node.declaration
69 if (!decl) {
70 return out
71 }
72 if (decl.type === AST_NODE_TYPES.VariableDeclaration) {
73 for (const d of decl.declarations) {
74 if (
75 d.id.type === AST_NODE_TYPES.Identifier &&
76 HTTP_METHODS.has(d.id.name) &&
77 d.init &&
78 (d.init.type === AST_NODE_TYPES.ArrowFunctionExpression ||
79 d.init.type === AST_NODE_TYPES.FunctionExpression)
80 ) {
81 out.push(d.init)
82 }
83 }
84 } else if (
85 decl.type === AST_NODE_TYPES.FunctionDeclaration &&
86 decl.id &&
87 HTTP_METHODS.has(decl.id.name)
88 ) {
89 out.push(decl)
90 }
91 return out
92 }
93
94 function walk(node: TSESTree.Node, visit: (n: TSESTree.Node) => void): void {
95 visit(node)
96 for (const key of Object.keys(node) as Array<keyof typeof node>) {
97 if (key === "parent") {
98 continue
99 }
100 const value = (node as unknown as Record<string, unknown>)[key as string]
101 if (!value) {
102 continue
103 }
104 if (Array.isArray(value)) {
105 for (const child of value) {
106 if (child && typeof child === "object" && "type" in child) {
107 walk(child as TSESTree.Node, visit)
108 }
109 }
110 } else if (typeof value === "object" && "type" in (value as object)) {
111 walk(value as TSESTree.Node, visit)
112 }
113 }
114 }
115
116 export const rule = createRule<Options, MessageIds>({
117 name: "no-service-mutations-in-api-route",
118 meta: {
119 type: "suggestion",
120 docs: {
121 description:
122 "Don't call service mutation methods directly from API route handlers; use a workflow instead.",
123 },
124 messages: {
125 noMutation:
126 "Avoid calling `{{service}}.{{method}}(...)` directly in an API route handler. Move the mutation into a workflow step and invoke it via `someWorkflow(req.scope).run({ input })`.",
127 },
128 schema: [
129 {
130 type: "object",
131 additionalProperties: false,
132 properties: {
133 allowedMutations: {
134 type: "array",
135 items: { type: "string" },
136 },
137 additionalMutationPrefixes: {
138 type: "array",
139 items: { type: "string" },
140 },
141 },
142 },
143 ],
144 },
145 defaultOptions: [{}],
146 create(context, [options]) {
147 const filename = context.filename
148 if (!filename || filename.startsWith("<")) {
149 return {}
150 }
151 if (!isUnderApiDir(filename)) {
152 return {}
153 }
154 if (!ROUTE_FILE_BASENAMES.has(path.basename(filename))) {
155 return {}
156 }
157
158 const allowed = new Set(options?.allowedMutations ?? [])
159 const mutationRegex = buildMutationRegex([
160 ...DEFAULT_MUTATION_PREFIXES,
161 ...(options?.additionalMutationPrefixes ?? []),
162 ])
163
164 const handlerFns: TSESTree.Node[] = []
165
166 return {
167 ExportNamedDeclaration(node) {
168 for (const fn of getHandlerFunctions(node)) {
169 handlerFns.push(fn)
170 }
171 },
172 "Program:exit"() {
173 for (const fn of handlerFns) {
174 const body = (fn as TSESTree.FunctionLike).body
175 if (!body) {
176 continue
177 }
178 const tracked = new Set<string>()
179
180 walk(body as TSESTree.Node, (n) => {
181 if (
182 n.type !== AST_NODE_TYPES.VariableDeclarator ||
183 n.id.type !== AST_NODE_TYPES.Identifier ||
184 !n.init
185 ) {
186 return
187 }
188 // Unwrap `await ...` to support `const x = await scope.resolve(...)`
189 // (resolve() is sync, but users sometimes await it.)
190 let init: TSESTree.Node = n.init
191 if (init.type === AST_NODE_TYPES.AwaitExpression) {
192 init = init.argument
193 }
194 if (
195 init.type !== AST_NODE_TYPES.CallExpression ||
196 !isResolveCallee(init.callee)
197 ) {
198 return
199 }
200 tracked.add(n.id.name)
201 })
202
203 if (tracked.size === 0) {
204 continue
205 }
206
207 walk(body as TSESTree.Node, (n) => {
208 if (n.type !== AST_NODE_TYPES.CallExpression) {
209 return
210 }
211 const callee = n.callee
212 if (
213 callee.type !== AST_NODE_TYPES.MemberExpression ||
214 callee.computed ||
215 callee.object.type !== AST_NODE_TYPES.Identifier ||
216 callee.property.type !== AST_NODE_TYPES.Identifier
217 ) {
218 return
219 }
220 if (!tracked.has(callee.object.name)) {
221 return
222 }
223 const method = callee.property.name
224 if (allowed.has(method)) {
225 return
226 }
227 if (!mutationRegex.test(method)) {
228 return
229 }
230 context.report({
231 node: callee,
232 messageId: "noMutation",
233 data: {
234 service: callee.object.name,
235 method,
236 },
237 })
238 })
239 }
240 },
241 }
242 },
243 })
244
245 export default rule