diff --git a/.github/workflows/deliverables.yml b/.github/workflows/deliverables.yml index e179189..ad7983f 100644 --- a/.github/workflows/deliverables.yml +++ b/.github/workflows/deliverables.yml @@ -13,7 +13,8 @@ jobs: matrix: # Every backend builds React too. Additional package managers are # exercised on the default platform stack rather than a 6x4 matrix. - case: [platform-pnpm, platform-npm, platform-yarn, express-pnpm, fastify-pnpm, hono-pnpm, nestjs-pnpm, elysia-bun] + # core-pnpm is a new-core plugin running its own gates on Node 26. + case: [platform-pnpm, platform-npm, platform-yarn, express-pnpm, fastify-pnpm, hono-pnpm, nestjs-pnpm, elysia-bun, core-pnpm] steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 @@ -21,14 +22,21 @@ jobs: version: 10 - uses: actions/setup-node@v4 with: - node-version: 22 + node-version: ${{ matrix.case == 'core-pnpm' && 26 || 22 }} cache: pnpm - uses: oven-sh/setup-bun@v2 with: bun-version: "1.x" - run: corepack enable yarn && corepack prepare yarn@4.18.1 --activate + - name: Postgres for the new-core plugin's tests + if: matrix.case == 'core-pnpm' + run: | + docker run -d -p 127.0.0.1:5432:5432 -e POSTGRES_USER=ci -e POSTGRES_PASSWORD=ci-only-password \ + -e POSTGRES_DB=postgres --health-cmd 'pg_isready -U ci' --health-interval 2s postgres:18 + until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker ps -lq)")" = healthy ]; do sleep 1; done - run: pnpm install --frozen-lockfile - name: Test packed CLI in a fresh external directory run: pnpm test:e2e env: E2E_CASE: ${{ matrix.case }} + DATA_TEST_URL: ${{ matrix.case == 'core-pnpm' && 'postgres://ci:ci-only-password@127.0.0.1:5432/postgres' || '' }} diff --git a/README.md b/README.md index 9c1cc8d..8826833 100644 --- a/README.md +++ b/README.md @@ -76,14 +76,18 @@ the directory command quotes the target path literally for that shell. `--erxes core` writes a plugin for the new core with one fixed stack and pnpm: Express 5, oRPC and Drizzle on Postgres in `api/`, and an Rsbuild 2 Module -Federation remote on React 19 with the React Compiler in `ui/`. It follows -core's `plugin-new` skill: the API registers its manifest with -`@erxes/plugin-sdk`, checks each request with `verifyPluginSession`, and keeps -one example table (`_items`, row-level security on `org_id`) with list, -create and update procedures. The UI is a list page and a record side panel -from `erxes-ui`, calling the API through `pluginFetch` with typed oRPC and -TanStack Query. `pnpm check` (format, lint, types), `pnpm test` (Vitest on a -real Postgres) and `pnpm build` are the gates; CI runs them and builds the image. +Federation remote on React 19 with the React Compiler in `ui/`, on Node 26. +The API registers its manifest with `@erxes/plugin-sdk`, checks each request +with `verifyPluginSession`, and keeps one reference feature for agents to copy: +the `_items` table (row-level security on `org_id`, names unique per +organisation) with keyset-paged list, create, update and delete, and a typed +`ITEM_NAME_TAKEN` error. The UI is a list page with optimistic delete and a +side-panel form from `erxes-ui`, calling the API through `pluginFetch` with +typed oRPC and TanStack Query. `AGENTS.md` carries core's quality section, and +`.claude/skills` links to the skills in `.agents/skills`. `pnpm check` (format, +lint, types), `pnpm test` (Vitest on a real Postgres), `pnpm check:rls` (the +tenancy guard) and `pnpm build` are the gates; CI runs them and builds the +image. The prompts after the plugin name ask whether this ports an old plugin: diff --git a/src/core-scaffold.ts b/src/core-scaffold.ts index 2533c46..3cb58db 100644 --- a/src/core-scaffold.ts +++ b/src/core-scaffold.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { mkdir } from "node:fs/promises"; +import { mkdir, symlink } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { x } from "tinyexec"; @@ -21,6 +21,22 @@ export type CoreOptions = { migrateFrom?: string; }; +/** + * Claude Code loads skills from `.claude/skills`; the repo keeps them in + * `.agents/skills`, so the first links to the second. Git commits the link. + */ +const linkSkills = async (targetDir: string) => { + const link = join(targetDir, ".claude", "skills"); + await mkdir(dirname(link), { recursive: true }); + try { + await symlink(join("..", ".agents", "skills"), link, "dir"); + } catch (error) { + // Windows without Developer Mode refuses symlinks; a junction needs no rights. + if (process.platform !== "win32") throw error; + await symlink(join(targetDir, ".agents", "skills"), link, "junction"); + } +}; + export const scaffoldCore = async (targetDir: string, options: CoreOptions) => { const { names, migrateFrom } = options; const tokens: [string, string][] = [ @@ -39,6 +55,11 @@ export const scaffoldCore = async (targetDir: string, options: CoreOptions) => { ], ]; await copyLayer("core/base", targetDir, tokens); + // `@__id__/api` takes its place in the sorted list only once it has the plugin's name. + const uiPackageJson = join(targetDir, "ui/package.json"); + const ui = await readJson(uiPackageJson); + await writeJson(uiPackageJson, { ...ui, devDependencies: sortKeys(ui.devDependencies ?? {}) }); + await linkSkills(targetDir); if (!migrateFrom) return; // The migrate layer's package.json holds only the scripts and dev diff --git a/templates/core/base/.agents/skills/endpoint/SKILL.md b/templates/core/base/.agents/skills/endpoint/SKILL.md index cef9492..37a3905 100644 --- a/templates/core/base/.agents/skills/endpoint/SKILL.md +++ b/templates/core/base/.agents/skills/endpoint/SKILL.md @@ -7,8 +7,8 @@ description: Add or change an API procedure. Use when editing api/src/modules, a there and into `manifest.permissions`, named `__id__..`. 2. Write the procedure in `api/src/modules//.ts` on `reads(action)` or `writes(action)` from `api/src/orpc.ts`, with a zod `.input()`. Query - through `context.tx` and filter on `context.member.orgId`. Lists page by - cursor, newest first, as `items.list` does. + through `context.tx` with no org filter: row-level security scopes it. + Lists page by cursor, newest first, as `items.list` does. 3. Fail with `ORPCError` (`NOT_FOUND`, `FORBIDDEN`, `CONFLICT`, `BAD_REQUEST`); the UI shows its `message`. 4. Add the module to `router` in `api/src/router.ts`. The UI's types follow. diff --git a/templates/core/base/.agents/skills/schema-change/SKILL.md b/templates/core/base/.agents/skills/schema-change/SKILL.md index 576a620..2303967 100644 --- a/templates/core/base/.agents/skills/schema-change/SKILL.md +++ b/templates/core/base/.agents/skills/schema-change/SKILL.md @@ -1,12 +1,12 @@ --- name: schema-change -description: Change the Postgres schema. Use when adding or altering a table, column or index in api/src/db/schema.ts, or when the CI migration drift check fails. +description: Change the Postgres schema. Use when adding or altering a table, column or index in api/src/db/schema.ts, or when the CI migration drift check or pnpm check:rls fails. --- 1. Edit `api/src/db/schema.ts`. Declare tables with `table('')` from `./table.ts`, which makes them `__id___`. A new table has - `id: text().primaryKey()` and `orgId: text().notNull()`, and its indexes lead - with `orgId` and carry their full `__id___` name. + `id: text().primaryKey()` and `orgId: text().notNull()`, and its indexes and + constraints lead with `orgId` and carry their full `__id___` name. 2. Run `pnpm db:generate` and read the SQL in `api/drizzle/`. For each new table, append to that same file: @@ -15,11 +15,14 @@ description: Change the Postgres schema. Use when adding or altering a table, co SELECT core_enable_tenant_rls('__id___'); ``` + A table that can't have `org_id` goes into `no_org_id` in + `tools/check-rls.sql`, with the reason. + 3. Migrations only add or alter. Never edit one that has been applied anywhere, and never run `drizzle-kit push`. To retire a column, stop reading and writing it and leave it in the table. -4. Run `pnpm db:check` and `pnpm test`. +4. Run `pnpm db:check`, then `pnpm check:rls` and `pnpm test` with + `DATA_TEST_URL`. Both migrate fresh databases. -Done when the schema change and its migration are in one commit, every new -table has its `core_enable_tenant_rls` line, and a second `pnpm db:generate` -writes nothing. +Done when the schema change and its migration are in one commit, +`pnpm check:rls` passes, and a second `pnpm db:generate` writes nothing. diff --git a/templates/core/base/.github/workflows/ci.yml b/templates/core/base/.github/workflows/ci.yml index 813c428..56f8925 100644 --- a/templates/core/base/.github/workflows/ci.yml +++ b/templates/core/base/.github/workflows/ci.yml @@ -44,5 +44,9 @@ jobs: - run: pnpm test env: DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres + # What lets queries rely on withOrg() instead of org filters (tools/check-rls.sql). + - run: pnpm check:rls + env: + DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres - run: pnpm image:context - run: docker build --build-arg VERSION=${{ github.sha }} -t __id__-plugin . diff --git a/templates/core/base/AGENTS.md b/templates/core/base/AGENTS.md index e4fe597..bfd37f4 100644 --- a/templates/core/base/AGENTS.md +++ b/templates/core/base/AGENTS.md @@ -2,14 +2,47 @@ An erxes plugin for the new core (Postgres). `api/` is the API: Express 5, oRPC and Drizzle. `ui/` is the Module Federation remote core-ui loads. Read the -`AGENTS.md` in the folder you edit. +`AGENTS.md` in the folder you edit. `api/src/modules/items` and `ui/src/items` +are the reference feature: copy their shape for a new one. + + + +## Quality + +Every erxes repo on the new stack has this section, unchanged. The brackets name the checks that +enforce a rule; `review` marks the part no tool can check. The rewrite keeps every feature and improves the +architecture. Agents write the code and the checks judge it, so a green check lets a change ship +without line-by-line review. + +- `pnpm check` is the type check: oxfmt, type-aware oxlint on tsrs and knip in about 10 s. Run it after each edit and before each commit; it replaces `tsc`. `pnpm fix` formats and autofixes. [pnpm check] +- Port what a feature does, not its code. Fix what the old code got wrong instead of carrying it over. [review] +- Use a maintained library when one does the job. Keep dependencies near their latest release and off deprecated APIs. [typescript/no-deprecated, review] +- One way to do each job. Search for the existing helper before writing one, merge the repeats you find, delete what nothing uses. [knip, review] +- Types flow from the database schema to the contract to the UI. Infer them, so each shape is written once. [pnpm check:generated, review] +- Parse outside input with zod and narrow it, so the code needs no `any`, cast or `!`. [typescript/no-explicit-any, typescript/no-unsafe-type-assertion, typescript/no-non-null-assertion] +- Lint and type rules are the spec: when one fires, fix the code. Silencing it is never the fix, whether by a disable comment, `@ts-ignore`, an override, an ignore, a weaker option or a raised limit. A rule that is wrong changes in its own PR. [typescript/ban-ts-comment, review] +- Split a file or function that outgrows its limit by responsibility (router, service, queries). [max-lines, max-lines-per-function, review] +- Finish the work in the change, with no TODO or FIXME left in code. [no-warning-comments] +- Tests call the public interface (HTTP, the typed client, the rendered page) and assert what it does, never source strings or code shapes. [review] +- Every test runs: a skipped test or an empty suite fails the run. A failing test gets its code or its wrong expectation fixed, never loosened or deleted. [pnpm test, review] +- Log through the structured logger, with the facts as fields. A caught error is rethrown or logged with its context. [no-console, review] +- Make the long-term change in one go, with no backward-compatibility shim, stopgap or speculative option. [review] +- Docs, PRs and copy are short: plain words, active voice, what it does or the number. [review] + + + +## This repo - Gates: `pnpm check` (format, lint, types), `pnpm test` (real Postgres via `DATA_TEST_URL`), `pnpm build`. `pnpm fix` formats and fixes lint. +- Three checks the section names aren't here yet, so their rules are `[review]` + in this repo: knip, `pnpm check:generated` (CI's migration drift check is the + nearest), and `pnpm test` failing a skipped test. - Core finds the plugin by these names, so they stay fixed: plugin `__id__`, remote `__id___ui` exposing `./config` and `./__id__`, pages under `/__id__/*`. - Every table, index and constraint starts with `__id___`, and every table has - `org_id` with row-level security. Core and other plugins share the database. + `org_id` with forced row-level security. Core and other plugins share the + database. [pnpm check:rls] - The plugin reaches core only through `@erxes/plugin-sdk` (`api/src/core.ts`) and the UI's `pluginFetch`. It never reads `core_*` tables or imports core code. - Members are signed in by core: the UI sends a session token, the API checks it @@ -17,5 +50,5 @@ oRPC and Drizzle. `ui/` is the Module Federation remote core-ui loads. Read the tell a public request's organisation. - Skills in `.agents/skills/`: `endpoint` for a procedure, `schema-change` for a table or column, `verify` before calling a change done.__migrationSkill__ -- Core's own rules for plugins are its `plugin-new` skill (erxes repo, branch - `postgre`, `.agents/skills/plugin-new/SKILL.md`). +- What core promises plugins, and what counts as a breaking change, is core's + `plugin-contract` skill (erxes repo, branch `postgre`). diff --git a/templates/core/base/Dockerfile b/templates/core/base/Dockerfile index 6ba4d58..990a2d8 100644 --- a/templates/core/base/Dockerfile +++ b/templates/core/base/Dockerfile @@ -1,6 +1,6 @@ # Packages what `pnpm image:context` built on the host: the bundled API with # its production node_modules (.runtime) and the UI remote, served at /ui. -FROM node:24-bookworm-slim +FROM node:26-bookworm-slim ARG VERSION=0.1.0 WORKDIR /app COPY --chown=node:node .runtime/ ./ diff --git a/templates/core/base/_node-version b/templates/core/base/_node-version index a45fd52..6f4247a 100644 --- a/templates/core/base/_node-version +++ b/templates/core/base/_node-version @@ -1 +1 @@ -24 +26 diff --git a/templates/core/base/api/AGENTS.md b/templates/core/base/api/AGENTS.md index d2ef6b6..001cce2 100644 --- a/templates/core/base/api/AGENTS.md +++ b/templates/core/base/api/AGENTS.md @@ -1,11 +1,10 @@ # api -Node 24 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`. +Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`. - `src/main.ts` starts in this order: migrations, `core.registerManifest(manifest)`, then the server. Core installs the plugin itself in development (`PLUGINS_AUTO_INSTALL`). -- `src/config.ts` is the only file that reads `process.env`. - `src/core.ts` holds the core client and the manifest. Every permission, event and kind in the manifest starts with `__id__.`. A new scope waits for the owner's approval, so ask for one only when a procedure needs it. @@ -14,7 +13,8 @@ Node 24 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`. `canChange()`). - `src/orpc.ts`: build every procedure on `reads(action)` or `writes(action)`. Both check the permission and run the handler in `withOrg(member.orgId)`, so - `context.tx` sees one organisation's rows. Queries still filter by `orgId`. + row-level security shows `context.tx` one organisation's rows. Queries carry + no org filter; only an insert sets `orgId`, from `context.member`. - Call core (`core.forOrg(orgId)...`) outside `context.tx`; a failed core call must not roll back the plugin's own change. - Tests: `vite-plus/test`, run with `call(procedure, input, { context: { member } })`. diff --git a/templates/core/base/api/drizzle/0000_items.sql b/templates/core/base/api/drizzle/0000_items.sql index 0f82f7e..00b1815 100644 --- a/templates/core/base/api/drizzle/0000_items.sql +++ b/templates/core/base/api/drizzle/0000_items.sql @@ -9,4 +9,5 @@ CREATE TABLE "__id___items" ( ); --> statement-breakpoint CREATE INDEX "__id___items_org_created_idx" ON "__id___items" USING btree ("org_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint +CREATE UNIQUE INDEX "__id___items_org_name_key" ON "__id___items" USING btree ("org_id",lower("name"));--> statement-breakpoint SELECT core_enable_tenant_rls('__id___items'); \ No newline at end of file diff --git a/templates/core/base/api/drizzle/meta/0000_snapshot.json b/templates/core/base/api/drizzle/meta/0000_snapshot.json index 12195a8..2b0934f 100644 --- a/templates/core/base/api/drizzle/meta/0000_snapshot.json +++ b/templates/core/base/api/drizzle/meta/0000_snapshot.json @@ -1,5 +1,5 @@ { - "id": "1a44ca23-aedb-456a-a471-51e60d63b732", + "id": "5ccdfe2d-a57a-4573-bbee-ba11f21e7ddc", "prevId": "00000000-0000-0000-0000-000000000000", "version": "7", "dialect": "postgresql", @@ -81,6 +81,27 @@ "concurrently": false, "method": "btree", "with": {} + }, + "__id___items_org_name_key": { + "name": "__id___items_org_name_key", + "columns": [ + { + "expression": "org_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"name\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": {}, diff --git a/templates/core/base/api/package.json b/templates/core/base/api/package.json index 87c4b96..6323da5 100644 --- a/templates/core/base/api/package.json +++ b/templates/core/base/api/package.json @@ -4,7 +4,8 @@ "private": true, "files": [ "dist", - "drizzle" + "drizzle", + "src" ], "type": "module", "imports": { @@ -16,6 +17,7 @@ "build": "vp pack src/main.ts src/telemetry.ts --format esm --sourcemap --no-dts", "start": "node --enable-source-maps --import ./dist/telemetry.mjs dist/main.mjs", "db:generate": "drizzle-kit generate", + "db:migrate": "node --env-file-if-exists=../.env src/db/migrate.ts", "db:check": "drizzle-kit check" }, "dependencies": { @@ -31,6 +33,7 @@ "cors": "^2.8.6", "drizzle-orm": "0.45.4", "express": "^5.3.0", + "import-in-the-middle": "^3.6.0", "pg": "^8.23.1", "pino": "^10.4.0", "pino-http": "^11.0.0", diff --git a/templates/core/base/api/src/config.ts b/templates/core/base/api/src/config.ts index 3e3e255..6080f0e 100644 --- a/templates/core/base/api/src/config.ts +++ b/templates/core/base/api/src/config.ts @@ -22,6 +22,8 @@ const Env = z.object({ CORE_UI_URL: z.url().optional(), LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'), VERSION: z.string().default('0.1.0'), + /** Traces go to this OTLP collector; the SDK reads the other OTEL_* variables itself. */ + OTEL_EXPORTER_OTLP_ENDPOINT: z.url().optional(), }); const env = Env.parse(process.env); @@ -37,4 +39,5 @@ export const config = { coreUiOrigin: new URL(env.CORE_UI_URL ?? env.CORE_URL).origin, logLevel: env.LOG_LEVEL, version: env.VERSION, + tracing: Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT), }; diff --git a/templates/core/base/api/src/db/client.ts b/templates/core/base/api/src/db/client.ts index f971095..0209b56 100644 --- a/templates/core/base/api/src/db/client.ts +++ b/templates/core/base/api/src/db/client.ts @@ -1,4 +1,4 @@ -import { sql } from 'drizzle-orm'; +import { DrizzleQueryError, sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/node-postgres'; import pg from 'pg'; import { config, PLUGIN } from '#/config.ts'; @@ -10,10 +10,17 @@ export const db = drizzle({ client: pool, schema, casing: 'snake_case' }); export type Tx = Parameters[0]>[0]; +/** The unique index a failed write hit (Postgres 23505), or undefined for any other error. */ +export const uniqueViolation = (error: unknown) => { + const cause = error instanceof DrizzleQueryError ? error.cause : error; + + return cause instanceof pg.DatabaseError && cause.code === '23505' ? cause.constraint : undefined; +}; + /** * Runs `fn` in a transaction scoped to one organisation. Row-level security - * shows nothing outside it, so every query that touches a table goes through - * here. Services still filter by `orgId`; RLS is the safety net. + * shows and accepts only that organisation's rows, so queries carry no org + * filter, and every query that touches a table goes through here. */ export const withOrg = (orgId: string, fn: (tx: Tx) => Promise) => db.transaction(async (tx) => { diff --git a/templates/core/base/api/src/db/migrate.ts b/templates/core/base/api/src/db/migrate.ts index 626855e..cf469f7 100644 --- a/templates/core/base/api/src/db/migrate.ts +++ b/templates/core/base/api/src/db/migrate.ts @@ -3,7 +3,7 @@ import { join, resolve } from 'node:path'; import { sql } from 'drizzle-orm'; import { readMigrationFiles } from 'drizzle-orm/migrator'; import { z } from 'zod'; -import { db } from './client.ts'; +import { db, pool } from './client.ts'; /** Our own tracking table: core and other plugins in the same database keep theirs. */ export const MIGRATIONS_TABLE = '__drizzle_migrations___id__'; @@ -69,3 +69,9 @@ export const runMigrations = async () => { return applied; }); }; + +// `pnpm db:migrate` applies them without starting the API. +if (import.meta.main) { + await runMigrations(); + await pool.end(); +} diff --git a/templates/core/base/api/src/db/schema.ts b/templates/core/base/api/src/db/schema.ts index e326e1d..3fec9d6 100644 --- a/templates/core/base/api/src/db/schema.ts +++ b/templates/core/base/api/src/db/schema.ts @@ -1,9 +1,13 @@ import { randomUUID } from 'node:crypto'; -import { index, text, timestamp } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; +import { index, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'; import { table } from './table.ts'; +/** Names are unique per organisation, ignoring case. A write that breaks it fails with 23505. */ +export const ITEM_NAME_INDEX = '__id___items_org_name_key'; + /** - * The example table. `org_id` is the core organisation; row-level security + * The reference table. `org_id` is the core organisation; row-level security * (`core_enable_tenant_rls` in the migration) shows each transaction only its * organisation's rows. Ids are text, so imported Mongo `_id`s fit. */ @@ -23,5 +27,8 @@ export const items = table( .defaultNow() .$onUpdate(() => new Date()), }, - (t) => [index('__id___items_org_created_idx').on(t.orgId, t.createdAt.desc(), t.id.desc())], + (t) => [ + index('__id___items_org_created_idx').on(t.orgId, t.createdAt.desc(), t.id.desc()), + uniqueIndex(ITEM_NAME_INDEX).on(t.orgId, sql`lower(${t.name})`), + ], ); diff --git a/templates/core/base/api/src/modules/items/__tests__/items.test.ts b/templates/core/base/api/src/modules/items/__tests__/items.test.ts index f2a3e8e..a80755f 100644 --- a/templates/core/base/api/src/modules/items/__tests__/items.test.ts +++ b/templates/core/base/api/src/modules/items/__tests__/items.test.ts @@ -1,66 +1,86 @@ import type { PluginMember } from '@erxes/plugin-sdk'; -import { call } from '@orpc/server'; +import { createRouterClient } from '@orpc/server'; import { describe, expect, it } from 'vite-plus/test'; import { PERMISSIONS } from '#/core.ts'; import { router } from '#/router.ts'; -const memberOf = (orgId: string, permissions: string[]): PluginMember => ({ - userId: `user-${orgId}`, - orgId, - role: 'member', - permissions, - can: (action) => permissions.includes(action), - tier: 'pro', - access: 'full', - canChange: () => true, -}); +/** The typed client the UI uses, served in-process as this member. */ +const clientAs = (orgId: string, permissions: string[] = Object.values(PERMISSIONS)) => { + const member: PluginMember = { + userId: `user-${orgId}`, + orgId, + role: 'member', + permissions, + can: (action) => permissions.includes(action), + tier: 'pro', + access: 'full', + canChange: () => true, + }; -const manager = (orgId: string) => ({ - context: { member: memberOf(orgId, [PERMISSIONS.view, PERMISSIONS.manage]) }, -}); + return createRouterClient(router, { context: { member } }); +}; describe('items', () => { - it('creates, lists newest first in pages, and updates', async () => { - const first = await call(router.items.create, { name: 'First' }, manager('org-a')); - const second = await call(router.items.create, { name: 'Second' }, manager('org-a')); + it('creates, lists newest first in pages, updates and deletes', async () => { + const client = clientAs('org-a'); + const first = await client.items.create({ name: 'First' }); + const second = await client.items.create({ name: 'Second' }); expect(first).toMatchObject({ name: 'First', description: '', createdBy: 'user-org-a' }); + expect(first).not.toHaveProperty('orgId'); - const page = await call(router.items.list, { limit: 1 }, manager('org-a')); + const page = await client.items.list({ limit: 1 }); expect(page.items.map((item) => item.id)).toEqual([second.id]); expect(page.nextCursor).toBe(second.id); - const next = await call(router.items.list, { limit: 1, cursor: second.id }, manager('org-a')); + const next = await client.items.list({ limit: 1, cursor: second.id }); expect(next.items.map((item) => item.id)).toEqual([first.id]); expect(next.nextCursor).toBeNull(); - const updated = await call( - router.items.update, - { id: first.id, description: 'Changed' }, - manager('org-a'), - ); + await expect( + client.items.update({ id: first.id, name: 'First', description: 'Changed' }), + ).resolves.toMatchObject({ name: 'First', description: 'Changed' }); + await expect(client.items.remove({ id: first.id })).resolves.toEqual({ id: first.id }); + await expect(client.items.list({})).resolves.toMatchObject({ items: [{ id: second.id }] }); + }); + + it('refuses a name the organisation already uses, ignoring case', async () => { + const client = clientAs('org-b'); + const taken = { code: 'ITEM_NAME_TAKEN', status: 409, defined: true }; + + await client.items.create({ name: 'Tools' }); + const other = await client.items.create({ name: 'Parts' }); - expect(updated).toMatchObject({ name: 'First', description: 'Changed' }); + await expect(client.items.create({ name: 'tools' })).rejects.toMatchObject({ + ...taken, + data: { name: 'tools' }, + }); + await expect(client.items.update({ id: other.id, name: 'TOOLS' })).rejects.toMatchObject({ + ...taken, + data: { name: 'TOOLS' }, + }); }); - it('shows each organisation only its own items', async () => { - const theirs = await call(router.items.create, { name: 'Theirs' }, manager('org-b')); - const ours = await call(router.items.list, {}, manager('org-c')); + it('shows and changes only the items of its own organisation', async () => { + const theirs = await clientAs('org-c').items.create({ name: 'Shared name' }); + const ours = clientAs('org-d'); - expect(ours.items).toEqual([]); - await expect( - call(router.items.update, { id: theirs.id, name: 'Mine now' }, manager('org-c')), - ).rejects.toMatchObject({ code: 'NOT_FOUND' }); + await expect(ours.items.list({})).resolves.toMatchObject({ items: [] }); + await expect(ours.items.create({ name: 'Shared name' })).resolves.toMatchObject({ + name: 'Shared name', + }); + await expect(ours.items.update({ id: theirs.id, name: 'Mine now' })).rejects.toMatchObject({ + code: 'NOT_FOUND', + }); + await expect(ours.items.remove({ id: theirs.id })).rejects.toMatchObject({ code: 'NOT_FOUND' }); }); it('refuses members without the permission', async () => { - const viewer = { context: { member: memberOf('org-d', [PERMISSIONS.view]) } }; + const viewer = clientAs('org-e', [PERMISSIONS.view]); - await expect(call(router.items.create, { name: 'No' }, viewer)).rejects.toMatchObject({ - code: 'FORBIDDEN', - }); - await expect(call(router.items.list, {}, viewer)).resolves.toMatchObject({ items: [] }); + await expect(viewer.items.create({ name: 'No' })).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect(viewer.items.list({})).resolves.toMatchObject({ items: [] }); }); }); diff --git a/templates/core/base/api/src/modules/items/items.ts b/templates/core/base/api/src/modules/items/items.ts index 1d79880..a864998 100644 --- a/templates/core/base/api/src/modules/items/items.ts +++ b/templates/core/base/api/src/modules/items/items.ts @@ -1,18 +1,39 @@ -import { ORPCError } from '@orpc/server'; -import { and, desc, eq, ilike, sql } from 'drizzle-orm'; +import { type ORPCErrorConstructorMap, ORPCError } from '@orpc/server'; +import { and, desc, eq, getTableColumns, ilike, sql } from 'drizzle-orm'; import { z } from 'zod'; import { PERMISSIONS } from '#/core.ts'; -import { items } from '#/db/schema.ts'; +import { uniqueViolation } from '#/db/client.ts'; +import { ITEM_NAME_INDEX, items } from '#/db/schema.ts'; import { reads, writes } from '#/orpc.ts'; -const Fields = z.object({ - name: z.string().trim().min(1).max(200), - description: z.string().trim().max(5000), -}); +/** What a procedure returns: the row without `org_id`, which the caller already knows. */ +const { orgId, ...columns } = getTableColumns(items); + +const Name = z.string().trim().min(1).max(200); +const Description = z.string().trim().max(5000); + +/** The failures a client can branch on: `isDefinedError(error) && error.code === ...`. */ +const itemErrors = { + ITEM_NAME_TAKEN: { + status: 409, + message: 'Another item has this name', + data: z.object({ name: z.string() }), + }, +}; + +/** The one place Postgres's 23505 on the name index becomes ITEM_NAME_TAKEN. */ +const nameTaken = + (errors: ORPCErrorConstructorMap, name: string) => + (error: unknown): never => { + if (uniqueViolation(error) === ITEM_NAME_INDEX) + throw errors.ITEM_NAME_TAKEN({ data: { name } }); + + throw error; + }; const escapeLike = (text: string) => text.replaceAll(/[\\%_]/g, '\\$&'); -/** Newest first, in pages: `nextCursor` is the id to pass for the next page. */ +/** Newest first, in keyset pages: `nextCursor` is the id to pass for the next page. */ const list = reads(PERMISSIONS.view) .input( z.object({ @@ -21,24 +42,18 @@ const list = reads(PERMISSIONS.view) limit: z.number().int().min(1).max(100).default(50), }), ) - .handler(async ({ input, context: { tx, member } }) => { + .handler(async ({ input, context: { tx } }) => { const after = input.cursor ? sql`(${items.createdAt}, ${items.id}) < (select created_at, id from ${items} where id = ${input.cursor})` : undefined; - const rows = await tx - .select() + .select(columns) .from(items) .where( - and( - eq(items.orgId, member.orgId), - input.search ? ilike(items.name, `%${escapeLike(input.search)}%`) : undefined, - after, - ), + and(input.search ? ilike(items.name, `%${escapeLike(input.search)}%`) : undefined, after), ) .orderBy(desc(items.createdAt), desc(items.id)) .limit(input.limit + 1); - const page = rows.slice(0, input.limit); return { @@ -48,12 +63,14 @@ const list = reads(PERMISSIONS.view) }); const create = writes(PERMISSIONS.manage) - .input(Fields.partial({ description: true })) - .handler(async ({ input, context: { tx, member } }) => { + .errors(itemErrors) + .input(z.object({ name: Name, description: Description.default('') })) + .handler(async ({ input, context: { tx, member }, errors }) => { const [item] = await tx .insert(items) .values({ ...input, orgId: member.orgId, createdBy: member.userId }) - .returning(); + .returning(columns) + .catch(nameTaken(errors, input.name)); if (!item) throw new ORPCError('INTERNAL_SERVER_ERROR'); @@ -61,17 +78,29 @@ const create = writes(PERMISSIONS.manage) }); const update = writes(PERMISSIONS.manage) - .input(Fields.partial().extend({ id: z.string() })) - .handler(async ({ input: { id, ...fields }, context: { tx, member } }) => { + .errors(itemErrors) + .input(z.object({ id: z.string(), name: Name, description: Description.optional() })) + .handler(async ({ input: { id, ...fields }, context: { tx }, errors }) => { const [item] = await tx .update(items) .set(fields) - .where(and(eq(items.id, id), eq(items.orgId, member.orgId))) - .returning(); + .where(eq(items.id, id)) + .returning(columns) + .catch(nameTaken(errors, fields.name)); + + if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' }); + + return item; + }); + +const remove = writes(PERMISSIONS.manage) + .input(z.object({ id: z.string() })) + .handler(async ({ input, context: { tx } }) => { + const [item] = await tx.delete(items).where(eq(items.id, input.id)).returning({ id: items.id }); if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' }); return item; }); -export const itemProcedures = { list, create, update }; +export const itemProcedures = { list, create, update, remove }; diff --git a/templates/core/base/api/src/telemetry.ts b/templates/core/base/api/src/telemetry.ts index 7d1486a..74f11ef 100644 --- a/templates/core/base/api/src/telemetry.ts +++ b/templates/core/base/api/src/telemetry.ts @@ -1,15 +1,16 @@ -import { register } from 'node:module'; import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'; import { PinoInstrumentation } from '@opentelemetry/instrumentation-pino'; import { NodeSDK } from '@opentelemetry/sdk-node'; +import { register } from 'import-in-the-middle/register-hooks.mjs'; +import { config } from '#/config.ts'; // Loaded before the app with `node --import ./src/telemetry.ts`. Off unless an -// OTLP endpoint is set; the SDK reads the other OTEL_* variables itself. -if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) { - // ESM modules are patched through this loader hook. - register('@opentelemetry/instrumentation/hook.mjs', import.meta.url); +// OTLP endpoint is set. +if (config.tracing) { + // ESM modules are patched through this in-thread loader hook (module.registerHooks). + register(); const sdk = new NodeSDK({ serviceName: '__id__-api', diff --git a/templates/core/base/api/src/test/core-functions.sql b/templates/core/base/api/src/test/core-functions.sql new file mode 100644 index 0000000..9a675a8 --- /dev/null +++ b/templates/core/base/api/src/test/core-functions.sql @@ -0,0 +1,18 @@ +-- Core's tenant functions (erxes packages/db/drizzle), which plugin migrations +-- call. Tests and tools/check-rls.sh install them in their throwaway databases. +CREATE OR REPLACE FUNCTION core_tenant_visible(p_org_id text) RETURNS boolean +LANGUAGE sql STABLE AS $$ + SELECT p_org_id = current_setting('app.org_id', true) + OR coalesce(current_setting('app.system', true), '') = 'on' +$$; +CREATE OR REPLACE FUNCTION core_enable_tenant_rls(p_table regclass, p_column text DEFAULT 'org_id') RETURNS void +LANGUAGE plpgsql AS $$ +BEGIN + IF p_column !~ '^[a-z_][a-z0-9_]*$' THEN + RAISE EXCEPTION 'core_enable_tenant_rls: invalid column %', p_column; + END IF; + EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', p_table); + EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', p_table); + EXECUTE format('DROP POLICY IF EXISTS tenant ON %s', p_table); + EXECUTE format('CREATE POLICY tenant ON %s USING (core_tenant_visible(%I)) WITH CHECK (core_tenant_visible(%I))', p_table, p_column, p_column); +END $$; diff --git a/templates/core/base/api/src/test/setup.ts b/templates/core/base/api/src/test/setup.ts index d142e7a..7becb81 100644 --- a/templates/core/base/api/src/test/setup.ts +++ b/templates/core/base/api/src/test/setup.ts @@ -1,4 +1,5 @@ import { randomBytes } from 'node:crypto'; +import { readFileSync } from 'node:fs'; import pg from 'pg'; import { afterAll } from 'vite-plus/test'; @@ -15,22 +16,8 @@ if (!adminUrl) { const ROLE = '__id___test'; const database = `__id___test_${randomBytes(4).toString('hex')}`; -// Core's tenant functions (erxes packages/db/drizzle), which plugin migrations call. -const CORE_FUNCTIONS = ` -CREATE OR REPLACE FUNCTION core_tenant_visible(p_org_id text) RETURNS boolean -LANGUAGE sql STABLE AS $$ - SELECT p_org_id = current_setting('app.org_id', true) - OR coalesce(current_setting('app.system', true), '') = 'on' -$$; -CREATE OR REPLACE FUNCTION core_enable_tenant_rls(p_table regclass, p_column text DEFAULT 'org_id') RETURNS void -LANGUAGE plpgsql AS $$ -BEGIN - EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', p_table); - EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', p_table); - EXECUTE format('DROP POLICY IF EXISTS tenant ON %s', p_table); - EXECUTE format('CREATE POLICY tenant ON %s USING (core_tenant_visible(%I)) WITH CHECK (core_tenant_visible(%I))', p_table, p_column, p_column); -END $$; -`; +// Core's tenant functions, which plugin migrations call. +const CORE_FUNCTIONS = readFileSync(new URL('./core-functions.sql', import.meta.url), 'utf8'); const urlOf = (name: string, role?: string) => { const url = new URL(adminUrl); diff --git a/templates/core/base/package.json b/templates/core/base/package.json index 984c412..a9dd901 100644 --- a/templates/core/base/package.json +++ b/templates/core/base/package.json @@ -11,18 +11,20 @@ "test": "vp test run", "db:generate": "pnpm --filter @__id__/api db:generate", "db:check": "pnpm --filter @__id__/api db:check", + "db:migrate": "pnpm --filter @__id__/api db:migrate", + "check:rls": "bash tools/check-rls.sh", "dev:api": "pnpm --filter @__id__/api dev", "dev:ui": "pnpm --filter @__id__/ui dev", "image:context": "pnpm build && rm -rf .runtime && pnpm --filter @__id__/api deploy --prod .runtime" }, "devDependencies": { - "@types/node": "^24.19.2", + "@types/node": "^26.6.6", "tsrs": "0.25.0-ts7.1.0-beta", "typescript": "7.0.2", "vite-plus": "catalog:" }, "engines": { - "node": ">=24" + "node": ">=26" }, "packageManager": "pnpm@__pnpmVersion__" } diff --git a/templates/core/base/pnpm-workspace.yaml b/templates/core/base/pnpm-workspace.yaml index 3d6a486..a24ca14 100644 --- a/templates/core/base/pnpm-workspace.yaml +++ b/templates/core/base/pnpm-workspace.yaml @@ -6,6 +6,10 @@ injectWorkspacePackages: true catalog: vite: npm:@voidzero-dev/vite-plus-core@1.6.0 vite-plus: 1.6.0 +# Core publishes its packages under the v2-next tag, often more than once a day; +# the release-age gate stays on for everything else. +minimumReleaseAgeExclude: + - '@erxes/*' overrides: 'vite@*': 'catalog:' # Install scripts nothing here needs: esbuild ships its binary as an optional diff --git a/templates/core/base/tools/check-rls.sh b/templates/core/base/tools/check-rls.sh new file mode 100644 index 0000000..6ac5918 --- /dev/null +++ b/templates/core/base/tools/check-rls.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Migrates a throwaway database on DATA_TEST_URL's server, runs the tenancy +# guard (tools/check-rls.sql) on it and fails on any problem it lists. +set -euo pipefail + +cd "$(dirname "$0")/.." + +server=${DATA_TEST_URL:?Set DATA_TEST_URL to a Postgres superuser URL, as for pnpm test} +name="__id___rls_check_$$" +# The same server and options, another database. +url=$(node -e 'const u = new URL(process.argv[1]); u.pathname = `/${process.argv[2]}`; process.stdout.write(u.href)' "$server" "$name") + +psql "$server" -qX -v ON_ERROR_STOP=1 -c "CREATE DATABASE $name" +trap 'psql "$server" -qX -c "DROP DATABASE IF EXISTS $name WITH (FORCE)"' EXIT + +# Core's tenant functions, which the migrations call. +psql "$url" -qX -v ON_ERROR_STOP=1 -f api/src/test/core-functions.sql +# Only DATA_URL matters to a migration; the others satisfy config.ts. +DATA_URL="$url" CORE_URL=http://127.0.0.1:9 PLUGIN_SECRET=rls-check-only-secret-xxxxxxxxxxxx \ + LOG_LEVEL=silent pnpm --silent db:migrate > /dev/null + +problems=$(psql "$url" -qXAt -v ON_ERROR_STOP=1 -f tools/check-rls.sql) + +if [[ -n "$problems" ]]; then + echo "$problems" + echo 'Tenancy guard failed (tools/check-rls.sql).' + exit 1 +fi + +echo 'Every table with org_id has forced row level security and only the tenant policy, every other table is listed, every name starts with __id___.' diff --git a/templates/core/base/tools/check-rls.sql b/templates/core/base/tools/check-rls.sql new file mode 100644 index 0000000..5696947 --- /dev/null +++ b/templates/core/base/tools/check-rls.sql @@ -0,0 +1,80 @@ +-- The tenancy guard, run by tools/check-rls.sh on a freshly migrated database. +-- Every row it returns is a problem; no rows means the schema passes. +-- +-- 1. A table with org_id has row level security enabled and forced, and the +-- tenant policy core_enable_tenant_rls() makes: permissive, for all +-- commands, USING and WITH CHECK core_tenant_visible(org_id). Any other +-- permissive policy would let more rows through, so it fails too. This is +-- what lets withOrg() isolate organisations with no filter in the query. +-- 2. A table without org_id is in no_org_id, with the reason. +-- 3. Every table, index, sequence and view, and every table constraint, +-- starts with __id___: core and other plugins share the database. +with no_org_id (table_name, reason) as ( + values + ('__drizzle_migrations___id__', 'The migration log (api/src/db/migrate.ts).') +), +relations as ( + select c.oid, n.nspname, c.relname, c.relkind, c.relrowsecurity, c.relforcerowsecurity + from pg_class c + join pg_namespace n on n.oid = c.relnamespace + where n.nspname not in ('pg_catalog', 'information_schema') and n.nspname not like 'pg\_toast%' +), +tables as ( + select r.*, + exists ( + select 1 from pg_attribute a where a.attrelid = r.oid and a.attname = 'org_id' and not a.attisdropped + ) as has_org_id, + l.table_name is not null as listed + from relations r + left join no_org_id l on r.nspname = 'public' and l.table_name = r.relname + where r.relkind in ('r', 'p', 'f') +), +tenant_tables as ( + select * from tables where has_org_id +), +policies as ( + select tt.oid, p.policyname, + p.permissive = 'PERMISSIVE' as permissive, + p.cmd = 'ALL' + and p.qual = 'core_tenant_visible(org_id)' + and p.with_check = 'core_tenant_visible(org_id)' as is_tenant_policy + from tenant_tables tt + join pg_policies p on p.schemaname = tt.nspname and p.tablename = tt.relname +) +select format('%s: %s', relname, concat_ws(', ', + case when not relrowsecurity then 'row level security is off' end, + case when not relforcerowsecurity then 'row level security is not forced' end, + case when not exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy) + then 'no tenant policy on core_tenant_visible(org_id): add SELECT core_enable_tenant_rls(...) to its migration' end)) +from tenant_tables tt +where not (relrowsecurity and relforcerowsecurity + and exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy)) +union all +select format('%s: permissive policy %s is not the tenant check, so it lets more rows through', tt.relname, p.policyname) +from tenant_tables tt +join policies p on p.oid = tt.oid +where p.permissive and not p.is_tenant_policy +union all +select format('%s has no org_id: add it, or list the table in no_org_id with the reason', relname) +from tables +where not has_org_id and not listed +union all +select format('no_org_id lists %s, which %s', l.table_name, + case when t.relname is null then 'does not exist' else 'has org_id' end) +from no_org_id l +left join tables t on t.nspname = 'public' and t.relname = l.table_name +where t.relname is null or t.has_org_id +union all +select format('%s %s does not start with __id___', + case relkind when 'i' then 'index' when 'I' then 'index' when 'S' then 'sequence' when 'v' then 'view' + when 'm' then 'materialized view' else 'table' end, relname) +from relations +where relkind in ('r', 'p', 'i', 'I', 'S', 'v', 'm', 'f') + and not starts_with(relname, '__id___') + and relname not in ('__drizzle_migrations___id__', '__drizzle_migrations___id___pkey', '__drizzle_migrations___id___id_seq') +union all +select format('constraint %s on %s does not start with __id___', co.conname, co.conrelid::regclass) +from pg_constraint co +join relations r on r.oid = co.conrelid +where not starts_with(co.conname, '__id___') and co.conrelid is distinct from to_regclass('public.__drizzle_migrations___id__') +order by 1; diff --git a/templates/core/base/ui/src/items/ItemSheet.tsx b/templates/core/base/ui/src/items/ItemSheet.tsx index c52669a..fe8f9bb 100644 --- a/templates/core/base/ui/src/items/ItemSheet.tsx +++ b/templates/core/base/ui/src/items/ItemSheet.tsx @@ -1,34 +1,25 @@ +import { isDefinedError } from '@orpc/client'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { Button, Input, Label, Sheet, Textarea, toast } from 'erxes-ui'; +import { Button, Input, Label, Sheet, Textarea } from 'erxes-ui'; import { useTranslation } from 'react-i18next'; import { orpc } from '../orpc.ts'; import { type Item, useOpenItem } from './useItems.ts'; const textOf = (value: FormDataEntryValue | null) => (typeof value === 'string' ? value : ''); -/** The side panel: a new item, or one from the list to change. */ -export const ItemSheet = ({ items }: { items: Item[] }) => { +/** A new item (`item` undefined) or a change to one. ITEM_NAME_TAKEN shows on the name field. */ +const ItemForm = ({ item, onSaved }: { item?: Item; onSaved: () => void }) => { const { t } = useTranslation('__id__'); - const { openId, close } = useOpenItem(); const queryClient = useQueryClient(); - const item = items.find((candidate) => candidate.id === openId); - - const options = { - onSuccess: () => { - void queryClient.invalidateQueries({ queryKey: orpc.items.key() }); - close(); - }, - onError: (error: Error) => { - toast({ - variant: 'destructive', - title: t('save-failed', 'Could not save'), - description: error.message, - }); - }, + const onSuccess = () => { + void queryClient.invalidateQueries({ queryKey: orpc.items.key() }); + onSaved(); }; - - const create = useMutation(orpc.items.create.mutationOptions(options)); - const update = useMutation(orpc.items.update.mutationOptions(options)); + const create = useMutation(orpc.items.create.mutationOptions({ onSuccess })); + const update = useMutation(orpc.items.update.mutationOptions({ onSuccess })); + const { error, isPending } = item ? update : create; + const takenName = + isDefinedError(error) && error.code === 'ITEM_NAME_TAKEN' ? error.data.name : null; const save = (form: FormData) => { const fields = { @@ -40,6 +31,50 @@ export const ItemSheet = ({ items }: { items: Item[] }) => { else create.mutate(fields); }; + return ( +
+ +
+ + + {takenName !== null && ( +

+ {t('name-taken', 'Another item is already called {{name}}.', { name: takenName })} +

+ )} +
+
+ +