@pikku/kysely 0.13.6 → 0.13.7

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 CHANGED
@@ -1,3 +1,328 @@
1
+ ## 0.13.7
2
+
3
+ ### Patch Changes
4
+
5
+ - 6a307f0: Fix four latent correctness bugs in the function, RPC and error runtimes, and
6
+ remove dead code from the workflow service surface.
7
+
8
+ `WorkflowService.getNodesWithoutSteps` is gone. It was declared on the abstract
9
+ service and implemented by all five storage backends, and nothing ever called
10
+ it — hence the non-core packages in this changeset, which only lose that method.
11
+
12
+ **An RPC could execute twice.** `RPCService.invoke`, its addon path, and
13
+ `rpcWithWire` each wrapped the _execution_ of a resolved function in a `try`
14
+ whose `catch` treated `RPCNotFoundError` as "not found locally" and re-dispatched
15
+ the call through `deploymentService`. A nested `rpc.invoke` to a missing name,
16
+ raised from inside an already-running function, therefore re-ran that function on
17
+ a remote instance after its local side effects had already committed. Resolution
18
+ is now separated from execution on all three paths, so only a genuinely
19
+ unresolvable name reaches the fallback. What escapes to callers is unchanged.
20
+
21
+ **`addonNamespace` leaked between sibling calls.** The function runner's
22
+ middleware path restored `rpc`, `functionId`, `audit` and `addonNamespace` after
23
+ an invocation; the non-middleware path restored the first three but not the
24
+ fourth. A call into an addon function with no middleware left the addon's
25
+ namespace on the wire, so subsequent sibling calls resolved the wrong
26
+ per-instance singletons and `credentialOverrides`.
27
+
28
+ **Errors registered on a subclass never resolved.** `misc.errors` was typed
29
+ `Map<PikkuError, ErrorDetails>` — instances — while `addError` stores
30
+ constructors, a mismatch hidden by its `error: any` parameter. The instance
31
+ lookup in `getErrorResponse` was consequently dead, and lookup fell through to a
32
+ scan comparing `constructor.name`, so a subclass of a registered error got no
33
+ status mapping at all. The map is now typed `Map<PikkuErrorConstructor, …>` and
34
+ lookup walks the prototype chain first. Name matching is retained, deliberately,
35
+ as the fallback that keeps error mapping working when two copies of
36
+ `@pikku/core` are installed.
37
+
38
+ **`createWeakUID` collided across instances.** The prefix was
39
+ `Date.now().toString(36)` evaluated at module load, so any two instances loading
40
+ the module in the same millisecond emitted identical `channelId` and `requestId`
41
+ sequences — reproducibly, not just in principle. It is now seeded lazily from
42
+ `crypto.randomUUID()`.
43
+
44
+ Also: `pikkuState` keys its global map with `Symbol.for` rather than `Symbol`, so
45
+ two copies of the package share registrations instead of silently getting
46
+ disjoint state; and the local channel upgrade path no longer keys its middleware
47
+ cache on the raw request path, which grew the cache without bound while the
48
+ cached value never varied by path.
49
+
50
+ - afef587: Close eleven security weaknesses found in a review of `@pikku/core`. Most are
51
+ breaking, and two invalidate data or credentials already in the wild — read the
52
+ migration notes before upgrading.
53
+
54
+ **Breaking: AI agent thread ownership now fails closed.** Reading, listing,
55
+ resuming or approving an existing thread or run requires a resolved session
56
+ principal (`userId`, or `orgId` for `sessionScope: 'org'`), regardless of the
57
+ agent's `auth` setting. Previously a request without a session had no ownership
58
+ model at all: the caller-supplied `resourceId` was accepted as the ownership
59
+ key, so any caller could read or resume another party's thread by naming its
60
+ `resourceId`. Worse, `threadOwnerConstraint` returned `undefined` for a
61
+ sessionless caller, and `undefined` means _no filter_ rather than _no rows_ —
62
+ so `getAgentThreads` returned every thread in the deployment. It now returns
63
+ `string[]`, empty for a sessionless caller, which every storage backend already
64
+ treats as matching nothing. Sessionless agents still run one-shot conversations,
65
+ each with a fresh unguessable owner; what they lose is cross-request continuity.
66
+ Wire a session to restore it.
67
+
68
+ **Breaking: stored secrets and credentials must be re-entered.** `deriveKey` ran
69
+ a single unsalted round of SHA-256 over the passphrase and used the digest
70
+ directly as the AES-GCM key — roughly one hash per brute-force guess, with one
71
+ rainbow table working against every deployment. It is now PBKDF2-HMAC-SHA256 at
72
+ 600,000 iterations over a random salt. There is no compatibility path: every
73
+ value held by the kysely, mongodb and redis secret services and the kysely
74
+ credential service becomes undecryptable. They fail loud, naming the key and
75
+ `key_version`, so the app hard-fails on first secret read until each is re-set.
76
+
77
+ The KEK salt is scoped to the key version and stored alongside it, rather than
78
+ per secret, so a bulk read costs one derivation instead of N — `getSecrets` over
79
+ 50 secrets went from ~2.3s to ~48ms, and rotation from ~4.6s to ~94ms. This adds
80
+ a salt table (kysely), hash field (redis) or collection (mongodb), created
81
+ automatically on first use.
82
+
83
+ **Breaking: `PIKKU_REMOTE_SECRET` must be at least 32 characters.** The
84
+ remote-RPC session envelope moved from PBKDF2 to HKDF, which expands
85
+ high-entropy key material rather than stretching a low-entropy passphrase. That
86
+ took a remote hop from ~269ms to ~0.4ms — PBKDF2 was running twice per request —
87
+ but HKDF supplies no brute-force resistance, so the secret must carry the
88
+ entropy itself. A shorter secret now throws `WeakKeyMaterialError` at both ends.
89
+ Generate one with `openssl rand -base64 32` and roll it out to every service in
90
+ the mesh together: existing bearer tokens are format-incompatible, so a partial
91
+ rollout produces 401s until every instance is updated. The Cloudflare, Lambda
92
+ and Azure deployment services each hand-rolled a copy of `buildRemoteHeaders`
93
+ and now call the shared one, which is what keeps the two sides in step.
94
+
95
+ **Breaking: previously signed content URLs stop verifying.** `LocalContent`
96
+ signed only `{signedAt, expiresAt, notBefore}`, so a signature proved when a URL
97
+ was issued but never what it was issued for — any valid token was a skeleton
98
+ key, and swapping the pathname from a public thumbnail to a private document
99
+ still verified. The signature now binds the request path. Separately, the
100
+ verifier returned "valid" when no JWT service was wired, which is how
101
+ `pikku serve` ran: a forged `?signedAt=0&expiresAt=99999999999999` was accepted.
102
+ It now rejects with 403, `LocalContent` requires a `JWTService`, and
103
+ `pikku serve`/`pikku dev` mint an ephemeral per-process signing key so local
104
+ development works without shipping a fail-open path. In-flight signed URLs must
105
+ be re-issued.
106
+
107
+ **Request body size limits now apply to every adapter.** The `maxBodySize` cap
108
+ existed only in `PikkuFetchHTTPRequest`. The real hole was uWebSockets, which
109
+ drove `res.onData` itself and concatenated every chunk with no bound and nothing
110
+ downstream able to intervene; it now drops chunks past the limit and replies 413
111
+ before routing. Fastify delegates to its native `bodyLimit` (set only when
112
+ `maxBodySize` is configured, so fastify's stricter 1 MB default is never
113
+ loosened), and `PikkuExpressServer` feeds the limit into its body parsers. Two
114
+ paths can only reject rather than prevent, and are documented as such:
115
+ `express-middleware` mounted on your own app receives an already-parsed body, so
116
+ that deployment must bound its own parser; Next server actions bottom out at
117
+ `experimental.serverActions.bodySizeLimit`.
118
+
119
+ **Breaking: the console addon's privileged functions are gated by default.**
120
+ `wireAddon` gains a `scopes` option that applies to every function in the
121
+ addon's namespace, and the console scaffold now generates
122
+ `wireAddon({ name: 'console', package: '@pikku/addon-console', scopes: ['admin'] })`.
123
+ Previously the console's entire privileged surface — around 54 functions
124
+ including `credentialGet`, which returns a resolved OAuth token for an arbitrary
125
+ `userId`, `updateFunctionBody`, and `installAddon`, which shells out to a
126
+ package install — was protected only by an optional host-registered
127
+ `addGlobalPermission`. `resolveGlobalPermissions` returns `[]` when none is
128
+ registered and permission checking then no-ops, so an app that never registered
129
+ one served those functions to anyone, and with the template's default
130
+ `scaffold.rpc: "no-auth"` that meant unauthenticated. All of them now return 403
131
+ `MissingScopeError` without an `admin`, `admin:*` or `*` scope. **Regenerating
132
+ is required** — an app holding an old `console.gen.ts` stays open.
133
+ `installAddon` and `installOpenapiAddon` additionally declare their own
134
+ `auth: true, scopes: ['admin']`, and `getAgentThreads` now scopes its listing to
135
+ the session's own threads unless the caller holds admin.
136
+
137
+ Addon scopes are enforced in `runPikkuFunc` rather than at the RPC boundary,
138
+ because a wiring can reference an addon function directly — the inspector
139
+ records the addon's `packageName` on HTTP, channel, schedule, queue, CLI,
140
+ trigger, gateway and MCP wirings — and those paths never call `resolveNamespace`.
141
+ Enforcing at the RPC seam would have covered only the `namespace:function` form
142
+ while reading as complete.
143
+
144
+ **Breaking: `wireAddon`'s `auth` and `tags` now apply on direct wirings too.**
145
+ Both were read only by `resolveAddonFunction`, so they had exactly the hole
146
+ scopes had: `wireAddon({ name: 'console', package: '@pikku/addon-console', auth:
147
+ true, tags: ['admin'] })` gated `rpc('console:credentialGet')` and gated nothing
148
+ at all on an HTTP route wired straight to `credentialGet`. A consumer who
149
+ reached for the documented way to lock an addon down got a control that was
150
+ silently inert on every wiring except one. Both now resolve in `runPikkuFunc`.
151
+ `auth` merges as an OR — `auth: false` from an addon is ignored on a direct
152
+ wiring, because an addon may require a session the wiring did not but must never
153
+ waive one it did. Addon tags resolve to concrete middleware against the **root**
154
+ tag groups before the call rather than being folded into the function's
155
+ inherited middleware: `addTagMiddleware('admin', …)` is written by the consuming
156
+ app and registers under the root package, whereas `combineMiddleware` would look
157
+ the tag up under the addon's own `packageName`, where it does not exist.
158
+
159
+ One consequence worth naming: an addon that wires `auth: true` and also runs its
160
+ own sessionless internal work — a scheduled task or queue worker inside the
161
+ addon calling a sibling function — is now gated where it previously was not,
162
+ because a bare `rpc('fn')` from inside the addon reaches `runPikkuFunc` with the
163
+ addon's `packageName` like any other call. This reverses a decision that
164
+ deliberately scoped the gate to the namespaced boundary; that reasoning held
165
+ only while the boundary was real, and a direct wiring can enter an addon without
166
+ crossing it, so "already inside" is not something the runtime can infer. Such an
167
+ addon should carry authorization on the function via
168
+ `pikkuFunc({ permissions })`, which has always been enforced on every path. A
169
+ follow-up will add execution provenance so an intra-addon call can be
170
+ distinguished from an external one and skip the addon-level check; that needs a
171
+ marker no caller outside the process can set, which is its own design problem
172
+ and does not belong in a security fix.
173
+
174
+ **Codegen now warns when an exposed function has no gate (PKU574).** The
175
+ generated `POST /rpc/:rpcName` dispatcher forwards to `rpc.exposed`, which
176
+ refuses anything without `expose: true` — but nothing checked whether the
177
+ target was gated, because a dispatcher cannot know what it dispatches to. The
178
+ console shipped ~54 privileged functions through that gap and the toolchain was
179
+ silent. The inspector now reports every function that is exposed, sessionless,
180
+ and carries no `auth`, `scopes` or `permissions` of its own and none from a
181
+ governing `wireAddon`. It is a `warn`, not a critical: `expose: true` on an
182
+ ungated sessionless function is correct for a genuinely public endpoint, so it
183
+ blocks a build only under `--fail-on-warn`.
184
+
185
+ Two pieces of metadata were missing for this to be answerable statically, and
186
+ both are now recorded. A `pikkuSessionlessFunc`'s own `auth: true` was read at
187
+ runtime but never written to function meta, so a self-gated function was
188
+ indistinguishable from an ungated one — `sessionless` carries the baseline, and
189
+ `auth` now carries the tightening. And `wireAddon`'s `scopes`, `auth` and `tags`
190
+ were not parsed at all: the inspector recorded the addon's `rpcEndpoint` and its
191
+ secret, variable and credential overrides, and dropped every one of its gates.
192
+ An addon whose gates are not statically knowable is treated as gated, because a
193
+ false positive on a correctly-secured addon costs more than the one case it
194
+ would catch.
195
+
196
+ **Breaking: an application's global permissions now apply inside addons.**
197
+ `resolveGlobalPermissions` read only the bucket matching the function's own
198
+ package, but the generated `addGlobalPermission` wrapper takes no package
199
+ argument and always registers under the root. An app-wide rule like "every
200
+ request needs a signed-in user" therefore stopped at the addon boundary, and the
201
+ bucket an addon's functions did read was one no host could write to — which is
202
+ why the console addon's recommended `addGlobalPermission([isAdmin],
203
+ '@pikku/addon-console')` was never a gate anybody could actually install. A
204
+ function now resolves the root bucket and its own package's, root first.
205
+ Unioning is safe in a way nothing else here would be: globals AND, so adding the
206
+ root ones can only tighten. Package buckets stay one-way — a package's globals
207
+ never reach root functions, or an installed addon could gate the whole
208
+ application. Apps with both a root global and addon-provided functions will see
209
+ those functions gated where they previously were not.
210
+
211
+ **Codegen now records whether each HTTP route requires a session, and warns
212
+ about inert addon tags (PKU575).** Four separate things can demand a session —
213
+ the function's `sessionless`, its own `auth`, the route's (or its group's)
214
+ `auth`, and the addon it belongs to — and answering "which routes are open?"
215
+ meant joining all four by hand and knowing which wins. Each route's meta now
216
+ carries the resolved `requiresSession` alongside the route's own `auth`. Scopes
217
+ count as requiring one, since they are matched against the session's and fail
218
+ closed. Anything not statically knowable resolves to `true`, matching PKU574:
219
+ a route that looks stricter than it is costs less than one that looks open and
220
+ isn't. Separately, `wireAddon({ tags: ['admin'] })` reads like a gate and is
221
+ applied like one right up until no `addTagMiddleware('admin', …)` exists, at
222
+ which point it resolves to an empty list and gates nothing; that now warns.
223
+ Only addon tags are reported — a tag on a function is as likely to be
224
+ organizational, and warning about those would bury the case that matters.
225
+
226
+ **Object-shorthand permissions were missing from meta.** The inspector visited
227
+ `ts.PropertyAssignment` but not `ts.ShorthandPropertyAssignment`, so
228
+ `permissions: { canAdminOrg }` — enforced identically to the longhand form at
229
+ runtime, since `verifyPermissions` has a non-array branch — was recorded as _no
230
+ permissions at all_. That is the most dangerous direction for meta to be wrong
231
+ in: an audit reading it sees an open door where one is shut. It cost this review
232
+ a false IDOR report across ~35 billing and org functions before the source
233
+ contradicted the metadata.
234
+
235
+ **Functions that authorize in their own body can say so.** A webhook receiver
236
+ verifying a signature, or a handler redeeming a signed invite, is genuinely
237
+ closed while carrying no session, scope or permission — indistinguishable in
238
+ meta from one nobody remembered to gate, and so warned about forever by PKU574.
239
+ `selfAuthenticated: true` on the function config records the claim and silences
240
+ the warning for that function. It is declarative only: nothing at runtime reads
241
+ it and it grants nothing. Detection was rejected deliberately — inferring it
242
+ from the body means a function that _looks_ like it checks something silences
243
+ the warning while checking nothing, and a warning that is usually wrong stops
244
+ being read.
245
+
246
+ **Breaking: `scaffold.<feature>` is now `boolean | { auth?, path? }`, and `true`
247
+ means authenticated.** The old `'auth' | 'no-auth' | false` read like a
248
+ starter-file preference while being a live authorization decision, set three
249
+ directories from the functions it governed — the shape the console incident
250
+ took. A surface now becomes public only by writing `{ auth: false }`, so
251
+ omitting a field can never open anything: the failure mode of a forgotten flag
252
+ is a locked door. `{ path }` additionally overrides where the file is
253
+ generated, which previously could only be set for all features at once via
254
+ `pikkuDir`.
255
+
256
+ The legacy strings are **refused, not coerced**. `resolveScaffoldFeature` throws
257
+ naming the key and its replacement (`"rpc": "no-auth"` → `"rpc": { "auth":
258
+ false }`), and it does so at config load, not downstream. An earlier design used
259
+ a bare `string` for the output path, under which `"no-auth"` would have parsed
260
+ as a file named `no-auth` and every unmigrated config would have silently
261
+ produced nonsense; the object form makes any string invalid, so the failure is
262
+ loud.
263
+
264
+ The collapse is deliberately not uniform in effect. For `rpc` the flag was a
265
+ blanket "no anonymous RPC in this app" set on a dispatcher that cannot know what
266
+ it dispatches to; for `userAdmin` it was redundant, since the generated
267
+ functions are already `pikkuFunc` with `scopes: ['admin:users:list']`. But for
268
+ `agent`, `workflow`, `events` and `scenarios` it is the only gate — those
269
+ generate real endpoints the app never authors — so `true` keeps them
270
+ authenticated rather than opening them as a side effect of a config cleanup.
271
+ `webhook` and `remoteRpc` have no auth dimension at all (`serialize-remote-rpc.ts`
272
+ hardcodes `auth: false`), so an `{ auth }` on them is ignored. The three
273
+ configs in this repo are migrated preserving their current behaviour exactly.
274
+
275
+ **Queue job identities are signed.** A job carried the producer's `pikkuUserId`
276
+ as a plain string and the worker resolved a session from it with no
277
+ verification, so write access to the queue backend was act-as-any-user. The
278
+ identity is now `pq1.<claim>.<hmac>`, HMAC-SHA256 over the claim and the
279
+ canonicalized job payload, keyed by HKDF expansion of a new
280
+ `PIKKU_QUEUE_IDENTITY_SECRET`. Producers opt in by wrapping their queue service
281
+ with `SignedQueueService`. This fails safe rather than closed: with no secret
282
+ configured the identity is dropped and jobs still process, warning once per
283
+ process, so no existing deployment breaks on upgrade — it simply loses queue
284
+ identity until the secret is set. The payload rather than the job id is bound
285
+ because SQS, Cloudflare Queues, Azure and the in-memory service all mint ids
286
+ after `add` returns.
287
+
288
+ **Workflow inline state is read from the run record.** `isInline` consulted a
289
+ process-local `Map`, while `WorkflowRun.inline` is durable. Any instance that
290
+ did not start a run disagreed with the record, so one instance could dispatch a
291
+ queued job for a workflow another was already executing in-process. It is now
292
+ async and resolves through the durable identity, cached only when a context
293
+ already exists so a passive reader allocates nothing. The same `Map` also leaked:
294
+ `nextStepKey` fabricated replay state on every step, and `releaseContext`
295
+ refused to free anything carrying it, so runs whose steps executed outside a
296
+ `beginReplay` bracket — the step-worker queue path — stranded their context and
297
+ step state for the process lifetime. Contexts are now released by an explicit
298
+ execution counter. Step ordinals reset per execution rather than accumulating
299
+ across step-worker invocations in one process, which makes step naming
300
+ independent of how work was distributed.
301
+
302
+ **Secret reads fail loud in every store.** `MongoDBSecretService.getSecrets`
303
+ skipped rows that failed to decrypt, and the redis equivalent dropped every
304
+ rejection via `Promise.allSettled`, including the "No KEK available for
305
+ key_version N" configuration error. Both now throw, naming the key and its key
306
+ version, matching the kysely behaviour. This matters most alongside the KEK
307
+ change above: without it, an upgrade surfaces as a partial secrets map and an
308
+ opaque downstream failure instead of an error naming the secret to re-enter.
309
+
310
+ **A second middleware registration for a pattern no longer erases the first.**
311
+ `addHTTPMiddleware`, `addTagMiddleware` and `addChannelMiddleware` groups are
312
+ keyed by pattern or tag and held one source file each, so a second file's call
313
+ overwrote the first's. Codegen emits its imports from what is stored, so the
314
+ losing file was never imported and its middleware never registered — the
315
+ runtime composes repeated registrations for a pattern happily, and only codegen
316
+ dropped one. Adding an unrelated `addHTTPMiddleware('*', …)` to an app was
317
+ enough to silently unregister the generated better-auth session bridge, which
318
+ fails open and gives no sign until a request arrives without a session. A group
319
+ now carries every registration made for it, and all of them are imported.
320
+
321
+ - Updated dependencies [6a307f0]
322
+ - Updated dependencies [afef587]
323
+ - Updated dependencies [8075f6a]
324
+ - @pikku/core@0.12.74
325
+
1
326
  ## 0.13.6
2
327
 
3
328
  ### Patch Changes
@@ -11,6 +11,8 @@ export interface KyselyCredentialServiceConfig {
11
11
  export declare class KyselyCredentialService implements CredentialService {
12
12
  private db;
13
13
  private initialized;
14
+ private kekSalts;
15
+ private keks;
14
16
  private key;
15
17
  private keyVersion;
16
18
  private previousKey?;
@@ -19,6 +21,7 @@ export declare class KyselyCredentialService implements CredentialService {
19
21
  constructor(db: Kysely<KyselyPikkuDB>, config: KyselyCredentialServiceConfig);
20
22
  init(): Promise<void>;
21
23
  private logAudit;
24
+ private getKEKSalt;
22
25
  private getKEK;
23
26
  private whereUserId;
24
27
  get<T = unknown>(name: string, userId?: string): Promise<T | null>;
@@ -1,9 +1,11 @@
1
- import { envelopeEncrypt, envelopeDecrypt, envelopeRewrap, } from '@pikku/core/crypto-utils';
1
+ import { deriveKEK, generateKEKSalt, envelopeEncrypt, envelopeDecrypt, envelopeRewrap, } from '@pikku/core/crypto-utils';
2
2
  import { ensurePikkuSchema } from './schema/index.js';
3
3
  import { credentialSchema } from './schema/credential.schema.js';
4
4
  export class KyselyCredentialService {
5
5
  db;
6
6
  initialized = false;
7
+ kekSalts = new Map();
8
+ keks = new Map();
7
9
  key;
8
10
  keyVersion;
9
11
  previousKey;
@@ -39,12 +41,47 @@ export class KyselyCredentialService {
39
41
  })
40
42
  .execute();
41
43
  }
42
- getKEK(version) {
43
- if (version === this.keyVersion)
44
- return this.key;
45
- if (this.previousKey)
46
- return this.previousKey;
47
- throw new Error(`No KEK available for key_version ${version}`);
44
+ async getKEKSalt(version) {
45
+ const cached = this.kekSalts.get(version);
46
+ if (cached)
47
+ return cached;
48
+ const existing = await this.db
49
+ .selectFrom('credentialKekSalts')
50
+ .select('salt')
51
+ .where('keyVersion', '=', version)
52
+ .executeTakeFirst();
53
+ let salt = existing?.salt;
54
+ if (!salt) {
55
+ await this.db
56
+ .insertInto('credentialKekSalts')
57
+ .values({
58
+ keyVersion: version,
59
+ salt: generateKEKSalt(),
60
+ createdAt: new Date().toISOString(),
61
+ })
62
+ .onConflict((oc) => oc.column('keyVersion').doNothing())
63
+ .execute();
64
+ const row = await this.db
65
+ .selectFrom('credentialKekSalts')
66
+ .select('salt')
67
+ .where('keyVersion', '=', version)
68
+ .executeTakeFirstOrThrow();
69
+ salt = row.salt;
70
+ }
71
+ this.kekSalts.set(version, salt);
72
+ return salt;
73
+ }
74
+ async getKEK(version) {
75
+ const cached = this.keks.get(version);
76
+ if (cached)
77
+ return cached;
78
+ const passphrase = version === this.keyVersion ? this.key : this.previousKey;
79
+ if (!passphrase) {
80
+ throw new Error(`No KEK available for key_version ${version}`);
81
+ }
82
+ const kek = await deriveKEK(passphrase, await this.getKEKSalt(version));
83
+ this.keks.set(version, kek);
84
+ return kek;
48
85
  }
49
86
  whereUserId(qb, userId) {
50
87
  return userId
@@ -60,7 +97,7 @@ export class KyselyCredentialService {
60
97
  const row = await qb.executeTakeFirst();
61
98
  if (!row)
62
99
  return null;
63
- const kek = this.getKEK(row.keyVersion);
100
+ const kek = await this.getKEK(row.keyVersion);
64
101
  const plaintext = await envelopeDecrypt(kek, row.ciphertext, row.wrappedDek);
65
102
  await this.logAudit(name, userId, 'read');
66
103
  try {
@@ -72,7 +109,7 @@ export class KyselyCredentialService {
72
109
  }
73
110
  async set(name, value, userId) {
74
111
  const plaintext = JSON.stringify(value);
75
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(this.key, plaintext);
112
+ const { ciphertext, wrappedDEK } = await envelopeEncrypt(await this.getKEK(this.keyVersion), plaintext);
76
113
  const now = new Date().toISOString();
77
114
  const exists = await this.has(name, userId);
78
115
  if (exists) {
@@ -127,7 +164,7 @@ export class KyselyCredentialService {
127
164
  .execute();
128
165
  const result = {};
129
166
  for (const row of rows) {
130
- const kek = this.getKEK(row.keyVersion);
167
+ const kek = await this.getKEK(row.keyVersion);
131
168
  const plaintext = await envelopeDecrypt(kek, row.ciphertext, row.wrappedDek);
132
169
  try {
133
170
  result[row.name] = JSON.parse(plaintext);
@@ -166,8 +203,10 @@ export class KyselyCredentialService {
166
203
  .select(['name', 'userId', 'wrappedDek'])
167
204
  .where('keyVersion', '<', this.keyVersion)
168
205
  .execute();
206
+ const oldKEK = await this.getKEK(this.keyVersion - 1);
207
+ const newKEK = await this.getKEK(this.keyVersion);
169
208
  for (const row of rows) {
170
- const newWrappedDEK = await envelopeRewrap(this.previousKey, this.key, row.wrappedDek);
209
+ const newWrappedDEK = await envelopeRewrap(oldKEK, newKEK, row.wrappedDek);
171
210
  let qb = this.db
172
211
  .updateTable('credentials')
173
212
  .set({
@@ -1,5 +1,6 @@
1
1
  import type { Role, ScopeService } from '@pikku/core/services';
2
2
  import type { FlatScope } from '@pikku/core/scope';
3
+ import type { SystemRole } from '@pikku/core/role';
3
4
  import type { Kysely } from 'kysely';
4
5
  import type { KyselyPikkuDB } from './kysely-tables.js';
5
6
  /**
@@ -33,9 +34,28 @@ export declare class KyselyScopeService implements ScopeService {
33
34
  listScopes(): Promise<Array<FlatScope & {
34
35
  declared: boolean;
35
36
  }>>;
37
+ /**
38
+ * Registers the roles declared with `defineSystemRole`.
39
+ *
40
+ * Additive on the same terms as `syncScopes` — a role whose declaration has
41
+ * gone is marked `declared = false` rather than deleted, so a rollback or a
42
+ * rolling deploy cannot strip everyone's grant. Its *scope set* is replaced
43
+ * outright, because that is the declaration's entire content: editing
44
+ * `defineSystemRole` is how you change what a role means, and the deploy is
45
+ * when it takes effect.
46
+ */
47
+ syncSystemRoles(roles: SystemRole[]): Promise<void>;
36
48
  createRole(role: Role): Promise<void>;
37
49
  deleteRole(name: string): Promise<void>;
38
50
  setRoleScopes(name: string, scopes: string[]): Promise<void>;
51
+ /**
52
+ * Whether the store holds this name as a system role.
53
+ *
54
+ * Asked of the store rather than of the generated `SYSTEM_ROLES`, because the
55
+ * store is where a shadow would actually collide — and because a role whose
56
+ * declaration was deleted is still immutable until someone prunes it.
57
+ */
58
+ private isSystemRole;
39
59
  listRoles(): Promise<Role[]>;
40
60
  addUserToRole(userId: string, role: string, grantedBy?: string): Promise<void>;
41
61
  removeUserFromRole(userId: string, role: string): Promise<void>;
@@ -56,4 +76,22 @@ export declare class KyselyScopeService implements ScopeService {
56
76
  * them. This revokes access, so it is never run implicitly.
57
77
  */
58
78
  pruneScopes(): Promise<string[]>;
79
+ /**
80
+ * System roles the last sync found no declaration for, with how many people
81
+ * still hold each. Powers `pikku roles audit`.
82
+ *
83
+ * The count is the whole point: "this role is gone from the code" and "this
84
+ * role is gone from the code and 40 people are standing on it" call for
85
+ * different decisions, and the number is what makes pruning a choice rather
86
+ * than a formality.
87
+ */
88
+ findStaleSystemRoles(): Promise<Array<{
89
+ role: string;
90
+ users: number;
91
+ }>>;
92
+ /**
93
+ * Removes undeclared system roles, cascading them out of every user grant
94
+ * that holds them. This revokes access, so it is never run implicitly.
95
+ */
96
+ pruneSystemRoles(): Promise<string[]>;
59
97
  }