diff --git a/bin/iapl-skills.mjs b/bin/iapl-skills.mjs index 9c59b82..ab98dbf 100755 --- a/bin/iapl-skills.mjs +++ b/bin/iapl-skills.mjs @@ -16,8 +16,8 @@ // text between the markers is ever rewritten; the project's own content stays as it is. import { createHash } from 'node:crypto' -import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { basename, dirname, join, relative, resolve, sep } from 'node:path' import { fileURLToPath } from 'node:url' const args = process.argv.slice(2) @@ -39,8 +39,22 @@ if (!destValue || destValue.startsWith('-')) { process.exit(1) } const dest = resolve(process.cwd(), destValue) -if (dest === resolve(process.cwd())) { - console.error('iapl-skills: --dest must be a subdirectory, not the project root') +// Compared AFTER resolving links: `--dest root-link` (a link to `.`), `..` or `/` would otherwise pass and lose +// the iapl-* folders of the project root, its parent or the filesystem root. A folder that does not exist yet is +// resolved through its nearest existing parent. +const real = (path) => { + const rest = [] + let at = path + while (!existsSync(at) && dirname(at) !== at) { + rest.unshift(basename(at)) + at = dirname(at) + } + return join(realpathSync(at), ...rest) +} +const realDest = real(dest) +const realRoot = real(resolve(process.cwd())) +if (realDest === realRoot || realRoot.startsWith(realDest.endsWith(sep) ? realDest : `${realDest}${sep}`)) { + console.error(`iapl-skills: --dest must be a folder inside the project or elsewhere, not the project root or a folder that holds it (${destValue} is ${realDest})`) process.exit(1) } diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 22450ce..02a1c5b 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -528,7 +528,7 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`, 1. **`proxy.ts`, never `middleware.ts`.** middleware.ts exists → delete it. Proxy: `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })`, the matcher - as an **inline literal** (`['/((?!api|admin|_next|.*\\..*).*)']`), not an import. + as an **inline literal** (`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']`), not an import. 2. **No explicit `` in the layout.** It pushes metadata into ``. `` in `` (React 19 hoists it). 3. **ISR:** `export const revalidate = 3600` in `page.tsx`. Refresh after save: diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index b2e4881..b6439d4 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -265,7 +265,7 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse }) // Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` ## Collections and globals diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index 6e48a13..8857e7c 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -399,7 +399,7 @@ import { createProxy } from '@intecion/ipal-kit' import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline LITERAL (importing DEFAULT_PROXY_MATCHER = 500 on /admin); with adminRoute '/its' write `its` instead of `admin` -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` `src/lib/content.ts` = PROGRAMISTA §2.7 1:1: `createContentHelpers({ config, content: contentConfig, i18n: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName: diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 5003745..d3b1365 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -245,7 +245,7 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline literal — Next analyzes it statically; importing a variable = proxy on /admin → 500 -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` Sets `x-locale` / `x-pathname`, the language cookie with consent, redirects `/`. The headers are for dynamic routes (API, route handlers) — in SSG/ISR pages, diff --git a/docs/doctor.md b/docs/doctor.md index 9448041..3f11bec 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -101,6 +101,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `env-live` | error | (deep) the project's env rules pass in the real environment | | security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection | | | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin | +| | `proxy-matcher` | warning | `src/proxy.ts`: a matcher that skips `api`, `admin` or `_next` without ending them at "/" (`(?!api|admin|…)`) also skips every page whose first segment only starts with them (`/administracja`): no locale redirect, no proxy CSP. Fix: the literal in i18n.md (1.17.1) | | | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` | | | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) | | | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) | diff --git a/docs/i18n.md b/docs/i18n.md index b684438..6fcbb3d 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -132,7 +132,7 @@ See [proxy in this section](#proxy-formerly-middleware) below. > import { createProxy } from '@intecion/ipal-kit' > import { i18nConfig } from '@/i18n.config' > export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // markdown: GEO, content.md -> export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +> export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } > ``` > Use the manual variant below only when you need your own logic in the proxy. @@ -171,7 +171,7 @@ export function proxy(req) { return res } -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline ``` Behavior: @@ -182,7 +182,7 @@ Behavior: `DEFAULT_MIDDLEWARE_MATCHER` excludes `api`, `admin`, `_next`, static files. The `admin` prefix is hard-coded — with a custom `adminRoute` (e.g. `/its`) add -it to the matcher (`'/((?!api|its|_next|.*\\..*).*)'`), otherwise the proxy redirects the admin panel +it to the matcher (`'/((?!(?:api|its|_next)(?:/|$)|.*\\..*).*)'`), otherwise the proxy redirects the admin panel to `/pl/its`. ## Locale cookie and consent (GDPR) @@ -398,7 +398,7 @@ in the proxy/middleware file, not an import/variable. Even though the plugin exp ```ts // proxy.ts — matcher INLINE (not an import) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` Use `DEFAULT_PROXY_MATCHER` as a reference value, but if Next complains diff --git a/package.json b/package.json index 7bea0ea..46b378b 100644 --- a/package.json +++ b/package.json @@ -204,6 +204,9 @@ "registry": "https://git.intecion.net/api/packages/IntecionSoftware/npm/" }, "pnpm": { + "ignoredBuiltDependencies": [ + "@swc/core" + ], "onlyBuiltDependencies": [ "sharp", "esbuild", diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index 6e48a13..8857e7c 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -399,7 +399,7 @@ import { createProxy } from '@intecion/ipal-kit' import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline LITERAL (importing DEFAULT_PROXY_MATCHER = 500 on /admin); with adminRoute '/its' write `its` instead of `admin` -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` `src/lib/content.ts` = PROGRAMISTA §2.7 1:1: `createContentHelpers({ config, content: contentConfig, i18n: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName: diff --git a/reference/src/proxy.ts b/reference/src/proxy.ts index ae749be..bd288ce 100644 --- a/reference/src/proxy.ts +++ b/reference/src/proxy.ts @@ -7,4 +7,4 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse }) // Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index b5cc8c6..ff91d18 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -60,6 +60,27 @@ export const securityRules: DoctorRule[] = [ group: 'security', source: 'static', }, + { + // A matcher whose lookahead names api / admin / _next without ending them at "/" also skips every page whose + // first segment merely STARTS with those letters (/administracja, /apis): no locale redirect, and no CSP from the + // proxy on a single-locale site (IAWL idea 36, fixed in the documented literal in 1.17.1). + id: 'proxy-matcher', + check: async (ctx) => { + const file = `${ctx.src}proxy.ts` + const code = stripComments(ctx.read(file)) + const loose = [...code.matchAll(/\(\?!((?:[\w-]+\|)*[\w-]+)\|/g)].map((m) => m[1]!.split('|')).find((names) => names.some((n) => ['_next', 'admin', 'api'].includes(n))) + if (!loose) {return []} + return [{ + file, + fix: "matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'] (i18n.md → Next matcher)", + message: `the proxy matcher skips every path that starts with ${loose.map((n) => `"${n}"`).join(', ')} (e.g. /${loose.includes('admin') ? 'administracja' : `${loose[0]}s`}), not only those folders: no locale redirect, no proxy CSP there`, + severity: 'warning', + }] + }, + docs: 'docs/i18n.md', + group: 'security', + source: 'static', + }, { id: 'client-hints', check: async (ctx) => { diff --git a/src/modules/forms/attachments/fileChecks.ts b/src/modules/forms/attachments/fileChecks.ts index d81026e..b214bb1 100644 --- a/src/modules/forms/attachments/fileChecks.ts +++ b/src/modules/forms/attachments/fileChecks.ts @@ -106,7 +106,10 @@ const REQUIRED_ENTRIES: Record = { xlsx: ['[Content_Types].xml', 'xl/workbook.xml'], } -const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)$/i +// Trailing dots and spaces count as the end of the name: Windows drops them when it writes the file, so an entry +// `setup.exe.` or `setup.exe ` becomes `setup.exe` once extracted. +const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)[.\s]*$/i +const MACRO_ENTRY = /vbaProject\.bin[.\s]*$/i const indexOfBytes = (bytes: Uint8Array, needle: readonly number[]) => { outer: for (let i = 0; i <= bytes.length - needle.length; i++) { @@ -188,7 +191,7 @@ export async function checkFileContent( if (!entries) {return 'signature'} const names = new Set(entries.map((e) => e.name)) if (required.some((name) => !names.has(name))) {return 'signature'} - if (entries.some((e) => e.encrypted || /vbaProject\.bin$/i.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'} + if (entries.some((e) => e.encrypted || MACRO_ENTRY.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'} } if ((key === 'doc' || key === 'xls') && oleHasMacros(bytes)) {return 'content'} if (key === 'pdf' && strictPdf && pdfHasActiveContent(bytes)) {return 'content'} diff --git a/src/modules/i18n/createProxy.ts b/src/modules/i18n/createProxy.ts index fa85f28..72e6f4d 100644 --- a/src/modules/i18n/createProxy.ts +++ b/src/modules/i18n/createProxy.ts @@ -81,7 +81,7 @@ type CreateProxyOptions = { * import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit' * import { i18nConfig } from '@/i18n.config' * export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) - * export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // inline literal + * export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } // inline literal */ export function createProxy( config: I18nConfig, diff --git a/src/modules/i18n/localeMiddleware.ts b/src/modules/i18n/localeMiddleware.ts index 94b4627..0b9fafe 100644 --- a/src/modules/i18n/localeMiddleware.ts +++ b/src/modules/i18n/localeMiddleware.ts @@ -164,5 +164,8 @@ export function createLocaleMiddleware({ /** * Default Next.js middleware matcher: run on everything except API routes, the * admin panel, Next internals, and files with an extension (static assets). + * `api`, `admin` and `_next` are skipped only as a WHOLE first segment (`/api`, `/api/…`): before 1.17.1 the + * lookahead did not end at "/", so `/administracja` or `/apis` skipped the proxy too (no locale redirect, no + * proxy CSP). The doctor's `proxy-matcher` rule reports the old literal. */ -export const DEFAULT_MIDDLEWARE_MATCHER = ['/((?!api|admin|_next|.*\\..*).*)'] +export const DEFAULT_MIDDLEWARE_MATCHER = ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] diff --git a/src/modules/starter/bundle.ts b/src/modules/starter/bundle.ts index e904fa4..f22ce74 100644 --- a/src/modules/starter/bundle.ts +++ b/src/modules/starter/bundle.ts @@ -4,7 +4,7 @@ * (`pnpm build:starter`); a checkout of the repo can read `reference/` directly instead. */ import { execFileSync } from 'node:child_process' -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs' import { join, relative, sep } from 'node:path' import { gunzipSync, gzipSync } from 'node:zlib' @@ -32,7 +32,8 @@ function walk(dir: string, root: string, out: string[]) { const rel = relative(root, full).split(sep).join('/') // never descend into installed or built trees if (name === 'node_modules' || name === '.next' || name === '.git') {continue} - if (statSync(full).isDirectory()) {walk(full, root, out)} + // lstat: a link is listed as itself (and refused below), never followed into its target + if (lstatSync(full).isDirectory()) {walk(full, root, out)} else {out.push(rel)} } } @@ -42,7 +43,7 @@ function listFiles(dir: string): string[] { try { const out = execFileSync('git', ['ls-files', '-z', '--cached', '--', '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }) const tracked = out.split('\0').filter(Boolean) - if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)))} + if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)) || lstatSync(join(dir, path), { throwIfNoEntry: false })?.isSymbolicLink())} } catch { // not a Git checkout (e.g. an unpacked tarball) — fall back to the folder } @@ -70,6 +71,11 @@ export function collectBundle(referenceDir: string): StarterBundle { if (path === MANIFEST || path === LOCKFILE) {continue} const role = fileRole(path, manifest) if (role === 'drop') {continue} + // A link would be read through: its TARGET (a key, another project's .env) would ship in the published bundle. + if (lstatSync(join(referenceDir, path)).isSymbolicLink()) { + problems.push(`${path}: symbolic link — commit the file itself, or drop it in the manifest`) + continue + } const content = readFileSync(join(referenceDir, path)) if (!isText(content)) { problems.push(`${path}: binary file — drop it in the manifest`) diff --git a/src/modules/starter/cli.ts b/src/modules/starter/cli.ts index f2f7b6d..777a823 100644 --- a/src/modules/starter/cli.ts +++ b/src/modules/starter/cli.ts @@ -5,7 +5,7 @@ import { spawnSync } from 'node:child_process' import { createHash, randomBytes } from 'node:crypto' import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { domainToASCII, fileURLToPath } from 'node:url' import type { SiteContext } from './generate.js' @@ -118,7 +118,17 @@ function run(log: Log, cwd: string, command: string, args: string[], env: Record return result.status === 0 } -function writeFiles(dir: string, files: Record) { +/** + * The new site's files, each under `dir`. A path that is absolute or climbs out with `..` stops the run before + * anything is written (the bundle is built from this repository's tracked files, so none does; a damaged or + * altered bundle must not write outside the new folder). + */ +export function writeFiles(dir: string, files: Record) { + const outside = Object.keys(files).filter((path) => { + const target = resolve(dir, path) + return isAbsolute(path) || (target !== dir && !target.startsWith(`${resolve(dir)}${sep}`)) + }) + if (outside.length) {throw new Error(`the starter bundle names files outside the new folder: ${outside.join(', ')} — nothing was written`)} for (const [path, content] of Object.entries(files)) { const target = join(dir, path) mkdirSync(dirname(target), { recursive: true }) @@ -208,7 +218,12 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. return 0 } - writeFiles(dir, files) + try { + writeFiles(dir, files) + } catch (error) { + log(`iapl create: ${(error as Error).message}`) + return 1 + } writeFileSync(join(dir, '.env'), localEnv(files['.env.example'] ?? '')) log(`Wrote ${Object.keys(files).length} files to ${relative(cwd, dir) || '.'}`) diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 171aa52..9d72c1d 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -493,6 +493,14 @@ describe('security and deep status', () => { expect(rules(await doctor(root, ['security']))).toContain('csp:info') expect(rules(await doctor(root, ['csp'], { config: { seen: { 'csp-report-only': '2026-09-01' } } }))).toEqual(['csp:warning']) }) + test('proxy-matcher: a lookahead that does not end api / admin / _next at "/" is a warning; the 1.17.1 literal is not', async () => { + const proxy = (matcher: string) => project({ ...base(), 'src/proxy.ts': `export const config = { matcher: ['${matcher}'] }` }) + expect(rules(await doctor(proxy('/((?!api|admin|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) + expect(rules(await doctor(proxy('/((?!api|cms|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) + expect(rules(await doctor(proxy('/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual([]) + expect(rules(await doctor(project(base()), ['proxy-matcher']))).toEqual([]) + }) + test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => { const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))')) expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info']) diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts index 3b76025..9f62c36 100644 --- a/test/formAttachments.test.ts +++ b/test/formAttachments.test.ts @@ -367,6 +367,13 @@ describe('3 · refused files leave no submission and send no e-mail', () => { await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file }) + test('a program inside an Office file is found also with trailing dots or spaces (Windows drops them)', async () => { + for (const entry of ['word/setup.exe', 'word/setup.exe.', 'word/setup.exe ', 'word/setup.EXE. .', 'word/vbaProject.bin.']) { + const data = zip({ '[Content_Types].xml': '', 'word/document.xml': '', [entry]: 'x' }) + await refused([{ name: 'cv.docx', data }], notAcceptable('cv.docx')) + } + }) + test('extra files: more than the field allows, a file under a key that is no File field', async () => { await refused( [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }], diff --git a/test/iaplSkillsDest.test.ts b/test/iaplSkillsDest.test.ts new file mode 100644 index 0000000..8837eb6 --- /dev/null +++ b/test/iaplSkillsDest.test.ts @@ -0,0 +1,60 @@ +/** + * `iapl-skills --dest`: the "not the project root" rule is checked on RESOLVED paths. Before 1.17.1 the check + * compared the paths as typed, so `--dest root-link` (a link to `.`), `--dest ..` or `--dest /` passed it, and the + * run removed the `iapl-*` folders of the project root, its parent or the filesystem root (IAWL idea 13). + */ +import { spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterAll, describe, expect, test } from 'vitest' + +const bin = path.resolve(import.meta.dirname, '../bin/iapl-skills.mjs') +const made: string[] = [] +afterAll(() => { + for (const dir of made) {rmSync(dir, { force: true, recursive: true })} +}) + +/** A throw-away project: a parent folder holding `project/` with an `iapl-mine` folder in its root. */ +function project() { + const parent = realpathSync(mkdtempSync(path.join(tmpdir(), 'iapl-skills-dest-'))) + made.push(parent) + const dir = path.join(parent, 'project') + mkdirSync(path.join(dir, 'iapl-mine'), { recursive: true }) + writeFileSync(path.join(dir, 'iapl-mine', 'keep.txt'), 'the project root holds this folder') + mkdirSync(path.join(parent, 'iapl-next-door')) + return { dir, parent } +} + +const run = (cwd: string, dest: string) => + spawnSync(process.execPath, [bin, '--dest', dest, '--no-pointer'], { cwd, encoding: 'utf8' }) + +describe('iapl-skills --dest is judged after the path is resolved', () => { + test('a link to the project root is refused and the root keeps its iapl-* folders', () => { + const { dir } = project() + symlinkSync('.', path.join(dir, 'root-link')) + const result = run(dir, 'root-link') + expect(result.status, result.stdout).toBe(1) + expect(result.stderr).toMatch(/not the project root/) + expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true) + }) + + test('a folder that holds the project (the parent, the filesystem root) is refused', () => { + const { dir, parent } = project() + for (const dest of ['..', '/', parent]) { + const result = run(dir, dest) + expect([dest, result.status]).toEqual([dest, 1]) + } + expect(existsSync(path.join(parent, 'iapl-next-door'))).toBe(true) + }) + + test('a folder inside the project, a new one, or one elsewhere still works', () => { + const { dir, parent } = project() + expect(run(dir, '.agents/skills').status).toBe(0) + expect(existsSync(path.join(dir, '.agents/skills/iapl-setup/SKILL.md'))).toBe(true) + const shared = path.join(parent, 'shared-skills') + expect(run(dir, shared).status).toBe(0) + expect(existsSync(path.join(shared, 'iapl-setup/SKILL.md'))).toBe(true) + expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true) + }) +}) diff --git a/test/proxyMatcher.test.ts b/test/proxyMatcher.test.ts new file mode 100644 index 0000000..5525c61 --- /dev/null +++ b/test/proxyMatcher.test.ts @@ -0,0 +1,38 @@ +/** + * The documented proxy matcher, compiled by Next's own code (the function `next build` uses for `config.matcher`): + * `api`, `admin` and `_next` are skipped only as a whole first segment. Before 1.17.1 `/administracja`, `/admin-guide` + * or `/apis` skipped the proxy as well (IAWL idea 36: a deny rule by name must end at "/"). + */ +import { readFileSync, realpathSync } from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { DEFAULT_PROXY_MATCHER } from '../src/modules/i18n/createProxy.js' + +const root = path.resolve(import.meta.dirname, '..') +const next = realpathSync(path.join(root, 'node_modules/next')) +const { getMiddlewareMatchers } = createRequire(import.meta.url)(path.join(next, 'dist/build/analysis/get-page-static-info.js')) as { + getMiddlewareMatchers: (matchers: string[], nextConfig: object) => { regexp: string }[] +} +const runs = (matcher: string) => { + const re = new RegExp(getMiddlewareMatchers([matcher], {})[0]!.regexp) + return (pathname: string) => re.test(pathname) +} + +describe('the proxy matcher', () => { + test('skips /api, /admin and /_next as whole segments and files; runs on pages that only START with those letters', () => { + const proxy = runs(DEFAULT_PROXY_MATCHER[0]!) + for (const skipped of ['/api', '/api/users', '/api/ipal/hit', '/admin', '/admin/', '/admin/collections/users', '/_next/static/chunk.js', '/robots.txt', '/sitemap.xml']) { + expect([skipped, proxy(skipped)]).toEqual([skipped, false]) + } + for (const page of ['/', '/o-nas', '/pl/o-nas', '/administracja', '/admin-guide', '/apis', '/api-docs', '/_nextish', '/md/pl/o-nas']) { + expect([page, proxy(page)]).toEqual([page, true]) + } + }) + + test('the reference site uses the same literal (Next reads it statically, it cannot be imported)', () => { + const proxyFile = readFileSync(path.join(root, 'reference/src/proxy.ts'), 'utf8') + expect(proxyFile).toContain(`matcher: ['${DEFAULT_PROXY_MATCHER[0]!.replace(/\\/g, '\\\\')}']`) + }) +}) diff --git a/test/starter.test.ts b/test/starter.test.ts index 228f41e..e1b53fb 100644 --- a/test/starter.test.ts +++ b/test/starter.test.ts @@ -1,4 +1,5 @@ -import { existsSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -29,7 +30,7 @@ import { unpackBundle, validateAnswers, } from '../src/exports/starter.js' -import { externalSkillNames, resolveExternal } from '../src/modules/starter/cli.js' +import { externalSkillNames, resolveExternal, writeFiles } from '../src/modules/starter/cli.js' const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const reference = path.join(root, 'reference') @@ -257,3 +258,49 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl') }) }) + +describe('starter: links and paths (IAWL ideas 12, 13)', () => { + const site = () => { + const dir = mkdtempSync(path.join(tmpdir(), 'iapl-starter-links-')) + const manifest: StarterManifest = { drop: [], keep: ['**'], placeholders: {}, schema: 1, template: [] } + writeFileSync(path.join(dir, 'starter.manifest.json'), JSON.stringify(manifest)) + writeFileSync(path.join(dir, 'pnpm-lock.yaml'), "lockfileVersion: '9.0'\n") + writeFileSync(path.join(dir, 'kept.ts'), 'export const a = 1\n') + return dir + } + + it('a symbolic link is refused: its target is never read into the published bundle', () => { + const dir = site() + const secret = path.join(dir, '..', `${path.basename(dir)}-secret.txt`) + writeFileSync(secret, 'PRIVATE KEY OF SOMEBODY ELSE') + symlinkSync(secret, path.join(dir, 'leak.txt')) + mkdirSync(path.join(dir, 'outside')) + symlinkSync(path.dirname(secret), path.join(dir, 'outside', 'up')) + try { + expect(() => collectBundle(dir)).toThrow(/leak\.txt: symbolic link/) + rmSync(path.join(dir, 'leak.txt')) + // a link to a folder is not walked into either + expect(() => collectBundle(dir)).toThrow(/outside\/up: symbolic link/) + rmSync(path.join(dir, 'outside'), { force: true, recursive: true }) + expect(Object.keys(collectBundle(dir).files)).toEqual(['kept.ts']) + } finally { + rmSync(dir, { force: true, recursive: true }) + rmSync(secret, { force: true }) + } + }) + + it('a bundle path outside the new folder stops the run before anything is written', () => { + const parent = mkdtempSync(path.join(tmpdir(), 'iapl-starter-paths-')) + const dir = path.join(parent, 'site') + try { + for (const bad of ['../escaped.txt', 'a/../../escaped.txt', path.join(parent, 'abs.txt')]) { + expect(() => writeFiles(dir, { 'ok.txt': 'fine', [bad]: 'no' }), bad).toThrow(/outside the new folder/) + } + expect(readdirSync(parent)).toEqual([]) + writeFiles(dir, { 'ok.txt': 'fine', 'src/a/b.ts': 'x' }) + expect(readdirSync(dir).sort()).toEqual(['ok.txt', 'src']) + } finally { + rmSync(parent, { force: true, recursive: true }) + } + }) +})