zenstackhq / zenstack

Fullstack TypeScript toolkit that enhances Prisma ORM with flexible Authorization layer for RBAC/ABAC/PBAC/ReBAC, offering auto-generated type-safe APIs and frontend hooks.
https://zenstack.dev
MIT License
2.07k stars 89 forks source link

Zenstack deleted all my code projects #1628

Open james-tindal opened 2 months ago

james-tindal commented 2 months ago

Description I ran this npx zenstack generate --schema schema/main.zmodel --output .. It deleted everything in the directory above the current directory.

Expected behavior I didn't expect it delete all my files.

It should check the output directory does not include the whole project before deleting it.

thejoecode commented 4 weeks ago

Could do a check similar to what Prisma does: https://github.com/prisma/prisma/blob/main/packages/client/src/generation/generateClient.ts#L772

Prisma passes the generated name to ensure it is the generated package.

If this route sounds good I could create a pull request.

packages\sdk\src\utils.ts

export function ensureEmptyDir(dir: string) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
        return;
    }

    const stats = fs.statSync(dir);
    if (stats.isDirectory()) {
        // *** If directory has files and we find the generated package ***
        // *** Then it is safe to delete recursively ***
        if (fs.readdirSync(dir).length !== 0 && require(`${dir}/package.json`).name?.startsWith(".zenstack")) {
            fs.rmSync(dir, { recursive: true });
            fs.mkdirSync(dir, { recursive: true });
        } else {
            throw new Error(`Path "${dir}" already exists and contains files that were not generated by zenstack`);
        }
    } else {
        throw new Error(`Path "${dir}" already exists and is not a directory`);
    }
}