@friggframework/devtools 2.0.0--canary.686.45cab16.0 → 2.0.0--canary.694.f66a64a.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.
Files changed (29) hide show
  1. package/frigg-cli/build-command/index.js +1 -32
  2. package/frigg-cli/deploy-command/index.js +2 -50
  3. package/frigg-cli/doctor-command/index.js +0 -7
  4. package/frigg-cli/generate-iam-command.js +0 -7
  5. package/frigg-cli/repair-command/index.js +0 -7
  6. package/frigg-cli/start-command/index.js +0 -58
  7. package/infrastructure/__tests__/template-generation.test.js +0 -7
  8. package/infrastructure/create-frigg-infrastructure.js +0 -14
  9. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  10. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  11. package/infrastructure/domains/scheduler/trigger-builder.js +114 -0
  12. package/infrastructure/domains/scheduler/trigger-builder.test.js +82 -0
  13. package/infrastructure/domains/shared/function-environments.js +9 -1
  14. package/infrastructure/domains/shared/function-environments.test.js +14 -0
  15. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  16. package/infrastructure/domains/shared/utilities/base-definition-factory.js +10 -28
  17. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +1 -85
  18. package/infrastructure/infrastructure-composer.js +2 -0
  19. package/infrastructure/infrastructure-composer.test.js +0 -7
  20. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  21. package/infrastructure/scripts/build-prisma-layer.test.js +0 -35
  22. package/package.json +7 -7
  23. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  24. package/frigg-cli/utils/provider-helper.js +0 -80
  25. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  26. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  27. package/infrastructure/provider-build.js +0 -119
  28. package/test/npm-install-guard.js +0 -104
  29. package/test/npm-install-guard.test.js +0 -53
@@ -1,335 +0,0 @@
1
- /**
2
- * Management API ↔ API Gateway route coverage
3
- *
4
- * The Management API (ADR-053) is served by the `auth` Lambda (v1, v2 and
5
- * the OAuth redirect) and, for /api/meta, by the DB-free `health` Lambda.
6
- * API Gateway HTTP APIs have no implicit catch-all: a request whose path
7
- * matches no declared route gets a gateway 404 and never reaches Express.
8
- * So every route those routers register must be covered by an httpApi event
9
- * on the right function, and no more-specific route on another function may
10
- * shadow it. Both the routers and the gateway routes come from core's route
11
- * registry; this test proves the outcome end to end.
12
- *
13
- * The Express routes are read from the live routers (not a hard-coded
14
- * list), so a route added to core later fails this test until the gateway
15
- * routes follow.
16
- */
17
-
18
- // Avoid AWS calls: hand the builders a fixed discovery result.
19
- jest.mock('../domains/shared/resource-discovery', () => {
20
- const actual = jest.requireActual('../domains/shared/resource-discovery');
21
- return {
22
- ...actual,
23
- gatherDiscoveredResources: jest.fn().mockResolvedValue({
24
- defaultVpcId: 'vpc-123456',
25
- vpcCidr: '172.31.0.0/16',
26
- defaultSecurityGroupId: 'sg-123456',
27
- privateSubnetId1: 'subnet-123456',
28
- privateSubnetId2: 'subnet-789012',
29
- publicSubnetId1: 'subnet-public-1',
30
- publicSubnetId2: 'subnet-public-2',
31
- defaultRouteTableId: 'rtb-123456',
32
- defaultKmsKeyId:
33
- 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
34
- existingNatGatewayId: 'nat-default123',
35
- auroraClusterEndpoint:
36
- 'test-cluster.cluster-abc123.us-east-1.rds.amazonaws.com',
37
- auroraPort: 5432,
38
- auroraEngine: 'aurora-postgresql',
39
- }),
40
- };
41
- });
42
-
43
- // The Management API routers load the app definition from the consuming
44
- // backend; give them one so they can be built in isolation. The entity proxy
45
- // is enabled so its route is checked too.
46
- jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
47
- loadAppDefinition: () => ({
48
- integrations: [],
49
- userConfig: {},
50
- managementApi: { proxy: { enable: true } },
51
- }),
52
- }));
53
-
54
- const { composeServerlessDefinition } = require('../infrastructure-composer');
55
-
56
- /** Routes registered on an Express router, including nested routers. */
57
- function collectRoutes(router, routes = new Map()) {
58
- const stack = (router._router || router).stack || [];
59
- for (const layer of stack) {
60
- if (layer.route) {
61
- for (const method of Object.keys(layer.route.methods)) {
62
- const route = {
63
- method: method === '_all' ? 'ANY' : method.toUpperCase(),
64
- path: layer.route.path,
65
- };
66
- routes.set(`${route.method} ${route.path}`, route);
67
- }
68
- } else if (layer.handle && Array.isArray(layer.handle.stack)) {
69
- collectRoutes(layer.handle, routes);
70
- }
71
- }
72
- return routes;
73
- }
74
-
75
- /**
76
- * Builds a core router with DB_TYPE set: the repository factories pick an
77
- * adapter from it (or the backend's app definition, which doesn't exist
78
- * here). Nothing connects.
79
- */
80
- function withDbType(build) {
81
- const previousDbType = process.env.DB_TYPE;
82
- process.env.DB_TYPE = 'postgresql';
83
- try {
84
- return build();
85
- } finally {
86
- if (previousDbType === undefined) delete process.env.DB_TYPE;
87
- else process.env.DB_TYPE = previousDbType;
88
- }
89
- }
90
-
91
- /** Every route the auth Lambda's router (core/handlers/routers/auth.js) serves. */
92
- function getAuthLambdaRoutes() {
93
- const { router } = withDbType(() =>
94
- require('@friggframework/core/handlers/routers/auth')
95
- );
96
- return [...collectRoutes(router).values()];
97
- }
98
-
99
- /** Every route the health Lambda serves under /api/meta. */
100
- function getMetaRoutes() {
101
- const { router } = withDbType(() =>
102
- require('@friggframework/core/handlers/routers/health')
103
- );
104
- return [...collectRoutes(router).values()].filter((r) =>
105
- r.path.startsWith('/api/meta')
106
- );
107
- }
108
-
109
- function getGatewayRoutes(definition) {
110
- const routes = [];
111
- for (const [functionName, fn] of Object.entries(definition.functions)) {
112
- for (const event of fn.events || []) {
113
- if (!event.httpApi) continue;
114
- routes.push({
115
- functionName,
116
- method: String(event.httpApi.method).toUpperCase(),
117
- path: event.httpApi.path,
118
- });
119
- }
120
- }
121
- return routes;
122
- }
123
-
124
- const segmentsOf = (p) => p.split('/').filter(Boolean);
125
-
126
- // Turn an Express path into a concrete request path, e.g.
127
- // /api/entities/:entityId/options -> /api/entities/sample-entityId/options
128
- const toConcretePath = (expressPath) =>
129
- expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
130
-
131
- /**
132
- * HTTP API path matching: literal segments match exactly, {param} matches
133
- * one segment, a trailing {proxy+} greedily matches one or more segments.
134
- * Returns null on no match, otherwise a specificity descriptor.
135
- */
136
- function matchGatewayPath(gatewayPath, requestPath) {
137
- const g = segmentsOf(gatewayPath);
138
- const r = segmentsOf(requestPath);
139
- let literals = 0;
140
- for (let i = 0; i < g.length; i++) {
141
- const seg = g[i];
142
- if (/^\{[^}]+\+\}$/.test(seg)) {
143
- if (i !== g.length - 1 || r.length <= i) return null;
144
- return { greedy: true, literals, prefixLength: i };
145
- }
146
- if (i >= r.length) return null;
147
- if (/^\{[^}]+\}$/.test(seg)) continue;
148
- if (seg !== r[i]) return null;
149
- literals++;
150
- }
151
- if (g.length !== r.length) return null;
152
- return { greedy: false, literals, prefixLength: g.length };
153
- }
154
-
155
- /**
156
- * Select the route API Gateway would invoke: a non-greedy match beats a
157
- * greedy one, then more literal segments, then the longer greedy prefix,
158
- * then an explicit method beats ANY.
159
- */
160
- function selectGatewayRoute(gatewayRoutes, method, requestPath) {
161
- const candidates = gatewayRoutes
162
- .filter(
163
- (r) => r.method === 'ANY' || method === 'ANY' || r.method === method
164
- )
165
- .map((r) => ({
166
- route: r,
167
- match: matchGatewayPath(r.path, requestPath),
168
- }))
169
- .filter((c) => c.match);
170
- candidates.sort(
171
- (a, b) =>
172
- Number(a.match.greedy) - Number(b.match.greedy) ||
173
- b.match.literals - a.match.literals ||
174
- b.match.prefixLength - a.match.prefixLength ||
175
- Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
176
- );
177
- return candidates.length ? candidates[0].route : null;
178
- }
179
-
180
- describe('Management API routes are reachable through API Gateway', () => {
181
- let gatewayRoutes;
182
- let managementRoutes;
183
- let metaRoutes;
184
- const originalArgv = process.argv;
185
-
186
- beforeAll(async () => {
187
- process.argv = ['node', 'test'];
188
- process.env.AWS_REGION = 'us-east-1';
189
- // The builders narrate their progress; keep the test output quiet.
190
- const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
191
- const warnSpy = jest
192
- .spyOn(console, 'warn')
193
- .mockImplementation(() => {});
194
- try {
195
- const definition = await composeServerlessDefinition({
196
- name: 'route-coverage-app',
197
- provider: 'aws',
198
- usePrismaLambdaLayer: false,
199
- database: { postgres: { enable: true } },
200
- websockets: { enable: true },
201
- adminScripts: [
202
- class ExampleScript {
203
- static Definition = { name: 'example-script' };
204
- },
205
- ],
206
- admin: { includeBuiltinReports: true },
207
- integrations: [
208
- {
209
- Definition: {
210
- name: 'acme',
211
- webhooks: true,
212
- extensions: {
213
- inbound: {
214
- extension: {
215
- routes: [
216
- { path: '/events', method: 'POST' },
217
- ],
218
- },
219
- },
220
- },
221
- },
222
- },
223
- // Integration names share the /api/ namespace with the
224
- // Management API; make sure they don't shadow it.
225
- { Definition: { name: 'entities' } },
226
- ],
227
- });
228
- gatewayRoutes = getGatewayRoutes(definition);
229
- } finally {
230
- logSpy.mockRestore();
231
- warnSpy.mockRestore();
232
- }
233
- managementRoutes = getAuthLambdaRoutes();
234
- metaRoutes = getMetaRoutes();
235
- });
236
-
237
- afterAll(() => {
238
- process.argv = originalArgv;
239
- delete process.env.AWS_REGION;
240
- });
241
-
242
- it('reads the Management API routes from the live auth and health routers', () => {
243
- const paths = managementRoutes.map((r) => r.path);
244
- expect(paths).toEqual(
245
- expect.arrayContaining([
246
- '/api/integrations',
247
- '/api/authorize',
248
- '/api/entity',
249
- '/api/entity/options/:credentialId',
250
- '/api/entities/:entityId',
251
- '/api/integrations/redirect/:appId',
252
- '/api/v2/integrations',
253
- '/api/v2/entities/types/:entityType/requirements',
254
- '/api/v2/entities/:entityId/proxy',
255
- '/api/v2/credentials/:credentialId/reauthorize',
256
- '/api/v2/authorize',
257
- ])
258
- );
259
- expect(metaRoutes.map((r) => r.path)).toEqual(
260
- expect.arrayContaining(['/api/meta', '/api/meta/openapi/v2.json'])
261
- );
262
- });
263
-
264
- it('routes /api/meta to the DB-free health function', () => {
265
- const unreachable = metaRoutes
266
- .map(({ method, path: requestPath }) => {
267
- const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
268
- return { route: `${method} ${requestPath}`, ok: selected?.functionName === 'health' };
269
- })
270
- .filter((r) => !r.ok)
271
- .map((r) => r.route);
272
- expect(unreachable).toEqual([]);
273
- });
274
-
275
- it('declares no /api/v2 catch-all', () => {
276
- expect(
277
- gatewayRoutes.filter((r) => r.path === '/api/v2/{proxy+}' || r.path === '/api/v2')
278
- ).toEqual([]);
279
- expect(selectGatewayRoute(gatewayRoutes, 'PATCH', '/api/v2/reports/daily')).toBeNull();
280
- });
281
-
282
- it('routes every Management API route to the auth function', () => {
283
- const unreachable = managementRoutes
284
- .map(({ method, path: expressPath }) => {
285
- const requestPath = toConcretePath(expressPath);
286
- const selected = selectGatewayRoute(
287
- gatewayRoutes,
288
- method,
289
- requestPath
290
- );
291
- return {
292
- route: `${method} ${expressPath}`,
293
- reachedBy: selected
294
- ? `${selected.method} ${selected.path} -> ${selected.functionName}`
295
- : 'no API Gateway route',
296
- ok: selected && selected.functionName === 'auth',
297
- };
298
- })
299
- .filter((r) => !r.ok)
300
- .map(({ route, reachedBy }) => `${route} (${reachedBy})`);
301
-
302
- expect(unreachable).toEqual([]);
303
- });
304
-
305
- it.each([
306
- ['GET', '/api/v2/reports', 'reportRouter'],
307
- ['POST', '/api/v2/reports/daily/run', 'reportRouter'],
308
- ['GET', '/api/v2/reports/daily', 'reportRouter'],
309
- ['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
310
- ['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
311
- ['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
312
- ['GET', '/api/acme-integration/custom', 'acme'],
313
- ['GET', '/api/entities-integration/custom', 'entities'],
314
- ['POST', '/user/login', 'user'],
315
- ['GET', '/health/ready', 'health'],
316
- ])('leaves %s %s on %s', (method, requestPath, functionName) => {
317
- const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
318
- expect(selected && selected.functionName).toBe(functionName);
319
- });
320
-
321
- it('declares no method + path pair on more than one function', () => {
322
- const seen = new Map();
323
- const duplicates = [];
324
- for (const r of gatewayRoutes) {
325
- const key = `${r.method} ${r.path}`;
326
- if (seen.has(key) && seen.get(key) !== r.functionName) {
327
- duplicates.push(
328
- `${key}: ${seen.get(key)} and ${r.functionName}`
329
- );
330
- }
331
- seen.set(key, r.functionName);
332
- }
333
- expect(duplicates).toEqual([]);
334
- });
335
- });
@@ -1,119 +0,0 @@
1
- /**
2
- * Build for a non-AWS provider (friggframework/frigg#545, 302ab9ba /
3
- * c8705715).
4
- *
5
- * Instead of the serverless/CloudFormation pipeline, the provider plugin
6
- * (resolved from appDefinition.provider) does the build:
7
- * 1. validate(appDefinition) - errors abort, warnings print
8
- * 2. generateConfig(appDefinition) - e.g. netlify.toml
9
- * 3. getFunctionEntryPoints(appDefinition) - written to <project>/netlify/functions
10
- * 4. getLibEntryPoints(appDefinition) - written to <project>/netlify/lib
11
- *
12
- * <project> is the directory that holds backend/: the generated entry points
13
- * require '../../backend/...', so they must sit beside it. #545 had two
14
- * copies of this, and the CLI one wrote into the backend directory itself,
15
- * where those relative requires do not resolve.
16
- *
17
- * Shared by createFriggInfrastructure() (`node infrastructure.js package`,
18
- * what a backend's `npm run build` runs) and `frigg build`.
19
- */
20
- const path = require('path');
21
- const fs = require('fs');
22
-
23
- const CONFIG_FILE_NAMES = { netlify: 'netlify.toml' };
24
-
25
- /**
26
- * @param {Object} params
27
- * @param {Object} params.appDefinition
28
- * @param {string} params.backendDir - directory containing the backend's index.js
29
- * @param {Object} [params.provider] - resolved plugin; defaults to resolveProvider(appDefinition)
30
- * @param {boolean} [params.verbose]
31
- * @param {Function} [params.exit] - called with 1 on validation errors (default process.exit)
32
- * @returns {{ projectDir: string, written: string[] }}
33
- */
34
- function buildWithProvider({
35
- appDefinition,
36
- backendDir,
37
- provider,
38
- verbose = false,
39
- exit = (code) => process.exit(code),
40
- }) {
41
- const providerName = appDefinition.provider;
42
- const plugin =
43
- provider ||
44
- require('@friggframework/core/providers/resolve-provider').resolveProvider(
45
- appDefinition
46
- );
47
- const projectDir = path.dirname(path.resolve(backendDir));
48
- const written = [];
49
-
50
- console.log(`Building for ${providerName} provider (skipping AWS infrastructure)...`);
51
-
52
- if (typeof plugin.validate === 'function') {
53
- const validation = plugin.validate(appDefinition);
54
- if (validation.errors?.length > 0) {
55
- console.error(`\nValidation errors for ${providerName}:`);
56
- for (const error of validation.errors) {
57
- console.error(` - ${error}`);
58
- }
59
- exit(1);
60
- return { projectDir, written };
61
- }
62
- for (const warning of validation.warnings || []) {
63
- console.warn(` Warning: ${warning}`);
64
- }
65
- }
66
-
67
- const write = (filePath, content) => {
68
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
69
- fs.writeFileSync(filePath, content, 'utf-8');
70
- written.push(filePath);
71
- if (verbose) console.log(` Written ${path.relative(projectDir, filePath)}`);
72
- };
73
-
74
- if (typeof plugin.generateConfig === 'function') {
75
- const fileName = CONFIG_FILE_NAMES[providerName] || `${providerName}.config`;
76
- write(path.join(projectDir, fileName), plugin.generateConfig(appDefinition));
77
- console.log(` Written ${fileName}`);
78
- }
79
-
80
- if (typeof plugin.getFunctionEntryPoints === 'function') {
81
- const entryPoints = plugin.getFunctionEntryPoints(appDefinition);
82
- for (const [fileName, content] of Object.entries(entryPoints)) {
83
- write(path.join(projectDir, 'netlify', 'functions', fileName), content);
84
- }
85
- console.log(` Generated ${Object.keys(entryPoints).length} function entry points`);
86
- }
87
-
88
- if (typeof plugin.getLibEntryPoints === 'function') {
89
- const libEntryPoints = plugin.getLibEntryPoints(appDefinition);
90
- for (const [fileName, content] of Object.entries(libEntryPoints)) {
91
- write(path.join(projectDir, 'netlify', 'lib', fileName), content);
92
- }
93
- console.log(` Generated ${Object.keys(libEntryPoints).length} lib entry points`);
94
- }
95
-
96
- if (typeof plugin.generateEnvTemplate === 'function') {
97
- const missing = Object.entries(plugin.generateEnvTemplate(appDefinition)).filter(
98
- ([key]) => !process.env[key]
99
- );
100
- if (missing.length > 0) {
101
- console.log('\n Environment variables not set locally (configure them on the platform):');
102
- for (const [key] of missing) console.log(` - ${key}`);
103
- }
104
- }
105
-
106
- console.log(`\nBuild complete for ${providerName}.`);
107
- return { projectDir, written };
108
- }
109
-
110
- /**
111
- * True when the app definition names a provider other than AWS.
112
- * @param {Object} [appDefinition]
113
- */
114
- function isNonAwsProvider(appDefinition) {
115
- const name = appDefinition?.provider;
116
- return Boolean(name) && name !== 'aws';
117
- }
118
-
119
- module.exports = { buildWithProvider, isNonAwsProvider };
@@ -1,104 +0,0 @@
1
- /**
2
- * Jest setup: no test may run a package-manager command that rewrites a
3
- * node_modules tree outside the OS temp directory.
4
- *
5
- * Why: two infrastructure tests composed a serverless definition in parallel,
6
- * each building the real Prisma layer under packages/devtools/layers/prisma.
7
- * One cleaned the layer while the other's `npm install --omit=dev` was
8
- * starting, npm found no package.json in its cwd, walked up into the
9
- * monorepo workspace and pruned the devDependencies (jest, jest-util) out of
10
- * the repository's root node_modules. Every later workspace then failed with
11
- * `jest: not found`.
12
- *
13
- * The guard wraps the real child_process functions. A test that mocks
14
- * child_process (jest.mock) gets its mock and is unaffected; anything that
15
- * reaches the real module with, for example, `npm install` in a repository
16
- * directory throws instead of running.
17
- */
18
- const childProcess = require('child_process');
19
- const fs = require('fs');
20
- const os = require('os');
21
- const path = require('path');
22
-
23
- const PACKAGE_MANAGERS = new Set(['npm', 'npx', 'yarn', 'pnpm']);
24
- const MUTATING = new Set([
25
- 'install', 'i', 'in', 'ci', 'add', 'prune', 'uninstall', 'remove', 'rm', 'r', 'un',
26
- 'update', 'up', 'upgrade', 'dedupe', 'link', 'rebuild',
27
- ]);
28
-
29
- function realpathOrSelf(p) {
30
- try {
31
- return fs.realpathSync(p);
32
- } catch {
33
- return path.resolve(p);
34
- }
35
- }
36
-
37
- const TMP = realpathOrSelf(os.tmpdir());
38
- // The monorepo root (packages/devtools/test -> ../../..). A checkout can
39
- // itself live under the temp directory, so "under tmp" alone is not enough.
40
- const REPO_ROOT = realpathOrSelf(path.resolve(__dirname, '..', '..', '..'));
41
-
42
- const within = (dir, root) => dir === root || dir.startsWith(root + path.sep);
43
-
44
- /** True only for a scratch directory: under tmp and outside this repository. */
45
- function insideTmp(dir) {
46
- const real = realpathOrSelf(dir);
47
- return within(real, TMP) && !within(real, REPO_ROOT);
48
- }
49
-
50
- /** @returns {string|null} the offending command, or null when allowed */
51
- function offending(tokens, cwd) {
52
- const [bin, ...args] = tokens;
53
- if (!bin || !PACKAGE_MANAGERS.has(path.basename(String(bin)))) return null;
54
- const sub = args.find((a) => !String(a).startsWith('-'));
55
- // npx <pkg> runs a package; only installs/prunes rewrite node_modules.
56
- if (path.basename(String(bin)) === 'npx' || !MUTATING.has(sub)) return null;
57
- const prefixAt = args.indexOf('--prefix');
58
- const target = prefixAt >= 0 ? args[prefixAt + 1] : cwd;
59
- if (insideTmp(target || process.cwd())) return null;
60
- return tokens.join(' ');
61
- }
62
-
63
- const GUARDED = Symbol.for('frigg.devtools.npmInstallGuard');
64
-
65
- function guard(name, fn, toTokens) {
66
- // setupFiles runs once per test file in a shared worker: wrap once.
67
- if (fn[GUARDED]) return fn;
68
- const guarded = function guarded(...callArgs) {
69
- const { tokens, cwd } = toTokens(callArgs);
70
- const bad = offending(tokens, cwd);
71
- if (bad) {
72
- throw new Error(
73
- `Test tried to run "${bad}" outside the temp directory (cwd ${cwd || process.cwd()}); ` +
74
- 'it would rewrite a real node_modules. Mock it or run it in a temp dir.'
75
- );
76
- }
77
- return fn.apply(this, callArgs);
78
- };
79
- guarded[GUARDED] = true;
80
- return guarded;
81
- }
82
-
83
- const fromString = ([command, options]) => ({
84
- tokens: String(command).trim().split(/\s+/),
85
- cwd: options?.cwd,
86
- });
87
- const fromFile = ([file, args, options]) =>
88
- Array.isArray(args)
89
- ? { tokens: [file, ...args], cwd: options?.cwd }
90
- : { tokens: [file], cwd: args?.cwd };
91
-
92
- for (const name of ['execSync', 'exec']) {
93
- childProcess[name] = guard(name, childProcess[name], fromString);
94
- }
95
- for (const name of ['execFileSync', 'execFile', 'spawn', 'spawnSync']) {
96
- const original = childProcess[name];
97
- childProcess[name] = guard(name, original, (callArgs) => {
98
- const opts = Array.isArray(callArgs[1]) ? callArgs[2] : callArgs[1];
99
- if (opts?.shell && !Array.isArray(callArgs[1])) return fromString([callArgs[0], opts]);
100
- return fromFile(callArgs);
101
- });
102
- }
103
-
104
- module.exports = { offending, insideTmp };
@@ -1,53 +0,0 @@
1
- const os = require('os');
2
- const path = require('path');
3
- const childProcess = require('child_process');
4
- // Read before this file loads the guard itself: jest's setupFiles must have
5
- // installed it already, for every test file.
6
- const guardedBySetup = Boolean(childProcess.execSync[Symbol.for('frigg.devtools.npmInstallGuard')]);
7
- const { offending } = require('./npm-install-guard');
8
-
9
- const repoDir = path.resolve(__dirname, '..');
10
-
11
- describe('npm install guard (jest setupFiles)', () => {
12
- // Every command here is a --dry-run, so even a broken guard that let it
13
- // through could not rewrite this repository's node_modules.
14
- it('is installed by jest setupFiles, before any test code runs', () => {
15
- expect(guardedBySetup).toBe(true);
16
- });
17
-
18
- it('blocks installs and prunes on the real child_process', () => {
19
- expect(() =>
20
- childProcess.execSync('npm install --dry-run --omit=dev', { cwd: repoDir, stdio: 'ignore' })
21
- ).toThrow(/outside the temp directory/);
22
- expect(() =>
23
- childProcess.spawnSync('npm', ['prune', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
24
- ).toThrow(/outside the temp directory/);
25
- expect(() =>
26
- childProcess.execFileSync('/usr/bin/npm', ['ci', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
27
- ).toThrow(/outside the temp directory/);
28
- });
29
-
30
- it('treats a temp dir inside this repository as part of the repository', () => {
31
- // A checkout may itself live under os.tmpdir() (as in some sandboxes).
32
- expect(offending(['npm', 'install'], path.join(repoDir, 'layers/prisma/nodejs'))).not.toBeNull();
33
- });
34
-
35
- it.each([
36
- [['npm', 'install', '--omit=dev'], repoDir, true],
37
- [['npm', 'ci'], repoDir, true],
38
- [['yarn', 'add', 'x'], repoDir, true],
39
- [['npm', 'install', '--prefix', repoDir], os.tmpdir(), true],
40
- [['npm', 'install'], os.tmpdir(), false],
41
- [['npm', 'install', '--prefix', path.join(os.tmpdir(), 'layer')], repoDir, false],
42
- [['npm', 'root'], repoDir, false],
43
- [['npm', 'run', 'build'], repoDir, false],
44
- [['npx', 'netlify-cli', 'deploy'], repoDir, false],
45
- [['git', 'install'], repoDir, false],
46
- ])('%j in %s -> blocked %s', (tokens, cwd, blocked) => {
47
- expect(offending(tokens, cwd) !== null).toBe(blocked);
48
- });
49
-
50
- it('lets harmless commands through', () => {
51
- expect(childProcess.execSync('node -e "process.stdout.write(\'ok\')"', { encoding: 'utf8' })).toBe('ok');
52
- });
53
- });