routeguard-cli 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Keerti Deshpande
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # routeguard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Find broken authorisation in Express APIs before attackers do.**
4
+
5
+ routeguard reads your Express code without running it. It maps every route to the checks that protect
6
+ it, then flags the [OWASP API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x11-t10/)
7
+ risks that general code scanners miss. The biggest of these is one user reaching another user's data.
8
+
9
+ ```
10
+ $ routeguard ./my-api
11
+
12
+ METHOD PATH MIDDLEWARE AUTH ROLE WHERE
13
+ GET /api/orders/:id auth ✅ ❌ routes/orders.js:12
14
+ DELETE /api/users/:id auth, admin ✅ ✅ routes/users.js:40
15
+ ...
16
+
17
+ [HIGH] BOLA GET /api/orders/:id (services/order.service.js:18)
18
+ API1:2023 Broken Object Level Authorization
19
+ findById via getOrder uses an id from the URL, and nothing on the way checks it against the caller.
20
+ Fix: scope the query to the caller: findOne({ _id: id, owner: req.user._id }).
21
+ ```
22
+
23
+ ## Why
24
+
25
+ Tools like Semgrep and Bearer are good at injection and secrets. Authorisation bugs are different:
26
+ the code looks fine line by line, and the flaw is a check that is *missing*. On a deliberately
27
+ vulnerable API, Semgrep found 1 of 9 bugs and Bearer found none ([benchmark](https://github.com/12keerti21/routeguard/blob/main/benchmark.md)).
28
+
29
+ ## What it checks
30
+
31
+ | OWASP API 2023 | Check |
32
+ |---|---|
33
+ | API1 Broken Object Level Authorization | A record is loaded or changed by a URL id, and nothing on the way checks it belongs to the caller. Follows the id into service functions. |
34
+ | API2 Broken Authentication | JWT algorithm confusion, `alg: none`, ignored expiry, signing keys in the code |
35
+ | API3 Broken Object Property Level Authorization | Whole request bodies written to records (`new User(req.body)`), `isAdmin` taken from the client, whole user records sent back |
36
+ | API4 Unrestricted Resource Consumption | Login, OTP, reset and sign-up routes with no rate limit |
37
+ | API5 Broken Function Level Authorization | Admin, debug, metrics and log routes with no role check; shared data any user can change |
38
+ | API6 Unrestricted Access to Sensitive Business Flows | Checkout, coupon, booking and review flows with nothing against bots |
39
+ | API7 Server Side Request Forgery | The server fetches a URL the client chose |
40
+ | API8 Security Misconfiguration | CORS open to any origin with credentials, stack traces in responses, missing security headers |
41
+ | API9 Improper Inventory Management | Old or development copies of an endpoint with weaker checks, routes missing from the OpenAPI spec |
42
+ | API10 Unsafe Consumption of APIs | Third-party responses stored, run or redirected to without validation; plain-http calls; API keys in URLs |
43
+
44
+ ## Use it
45
+
46
+ ```bash
47
+ npx routeguard-cli <path-to-express-app>
48
+ ```
49
+
50
+ Or install it with `npm install -g routeguard-cli` and run `routeguard`. From a clone of this repo:
51
+
52
+ ```bash
53
+ cd tool && npm install
54
+ node bin/cli.js <path-to-express-app> # table and findings
55
+ node bin/cli.js <path-to-express-app> --json # machine-readable
56
+ node bin/cli.js <path-to-express-app> --sarif # for GitHub code scanning
57
+ node bin/cli.js <path-to-express-app> --fail-on HIGH # exit 2 only on HIGH findings
58
+ ```
59
+
60
+ Requires Node 20 or later. Works with JavaScript and TypeScript, `require` and `import`, monorepos and
61
+ package.json `#imports`.
62
+
63
+ ### In GitHub Actions
64
+
65
+ ```yaml
66
+ name: routeguard
67
+ on: [pull_request]
68
+ permissions:
69
+ contents: read
70
+ security-events: write
71
+ jobs:
72
+ scan:
73
+ runs-on: ubuntu-latest
74
+ steps:
75
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
76
+ with:
77
+ persist-credentials: false
78
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
79
+ with:
80
+ node-version: 20
81
+ - id: routeguard
82
+ uses: 12keerti21/routeguard@v1
83
+ with:
84
+ path: .
85
+ fail-on: HIGH
86
+ - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
87
+ if: always()
88
+ with:
89
+ sarif_file: ${{ steps.routeguard.outputs.sarif-file }}
90
+ ```
91
+
92
+ Findings appear on the pull request and under **Security → Code scanning**.
93
+
94
+ ### Silence a reviewed finding
95
+
96
+ Put a comment in the three lines above the route:
97
+
98
+ ```js
99
+ // the share id is unguessable and is the key
100
+ // routeguard-ignore BOLA
101
+ router.get("/shared/:shareId", getSharedNote)
102
+ ```
103
+
104
+ Leave out the rule name to silence every rule for that route.
105
+
106
+ ## How it works
107
+
108
+ 1. **Map the routes.** Parses every source file and follows `app.use` and `router.use` mounts, so each
109
+ route gets its full path and every middleware in front of it, including middleware applied to a
110
+ whole path or router.
111
+ 2. **Read the handlers.** Finds each route's handler, even in another file, a controller object or a
112
+ wrapper like `catchAsync(...)`.
113
+ 3. **Follow the data.** For object-level checks, traces the URL id from the handler into the
114
+ services it calls. It looks for the caller (`req.user`) limiting that id along the way: in the
115
+ query, in a comparison, or in a check such as `canEdit(user, course)`.
116
+ 4. **Report.** Each finding has a severity, the OWASP category, the file and line, and a fix.
117
+
118
+ ## Limits
119
+
120
+ - routeguard trusts what a check returns. If `canEdit()` itself has a logic bug, it won't see it.
121
+ - Static analysis cannot know an id is unguessable. Capability links need a `routeguard-ignore` comment.
122
+ - Express only for now.
123
+
124
+ ## Results
125
+
126
+ Tested on deliberately vulnerable APIs and 14 open-source Express apps (1,400+ routes). See
127
+ [benchmark.md](https://github.com/12keerti21/routeguard/blob/main/benchmark.md).
128
+
129
+ ## Development
130
+
131
+ ```bash
132
+ cd tool && npm test
133
+ ```
134
+
135
+ Tests run every check against a small fixture app that has a vulnerable and a safe version of each
136
+ pattern.
package/bin/cli.js ADDED
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs"
3
+ import path from "node:path"
4
+ import { mapRoutes } from "../src/mapper.js"
5
+ import { toSarif } from "../src/sarif.js"
6
+ import { bola } from "../src/rules/bola.js"
7
+ import { bfla } from "../src/rules/bfla.js"
8
+ import { massAssignment } from "../src/rules/massAssignment.js"
9
+ import { ssrf } from "../src/rules/ssrf.js"
10
+ import { rateLimit } from "../src/rules/rateLimit.js"
11
+ import { dataExposure } from "../src/rules/dataExposure.js"
12
+ import { misconfig } from "../src/rules/misconfig.js"
13
+ import { inventory } from "../src/rules/inventory.js"
14
+ import { businessFlow } from "../src/rules/businessFlow.js"
15
+ import { consumption } from "../src/rules/consumption.js"
16
+
17
+ const RULES = [bola, bfla, massAssignment, dataExposure, ssrf, rateLimit, businessFlow]
18
+
19
+ const SEVERITIES = ["LOW", "MEDIUM", "HIGH"]
20
+
21
+ const args = process.argv.slice(2)
22
+ const option = name => {
23
+ const i = args.indexOf(name)
24
+ return i === -1 ? null : args[i + 1]
25
+ }
26
+ const json = args.includes("--json")
27
+ const sarif = args.includes("--sarif")
28
+ // --fail-on HIGH: exit 2 only for findings at or above that severity (default LOW: any finding)
29
+ const failOn = (option("--fail-on") ?? "LOW").toUpperCase()
30
+ const target = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--fail-on")
31
+
32
+ if (!target || !SEVERITIES.includes(failOn)) {
33
+ console.error("Usage: routeguard <express-project-dir> [--json | --sarif] [--fail-on LOW|MEDIUM|HIGH]")
34
+ process.exit(1)
35
+ }
36
+
37
+ const routes = mapRoutes(path.resolve(target))
38
+ const suppressed = (route, finding) => route.ignored === "all" || route.ignored?.has(finding.rule)
39
+ // a router mounted twice reports the same code twice
40
+ const seen = new Set()
41
+ const root = path.resolve(target)
42
+ const findings = [
43
+ ...routes.flatMap(r => RULES.map(rule => rule(r)).filter(f => f && !suppressed(r, f))),
44
+ // checks that look at the app as a whole, not one route
45
+ ...inventory(routes, root),
46
+ ...misconfig(root),
47
+ ...consumption(root)
48
+ ].filter(f => !seen.has(`${f.rule} ${f.route} ${f.where}`) && seen.add(`${f.rule} ${f.route} ${f.where}`))
49
+
50
+ const exitCode = findings.some(f => SEVERITIES.indexOf(f.severity) >= SEVERITIES.indexOf(failOn)) ? 2 : 0
51
+
52
+ if (json) {
53
+ console.log(JSON.stringify({ routes, findings }, null, 2))
54
+ process.exit(exitCode)
55
+ }
56
+
57
+ if (sarif) {
58
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
59
+ console.log(JSON.stringify(toSarif(findings, version), null, 2))
60
+ process.exit(exitCode)
61
+ }
62
+
63
+ const mark = ok => (ok ? "✅" : "❌")
64
+ const rows = routes.map(r => [
65
+ r.method,
66
+ r.path,
67
+ r.middleware.join(", ") || "-",
68
+ mark(r.auth),
69
+ mark(r.role),
70
+ `${r.file}:${r.line}`
71
+ ])
72
+ const header = ["METHOD", "PATH", "MIDDLEWARE", "AUTH", "ROLE", "WHERE"]
73
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)))
74
+ const line = cells => cells.map((c, i) => c.padEnd(widths[i])).join(" ")
75
+
76
+ console.log(line(header))
77
+ console.log(widths.map(w => "-".repeat(w)).join(" "))
78
+ rows.forEach(r => console.log(line(r)))
79
+
80
+ const noAuth = routes.filter(r => !r.auth).length
81
+ console.log(`\n${routes.length} routes · ${noAuth} without an auth check · ${routes.filter(r => !r.role).length} without a role check`)
82
+
83
+ console.log(`\nFINDINGS (${findings.length})\n`)
84
+ for (const f of findings) {
85
+ console.log(`[${f.severity}] ${f.rule} ${f.route} (${f.where})`)
86
+ console.log(` ${f.owasp}`)
87
+ console.log(` ${f.message}`)
88
+ console.log(` Fix: ${f.fix}\n`)
89
+ }
90
+ process.exit(exitCode)
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "routeguard-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Find broken authorisation in Express APIs: maps routes to their checks and flags the OWASP API Security Top 10",
5
+ "type": "module",
6
+ "bin": {
7
+ "routeguard": "bin/cli.js"
8
+ },
9
+ "scripts": {
10
+ "map": "node bin/cli.js",
11
+ "test": "node --test test/*.test.js",
12
+ "prepack": "cp ../README.md ../LICENSE ."
13
+ },
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "license": "MIT",
18
+ "dependencies": {
19
+ "@babel/parser": "^7.29.15"
20
+ },
21
+ "keywords": [
22
+ "security",
23
+ "owasp",
24
+ "api-security",
25
+ "express",
26
+ "authorization",
27
+ "bola",
28
+ "sast",
29
+ "static-analysis"
30
+ ],
31
+ "author": "Keerti Deshpande",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/12keerti21/routeguard.git",
35
+ "directory": "tool"
36
+ },
37
+ "homepage": "https://github.com/12keerti21/routeguard#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/12keerti21/routeguard/issues"
40
+ },
41
+ "files": [
42
+ "bin",
43
+ "src",
44
+ "README.md",
45
+ "LICENSE"
46
+ ]
47
+ }
package/src/flow.js ADDED
@@ -0,0 +1,217 @@
1
+ import { walk, isCallNode, isMemberNode } from "./mapper.js"
2
+ import { DB_CALL, DB_WRITE, handlerParams, isMember } from "./rules/handler.js"
3
+
4
+ // a call that takes the caller and decides: canEdit(user, course), assertCourseReach(user, id), findOwnedCourse(id, user)
5
+ const CHECK_FN = /can[A-Z_]|check|assert|ensure|reach|access|permi(t|ssion)|authori[sz]|verify|owned|own[A-Z]|allowed|guard|scope/i
6
+ // an unresolved call that looks like it loads a record: userService.getUserById(id)
7
+ const SERVICE_LOOKUP = /^(get|find|fetch|load|read|update|edit|patch|delete|remove|destroy|archive)[A-Z_]/
8
+ const IDENTITY_KEYS = new Set(["user", "auth", "session", "userId", "currentUser"])
9
+ const IDENTITY_FN = /user|auth|jwt|token|session|identity|principal|caller/i
10
+ const APPENDS_USER = /(append|set|attach|inject|add)_?user/i
11
+ const BODY_USER_FIELD = /^(user_?id|owner_?id|owner)$/i
12
+ const MAX_DEPTH = 4
13
+ // a record created for the caller: comment.create({ author: user.id })
14
+ const CREATE = /^(create|insert|insertOne|insertMany|save|build|bulkCreate)$/
15
+ const SERVICE_WRITE = /^(update|edit|patch|delete|remove|destroy|archive)[A-Z_]/
16
+
17
+ // identifiers a node reads, skipping property names: in course.user, "user" is not a variable
18
+ function identifiers(node, out = []) {
19
+ if (!node || typeof node.type !== "string") return out
20
+ if (node.type === "Identifier") {
21
+ out.push(node.name)
22
+ return out
23
+ }
24
+ if (isMemberNode(node)) {
25
+ identifiers(node.object, out)
26
+ if (node.computed) identifiers(node.property, out)
27
+ return out
28
+ }
29
+ if (node.type === "ObjectProperty") {
30
+ if (node.computed) identifiers(node.key, out)
31
+ identifiers(node.value, out)
32
+ return out
33
+ }
34
+ for (const key of Object.keys(node)) {
35
+ if (key === "loc" || key === "start" || key === "end") continue
36
+ const child = node[key]
37
+ if (Array.isArray(child)) child.forEach(c => identifiers(c, out))
38
+ else if (child && typeof child.type === "string") identifiers(child, out)
39
+ }
40
+ return out
41
+ }
42
+
43
+ function boundNames(id) {
44
+ if (!id) return []
45
+ if (id.type === "Identifier") return [id.name]
46
+ if (id.type === "AssignmentPattern") return boundNames(id.left)
47
+ if (id.type === "RestElement") return boundNames(id.argument)
48
+ if (id.type === "ObjectPattern") return id.properties.flatMap(p => boundNames(p.value ?? p.argument))
49
+ if (id.type === "ArrayPattern") return id.elements.flatMap(boundNames)
50
+ return []
51
+ }
52
+
53
+ const isFunction = node => ["ArrowFunctionExpression", "FunctionExpression"].includes(node?.type)
54
+
55
+ // solveIf(() => user.bid != id): a callback is code, not a value; its body is read where it is written
56
+ const valueArgs = call => call.arguments.filter(a => !isFunction(a))
57
+
58
+ const calleeName = call => (isMemberNode(call.callee) ? call.callee.property.name : call.callee.name) ?? ""
59
+
60
+ // how a request object marks URL values and the caller, under whatever name it has here
61
+ function requestPredicates(req, bodyIsCaller) {
62
+ if (!req) return { isId: () => false, isCaller: () => false }
63
+ return {
64
+ isId: n => isMember(n, req, "params") || (isMemberNode(n) && isMember(n.object, req, "params")),
65
+ isCaller: n =>
66
+ (isMember(n, req) && IDENTITY_KEYS.has(n.property.name)) ||
67
+ (bodyIsCaller && isMemberNode(n) && isMember(n.object, req, "body") && BODY_USER_FIELD.test(n.property.name ?? "")) ||
68
+ (isCallNode(n) &&
69
+ n.arguments.some(a => a.type === "Identifier" && a.name === req) &&
70
+ IDENTITY_FN.test(isMemberNode(n.callee) ? `${n.callee.object.name ?? n.callee.object.property?.name ?? ""}.${n.callee.property.name}` : (n.callee.name ?? "")))
71
+ }
72
+ }
73
+
74
+ function reads(node, names, predicate) {
75
+ if (!node) return false
76
+ if (identifiers(node).some(name => names.has(name))) return true
77
+ let found = false
78
+ walk(node, n => {
79
+ if (!found && predicate(n)) found = true
80
+ })
81
+ return found
82
+ }
83
+
84
+ // pass the caller's arguments onto the callee's parameters
85
+ function bindArguments(fn, args, ctx, readsId, readsCaller) {
86
+ const ids = new Set()
87
+ const callers = new Set()
88
+ let req = null
89
+ fn.params.forEach((param, i) => {
90
+ const arg = args[i]
91
+ if (!arg || isFunction(arg)) return
92
+ const target = param.type === "AssignmentPattern" ? param.left : param
93
+ // service(req): the whole request travels, under the parameter's name
94
+ if (arg.type === "Identifier" && arg.name === ctx.req && target.type === "Identifier") req = target.name
95
+ if (target.type === "ObjectPattern" && arg.type === "ObjectExpression") {
96
+ for (const prop of target.properties) {
97
+ const value = arg.properties.find(a => a.key?.name === prop.key?.name)?.value
98
+ if (!value) continue
99
+ if (readsCaller(value)) boundNames(prop.value).forEach(n => callers.add(n))
100
+ else if (readsId(value)) boundNames(prop.value).forEach(n => ids.add(n))
101
+ }
102
+ return
103
+ }
104
+ if (readsCaller(arg)) boundNames(target).forEach(n => callers.add(n))
105
+ if (readsId(arg)) boundNames(target).forEach(n => ids.add(n))
106
+ })
107
+ return { ids, callers, req }
108
+ }
109
+
110
+ // Does the caller limit the record that the URL id reaches, here or in what this function calls?
111
+ // scoped: true, the caller is in the query, a guard or a check call
112
+ // scoped: false, a query uses the id and nothing on the way looks at the caller (at: where)
113
+ // scoped: null, nothing conclusive (trusted: the caller was handed to code we cannot read)
114
+ export function traceScope(ctx) {
115
+ const { fn, file, resolve, depth = 0, seen = new Set(), chain = [] } = ctx
116
+ const ids = new Set(ctx.ids ?? [])
117
+ const callers = new Set(ctx.callers ?? [])
118
+ const { isId, isCaller } = requestPredicates(ctx.req, ctx.bodyIsCaller)
119
+ const readsId = node => reads(node, ids, isId)
120
+ const readsCaller = node => reads(node, callers, isCaller)
121
+
122
+ // const course = await findOwnedCourse(id, user) stands for the caller from here on
123
+ for (let pass = 0; pass < 2; pass++) {
124
+ walk(fn.body, n => {
125
+ if (n.type !== "VariableDeclarator" || !n.init) return
126
+ // a value built from both (findOwnedCourse(id, user)) belongs to both sets
127
+ const caller = readsCaller(n.init)
128
+ const id = readsId(n.init)
129
+ if (caller) boundNames(n.id).forEach(name => callers.add(name))
130
+ if (id) boundNames(n.id).forEach(name => ids.add(name))
131
+ })
132
+ }
133
+
134
+ let scoped = false
135
+ let why = null
136
+ let trusted = false
137
+ let ownedCreate = false
138
+ const scope = (n, reason) => {
139
+ if (!scoped) why = { file, line: n.loc.start.line, reason, chain }
140
+ scoped = true
141
+ }
142
+ const unscoped = []
143
+
144
+ walk(fn.body, n => {
145
+ // if (course.ownerOrgId !== user.orgId): the caller compared with what the id reached.
146
+ // if (!user) alone checks login, not ownership.
147
+ // history[noteId] where history is the caller's own: the id only picks among the caller's records
148
+ if (isMemberNode(n) && n.computed && readsCaller(n.object) && readsId(n.property)) scope(n, "id looked up in the caller's own data")
149
+ if ((n.type === "IfStatement" || n.type === "ConditionalExpression") && readsCaller(n.test) && readsId(n.test))
150
+ scope(n, "guard comparing the caller with the record")
151
+ if (!isCallNode(n)) return
152
+
153
+ const name = calleeName(n)
154
+ const takesId = valueArgs(n).some(readsId)
155
+ const takesCaller = valueArgs(n).some(readsCaller)
156
+ if (takesCaller && CHECK_FN.test(name)) scope(n, `${name}(… caller …)`)
157
+ if (takesCaller && CREATE.test(name)) ownedCreate = true
158
+ // getHistory(req.user.id, (err, history) => …): history is the caller's
159
+ if (takesCaller) n.arguments.filter(isFunction).forEach(cb => cb.params.flatMap(boundNames).forEach(p => callers.add(p)))
160
+ if (!takesId || scoped) return
161
+
162
+ const line = n.loc.start.line
163
+ if (DB_CALL.test(name)) {
164
+ if (takesCaller) scope(n, `${name} scoped to the caller`)
165
+ else unscoped.push({ file, line, method: name, chain, write: DB_WRITE.test(name) })
166
+ return
167
+ }
168
+
169
+ const target = depth < MAX_DEPTH ? resolve?.(file, n.callee) : null
170
+ const key = target && `${target.file}:${target.fn.start}`
171
+ if (!target || seen.has(key)) {
172
+ if (takesCaller) trusted = true
173
+ else if (SERVICE_LOOKUP.test(name)) unscoped.push({ file, line, method: name, chain, write: SERVICE_WRITE.test(name) })
174
+ return
175
+ }
176
+
177
+ const bound = bindArguments(target.fn, n.arguments, ctx, readsId, readsCaller)
178
+ const result = traceScope({
179
+ fn: target.fn,
180
+ file: target.file,
181
+ resolve,
182
+ ids: bound.ids,
183
+ callers: bound.callers,
184
+ req: bound.req,
185
+ bodyIsCaller: ctx.bodyIsCaller,
186
+ depth: depth + 1,
187
+ seen: new Set([...seen, key]),
188
+ chain: [...chain, name]
189
+ })
190
+ if (result.scoped === true) {
191
+ if (!scoped) why = result.why
192
+ scoped = true
193
+ }
194
+ else if (result.scoped === false) unscoped.push(...result.unscoped)
195
+ else if (takesCaller || result.trusted) trusted = true
196
+ if (result.ownedCreate) ownedCreate = true
197
+ })
198
+
199
+ if (scoped) return { scoped: true, why }
200
+ const writes = unscoped.filter(u => u.write)
201
+ // reading a public parent to attach the caller's own record is fine; changing it is not
202
+ if (ownedCreate && writes.length === 0) return { scoped: true, why: { file, line: fn.loc.start.line, reason: "new record owned by the caller", chain }, ownedCreate }
203
+ if (unscoped.length) return { scoped: false, at: writes[0] ?? unscoped[0], unscoped, ownedCreate }
204
+ return { scoped: null, trusted, ownedCreate }
205
+ }
206
+
207
+ // start at a route's handler, where req.params are the ids and req.user is the caller
208
+ export function traceRoute(route) {
209
+ const { req } = handlerParams(route.fn)
210
+ return traceScope({
211
+ fn: route.fn,
212
+ file: route.fnPath,
213
+ resolve: route.resolve,
214
+ req,
215
+ bodyIsCaller: route.middleware.some(m => APPENDS_USER.test(m))
216
+ })
217
+ }