@pikku/inspector 0.12.52 → 0.12.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +341 -0
  2. package/dist/add/add-functions.js +46 -4
  3. package/dist/add/add-keyed-wiring.js +3 -1
  4. package/dist/add/add-personas.js +7 -1
  5. package/dist/add/add-workflow.js +12 -1
  6. package/dist/error-codes.d.ts +8 -1
  7. package/dist/error-codes.js +12 -0
  8. package/dist/types.d.ts +9 -0
  9. package/dist/utils/check-secret-sinks.d.ts +31 -0
  10. package/dist/utils/check-secret-sinks.js +117 -0
  11. package/dist/utils/post-process.js +4 -1
  12. package/dist/utils/single-declaration.d.ts +32 -0
  13. package/dist/utils/single-declaration.js +43 -0
  14. package/dist/utils/validate-exposed-functions-gated.js +15 -7
  15. package/dist/utils/workflow/dsl/extract-dsl-workflow.d.ts +6 -0
  16. package/dist/utils/workflow/dsl/extract-dsl-workflow.js +48 -1
  17. package/dist/utils/workflow/dsl/patterns.d.ts +9 -4
  18. package/dist/utils/workflow/dsl/patterns.js +26 -4
  19. package/package.json +3 -3
  20. package/src/add/add-functions.ts +57 -5
  21. package/src/add/add-keyed-wiring.ts +3 -0
  22. package/src/add/add-personas.test.ts +115 -1
  23. package/src/add/add-personas.ts +18 -9
  24. package/src/add/add-scenario-step.test.ts +38 -2
  25. package/src/add/add-scope.test.ts +73 -0
  26. package/src/add/add-system-role.test.ts +83 -0
  27. package/src/add/add-workflow.ts +21 -1
  28. package/src/add/allow-escape-hatches.test.ts +144 -0
  29. package/src/add/audit-meta.test.ts +75 -0
  30. package/src/add/secret-sink-check.test.ts +211 -0
  31. package/src/error-codes.ts +13 -0
  32. package/src/types.ts +9 -0
  33. package/src/utils/check-secret-sinks.ts +145 -0
  34. package/src/utils/post-process.ts +4 -1
  35. package/src/utils/single-declaration.ts +57 -0
  36. package/src/utils/validate-exposed-functions-gated.test.ts +2 -2
  37. package/src/utils/validate-exposed-functions-gated.ts +16 -7
  38. package/src/utils/workflow/dsl/extract-dsl-workflow.ts +57 -0
  39. package/src/utils/workflow/dsl/patterns.ts +33 -4
  40. package/tsconfig.tsbuildinfo +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,344 @@
1
+ ## 0.12.55
2
+
3
+ ### Patch Changes
4
+
5
+ - ae4e898: Carry a secret's `allowedHosts` through code generation, and close three gaps in
6
+ the SSRF guard.
7
+
8
+ `allowedHosts` was declared and enforced but never survived codegen: the
9
+ inspector did not read the property off the `defineSecret` literal, and the meta
10
+ builder rebuilt its objects without it. Enforcement in `assertSecretAllowedForHost`
11
+ then always saw `undefined`, so the egress restriction was a no-op by default —
12
+ and, with `secrets.requireAllowedHosts` set, threw for every secret including the
13
+ ones that correctly declared hosts. Both stages now carry the field, and the
14
+ secrets verifier asserts it against the generated JSON rather than a hand-written
15
+ meta literal, which is why the existing tests stayed green.
16
+
17
+ `isPrivateHost` now checks an explicit CIDR table instead of ad-hoc octet
18
+ comparisons. It previously missed `100.64.0.0/10` — which contains Alibaba
19
+ Cloud's `100.100.100.200` metadata endpoint — along with `192.0.0.0/24`,
20
+ `198.18.0.0/15`, `192.88.99.0/24`, the TEST-NETs, multicast and reserved space.
21
+ IPv6 gains a real parser, so `fec0::/10`, `ff00::/8`, and NAT64 (`64:ff9b::/96`)
22
+ and 6to4 (`2002::/16`) forms wrapping an internal IPv4 address are caught.
23
+
24
+ `safeFetch` takes an optional `resolveHost`, checked on the initial URL and every
25
+ redirect hop, so a _public_ hostname pointing at a private address is refused —
26
+ the `169-254-169-254.nip.io` shape a literal-only check cannot see. Core cannot
27
+ resolve DNS itself (Workers has no DNS API), so the Node resolver ships as
28
+ `@pikku/core/node-host-resolver` and the Node server runtimes install it during
29
+ `init()`. The connection is not pinned to the address that was checked, so a
30
+ rebind between check and connect is still possible.
31
+
32
+ The graph addon's `httpRequest` node called bare `fetch`, bypassing the guard
33
+ entirely; it now goes through `safeFetch`.
34
+
35
+ - Updated dependencies [e848eb2]
36
+ - Updated dependencies [b170489]
37
+ - Updated dependencies [ae4e898]
38
+ - @pikku/core@0.12.79
39
+
40
+ ## 0.12.54
41
+
42
+ ### Patch Changes
43
+
44
+ - 62ea4cc: The audit trail is now readable — in the generated meta, through an RPC, and as
45
+ a page in the console.
46
+
47
+ `audit: true` reaches `FunctionRuntimeMeta.audit` as its resolved form
48
+ (`{ durability }`), so which functions record anything is answerable without
49
+ running them. It is informational: the runner still resolves audit from the live
50
+ function config, so meta and runtime cannot disagree.
51
+
52
+ `AuditService` grows an optional read side — `query(AuditQuery)` and `facets()`.
53
+ Optional because a sink can legitimately be write-only: a queue producer that
54
+ hands events to another system has nothing to read back, and a reader that finds
55
+ these absent should say the trail is not readable here rather than that it is
56
+ empty. The two are very different answers to give someone auditing a system.
57
+
58
+ `KyselyAuditService` implements both, newest first with offset paging, filtered
59
+ by user, action and time window. Two things it now gets right that are easy to
60
+ get wrong: an empty filter array means "match nothing" rather than "no filter",
61
+ and results are read by physical _and_ camelCase key, because `CamelCasePlugin`
62
+ is on most pikku Kysely instances and renames result keys on the way out — the
63
+ mismatch does not throw, it returns a page of `undefined`. `init()` creates the
64
+ `audit` table for projects that do not migrate it themselves, from a new
65
+ exported `auditSchema` that stays out of `pikkuSchemas` because the runtime does
66
+ not need it.
67
+
68
+ The console addon exposes `console:getAudits` and `console:getAuditFilters`
69
+ behind a new `pikku:audit:read` scope, and forwards the application's `audit`
70
+ service into the addon's own services — without that last part every install
71
+ reported the trail as unreadable, whatever sink it had configured.
72
+
73
+ The console gets an Audit trail page: an infinite list filtered server-side by
74
+ user and action, and a row that opens the whole event, metadata rendered as a
75
+ JSON tree. Refused, unreadable and empty are three different screens, because
76
+ "you may not read this", "nobody can read this" and "nothing happened" are three
77
+ different facts.
78
+
79
+ Events name the person who caused them. The trail records a user id — the only
80
+ thing stable enough to record, since a name can change after the event — so
81
+ `getAudits` resolves those ids against better-auth's user directory at read
82
+ time, and the page shows the name while keeping the recorded id on the event.
83
+ The filter follows: pick a colleague by name, filter by the id. A scenario
84
+ actor is labelled as one, so synthetic traffic is not mistaken for real, and a
85
+ caller who was signed out shows the wire identity pikku resolved for them
86
+ rather than being credited to the system.
87
+
88
+ **Breaking, for anyone already reading `AuditEvent`:** `actor` is now
89
+ `userIdentity`, and its type `AuditActor` is `AuditUserIdentity`; `AuditQuery`
90
+ takes `userIds`/`orgId` in place of `actorUserIds`/`actorOrgId`, and
91
+ `AuditFacets` returns `userIds`. In pikku an _actor_ is a synthetic person a
92
+ scenario drives, flagged on the user row — so naming the causer of an event
93
+ `actor` made the synthetic case unsayable (`actor.actor === true`) and implied
94
+ every recorded action was a test. The overwhelming majority are ordinary
95
+ customers. The `audit` table follows: `actor_user_id` / `actor_org_id`
96
+ are now `user_id` / `org_id`, and a `pikku_user_id` column joins them so the
97
+ wire identity of a caller who never signed in survives the round trip — the
98
+ sink was dropping it, which left the console's Session field permanently
99
+ blank. A project that already migrated the table needs to rename the two
100
+ columns and add the third; `KyselyAuditService.init()` creates the new shape
101
+ for anyone who did not.
102
+
103
+ - 9dddff8: Split a column's at-rest form out of its classification.
104
+
105
+ `security: 'encrypted'` sat beside `'secret'` as though the two were
106
+ alternatives, which made the field unanswerable: a token hash and a live bearer
107
+ token are both secret, one must never be encrypted — the digest _is_ the lookup
108
+ key — and the other must always be. A column now carries a second, independent
109
+ `form: 'plain' | 'hashed' | 'wrapped' | 'sealed'` saying how the bytes are held.
110
+
111
+ Declaring a form other than `plain` makes the column's INSERT/UPDATE type
112
+ nominal — `WrappedValue`, `SealedValue`, `HashedValue` — so a plain string no
113
+ longer compiles there and the only way to write the column is with something an
114
+ encrypt, seal or hash call produced. `envelopeEncrypt`, `envelopeRewrap` and
115
+ `wrapDEK` now return the brand, and a new `hashToken` produces `HashedValue`, so
116
+ the round trip needs no casts; `column-form.ts` exports deliberately-named
117
+ `unsafeAs*` assertions for backfills, fixtures and values sealed elsewhere.
118
+ Reads are unaffected — the brands widen to `string` and compose with the
119
+ classification brand as `Secret<WrappedValue>`.
120
+
121
+ `wrapped` and `sealed` stay distinct because a sealed value is one the
122
+ application cannot read back; storing one where the other belongs is a row
123
+ nobody can open.
124
+
125
+ A `secret` column that has not declared a form now warns (PKU483), and a form on
126
+ a non-text column warns and is dropped (PKU484). Both are warnings, so existing
127
+ projects keep migrating — `pikku db --fail-on-warn` opts into the ratchet, and
128
+ an explicit `form: 'plain'` is the acknowledgement that silences it. The legacy
129
+ `security: 'encrypted'` keeps working and now expands to the pair it always
130
+ meant, `secret` + `wrapped`.
131
+
132
+ - 9dddff8: Read schema-qualified annotations, and let a project name its default schema.
133
+
134
+ `DbClassificationMap` nests tables under their schema whenever a project sets
135
+ `db.schema`, but `loadAnnotations` read the sidecar as a flat table→column map.
136
+ It therefore took the schema for a table and each table for a column, found no
137
+ recognised fields, and dropped every annotation on the floor — so a project
138
+ could mark a column `secret` and watch it generate as `private`, with no error
139
+ anywhere. The parser now detects the extra level (a column entry's values are
140
+ primitives; a table's are objects) and flattens it, so both shapes load.
141
+
142
+ New `db.defaultSchema` drops one schema's qualifier from the generated types:
143
+ with `defaultSchema: 'app'`, `app.user` is queried as `selectFrom('user')` and
144
+ typed as `User` rather than `AppUser`, matching what a project whose
145
+ `search_path` already resolves the schema actually writes. Tables in other
146
+ schemas stay qualified. Where dropping the qualifier would make two tables
147
+ share a name, the table keeps its qualifier and the codegen warns (PKU485)
148
+ rather than letting one silently shadow the other — queries against the loser
149
+ would have typechecked against the wrong columns.
150
+
151
+ The generated key is what Kysely puts in the SQL, so this is opt-in and
152
+ separate from `db.schema`: setting it for a schema the connection does not
153
+ resolve gives you queries that compile and then fail to find their table.
154
+
155
+ - 155528a: The PKU910 sessionless-output diagnostic advised marking a column `@public`, a
156
+ SQL-comment annotation syntax that no longer exists. Column classification is
157
+ sourced solely from the hand-authored `db/annotations.ts`, so the message now
158
+ points there.
159
+ - 78b29f0: `SecretService` now returns a `SecretValue<T>` rather than the bare value, so a
160
+ vault secret cannot reach a sink by accident.
161
+
162
+ `SecretValue` is nominally typed, which means it is not assignable to `string`
163
+ (or to any other concretely-typed field). Every sink with a real type — a
164
+ database column, an email body, a session payload — rejects it with no lint
165
+ rule involved. The sinks typed `any`, `unknown`, or a free generic — the logger,
166
+ queue payloads, webhook and email inputs, and a function's own output — are
167
+ guarded with `Safe<T>`, which collapses a `SecretValue` found anywhere inside
168
+ `T`, however deeply nested, to `never`.
169
+
170
+ Unwrap deliberately at the point the secret reaches the wire:
171
+
172
+ ```ts
173
+ const secret = await secrets.getSecret('BETTER_AUTH_SECRET')
174
+ betterAuth({ secret: secret.reveal() })
175
+ ```
176
+
177
+ Two behaviours cover what types cannot see. Structured serialization redacts —
178
+ `JSON.stringify` and node's inspect both yield `[secret]`, so an audit or log
179
+ write stays honest without crashing the request. String coercion throws
180
+ `SecretCoercionError`, because a template literal is always a leak.
181
+
182
+ `AuditLog.write` is guarded the same way as the logger, since an audit event
183
+ carries `input` and `metadata` as `unknown` and nominality alone cannot stop a
184
+ secret landing in one.
185
+
186
+ `.reveal()` is the deliberate escape hatch, and what it hands back is an
187
+ ordinary string as far as every sink signature is concerned. **PKU953** closes
188
+ that gap: under `pikku all --security` the inspector reports a revealed secret
189
+ that flows into a logger, an audit, a queue, an email or a webhook — `console` included.
190
+
191
+ This also fixed a real one: `remote-addon-auth.ts` called `String(token)` on an
192
+ `unknown` and wrote the result straight into an `Authorization` header.
193
+
194
+ - Updated dependencies [62ea4cc]
195
+ - Updated dependencies [9dddff8]
196
+ - Updated dependencies [78b29f0]
197
+ - @pikku/core@0.12.76
198
+
199
+ ## 0.12.53
200
+
201
+ ### Patch Changes
202
+
203
+ - fd72e58: Drop `scenario.step` — a scenario step is now always a `given`, `when` or
204
+ `then`.
205
+
206
+ `step` rendered no keyword, which made it the phase to reach for whenever a
207
+ step did not obviously fit one of the three. That is exactly the step a reader
208
+ cannot check: a scenario is read by people deciding whether it describes the
209
+ behaviour they wanted, and a row that says what it does without saying whether
210
+ it is setup, action or claim tells them nothing to agree or disagree with. It
211
+ was also the escape hatch from the assertion lint — a scenario with no `then`
212
+ could be made to stop complaining by demoting its steps rather than by
213
+ asserting anything.
214
+
215
+ Replace `scenario.step(...)` with whichever of `given`, `when` or `then` the
216
+ step actually is. `then` is not a rename: it makes the step's bindings
217
+ witnesses rather than alternatives, so every declared surface runs and they
218
+ must agree.
219
+
220
+ - d041d5b: Let a generated file declare scopes, roles and personas without taking the
221
+ single-declaration slot.
222
+
223
+ `defineScope`, `defineSystemRole` and `definePersonas` are one-per-codebase, and
224
+ the CLI generates declarations of its own — `user-admin.gen.ts` ships the whole
225
+ `admin` scope tree. Any project that scaffolded one therefore had two
226
+ declarations and failed codegen with PKU583, and the losing file's scopes were
227
+ dropped from the metadata rather than merged.
228
+
229
+ The rule exists to name the one place a person reads from and adds to, and
230
+ nobody adds to a file the next codegen run overwrites. A generated declaration
231
+ is still extracted; it just neither claims the slot nor collides with the app's
232
+ own.
233
+
234
+ - fd72e58: Make personas a first-class surface rather than a detail of the test runner.
235
+
236
+ A persona is now read in three places — the knowledge base resolves `persona:`
237
+ URIs against it, scenarios cast it as an actor, and a virtual user runs as it —
238
+ so it gets its own page at `/personas` under a new **People** section in the
239
+ rail, alongside Users. The card is a profile: avatar, name, job title, computed
240
+ address, the system roles they hold, and how many scenarios cast them. Opening
241
+ one expands each role to the scopes it confers, which is the half of the picture
242
+ that explains a 403.
243
+
244
+ `definePersonas` takes an optional `avatarUrl` — any URL a browser can load.
245
+ Nothing is derived from the address: a persona's address is synthetic, so a
246
+ derived identicon would be the same shrug for everyone. Omitted, the console
247
+ keeps drawing the deterministic colour-and-icon avatar from the persona's id.
248
+
249
+ - fd72e58: Read the actors that are not people on the personas page.
250
+
251
+ The platform — the app acting on itself, what `pikkuPlatformScenarioStep`
252
+ declares — now has a row of its own, alongside one per addon whose system a
253
+ step makes act. They sit behind a People / System / All filter that opens on
254
+ the people: a subject holds no roles and signs in as nobody, so leading with it
255
+ would put the rows nothing is authorized through above the ones that are.
256
+
257
+ The platform row is built in rather than derived. A project that has never
258
+ written a platform step still has a platform, and a card that appeared the
259
+ moment somebody declared their first step would read as a feature they had
260
+ switched on.
261
+
262
+ Also: PKU680 now counts `expectService`, `expectError` and `expectEventually`
263
+ as assertions. They are inline steps and carry no phase, so a scenario whose
264
+ only witness was a recorded service call was being told it never asserts.
265
+
266
+ - 894b2f8: `defineScope` and `defineSystemRole` accumulate across call sites again. Only `definePersonas` is one-per-codebase.
267
+
268
+ The previous release made all three single-declaration constructs, which no project scaffolding user-admin could satisfy: the CLI generates a `defineScope` of its own in `user-admin.gen.ts` carrying the whole `admin` tree, and `@pikku/addon-console` spells the same tree out again, so a second hand-written declaration failed the build with PKU583 — and the losing file's scopes were dropped from the metadata rather than merged.
269
+
270
+ Exempting generated files would have reinstated exactly the ambiguity the rule removes, only for the files nobody can read the rule from. The real fix is for `admin` to be a default scope nobody declares, at which point the rule can come back for scopes and roles.
271
+
272
+ `definePersonas` is unaffected: nothing generates one, so its single call site stands.
273
+
274
+ - dd19aa7: Drop `scopes` from sessionless functions, rename `selfAuthenticated`, and make both
275
+ escape hatches opt-in.
276
+
277
+ **`scopes` are gone from `pikkuSessionlessFunc`.** They are AND-ed and `verifyScopes`
278
+ fails closed on a session that does not exist, so every scope listed on a sessionless
279
+ function rejected the anonymous caller it exists to serve. `CorePikkuSessionlessFunctionConfig`
280
+ now states this once in core, and the generated `pikkuSessionlessFunc` / `pikkuVoidFunc`
281
+ configs derive from it — so the field is absent rather than subtracted.
282
+
283
+ `@pikku/addon-console`'s `installAddon` and `installOpenapiAddon` are now `pikkuFunc`.
284
+ Both set `auth: true` and `scopes: ['admin']`, and a test exercises that gate, so the
285
+ scopes were load-bearing — they only compiled as sessionless because the config accepted
286
+ a field it could not honour. No behaviour change: both already required a session.
287
+
288
+ **`selfAuthenticated` is now `permissionsInBody`.** It never described authentication:
289
+ what it records is that the permission check lives in the function body rather than in a
290
+ declared `permissions` entry.
291
+
292
+ **Both escape hatches must be opted into**, via a new `allow` block in
293
+ `pikku.config.json`:
294
+
295
+ ```json
296
+ "allow": { "permissionsInBody": true, "complexWorkflows": true }
297
+ ```
298
+
299
+ Unset means unavailable, and using the feature is a build error naming the flag that
300
+ would permit it — PKU576 for `permissionsInBody`, PKU643 for `pikkuWorkflowComplexFunc`.
301
+ Both trade something the tooling can inspect for something only a reader can verify: a
302
+ permission check buried in a body, or workflow steps that cannot be serialized into the
303
+ graph, replayed, or migrated. Both are occasionally right, and both are the path of least
304
+ resistance whenever the declarative form is merely inconvenient. Whoever owns the project
305
+ makes that call once, in writing, instead of every author making it silently at the call
306
+ site.
307
+
308
+ **PKU574's message no longer contradicts any of this.** Every function it reports is
309
+ sessionless — that is how the population is selected, not a finding — yet it opened by
310
+ reporting that they "require neither a session", then advised adding scopes. It now names
311
+ them as sessionless and recommends only gates an anonymous caller can meet:
312
+ `permissions`, `auth: true`, `wireAddon({ auth: true })`, or dropping `expose: true`.
313
+ `permissionsInBody` is deliberately absent from that list: a diagnostic should not
314
+ advertise its own escape hatch.
315
+
316
+ - 50ec500: Make `defineScope`, `defineSystemRole` and `definePersonas` single-declaration constructs
317
+ — exactly one call site per codebase, the rule `pikkuBetterAuth` has always had.
318
+
319
+ Each of the three already takes a keyed object, so one call declares as many entries as
320
+ you like. Spreading the calls across files bought nothing and cost the thing that matters:
321
+ there was no answer to "where do I add a persona?", so downstream tooling and agents had
322
+ nowhere unambiguous to read from or append to. The only duplicate handling that existed
323
+ caught a narrow case — the same id declared twice with different content — and said
324
+ nothing about the same id declared twice in two files.
325
+
326
+ A second call now fails the build with `PKU583` (`defineScope`), `PKU584`
327
+ (`defineSystemRole`) or `PKU585` (`definePersonas`), naming both source files and saying
328
+ to declare them all in one call. A second call in the _same_ file is refused too: "the
329
+ file" is not an answer either when the file holds two calls.
330
+
331
+ - Updated dependencies [32277d5]
332
+ - Updated dependencies [ea8aabf]
333
+ - Updated dependencies [33e96ab]
334
+ - Updated dependencies [fd72e58]
335
+ - Updated dependencies [fd72e58]
336
+ - Updated dependencies [fd72e58]
337
+ - Updated dependencies [894b2f8]
338
+ - Updated dependencies [dd19aa7]
339
+ - Updated dependencies [50ec500]
340
+ - @pikku/core@0.12.75
341
+
1
342
  ## 0.12.52
2
343
 
3
344
  ### Patch Changes
@@ -29,6 +29,7 @@ import { resolvePermissions } from '../utils/permissions.js';
29
29
  import { extractWireNames } from '../utils/post-process.js';
30
30
  import { ErrorCode } from '../error-codes.js';
31
31
  import { findPiiPaths } from '../utils/check-pii-output.js';
32
+ import { findRevealedSecretSinks } from '../utils/check-secret-sinks.js';
32
33
  import { isScenarioInstrumentationFunction } from './scenario-instrumentation.js';
33
34
  const isValidVariableName = (name) => {
34
35
  const regex = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
@@ -403,7 +404,9 @@ export const addFunctions = (logger, node, checker, state, options) => {
403
404
  */
404
405
  let auth;
405
406
  /** The author's claim that the body authorizes its own callers. */
406
- let selfAuthenticated;
407
+ let permissionsInBody;
408
+ /** The function's `audit` config, resolved to its object form. */
409
+ let audit;
407
410
  let readonly_;
408
411
  let deploy;
409
412
  let approvalRequired;
@@ -480,7 +483,33 @@ export const addFunctions = (logger, node, checker, state, options) => {
480
483
  remote = getPropertyValue(firstArg, 'remote');
481
484
  mcp = getPropertyValue(firstArg, 'mcp');
482
485
  auth = getPropertyValue(firstArg, 'auth');
483
- selfAuthenticated = getPropertyValue(firstArg, 'selfAuthenticated');
486
+ permissionsInBody = getPropertyValue(firstArg, 'permissionsInBody');
487
+ if (permissionsInBody && !options.allow?.permissionsInBody) {
488
+ logger.critical(ErrorCode.PERMISSIONS_IN_BODY_NOT_ALLOWED, `'${name}' declares \`permissionsInBody: true\`, which this project has not enabled. ` +
489
+ `It silences the exposed-and-ungated audit without gating anything, so it is opt-in: ` +
490
+ `set \`allow: { permissionsInBody: true }\` in pikku.config.json if the project accepts ` +
491
+ `permission checks that only a reader can verify. Otherwise express the check as a ` +
492
+ `\`permissions\` entry, or drop \`expose: true\` if the function was not meant to be ` +
493
+ `callable from outside.`);
494
+ return;
495
+ }
496
+ // `audit` is either `true` or `{ durability }`, so it needs the nested read:
497
+ // getPropertyValue stringifies an object initializer rather than parsing it.
498
+ // Mirrors core's `resolveAuditConfig` — the two must agree, or meta would
499
+ // claim a durability the runner does not use.
500
+ const auditProp = firstArg.properties.find((p) => ts.isPropertyAssignment(p) &&
501
+ ts.isIdentifier(p.name) &&
502
+ p.name.text === 'audit');
503
+ if (auditProp && ts.isPropertyAssignment(auditProp)) {
504
+ const auditInit = auditProp.initializer;
505
+ if (auditInit.kind === ts.SyntaxKind.TrueKeyword) {
506
+ audit = { durability: 'best-effort' };
507
+ }
508
+ else if (ts.isObjectLiteralExpression(auditInit)) {
509
+ const durability = getPropertyValue(auditInit, 'durability');
510
+ audit = { durability: durability ?? 'best-effort' };
511
+ }
512
+ }
484
513
  readonly_ = getPropertyValue(firstArg, 'readonly');
485
514
  deploy = getPropertyValue(firstArg, 'deploy');
486
515
  approvalRequired = getPropertyValue(firstArg, 'approvalRequired');
@@ -847,6 +876,18 @@ export const addFunctions = (logger, node, checker, state, options) => {
847
876
  // it runs ONLY when explicitly requested (`pikku all --security`) — see the
848
877
  // classificationCheck option. Default codegen skips it entirely.
849
878
  if (options.classificationCheck) {
879
+ // A revealed vault secret is invisible to the return-type scan below when it
880
+ // is written out mid-body rather than returned, so walk the sinks too.
881
+ for (const violation of findRevealedSecretSinks(checker, handler)) {
882
+ logger.diagnostic({
883
+ severity: 'error',
884
+ code: ErrorCode.SECRET_REVEALED_INTO_SINK,
885
+ message: `Function '${name}' passes a revealed secret to '${violation.sink}' ` +
886
+ `at line ${violation.line} (path '${violation.path}').\n ` +
887
+ `A vault secret must not be written to a log, an audit, a queue, an email or a webhook. ` +
888
+ `Pass the value only to the client that needs it, and reveal it there.`,
889
+ });
890
+ }
850
891
  const sig = checker.getSignatureFromDeclaration(handler);
851
892
  if (sig) {
852
893
  const rawRet = checker.getReturnTypeOfSignature(sig);
@@ -875,7 +916,7 @@ export const addFunctions = (logger, node, checker, state, options) => {
875
916
  message: `Sessionless function '${name}' exposes private-classified field(s) in its return type: ` +
876
917
  privatePaths.map((p) => `'${p}'`).join(', ') +
877
918
  `.\n Private fields are only safe to return from authenticated (sessioned) functions. ` +
878
- `Either require a session (use pikkuFunc) or mark the column @public if it is safe to expose publicly.`,
919
+ `Either require a session (use pikkuFunc) or set the column's security to 'public' in db/annotations.ts if it is safe to expose publicly.`,
879
920
  });
880
921
  }
881
922
  }
@@ -937,7 +978,8 @@ export const addFunctions = (logger, node, checker, state, options) => {
937
978
  outputs: outputNames.filter((n) => n !== 'void') ?? null,
938
979
  expose: expose || undefined,
939
980
  auth: auth || undefined,
940
- selfAuthenticated: selfAuthenticated || undefined,
981
+ permissionsInBody: permissionsInBody || undefined,
982
+ audit,
941
983
  remote: remote || undefined,
942
984
  scenarioStep: isScenarioStep || undefined,
943
985
  scenario: isScenario || undefined,
@@ -1,5 +1,5 @@
1
1
  import * as ts from 'typescript';
2
- import { getPropertyValue, assertStringLiteralProperty, } from '../utils/get-property-value.js';
2
+ import { getPropertyValue, getArrayPropertyValue, assertStringLiteralProperty, } from '../utils/get-property-value.js';
3
3
  import { ErrorCode } from '../error-codes.js';
4
4
  import { detectSchemaVendorOrError } from '../utils/detect-schema-vendor.js';
5
5
  import { parseDurationString } from '@pikku/core';
@@ -27,6 +27,7 @@ export const createAddKeyedWiring = (config) => {
27
27
  const descriptionValue = getPropertyValue(obj, 'description');
28
28
  const rotationPeriodValue = getPropertyValue(obj, 'rotationPeriod');
29
29
  const docsUrlValue = getPropertyValue(obj, 'docsUrl');
30
+ const allowedHostsValue = getArrayPropertyValue(obj, 'allowedHosts');
30
31
  const idValue = getPropertyValue(obj, config.idField);
31
32
  let schemaVariableName = null;
32
33
  let schemaSourceFile = null;
@@ -104,6 +105,7 @@ export const createAddKeyedWiring = (config) => {
104
105
  description: descriptionValue || undefined,
105
106
  rotationPeriod: rotationPeriodValue || undefined,
106
107
  docsUrl: docsUrlValue || undefined,
108
+ allowedHosts: allowedHostsValue || undefined,
107
109
  [config.idField]: idValue,
108
110
  schema: schemaLookupName,
109
111
  sourceFile,
@@ -2,6 +2,7 @@ import * as ts from 'typescript';
2
2
  import { DISPOSITIONS } from '@pikku/core/virtual-user';
3
3
  import { isRunnablePersona } from '@pikku/core/persona';
4
4
  import { ErrorCode } from '../error-codes.js';
5
+ import { claimSingleDeclaration } from '../utils/single-declaration.js';
5
6
  import { booleanProperty, getProperty, numberProperty, stringArrayProperty, stringProperty, unwrapAs, } from '../utils/literal-properties.js';
6
7
  /** A dial and the range outside which it is a mistake rather than a choice. */
7
8
  const RATES = [
@@ -123,6 +124,9 @@ export const addPersonas = (logger, node, _checker, state) => {
123
124
  return;
124
125
  }
125
126
  const sourceFile = node.getSourceFile().fileName;
127
+ if (!claimSingleDeclaration(logger, state.personas.files, ErrorCode.DUPLICATE_PERSONAS_DEFINITION, 'definePersonas', sourceFile)) {
128
+ return;
129
+ }
126
130
  const known = Object.keys(DISPOSITIONS);
127
131
  for (const prop of unwrapped.properties) {
128
132
  if (!ts.isPropertyAssignment(prop)) {
@@ -182,6 +186,9 @@ export const addPersonas = (logger, node, _checker, state) => {
182
186
  const description = stringProperty(config, 'description');
183
187
  if (description !== undefined)
184
188
  persona.description = description;
189
+ const avatarUrl = stringProperty(config, 'avatarUrl');
190
+ if (avatarUrl !== undefined)
191
+ persona.avatarUrl = avatarUrl;
185
192
  const personality = stringProperty(config, 'personality');
186
193
  if (personality !== undefined)
187
194
  persona.personality = personality;
@@ -204,7 +211,6 @@ export const addPersonas = (logger, node, _checker, state) => {
204
211
  const linkedAccounts = linkedAccountsProperty(config, id, logger);
205
212
  if (linkedAccounts !== undefined)
206
213
  persona.linkedAccounts = linkedAccounts;
207
- state.personas.files.add(sourceFile);
208
214
  state.personas.definitions.push(persona);
209
215
  }
210
216
  };
@@ -208,7 +208,7 @@ function getWorkflowInvocations(node, checker, state, workflowName, steps) {
208
208
  * Inspector for pikkuWorkflowFunc(), pikkuWorkflowComplexFunc() and
209
209
  * pikkuScenario() calls. Detects workflow registration and extracts metadata.
210
210
  */
211
- export const addWorkflow = (logger, node, checker, state) => {
211
+ export const addWorkflow = (logger, node, checker, state, options) => {
212
212
  if (!ts.isCallExpression(node)) {
213
213
  return;
214
214
  }
@@ -223,6 +223,14 @@ export const addWorkflow = (logger, node, checker, state) => {
223
223
  wrapperType = 'dsl';
224
224
  }
225
225
  else if (expression.text === 'pikkuWorkflowComplexFunc') {
226
+ if (!options.allow?.complexWorkflows) {
227
+ logger.critical(ErrorCode.COMPLEX_WORKFLOW_NOT_ALLOWED, `'${expression.text}' is used here, but this project has not enabled complex workflows. ` +
228
+ `Their inline steps cannot be serialized, so they are absent from the workflow graph and ` +
229
+ `cannot be replayed or migrated across a definition change. Express the workflow with ` +
230
+ `pikkuWorkflowFunc and the step DSL, or set \`allow: { complexWorkflows: true }\` in ` +
231
+ `pikku.config.json if the project accepts that trade.`);
232
+ return;
233
+ }
226
234
  wrapperType = 'complex';
227
235
  }
228
236
  else if (expression.text === 'pikkuScenario') {
@@ -292,6 +300,7 @@ export const addWorkflow = (logger, node, checker, state) => {
292
300
  let steps = [];
293
301
  let context = undefined;
294
302
  let dsl = undefined;
303
+ let asserts = undefined;
295
304
  // Try DSL workflow extraction first
296
305
  // Pass the whole CallExpression node so findWorkflowFunction can find the arrow function
297
306
  const result = extractDSLWorkflow(node, checker, {
@@ -301,6 +310,7 @@ export const addWorkflow = (logger, node, checker, state) => {
301
310
  // Extraction succeeded
302
311
  steps = result.steps;
303
312
  context = result.context;
313
+ asserts = result.asserts;
304
314
  // Check if workflow contains inline steps (non-serializable)
305
315
  if (hasInlineSteps(steps)) {
306
316
  if (wrapperType === 'dsl') {
@@ -374,6 +384,7 @@ export const addWorkflow = (logger, node, checker, state) => {
374
384
  expose,
375
385
  skip,
376
386
  scenario: wrapperType === 'scenario' ? true : undefined,
387
+ asserts,
377
388
  actors: actorNames.length > 0 ? actorNames : undefined,
378
389
  };
379
390
  // The scenario "logger/config only" rule (PKU673) and the implicit
@@ -27,21 +27,27 @@ export declare enum ErrorCode {
27
27
  WORKFLOW_ORCHESTRATOR_NOT_CONFIGURED = "PKU600",
28
28
  INVALID_DSL_WORKFLOW = "PKU641",
29
29
  WORKFLOW_GRAPH_ADDON_NOT_WIRED = "PKU642",
30
+ COMPLEX_WORKFLOW_NOT_ALLOWED = "PKU643",
30
31
  REMOTE_ADDON_NOT_DEV_DEPENDENCY = "PKU338",
31
32
  REMOTE_ADDON_AUTH_UNRESOLVED = "PKU339",
32
33
  DB_COLUMN_NAME_TYPE_CONTRADICTION = "PKU480",
33
34
  DB_JSON_COLUMN_UNTYPED = "PKU481",
34
35
  DB_FORMAT_ON_NON_STRING = "PKU482",
36
+ DB_SECRET_COLUMN_STORED_PLAIN = "PKU483",
37
+ DB_FORM_ON_NON_STRING = "PKU484",
38
+ DB_DEFAULT_SCHEMA_NAME_COLLISION = "PKU485",
35
39
  SCHEMA_GENERATION_ERROR = "PKU456",
36
40
  INLINE_SCHEMA = "PKU489",
37
41
  FUNCTION_METADATA_NOT_FOUND = "PKU559",
38
42
  DUPLICATE_AUTH_DEFINITION = "PKU581",
39
43
  AUTH_NOT_EXPORTED = "PKU582",
44
+ DUPLICATE_PERSONAS_DEFINITION = "PKU585",
40
45
  ROUTE_PARAM_MISMATCH = "PKU571",
41
46
  ROUTE_QUERY_MISMATCH = "PKU572",
42
47
  AUTH_DISABLED_REQUIRES_SESSIONLESS = "PKU573",
43
48
  EXPOSED_FUNCTION_HAS_NO_GATE = "PKU574",
44
49
  TAG_RESOLVES_TO_NO_MIDDLEWARE = "PKU575",
50
+ PERMISSIONS_IN_BODY_NOT_ALLOWED = "PKU576",
45
51
  DUPLICATE_FUNCTION_VERSION = "PKU850",
46
52
  DUPLICATE_FUNCTION_NAME = "PKU851",
47
53
  MANIFEST_MISSING = "PKU860",
@@ -67,7 +73,8 @@ export declare enum ErrorCode {
67
73
  RPC_INVOCATION_TYPE_CAST = "PKU940",
68
74
  SECRET_SERVICE_ALIASED = "PKU950",
69
75
  SECRET_NOT_DECLARED = "PKU951",
70
- SECRET_KEY_NOT_STATIC = "PKU952"
76
+ SECRET_KEY_NOT_STATIC = "PKU952",
77
+ SECRET_REVEALED_INTO_SINK = "PKU953"
71
78
  }
72
79
  /**
73
80
  * Severity of a tracked, coded diagnostic. `critical` always blocks the build;
@@ -29,6 +29,7 @@ export var ErrorCode;
29
29
  ErrorCode["WORKFLOW_ORCHESTRATOR_NOT_CONFIGURED"] = "PKU600";
30
30
  ErrorCode["INVALID_DSL_WORKFLOW"] = "PKU641";
31
31
  ErrorCode["WORKFLOW_GRAPH_ADDON_NOT_WIRED"] = "PKU642";
32
+ ErrorCode["COMPLEX_WORKFLOW_NOT_ALLOWED"] = "PKU643";
32
33
  // Remote addon (wireRemoteAddon) validation
33
34
  ErrorCode["REMOTE_ADDON_NOT_DEV_DEPENDENCY"] = "PKU338";
34
35
  ErrorCode["REMOTE_ADDON_AUTH_UNRESOLVED"] = "PKU339";
@@ -36,6 +37,9 @@ export var ErrorCode;
36
37
  ErrorCode["DB_COLUMN_NAME_TYPE_CONTRADICTION"] = "PKU480";
37
38
  ErrorCode["DB_JSON_COLUMN_UNTYPED"] = "PKU481";
38
39
  ErrorCode["DB_FORMAT_ON_NON_STRING"] = "PKU482";
40
+ ErrorCode["DB_SECRET_COLUMN_STORED_PLAIN"] = "PKU483";
41
+ ErrorCode["DB_FORM_ON_NON_STRING"] = "PKU484";
42
+ ErrorCode["DB_DEFAULT_SCHEMA_NAME_COLLISION"] = "PKU485";
39
43
  // Configuration errors
40
44
  ErrorCode["SCHEMA_GENERATION_ERROR"] = "PKU456";
41
45
  ErrorCode["INLINE_SCHEMA"] = "PKU489";
@@ -44,12 +48,19 @@ export var ErrorCode;
44
48
  // Auth errors
45
49
  ErrorCode["DUPLICATE_AUTH_DEFINITION"] = "PKU581";
46
50
  ErrorCode["AUTH_NOT_EXPORTED"] = "PKU582";
51
+ // Single-declaration constructs — one call site per codebase.
52
+ // PKU583 (defineScope) and PKU584 (defineSystemRole) are retired, not free:
53
+ // scopes and roles held this rule until the generated `admin` tree made it
54
+ // unsatisfiable, and get it back once `admin` is a default scope nobody
55
+ // declares. Do not reuse those two numbers for anything else.
56
+ ErrorCode["DUPLICATE_PERSONAS_DEFINITION"] = "PKU585";
47
57
  // HTTP Route errors
48
58
  ErrorCode["ROUTE_PARAM_MISMATCH"] = "PKU571";
49
59
  ErrorCode["ROUTE_QUERY_MISMATCH"] = "PKU572";
50
60
  ErrorCode["AUTH_DISABLED_REQUIRES_SESSIONLESS"] = "PKU573";
51
61
  ErrorCode["EXPOSED_FUNCTION_HAS_NO_GATE"] = "PKU574";
52
62
  ErrorCode["TAG_RESOLVES_TO_NO_MIDDLEWARE"] = "PKU575";
63
+ ErrorCode["PERMISSIONS_IN_BODY_NOT_ALLOWED"] = "PKU576";
53
64
  // Versioning errors
54
65
  ErrorCode["DUPLICATE_FUNCTION_VERSION"] = "PKU850";
55
66
  ErrorCode["DUPLICATE_FUNCTION_NAME"] = "PKU851";
@@ -86,4 +97,5 @@ export var ErrorCode;
86
97
  ErrorCode["SECRET_SERVICE_ALIASED"] = "PKU950";
87
98
  ErrorCode["SECRET_NOT_DECLARED"] = "PKU951";
88
99
  ErrorCode["SECRET_KEY_NOT_STATIC"] = "PKU952";
100
+ ErrorCode["SECRET_REVEALED_INTO_SINK"] = "PKU953";
89
101
  })(ErrorCode || (ErrorCode = {}));
package/dist/types.d.ts CHANGED
@@ -268,6 +268,15 @@ export type InspectorOptions = Partial<{
268
268
  * function, which is expensive. Enabled via `pikku all --security`.
269
269
  */
270
270
  classificationCheck: boolean;
271
+ /**
272
+ * Escape hatches the project has opted into, from `allow` in
273
+ * `pikku.config.json`. Absent or false means the feature is refused with a
274
+ * critical naming the flag that would permit it.
275
+ */
276
+ allow: Partial<{
277
+ permissionsInBody: boolean;
278
+ complexWorkflows: boolean;
279
+ }>;
271
280
  }>;
272
281
  export interface InspectorLogger {
273
282
  info: (message: string) => void;