@starci/eslint-canon-be 3.6.6 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +1 -0
- package/dist/ai-gateway.d.ts +19 -0
- package/dist/ai-gateway.js +184 -0
- package/dist/app-composition.d.ts +1 -1
- package/dist/app-composition.js +18 -5
- package/dist/auth-passport.d.ts +14 -0
- package/dist/auth-passport.js +106 -0
- package/dist/index.js +6 -0
- package/dist/infra-owner.js +7 -5
- package/dist/jwt-alg.js +1 -1
- package/dist/lib/hfs-view.d.ts +5 -0
- package/dist/module-layering.js +6 -2
- package/dist/no-raw-sql.d.ts +9 -0
- package/dist/no-raw-sql.js +78 -0
- package/package.json +1 -1
- package/runtime/knowledge/hfs/canon-pins.yaml +54 -24
- package/runtime/knowledge/hfs/fe-stack.yaml +4 -11
- package/runtime/knowledge/hfs/rules.yaml +248 -155
- package/runtime/knowledge/hfs/slots.yaml +185 -174
- package/runtime/scripts/hfs/architecture/canon-clones.mjs +1 -1
- package/runtime/scripts/hfs/architecture/{supabase-be.mjs → identity.mjs} +45 -15
- package/runtime/scripts/hfs/architecture/index.mjs +2 -3
- package/runtime/scripts/hfs/architecture/{supabase-ast.mjs → jwt-ast.mjs} +2 -103
- package/runtime/scripts/hfs/architecture/register-once.mjs +1 -1
- package/runtime/scripts/hfs/architecture/schema-owner.mjs +29 -4
- package/runtime/scripts/hfs/architecture/server-action.mjs +3 -4
- package/runtime/scripts/hfs/architecture/side-boundary.mjs +1 -1
- package/runtime/scripts/hfs/architecture/{supabase-keys.mjs → sql-keys.mjs} +1 -1
- package/runtime/scripts/hfs/architecture/sql-owner.mjs +25 -27
- package/runtime/scripts/hfs/architecture/transport-owner.mjs +7 -3
- package/runtime/scripts/hfs/declaration-shape.mjs +15 -18
- package/runtime/scripts/hfs/manifest-shape.mjs +4 -4
- package/runtime/scripts/hfs/rule-params-shape.mjs +4 -1
- package/runtime/scripts/hfs/rules/database-constants.mjs +8 -10
- package/runtime/scripts/hfs/rules/database-migrations.mjs +3 -3
- package/runtime/scripts/hfs/slot-app-view.mjs +1 -1
- package/runtime/scripts/hfs/slots.mjs +8 -2
- package/runtime/scripts/lib/secret-patterns.mjs +2 -2
- package/runtime/scripts/hfs/architecture/supabase-tables.mjs +0 -50
- package/runtime/scripts/hfs/architecture/supabase.mjs +0 -226
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.7.0 - 2026-10-29
|
|
4
|
+
|
|
5
|
+
- Added: the `auth-passport` law (contexts/code/be/api-auth.md BE-AUTH-2): `own-jwks-only` (R329 `BE_AUTH_JWT_OWN_JWKS`) refuses `createRemoteJWKSet`, `decodeJwt` and `decodeProtectedHeader` of jose anywhere and `jwtVerify` outside `integrations/passport`; `refresh-token-cookie-only` (R330 `BE_AUTH_REFRESH_COOKIE`) refuses a `refreshToken`/`refresh_token` property or member and a refresh cookie set or cleared outside `integrations/passport`.
|
|
6
|
+
- Added: `no-raw-sql` (R334 `BE_PERSISTENCE_NO_RAW_SQL`, lite): no `.query(` and no `sql` template outside `platform/database`, and `callDbFunction` names only a listed database function.
|
|
7
|
+
- Changed: `no-raw-sql` also refuses a query builder that names no entity (`createQueryBuilder("orders", "o")`, `createQueryBuilder()`) and `getRepository(...)` outside `platform/database`: a builder is `createQueryBuilder(Entity, "alias")` on the injected EntityManager.
|
|
8
|
+
- Changed: `no-folder-reexport` admits, in lite only, a capability's `persistence/entities/index.ts` that declares its `<c>Entities` list (BE-PERSISTENCE-3); the machine `schema-owner` (R35) checks the lite shape (the list and its name in `PRIMARY_ENTITIES`), and the dead-export count already counts `<c>Entities` once `PRIMARY_ENTITIES` names it (spec added).
|
|
9
|
+
- Changed: `app-file-budget` (R246 `BE_APP_COMPOSITION_BUDGET`) counts a slot file's lines excluding import declarations, a multi-line import included, so naming one more capability costs no budget; the numbers are unchanged (`<app>.env.ts` 150 in both editions).
|
|
10
|
+
- Changed: the bundled slot manifest 3.9.0 replaces the lite `app.supabase*` slots with `app.db` (`db/migrations`, `db/migrations/archive`, `db/seed.sql`, the managed `db/bootstrap.sql`), `be.integrations.supabase` with `be.integrations.passport` and `be.integrations.object-storage`, removes `fe.route.callback`, sets lite `schemaAuthority: sql`, gives lite TypeORM entities in `be.persistence`, adds `ruleParams.be.dbFunctions`, and moves the S3 SDKs to `integrations/object-storage` and the identity libraries to `integrations/passport` in `infraOwners` (`@supabase/*`, `minio` and `bcrypt` nowhere); the bundled rule catalog retires R216, R217, R219, R254 and R287 and adds R328-R334, so `infra-import-owner` holds R328 `BE_AUTH_PASSPORT_OWNER` and R331 `BE_STORAGE_OWNER`; R36 runs in full only; `jwt-alg-pinned` reads `architecture/jwt-ast.mjs`; the bundled canon pins name hfs 4.10.0, eslint-canon-be 3.7.0, eslint-canon-fe 9.5.0 and the Grammar family 0.15.11, pin `@nestjs/passport` 11.0.5 (CommonJS on the Nest 11 line), `passport` 0.7.0, `passport-google-oauth20` 2.0.0, `passport-local` 1.0.0, `bcryptjs` 3.0.3 and their types (tokens are signed and verified with `jose`; `@nestjs/jwt` stays allowed in `integrations/passport` but unpinned), and drop `@supabase/ssr`, `@supabase/supabase-js` and the `supabase` CLI.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
## 3.6.8 - 2026-10-29
|
|
14
|
+
|
|
15
|
+
- Added: the `ai-gateway` law (contexts/code/be/ai.md). `provider-key-custody` (R326 `BE_AI_KEY_CUSTODY`) refuses an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, the one list: `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY` and the rest, with their `_FILE` twins) named in a literal, a member or a property anywhere but the gateway's custody owner `integrations/ai-gateway`, specs and the test world included. `ai-client-through-gateway` (R327 `BE_AI_GATEWAY_CLIENT`) lets code build only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai` (found by import), each from an inline options object with no spread, `configuration.baseURL` a member of a `<c>.options.ts` type and `apiKey` the `reveal()` of a `platform/config` `Secret`.
|
|
16
|
+
- Changed: the bundled slot manifest gives the model libraries their owners in `ruleParams.be.infraOwners` (`@starci/ai-router` to `integrations/ai-gateway`, `@langchain/*` to `integrations/ai`; `openai`, `langchain`, `@langchain/langgraph`, `@langchain/community` and the provider SDKs nowhere) and lists R326 and R327 on `be.integrations`, so `infra-import-owner` (R90) holds LangChain in one integration and refuses provider SDKs and agent frameworks; its `nowhere` message names the model and agent owners. The bundled rule catalog carries R326 and R327; the bundled canon pins name hfs 4.9.11, eslint-canon-be 3.6.8, eslint-canon-fe 9.4.9, the Grammar family 0.15.10 (grammar, eslint-grammar-core, eslint-grammar-offset-pop), and pin `@langchain/core` 1.3.1 and `@langchain/openai` 1.8.0.
|
|
17
|
+
|
|
18
|
+
## 3.6.7 - 2026-10-29
|
|
19
|
+
|
|
20
|
+
- Changed: the bundled canon pins name hfs 4.9.10, eslint-canon-be 3.6.7, eslint-canon-fe 9.4.8, eslint-grammar-core 0.15.9 and eslint-grammar-offset-pop 0.15.9. No rule changed.
|
|
21
|
+
|
|
3
22
|
## 3.6.6 - 2026-10-29
|
|
4
23
|
|
|
5
24
|
- Changed: the bundled canon pins name the Grammar family 0.15.8 (grammar, eslint-grammar-core, eslint-grammar-offset-pop), eslint-canon-fe 9.4.7 and eslint-canon-be 3.6.6. No rule changed.
|
package/README.md
CHANGED
|
@@ -40,6 +40,7 @@ A sample, not the list:
|
|
|
40
40
|
| **Errors** | A `catch` rethrows, calls a method on a `Logger` receiver (typed, from `platform/logging`) or returns an outcome carrying its cause; a `DomainError` subclass lives only in `errors/<capability>.error.ts` of its owner, and that file is one code enum, one `Record<Code, ErrorKind>` table and one empty class; a `throw` throws a `DomainError`, never a bare `Error`, a framework exception or a platform error out of a domain (`catch-must-account`, `error-home`, `throw-domain-error`, `error-family-shape`) |
|
|
41
41
|
| **Schema authority** | Migrations only: every DataSource or TypeORM options object states the literal `synchronize: false` (found by the contextual type), no `migrationsRun`, no DDL string outside a migration, no entity glob; no `@Entity` type reachable from a transport signature, a handler `execute`, a contract or a message, and no GraphQL or validator import in an entity file (`no-runtime-schema`, `no-entity-in-contract`) |
|
|
42
42
|
| **Config and secrets** | `process.env` (any form) is allowed in the `platform/config` file declaring `EnvSource`, the test world (slot `be.tests.world`) and the app bootstrap roles `apps/<app>/src/main.ts` and its matching `<app>.env.ts`; only those two app roles may read `EnvSource` or capability parse helpers. Compose groups and `<app>.options.ts` never read `process.env` or `EnvSource`. `@nestjs/config` and `dotenv` are forbidden config paths. A function exported by a `<capability>.config.ts` keeps its existing name and is called only from these bootstrap roles, its own config file or spec, the test world and a provider contract spec (`config-parsed-in-main`). Secrets use `EnvSource.secret()`: `<NAME>_FILE` takes priority for `.starcistacks` custody, and plain `<NAME>` is read only when the file key is absent; a declared file supplies exact contents and an empty or unreadable path fails startup without fallback. No default of any kind for a value typed `Secret` or `Url`; secrets compare with `timingSafeEqual` (`no-direct-env-read`, `config-parsed-in-main`, `no-secret-default`, `secret-compare-timing-safe`) |
|
|
43
|
+
| **Model calls** (R326, R327) | Every model call goes through the `@starci/ai-router` gateway: an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, with its `_FILE` twin) is named only in the gateway's custody owner `integrations/ai-gateway`, specs and the test world included; code builds only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai`, each from an inline options object whose `configuration.baseURL` is read from a `<c>.options.ts` type and whose `apiKey` is a `platform/config` `Secret` revealed. Which owner may import LangChain, `openai`, a provider SDK or an agent framework is the infrastructure table (`provider-key-custody`, `ai-client-through-gateway`, `infra-import-owner`) |
|
|
43
44
|
| **Ambient ids** (R142) | `randomUUID` of Node's crypto (named, namespace or global), the `v1`, `v4`, `v6` and `v7` generators of `uuid`, `nanoid` and `ulid` are used only inside `platform/ids`, specs included: code asks the injected `Ids` port and a spec provides `fakeIds()`; the generators are found by the module they are imported from, never by a local name (`no-ambient-id`) |
|
|
44
45
|
| **App composition** (R245, R246) | `apps/<app>/src/<app>.env.ts` exports an explicit typed `<App>Env` interface and `read<App>Env(env: EnvSource): <App>Env` (for example `ApiEnv` and `readApiEnv`). The interface declares its own readonly parsed members, such as `readonly server: ReturnType<typeof parseServerConfig>`, structurally compatible with the app's options. The role name stays `<app>.env.ts`, never `env.ts`; capability `<capability>.config.ts` files stay unchanged. `main.ts` creates `EnvSource` once, imports and calls the reader, builds options and boots. The env file holds fail-fast parsing only, with no localhost or default host fallback, logic, module composition, business code or feature imports; `<app>.options.ts` holds env-derived options and port bindings only, with no parsing. Both refuse an array listing `*Module` classes, module or queue registrations (`register`, `forRoot`, `registerQueue`) or scheduler entries, and an `imports`, `modules`, `schedulers` or `processors` list; the env file also refuses standalone module or queue registration calls. Composition belongs in a `compose/<area>.ts` group that `app.module.ts` spreads (`app-options-composition-free`, `BE_APP_OPTIONS_COMPOSITION`). Each app file stays within its slot's line budget: `main.ts` 80, env 150, options 200, group 120, root 250 (`app-file-budget`, `BE_APP_COMPOSITION_BUDGET`). The interface and reader exports are a documented scaffold contract; they need no new lint rule |
|
|
45
46
|
| **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`); the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Recommended, RuleModule } from "./lib/rule.js";
|
|
2
|
+
/** The owner id (`<tier>/<capability>`) that holds the provider keys and registers the gateway's pool. */
|
|
3
|
+
export declare const GATEWAY_CUSTODY = "integrations/ai-gateway";
|
|
4
|
+
/**
|
|
5
|
+
* The upstream provider key variables, the one list: a key that reaches any of these providers is read only by the
|
|
6
|
+
* gateway's custody owner. A provider the gateway adds joins this list.
|
|
7
|
+
*/
|
|
8
|
+
export declare const PROVIDER_KEY_VARIABLES: readonly string[];
|
|
9
|
+
/** Only the gateway's custody owner names an upstream provider key. */
|
|
10
|
+
export declare const providerKeyCustody: RuleModule;
|
|
11
|
+
/** The LangChain clients point at the gateway: base URL from options, virtual key from a `Secret`. */
|
|
12
|
+
export declare const aiClientThroughGateway: RuleModule;
|
|
13
|
+
/** The rules this law contributes to the plugin. */
|
|
14
|
+
export declare const rules: {
|
|
15
|
+
"provider-key-custody": RuleModule;
|
|
16
|
+
"ai-client-through-gateway": RuleModule;
|
|
17
|
+
};
|
|
18
|
+
/** Every rule of this law at `error`. */
|
|
19
|
+
export declare const recommended: Recommended;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rules that hold model calls behind the ai-router gateway (catalog R326 `BE_AI_KEY_CUSTODY`, R327
|
|
3
|
+
* `BE_AI_GATEWAY_CLIENT`; contexts/code/be/ai.md BE-AI-1 and BE-AI-3).
|
|
4
|
+
*
|
|
5
|
+
* - `provider-key-custody` keeps every upstream provider key inside the gateway's custody owner, `integrations/ai-gateway`,
|
|
6
|
+
* the one owner that registers `@starci/ai-router` with the provider pool. Anywhere else a provider key variable
|
|
7
|
+
* (`PROVIDER_KEY_VARIABLES` below, the one list) is refused in any spelling a read can take: a string literal or a
|
|
8
|
+
* template without substitutions naming it or its `<NAME>_FILE` custody twin, and a non-computed member or property
|
|
9
|
+
* named like it (`process.env.OPENAI_API_KEY`, `{ OPENROUTER_API_KEY } = env`, `{ OPENAI_API_KEY: value }`). Specs and the
|
|
10
|
+
* test world are judged too: they reach a model through the gateway's fake provider, never with a provider key.
|
|
11
|
+
* - `ai-client-through-gateway` judges every `new` of an export of `@langchain/openai`, the one LangChain provider package:
|
|
12
|
+
* only `ChatOpenAI` and `OpenAIEmbeddings` are built, each from an inline options object with no spread, whose
|
|
13
|
+
* `configuration.baseURL` is a member read off an options type declared in a `<c>.options.ts` (the gateway URL the
|
|
14
|
+
* integration's config parsed), and whose `apiKey` is the `reveal()` of a `Secret` of `platform/config` (the gateway's
|
|
15
|
+
* virtual key). A literal provider URL, a missing base URL (the library falls back to the provider's own) and a
|
|
16
|
+
* missing key (the library falls back to `OPENAI_API_KEY`) are refused. The constructor is found by its import, never
|
|
17
|
+
* by its spelling.
|
|
18
|
+
*
|
|
19
|
+
* Which owner may import LangChain, `openai` or another provider SDK at all is the infrastructure table of the slot
|
|
20
|
+
* manifest (`ruleParams.be.infraOwners`, judged by `infra-import-owner`, R90).
|
|
21
|
+
*/
|
|
22
|
+
import { keyName, staticText } from "./lib/ast.js";
|
|
23
|
+
import { originsOf } from "./lib/declared.js";
|
|
24
|
+
import { hfsOf } from "./lib/hfs.js";
|
|
25
|
+
import { importOf } from "./lib/import-source.js";
|
|
26
|
+
import { isOwnedType } from "./lib/ports.js";
|
|
27
|
+
/** The owner id (`<tier>/<capability>`) that holds the provider keys and registers the gateway's pool. */
|
|
28
|
+
export const GATEWAY_CUSTODY = "integrations/ai-gateway";
|
|
29
|
+
/**
|
|
30
|
+
* The upstream provider key variables, the one list: a key that reaches any of these providers is read only by the
|
|
31
|
+
* gateway's custody owner. A provider the gateway adds joins this list.
|
|
32
|
+
*/
|
|
33
|
+
export const PROVIDER_KEY_VARIABLES = Object.freeze([
|
|
34
|
+
"OPENROUTER_API_KEY",
|
|
35
|
+
"OPENROUTER_KEY",
|
|
36
|
+
"OPENAI_API_KEY",
|
|
37
|
+
"OPENAI_KEY",
|
|
38
|
+
"ANTHROPIC_API_KEY",
|
|
39
|
+
"CLAUDE_API_KEY",
|
|
40
|
+
"GEMINI_API_KEY",
|
|
41
|
+
"GOOGLE_API_KEY",
|
|
42
|
+
"GOOGLE_GENERATIVE_AI_API_KEY",
|
|
43
|
+
"AZURE_OPENAI_API_KEY",
|
|
44
|
+
"MISTRAL_API_KEY",
|
|
45
|
+
"GROQ_API_KEY",
|
|
46
|
+
"DEEPSEEK_API_KEY",
|
|
47
|
+
"TOGETHER_API_KEY",
|
|
48
|
+
"FIREWORKS_API_KEY",
|
|
49
|
+
"COHERE_API_KEY",
|
|
50
|
+
"XAI_API_KEY",
|
|
51
|
+
"PERPLEXITY_API_KEY",
|
|
52
|
+
"HUGGINGFACEHUB_API_KEY",
|
|
53
|
+
"HF_TOKEN",
|
|
54
|
+
]);
|
|
55
|
+
const PROVIDER_KEYS = new Set(PROVIDER_KEY_VARIABLES.flatMap((name) => [name, `${name}_FILE`]));
|
|
56
|
+
/** The LangChain provider package whose clients are judged, and the clients code may build from it. */
|
|
57
|
+
const LANGCHAIN_OPENAI = "@langchain/openai";
|
|
58
|
+
const GATEWAY_CLIENTS = new Set(["ChatOpenAI", "OpenAIEmbeddings"]);
|
|
59
|
+
/** The owner id of a file: the last two segments of its owner root, or null when no owner holds it. */
|
|
60
|
+
const ownerIdOf = (context, filename) => {
|
|
61
|
+
const root = hfsOf(context).ownerOf(filename);
|
|
62
|
+
return root === null ? null : root.split("/").slice(-2).join("/");
|
|
63
|
+
};
|
|
64
|
+
/** Only the gateway's custody owner names an upstream provider key. */
|
|
65
|
+
export const providerKeyCustody = {
|
|
66
|
+
meta: {
|
|
67
|
+
type: "problem",
|
|
68
|
+
docs: { description: "An upstream provider key variable (OPENROUTER_API_KEY, OPENAI_API_KEY, ...) is read only by the gateway's custody owner `integrations/ai-gateway`." },
|
|
69
|
+
schema: [],
|
|
70
|
+
messages: {
|
|
71
|
+
custody: "`{{name}}` is an upstream provider key, held only by the ai-router gateway's custody owner `integrations/ai-gateway`. Call a model through the gateway: the `integrations/ai` LangChain client with its virtual key (`sk-starci-...`), or the agent runtime's own virtual key.",
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
create(context) {
|
|
75
|
+
if (ownerIdOf(context, context.filename) === GATEWAY_CUSTODY)
|
|
76
|
+
return {};
|
|
77
|
+
const judge = (node, name) => {
|
|
78
|
+
if (name !== null && PROVIDER_KEYS.has(name))
|
|
79
|
+
context.report({ node, messageId: "custody", data: { name } });
|
|
80
|
+
};
|
|
81
|
+
return {
|
|
82
|
+
Literal(node) {
|
|
83
|
+
judge(node, staticText(node));
|
|
84
|
+
},
|
|
85
|
+
TemplateLiteral(node) {
|
|
86
|
+
judge(node, staticText(node));
|
|
87
|
+
},
|
|
88
|
+
MemberExpression(node) {
|
|
89
|
+
if (!node.computed)
|
|
90
|
+
judge(node.property, keyName(node.property));
|
|
91
|
+
},
|
|
92
|
+
Property(node) {
|
|
93
|
+
if (!node.computed && node.key.type === "Identifier")
|
|
94
|
+
judge(node.key, node.key.name);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
/** The `@langchain/openai` export a constructor callee names, or null when it names none. */
|
|
100
|
+
const langchainExportOf = (context, callee) => {
|
|
101
|
+
const fromPackage = (source) => source === LANGCHAIN_OPENAI || source.startsWith(`${LANGCHAIN_OPENAI}/`);
|
|
102
|
+
if (callee.type === "Identifier") {
|
|
103
|
+
const binding = importOf(context, callee);
|
|
104
|
+
return binding !== null && fromPackage(binding.source) ? (binding.imported ?? "default") : null;
|
|
105
|
+
}
|
|
106
|
+
if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier") {
|
|
107
|
+
const binding = importOf(context, callee.object);
|
|
108
|
+
return binding?.imported === "*" && fromPackage(binding.source) ? keyName(callee.property) : null;
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
};
|
|
112
|
+
/** The value of a plain (non-computed, non-spread) property of an object literal, or null. */
|
|
113
|
+
const propertyOf = (object, name) => {
|
|
114
|
+
for (const property of object.properties) {
|
|
115
|
+
if (property.type === "Property" && !property.computed && keyName(property.key) === name)
|
|
116
|
+
return property.value;
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
};
|
|
120
|
+
/** True when the object literal, or any object literal nested in it, spreads another value in. */
|
|
121
|
+
const spreads = (object) => object.properties.some((property) => property.type === "SpreadElement" || (property.value.type === "ObjectExpression" && spreads(property.value)));
|
|
122
|
+
/** A member read off a value whose type a `<c>.options.ts` of the repository declares: the URL the integration's config parsed. */
|
|
123
|
+
const isOptionsMember = (context, node) => {
|
|
124
|
+
if (node.type !== "MemberExpression" || node.computed)
|
|
125
|
+
return false;
|
|
126
|
+
const hfs = hfsOf(context);
|
|
127
|
+
return originsOf(context, node.object).some((origin) => origin.file.endsWith(".options.ts") && hfs.slotOf(origin.file) !== null);
|
|
128
|
+
};
|
|
129
|
+
/** `secret.reveal()` on a `Secret` of `platform/config`: the virtual key handed to the library that needs it. */
|
|
130
|
+
const isRevealedSecret = (context, node) => node.type === "CallExpression" &&
|
|
131
|
+
node.arguments.length === 0 &&
|
|
132
|
+
node.callee.type === "MemberExpression" &&
|
|
133
|
+
!node.callee.computed &&
|
|
134
|
+
keyName(node.callee.property) === "reveal" &&
|
|
135
|
+
isOwnedType(context, node.callee.object, { name: "Secret", capability: "config", tier: "platform" });
|
|
136
|
+
/** The LangChain clients point at the gateway: base URL from options, virtual key from a `Secret`. */
|
|
137
|
+
export const aiClientThroughGateway = {
|
|
138
|
+
meta: {
|
|
139
|
+
type: "problem",
|
|
140
|
+
docs: { description: "Only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai` are built, each with `configuration.baseURL` read from the integration's options and `apiKey` revealed from a `Secret`." },
|
|
141
|
+
schema: [],
|
|
142
|
+
messages: {
|
|
143
|
+
client: "`{{name}}` of `@langchain/openai` is not a gateway client. Build `ChatOpenAI` for chat and `OpenAIEmbeddings` for vectors, both pointed at the ai-router gateway; another provider is a pool entry of the gateway, never a client here.",
|
|
144
|
+
inline: "`{{name}}` takes an inline options object with no spread, so its base URL and key are visible here: `new {{name}}({ model, apiKey: this.options.virtualKey.reveal(), configuration: { baseURL: this.options.gatewayUrl } })`.",
|
|
145
|
+
baseUrl: "`{{name}}` needs `configuration.baseURL` read from the integration's options (`this.options.gatewayUrl`, parsed by its `<c>.config.ts`). A missing base URL calls the provider directly and a literal URL hard-codes one: every model call goes through the ai-router gateway.",
|
|
146
|
+
apiKey: "`{{name}}` needs `apiKey` set to the gateway's virtual key as `<secret>.reveal()` of a `Secret` from `platform/config` (`this.options.virtualKey.reveal()`). Without it the library reads `OPENAI_API_KEY` from the environment.",
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
create(context) {
|
|
150
|
+
return {
|
|
151
|
+
NewExpression(node) {
|
|
152
|
+
const name = langchainExportOf(context, node.callee);
|
|
153
|
+
if (name === null)
|
|
154
|
+
return;
|
|
155
|
+
if (!GATEWAY_CLIENTS.has(name)) {
|
|
156
|
+
context.report({ node, messageId: "client", data: { name } });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const options = node.arguments[0];
|
|
160
|
+
if (node.arguments.length !== 1 || options?.type !== "ObjectExpression" || spreads(options)) {
|
|
161
|
+
context.report({ node, messageId: "inline", data: { name } });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const configuration = propertyOf(options, "configuration");
|
|
165
|
+
const baseUrl = configuration?.type === "ObjectExpression" ? propertyOf(configuration, "baseURL") : null;
|
|
166
|
+
if (baseUrl === null || !isOptionsMember(context, baseUrl))
|
|
167
|
+
context.report({ node: baseUrl ?? node, messageId: "baseUrl", data: { name } });
|
|
168
|
+
const apiKey = propertyOf(options, "apiKey");
|
|
169
|
+
if (apiKey === null || !isRevealedSecret(context, apiKey))
|
|
170
|
+
context.report({ node: apiKey ?? node, messageId: "apiKey", data: { name } });
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
/** The rules this law contributes to the plugin. */
|
|
176
|
+
export const rules = {
|
|
177
|
+
"provider-key-custody": providerKeyCustody,
|
|
178
|
+
"ai-client-through-gateway": aiClientThroughGateway,
|
|
179
|
+
};
|
|
180
|
+
/** Every rule of this law at `error`. */
|
|
181
|
+
export const recommended = {
|
|
182
|
+
"starci-be/provider-key-custody": "error",
|
|
183
|
+
"starci-be/ai-client-through-gateway": "error",
|
|
184
|
+
};
|
|
@@ -7,7 +7,7 @@ export declare const appCompositionTyped: RuleModule;
|
|
|
7
7
|
export declare const appEnvRequired: RuleModule;
|
|
8
8
|
/** R289: module lists in the app root contain only spreads of its own compose groups. */
|
|
9
9
|
export declare const appModuleListInline: RuleModule;
|
|
10
|
-
/** Each composition file of an app stays within the line budget its app slot names. */
|
|
10
|
+
/** Each composition file of an app stays within the line budget its app slot names, counted without its import lines. */
|
|
11
11
|
export declare const appFileBudget: RuleModule;
|
|
12
12
|
/** The rules this law contributes to the plugin. */
|
|
13
13
|
export declare const rules: {
|
package/dist/app-composition.js
CHANGED
|
@@ -14,7 +14,9 @@
|
|
|
14
14
|
* options files and composition groups receive the typed result of `read<App>Env(env: EnvSource)`.
|
|
15
15
|
* - `app-file-budget` (`BE_APP_COMPOSITION_BUDGET`) holds each composition file to the line budget its app slot names
|
|
16
16
|
* (`budget` of the slot, keyed by the same entry: `app.module.ts` 250, `<app>.env.ts` 150, `<app>.options.ts` 200, `compose/<area>.ts` 120,
|
|
17
|
-
* `main.ts` 80)
|
|
17
|
+
* `main.ts` 80), counted in lines EXCLUDING import declarations (a multi-line import counts none of its lines): an import
|
|
18
|
+
* is the cost of naming a capability, not composition. The budget is absolute, not a ratchet: an app root that outgrows it moves
|
|
19
|
+
* an area into a new group.
|
|
18
20
|
*
|
|
19
21
|
* R265 resolves composition from types, including renamed constructors, factories, maps and scheduler tables. All
|
|
20
22
|
* three rules ask the slot view which entry a file matches; none keeps a path of its own.
|
|
@@ -564,14 +566,25 @@ export const appModuleListInline = {
|
|
|
564
566
|
};
|
|
565
567
|
},
|
|
566
568
|
};
|
|
567
|
-
/**
|
|
569
|
+
/** The lines of a source text that no import declaration (`import ...` or `import x = require(...)`) covers, one or many lines each. */
|
|
570
|
+
const linesExcludingImports = (text, body) => {
|
|
571
|
+
const covered = new Set();
|
|
572
|
+
for (const statement of body) {
|
|
573
|
+
if ((statement.type !== "ImportDeclaration" && statement.type !== "TSImportEqualsDeclaration") || !statement.loc)
|
|
574
|
+
continue;
|
|
575
|
+
for (let line = statement.loc.start.line; line <= statement.loc.end.line; line += 1)
|
|
576
|
+
covered.add(line);
|
|
577
|
+
}
|
|
578
|
+
return lineCount(text) - covered.size;
|
|
579
|
+
};
|
|
580
|
+
/** Each composition file of an app stays within the line budget its app slot names, counted without its import lines. */
|
|
568
581
|
export const appFileBudget = {
|
|
569
582
|
meta: {
|
|
570
583
|
type: "problem",
|
|
571
|
-
docs: { description: "`main.ts`, `app.module.ts`, `<app>.env.ts`, `<app>.options.ts` and `compose/<area>.ts` stay within the line budget of their app slot." },
|
|
584
|
+
docs: { description: "`main.ts`, `app.module.ts`, `<app>.env.ts`, `<app>.options.ts` and `compose/<area>.ts` stay within the line budget of their app slot, counted without import lines." },
|
|
572
585
|
schema: [],
|
|
573
586
|
messages: {
|
|
574
|
-
over: "This {{role}} has {{lines}} lines, over its budget of {{max}} (the `budget` of slot {{slot}}). {{fix}}",
|
|
587
|
+
over: "This {{role}} has {{lines}} lines excluding imports, over its budget of {{max}} (the `budget` of slot {{slot}}). {{fix}}",
|
|
575
588
|
},
|
|
576
589
|
},
|
|
577
590
|
create(context) {
|
|
@@ -592,7 +605,7 @@ export const appFileBudget = {
|
|
|
592
605
|
: "Move one area of the composition into its own group `apps/<app>/src/compose/<area>.ts` and spread it in `app.module.ts`.";
|
|
593
606
|
return {
|
|
594
607
|
"Program:exit"(node) {
|
|
595
|
-
const lines =
|
|
608
|
+
const lines = linesExcludingImports((context.sourceCode || context.getSourceCode()).text, node.body);
|
|
596
609
|
if (lines > max)
|
|
597
610
|
context.report({ node, loc: { line: 1, column: 0 }, messageId: "over", data: { role: role.entry, lines, max, slot: role.slot, fix } });
|
|
598
611
|
},
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Recommended, RuleModule } from "./lib/rule.js";
|
|
2
|
+
/** The owner id (`<tier>/<capability>`) of the lite identity integration. */
|
|
3
|
+
export declare const PASSPORT_OWNER = "integrations/passport";
|
|
4
|
+
/** A lite principal comes only from the app's own verified token. */
|
|
5
|
+
export declare const ownJwksOnly: RuleModule;
|
|
6
|
+
/** A refresh token lives only in the integration's httpOnly cookie. */
|
|
7
|
+
export declare const refreshTokenCookieOnly: RuleModule;
|
|
8
|
+
/** The rules of the lite identity law, by name. */
|
|
9
|
+
export declare const rules: {
|
|
10
|
+
"own-jwks-only": RuleModule;
|
|
11
|
+
"refresh-token-cookie-only": RuleModule;
|
|
12
|
+
};
|
|
13
|
+
/** Both rules on at error. */
|
|
14
|
+
export declare const recommended: Recommended;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rules of the lite identity (catalog R329 `BE_AUTH_JWT_OWN_JWKS`, R330 `BE_AUTH_REFRESH_COOKIE`; contexts/code/be/api-auth.md
|
|
3
|
+
* BE-AUTH-2 and BE-AUTH-3). Which owner may import the identity and S3 libraries at all is the infrastructure table of the slot
|
|
4
|
+
* manifest (`ruleParams.be.infraOwners`, judged by `infra-import-owner`: R328 `BE_AUTH_PASSPORT_OWNER`, R331 `BE_STORAGE_OWNER`).
|
|
5
|
+
*
|
|
6
|
+
* - `own-jwks-only`: the app verifies only its own access tokens. `createRemoteJWKSet` (a remote identity provider's key set),
|
|
7
|
+
* `decodeJwt` and `decodeProtectedHeader` (a token read without its signature) are refused wherever jose is imported, and
|
|
8
|
+
* `jwtVerify` is imported only by `integrations/passport`. The architecture machine (`own-jwks-principal`) proves the rest:
|
|
9
|
+
* the verifier checks `createLocalJWKSet` over the app's keys with issuer, audience and algorithms pinned.
|
|
10
|
+
* - `refresh-token-cookie-only`: a refresh token never travels in a body. Outside `integrations/passport` no object literal,
|
|
11
|
+
* class property or type member is named `refreshToken` or `refresh_token`, and no `.cookie()`/`.clearCookie()` call names a
|
|
12
|
+
* refresh cookie: the cookie is set, rotated and cleared only by the integration's `setRefreshCookie`/`clearRefreshCookie`.
|
|
13
|
+
* Its attributes (httpOnly, Secure, SameSite=Strict, the refresh path) are `response-cookie-attributes` (R141) and the
|
|
14
|
+
* integration's own spec; rotation with reuse detection is held by the identity domain's spec and review.
|
|
15
|
+
*/
|
|
16
|
+
import { keyName, staticText } from "./lib/ast.js";
|
|
17
|
+
import { hfsOf } from "./lib/hfs.js";
|
|
18
|
+
/** The owner id (`<tier>/<capability>`) of the lite identity integration. */
|
|
19
|
+
export const PASSPORT_OWNER = "integrations/passport";
|
|
20
|
+
/** The jose exports no file uses: a remote key set and the unverified decoders. */
|
|
21
|
+
const FORBIDDEN_JOSE = new Set(["createRemoteJWKSet", "decodeJwt", "decodeProtectedHeader"]);
|
|
22
|
+
const REFRESH_NAME = /^refresh_?token$/i;
|
|
23
|
+
const REFRESH_COOKIE = /refresh/i;
|
|
24
|
+
/** The owner id of a file: the last two segments of its owner root, or null when no owner holds it. */
|
|
25
|
+
const ownerIdOf = (context, filename) => {
|
|
26
|
+
const root = hfsOf(context).ownerOf(filename);
|
|
27
|
+
return root === null ? null : root.split("/").slice(-2).join("/");
|
|
28
|
+
};
|
|
29
|
+
/** A lite principal comes only from the app's own verified token. */
|
|
30
|
+
export const ownJwksOnly = {
|
|
31
|
+
meta: {
|
|
32
|
+
type: "problem",
|
|
33
|
+
docs: { description: "Only integrations/passport verifies a token (jose jwtVerify over the app's own key set); no remote JWKS and no unverified decode anywhere." },
|
|
34
|
+
schema: [],
|
|
35
|
+
messages: {
|
|
36
|
+
forbidden: "`{{name}}` of jose {{why}}. The app verifies only its own access tokens through the token kit of `integrations/passport` (jwtVerify over createLocalJWKSet).",
|
|
37
|
+
verifier: "`jwtVerify` is imported outside `integrations/passport`. Verify a token through the integration's verifier (`OWN_TOKEN_VERIFIER`), which domain/identity turns into the principal.",
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
create(context) {
|
|
41
|
+
const owner = ownerIdOf(context, context.filename) === PASSPORT_OWNER;
|
|
42
|
+
return {
|
|
43
|
+
ImportDeclaration(node) {
|
|
44
|
+
if (node.source.value !== "jose")
|
|
45
|
+
return;
|
|
46
|
+
for (const specifier of node.specifiers) {
|
|
47
|
+
if (specifier.type !== "ImportSpecifier")
|
|
48
|
+
continue;
|
|
49
|
+
const name = keyName(specifier.imported);
|
|
50
|
+
if (name !== null && FORBIDDEN_JOSE.has(name)) {
|
|
51
|
+
context.report({ node: specifier, messageId: "forbidden", data: { name, why: name === "createRemoteJWKSet" ? "trusts another issuer's key set" : "reads a token without proving its signature" } });
|
|
52
|
+
}
|
|
53
|
+
else if (name === "jwtVerify" && !owner)
|
|
54
|
+
context.report({ node: specifier, messageId: "verifier" });
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
/** A refresh token lives only in the integration's httpOnly cookie. */
|
|
61
|
+
export const refreshTokenCookieOnly = {
|
|
62
|
+
meta: {
|
|
63
|
+
type: "problem",
|
|
64
|
+
docs: { description: "A refresh token never appears as a body field, and only integrations/passport sets or clears the refresh cookie." },
|
|
65
|
+
schema: [],
|
|
66
|
+
messages: {
|
|
67
|
+
field: "`{{name}}` carries a refresh token in a body. The refresh token lives only in the httpOnly, Secure, SameSite=Strict cookie that `integrations/passport` rotates (`setRefreshCookie`).",
|
|
68
|
+
cookie: "`{{call}}` names the refresh cookie outside `integrations/passport`. Set and clear it only through `setRefreshCookie` and `clearRefreshCookie`.",
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
create(context) {
|
|
72
|
+
if (ownerIdOf(context, context.filename) === PASSPORT_OWNER)
|
|
73
|
+
return {};
|
|
74
|
+
const field = (node, key, computed) => {
|
|
75
|
+
const name = computed ? null : keyName(key);
|
|
76
|
+
if (name !== null && REFRESH_NAME.test(name))
|
|
77
|
+
context.report({ node, messageId: "field", data: { name } });
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
Property(node) {
|
|
81
|
+
field(node, node.key, node.computed);
|
|
82
|
+
},
|
|
83
|
+
PropertyDefinition(node) {
|
|
84
|
+
field(node, node.key, node.computed);
|
|
85
|
+
},
|
|
86
|
+
TSPropertySignature(node) {
|
|
87
|
+
field(node, node.key, node.computed);
|
|
88
|
+
},
|
|
89
|
+
CallExpression(node) {
|
|
90
|
+
if (node.callee.type !== "MemberExpression" || node.callee.computed)
|
|
91
|
+
return;
|
|
92
|
+
const method = keyName(node.callee.property);
|
|
93
|
+
if (method !== "cookie" && method !== "clearCookie")
|
|
94
|
+
return;
|
|
95
|
+
const [first] = node.arguments;
|
|
96
|
+
const name = first === undefined ? null : staticText(first);
|
|
97
|
+
if (name !== null && REFRESH_COOKIE.test(name))
|
|
98
|
+
context.report({ node, messageId: "cookie", data: { call: `.${method}("${name}")` } });
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
/** The rules of the lite identity law, by name. */
|
|
104
|
+
export const rules = { "own-jwks-only": ownJwksOnly, "refresh-token-cookie-only": refreshTokenCookieOnly };
|
|
105
|
+
/** Both rules on at error. */
|
|
106
|
+
export const recommended = { "starci-be/own-jwks-only": "error", "starci-be/refresh-token-cookie-only": "error" };
|
package/dist/index.js
CHANGED
|
@@ -18,6 +18,9 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { buildBeConfig } from "./lib/config.js";
|
|
20
20
|
import { pluginForEdition } from "./lib/edition.js";
|
|
21
|
+
import { recommended as aiGatewayRecommended, rules as aiGatewayRules } from "./ai-gateway.js";
|
|
22
|
+
import { recommended as authPassportRecommended, rules as authPassportRules } from "./auth-passport.js";
|
|
23
|
+
import { recommended as noRawSqlRecommended, rules as noRawSqlRules } from "./no-raw-sql.js";
|
|
21
24
|
import { recommended as ambientIdRecommended, rules as ambientIdRules } from "./ambient-id.js";
|
|
22
25
|
import { recommended as appCompositionRecommended, rules as appCompositionRules } from "./app-composition.js";
|
|
23
26
|
import { recommended as asyncDisciplineRecommended, rules as asyncDisciplineRules } from "./async-discipline.js";
|
|
@@ -72,6 +75,9 @@ import { recommended as sonarParityRecommended, rules as sonarParityRules } from
|
|
|
72
75
|
/** Each law's contribution, kept separate so a duplicate name is detectable rather than silent. */
|
|
73
76
|
const CONTRIBUTIONS = [
|
|
74
77
|
{ law: "project-graph", rules: projectGraphRules, recommended: projectGraphRecommended },
|
|
78
|
+
{ law: "ai-gateway", rules: aiGatewayRules, recommended: aiGatewayRecommended },
|
|
79
|
+
{ law: "auth-passport", rules: authPassportRules, recommended: authPassportRecommended },
|
|
80
|
+
{ law: "no-raw-sql", rules: noRawSqlRules, recommended: noRawSqlRecommended },
|
|
75
81
|
{ law: "ambient-id", rules: ambientIdRules, recommended: ambientIdRecommended },
|
|
76
82
|
{ law: "app-composition", rules: appCompositionRules, recommended: appCompositionRecommended },
|
|
77
83
|
{ law: "async-discipline", rules: asyncDisciplineRules, recommended: asyncDisciplineRecommended },
|
package/dist/infra-owner.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The rule that holds BE-CONVENTION 1.10-1.14 (R90 `BE_INFRA_OWNER`).
|
|
3
3
|
*
|
|
4
|
-
* Every raw infrastructure library (HTTP, cache, queue, scheduler, logger, date, config, in-process events
|
|
5
|
-
* one owning platform or integration capability, and only files of that capability may import it or reach
|
|
6
|
-
* global. The table lives in the slot manifest (`ruleParams.be.infraOwners`: specifier -> owners, `[]` for
|
|
7
|
-
* so the rule holds no library name of its own and the messages and the check read one source.
|
|
4
|
+
* Every raw infrastructure library (HTTP, cache, queue, scheduler, logger, date, config, in-process events, model SDKs)
|
|
5
|
+
* has exactly one owning platform or integration capability, and only files of that capability may import it or reach
|
|
6
|
+
* for it as a global. The table lives in the slot manifest (`ruleParams.be.infraOwners`: specifier -> owners, `[]` for
|
|
7
|
+
* "nowhere"), so the rule holds no library name of its own and the messages and the check read one source. A key covers
|
|
8
|
+
* its subpaths, so a scope key (`@langchain`) covers every package of the scope, and the longest key wins
|
|
9
|
+
* (`@langchain/langgraph` over `@langchain`).
|
|
8
10
|
*
|
|
9
11
|
* "Owning capability" is asked of the slot view (`ownerOf(filename)`), never of a path pattern. A reference is an
|
|
10
12
|
* import (static, dynamic, `require`, `export ... from`) of the specifier or of a subpath of it, or a value reference to
|
|
@@ -53,7 +55,7 @@ export const infraImportOwner = {
|
|
|
53
55
|
schema: [],
|
|
54
56
|
messages: {
|
|
55
57
|
foreign: "`{{name}}` is owned by {{owners}}. Use that capability's port (injected with its `Inject*()` decorator) instead of the raw library, or move this code into the owner.",
|
|
56
|
-
nowhere: "`{{name}}` is not used in a back end: its job belongs to
|
|
58
|
+
nowhere: "`{{name}}` is not used in a back end: its job belongs to another owner's port (config through the typed `<c>.config.ts`, events through `eventBus.publish(event, tx)` of `platform/event-bus`, schedules and background jobs through a queue's BullMQ job scheduler of `platform/queue`, a model call through the LangChain client of `integrations/ai` and the ai-router gateway, an agent loop in the agent runtime). Remove it.",
|
|
57
59
|
},
|
|
58
60
|
},
|
|
59
61
|
create(context) {
|
package/dist/jwt-alg.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import ts from "typescript";
|
|
3
3
|
import { typed } from "./lib/types.js";
|
|
4
4
|
import { isDeclarationFile } from "./lib/path.js";
|
|
5
|
-
import { jwtPolicyProblems } from "../runtime/scripts/hfs/architecture/
|
|
5
|
+
import { jwtPolicyProblems } from "../runtime/scripts/hfs/architecture/jwt-ast.mjs";
|
|
6
6
|
/** The text of a module specifier (a string literal), or undefined for any other expression. */
|
|
7
7
|
const specifierText = (specifier) => ("text" in specifier ? specifier.text : undefined);
|
|
8
8
|
/** Recognize jose imports and aliases through their declarations, including namespace imports. */
|
package/dist/lib/hfs-view.d.ts
CHANGED
|
@@ -98,6 +98,11 @@ export interface HfsRuleParams {
|
|
|
98
98
|
readonly logicRoles?: readonly string[];
|
|
99
99
|
readonly valueRoles?: readonly string[];
|
|
100
100
|
readonly thinRoles?: readonly string[];
|
|
101
|
+
/** The database functions `callDbFunction` of platform/database may call, each with its reason (`ruleParams.be.dbFunctions` plus hfs.json `sides.be.dbFunctions`). */
|
|
102
|
+
readonly dbFunctions?: readonly {
|
|
103
|
+
readonly name: string;
|
|
104
|
+
readonly reason: string;
|
|
105
|
+
}[];
|
|
101
106
|
}
|
|
102
107
|
/** The frozen view of one side of an app. */
|
|
103
108
|
export interface HfsView {
|
package/dist/module-layering.js
CHANGED
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
* - `no-relative-capability-escape` - a relative import never walks out of its own owner.
|
|
13
13
|
* - `no-folder-reexport` - a specifier that names a directory is refused; a nested `index.ts` (any index that is not
|
|
14
14
|
* at its owner's root) is refused; an owner's `index.ts` holds only named `export { }` / `export type { }` lines
|
|
15
|
-
* re-exporting from files, never `export *`, never a declaration, and at most `budget.indexExports` names.
|
|
15
|
+
* re-exporting from files, never `export *`, never a declaration, and at most `budget.indexExports` names. One
|
|
16
|
+
* sanctioned exception, lite only: `<owner>/persistence/entities/index.ts` imports its entity files and declares the
|
|
17
|
+
* owner's `<c>Entities` array, the list `platform/database/entities.ts` names (persistence.md BE-PERSISTENCE-3).
|
|
16
18
|
*
|
|
17
19
|
* "Which owner does this file belong to" is `hfs.ownerOf`; "which owner does this specifier reach" is the same question
|
|
18
20
|
* asked of the file the specifier resolves to. Nothing here touches disk.
|
|
@@ -140,6 +142,8 @@ export const noSelfModuleAlias = {
|
|
|
140
142
|
},
|
|
141
143
|
};
|
|
142
144
|
// -- no-folder-reexport ----------------------------------------------------------------------------
|
|
145
|
+
/** The lite entity list of a capability: `<owner>/persistence/entities/index.ts` (BE-PERSISTENCE-3). */
|
|
146
|
+
const LITE_ENTITY_LIST = /(?:^|\/)persistence\/entities\/index\.ts$/;
|
|
143
147
|
/** Whether a file is an index by its role name. */
|
|
144
148
|
const isIndexFile = (filename) => /^index\.[cm]?[jt]sx?$/.test(baseName(filename));
|
|
145
149
|
/**
|
|
@@ -170,7 +174,7 @@ export const noFolderReexport = {
|
|
|
170
174
|
create(context) {
|
|
171
175
|
const filename = context.filename || context.getFilename();
|
|
172
176
|
const hfs = hfsOf(context);
|
|
173
|
-
const isIndex = isIndexFile(filename);
|
|
177
|
+
const isIndex = isIndexFile(filename) && !(hfs.edition === "lite" && LITE_ENTITY_LIST.test(hfs.relative(filename)));
|
|
174
178
|
const max = indexExportBudget(hfs, filename);
|
|
175
179
|
let count = 0;
|
|
176
180
|
return {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { RuleModule, Recommended } from "./lib/rule.js";
|
|
2
|
+
/** No raw SQL in lite domain or feature code: entities on the EntityManager carry every read and write. */
|
|
3
|
+
export declare const noRawSql: RuleModule;
|
|
4
|
+
/** The rule of the lite persistence law, by name. */
|
|
5
|
+
export declare const rules: {
|
|
6
|
+
"no-raw-sql": RuleModule;
|
|
7
|
+
};
|
|
8
|
+
/** On at error; the catalog limits it to lite. */
|
|
9
|
+
export declare const recommended: Recommended;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lite persistence law (catalog R334 `BE_PERSISTENCE_NO_RAW_SQL`; contexts/code/be/persistence.md BE-PERSISTENCE-1 and -2):
|
|
3
|
+
* domain and feature code reads and writes through TypeORM entities on the injected EntityManager (`find`, `save`, `update`,
|
|
4
|
+
* `delete`, `upsert`, `createQueryBuilder(Entity, "alias")` with named parameters), never through raw SQL.
|
|
5
|
+
*
|
|
6
|
+
* - `no-raw-sql` refuses, outside `platform/database`, every `.query(` call and every `sql` tagged template. A database function
|
|
7
|
+
* TypeORM cannot express is called through the typed helpers of `platform/database` (`callDbFunction(manager, name, args)`,
|
|
8
|
+
* `advisoryXactLock(manager, key)`, `notify(manager, channel, payload)`), and a literal function name handed to
|
|
9
|
+
* `callDbFunction` must be one `ruleParams.be.dbFunctions` lists (the canon's pg built-ins plus hfs.json `sides.be.dbFunctions`).
|
|
10
|
+
* The allow-list governs WHICH functions may be called, the helper WHERE the SQL is built. A query builder names its entity
|
|
11
|
+
* (`createQueryBuilder(Entity, "alias")`): a builder over a table-name string, a builder with no entity, and a
|
|
12
|
+
* `getRepository(...)` are refused, because they bypass the entity mapping. The rule runs in lite only (the
|
|
13
|
+
* catalog's `editions`); full keeps R36.
|
|
14
|
+
*
|
|
15
|
+
* Schema authority stays `db/migrations/*.sql`; whether the entities match it is `BE_ENTITY_SCHEMA_DRIFT` of `starci app db drift`.
|
|
16
|
+
*/
|
|
17
|
+
import { staticText } from "./lib/ast.js";
|
|
18
|
+
import { hfsOf } from "./lib/hfs.js";
|
|
19
|
+
/** The owner id (`<tier>/<capability>`) that keeps the migration runner and the database-function helpers. */
|
|
20
|
+
const DATABASE_OWNER = "platform/database";
|
|
21
|
+
/** The helper of platform/database whose second argument names the function it calls. */
|
|
22
|
+
const CALL_HELPER = "callDbFunction";
|
|
23
|
+
/** True when a builder's first argument can be an entity class: neither absent nor a string. */
|
|
24
|
+
const namesEntity = (argument) => {
|
|
25
|
+
if (argument === undefined || argument === null || typeof argument !== "object")
|
|
26
|
+
return false;
|
|
27
|
+
const node = argument;
|
|
28
|
+
return !((node.type === "Literal" && typeof node.value === "string") || node.type === "TemplateLiteral");
|
|
29
|
+
};
|
|
30
|
+
/** No raw SQL in lite domain or feature code: entities on the EntityManager carry every read and write. */
|
|
31
|
+
export const noRawSql = {
|
|
32
|
+
meta: {
|
|
33
|
+
type: "problem",
|
|
34
|
+
docs: { description: "Lite domain and feature code uses TypeORM entities on the EntityManager; `.query(` and `sql` templates stay in platform/database, and callDbFunction names only listed functions." },
|
|
35
|
+
schema: [],
|
|
36
|
+
messages: {
|
|
37
|
+
query: "`.query(` runs raw SQL outside `platform/database`. Read and write through the entity on the EntityManager (`find`, `save`, `update`, `upsert`, `createQueryBuilder(Entity, \"alias\")` with named parameters); call a database function TypeORM cannot express through `callDbFunction(manager, name, args)` (or `advisoryXactLock`, `notify`) of `platform/database`.",
|
|
38
|
+
template: "A `sql` template outside `platform/database`. Lite persistence maps tables with TypeORM entities; build the query with the EntityManager or `createQueryBuilder`, or call a database function through `callDbFunction`.",
|
|
39
|
+
builder: "A query builder must name its entity: `manager.createQueryBuilder(Entity, \"alias\")` on the injected EntityManager. A table-name string, a builder with no entity and a Repository bypass the entity mapping.",
|
|
40
|
+
unlisted: "`{{name}}` is not a listed database function. Add it to hfs.json `sides.be.dbFunctions` with the reason TypeORM cannot express it, or map the work with an entity.",
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
create(context) {
|
|
44
|
+
const hfs = hfsOf(context);
|
|
45
|
+
const root = hfs.ownerOf(context.filename);
|
|
46
|
+
const inDatabase = root !== null && root.split("/").slice(-2).join("/") === DATABASE_OWNER;
|
|
47
|
+
const listed = new Set((hfs.ruleParams.dbFunctions ?? []).map((entry) => entry.name));
|
|
48
|
+
return {
|
|
49
|
+
CallExpression(node) {
|
|
50
|
+
const callee = node.callee;
|
|
51
|
+
if (callee.type === "Identifier" && callee.name === CALL_HELPER) {
|
|
52
|
+
const name = node.arguments[1] === undefined ? null : staticText(node.arguments[1]);
|
|
53
|
+
if (name !== null && !listed.has(name))
|
|
54
|
+
context.report({ node, messageId: "unlisted", data: { name } });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (inDatabase || callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier")
|
|
58
|
+
return;
|
|
59
|
+
const method = callee.property.name;
|
|
60
|
+
if (method === "query")
|
|
61
|
+
context.report({ node, messageId: "query" });
|
|
62
|
+
else if (method === "getRepository")
|
|
63
|
+
context.report({ node, messageId: "builder" });
|
|
64
|
+
else if (method === "createQueryBuilder" && !namesEntity(node.arguments[0]))
|
|
65
|
+
context.report({ node, messageId: "builder" });
|
|
66
|
+
},
|
|
67
|
+
TaggedTemplateExpression(node) {
|
|
68
|
+
if (inDatabase || node.tag.type !== "Identifier" || node.tag.name !== "sql")
|
|
69
|
+
return;
|
|
70
|
+
context.report({ node, messageId: "template" });
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
/** The rule of the lite persistence law, by name. */
|
|
76
|
+
export const rules = { "no-raw-sql": noRawSql };
|
|
77
|
+
/** On at error; the catalog limits it to lite. */
|
|
78
|
+
export const recommended = { "starci-be/no-raw-sql": "error" };
|