@gadicc/loom 1.34.0 → 1.35.1

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 (104) hide show
  1. package/README.md +126 -49
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +3060 -451
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +3061 -451
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +125 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
package/README.md CHANGED
@@ -148,10 +148,14 @@ documented in [`docs/project-tooling.md`](docs/project-tooling.md).
148
148
  not authorize existing routes, change jobs, or generate migrations.
149
149
  - `@gadicc/loom/apiKeys` provides typed scope registries, exact-match policy
150
150
  dispatch, credential extraction, fingerprints, authorization/audit contracts,
151
- country normalization, and bounded audit retention.
152
- `@gadicc/loom/next/apiKeys` adds App Router authorization, session-or-key
153
- composition, completion auditing, and explicit Vercel request context.
154
- `@gadicc/loom/mui/apiKeys` provides optional lifecycle and audit UI.
151
+ country normalization, and bounded audit retention. It also provides a
152
+ structurally typed Better Auth verifier that classifies scope misses as
153
+ `insufficient_permission`, shared name/expiry limits and validators, and
154
+ `withBetterAuthApiKeyHttpPathsDisabled` for the plugin's HTTP endpoints, which
155
+ `loom check` expects in `disabledPaths`. `@gadicc/loom/next/apiKeys` adds App
156
+ Router authorization, session-or-key composition, completion auditing, and
157
+ explicit Vercel request context. `@gadicc/loom/mui/apiKeys` provides optional
158
+ lifecycle and audit UI.
155
159
  - `loom api-keys integrate jobs --resource <name> --action <name>` records an
156
160
  explicit additive jobs authorization integration after the app has protected
157
161
  its HTTP jobs route with fresh session/admin policy. Direct local runners are
@@ -231,28 +235,81 @@ documented in [`docs/project-tooling.md`](docs/project-tooling.md).
231
235
  `loom db release promote-vercel <deployment-id>` for bounded project API
232
236
  promotion and terminal readback.
233
237
  - `loom dev local /path/to/loom` enables local unpublished Loom development. It
234
- adds a managed `file:` override in `pnpm-workspace.yaml` for pnpm projects or
235
- a Deno `links` entry in `deno.json(c)`, then runs the local-dev sync flow when
236
- needed.
237
- - `loom dev sync` rebuilds the local Loom package when source files are newer
238
- than the generated npm output, then refreshes the consuming app with the pnpm
239
- update/install flow or `deno install` when the installed linked dependency is
240
- stale. Other Loom commands also run this sync automatically when the managed
241
- local-dev override is active; pass `--no-sync` to skip it. Each sync records
242
- the Loom source commit in the managed `pnpm-workspace.yaml` block and
243
- gitignored `.loom/dev-state.json` when the local package path points at a Loom
244
- git checkout.
238
+ adds a managed `file:` override for pnpm projects or a Deno `links` entry in
239
+ `deno.json(c)`, then runs the local-dev sync flow when needed. The pnpm
240
+ override goes where the project's pnpm version applies it (verified with real
241
+ pnpm 9.7.0 to 11.25.0): pnpm before 10.5.1 reads overrides only from
242
+ `package.json` `resolutions`/`pnpm.overrides`; pnpm 10.5.1 to 10.x reads
243
+ `pnpm-workspace.yaml` `overrides` only while both `package.json` maps are
244
+ empty and otherwise ignores the workspace map entirely; pnpm 11 reads only
245
+ `pnpm-workspace.yaml`. Loom uses a managed block in `pnpm-workspace.yaml` or
246
+ an entry in the applicable `package.json` map (creating `resolutions` for
247
+ older pnpm when needed). Unlinking removes only Loom's own entry with a
248
+ minimal edit, plus a map only if Loom created it (recorded in
249
+ `.loom/dev-state.json`); package.json is never restored from a snapshot.
250
+ - `loom dev sync` rebuilds the local Loom package when its package-relevant
251
+ source content differs from the fingerprint the build recorded (builds without
252
+ that record fall back to comparing timestamps), then runs `pnpm install` (or
253
+ `deno install`) when the consuming app has not applied the override yet or its
254
+ installed copy differs from the built package by file list or content. pnpm 10
255
+ and 11 re-import a local directory dependency on every install, and a plain
256
+ install keeps every other locked version. The sync fails with an explanation
257
+ if pnpm-lock.yaml does not record the override afterwards, and warns when the
258
+ install added duplicate peer variants of one package version. Other Loom
259
+ commands also run this sync automatically when the managed local-dev override
260
+ is active; pass `--no-sync` to skip it. After a sync that refreshed the
261
+ package, `loom env -- <command>` still runs its command (the sync's build and
262
+ install output goes to stderr, so the command's stdout stays clean), while
263
+ other commands exit with status 75 and ask for a rerun instead of running
264
+ stale Loom code. Concurrent syncs in one project, and `loom dev local` or
265
+ `loom dev published`, take turns through a gitignored `.loom/dev-sync.lock`: a
266
+ waiting command re-reads the link and re-checks freshness after the first
267
+ finishes and, if the Loom package it loaded was replaced meanwhile, counts
268
+ that as a refresh (other commands exit 75, `loom env` continues). The holder
269
+ refreshes the lock every 5 seconds and removes it on SIGINT, SIGTERM, or
270
+ SIGHUP. Waiters break a lock nobody refreshed for a minute, whatever its host
271
+ or PID (after about 12 seconds when its process is gone on this host or it was
272
+ already a minute old, but only after five minutes when its process still
273
+ exists on this host, such as a paused command), one waiter at a time under a
274
+ short-lived `.loom/dev-sync.lock.break` lock so no waiter can remove the fresh
275
+ lock another has just taken. A holder checks that it still owns the lock
276
+ before each build, install, or state write and stops with an explanation if it
277
+ lost it. A wait longer than 10 minutes fails with the holder's PID and the
278
+ lock path. Each Loom build records its provenance (the git commit it was built
279
+ from, whether that checkout was clean and no package-relevant file was written
280
+ while the build ran (even if reverted), and a digest of the packed output) in
281
+ `npm/.loom-build.json`, which stays out of the packed package. Each sync also
282
+ records the Loom source commit in gitignored `.loom/dev-state.json` (and in
283
+ the managed `pnpm-workspace.yaml` block when that holds the override) for
284
+ `loom status` and `loom check`.
245
285
  - `loom dev published` removes that managed local-dev override so the app can
246
- return to the published package version. When a prior sync recorded a Loom
247
- source commit, this command verifies that the commit is reachable from
286
+ return to the published package version, once it has proved, from build
287
+ provenance, that what is installed is published. It collects every local Loom
288
+ target (the managed pnpm override, any hand-written `file:`/`link:` Loom entry
289
+ in the `pnpm-workspace.yaml` `overrides:` map and any local `pnpm-lock.yaml`
290
+ resolution, or every Deno link to Loom) and refuses when they name more than
291
+ one package. The target's build must record a clean commit and still match its
292
+ recorded output digest, the installed copy must match that build (pnpm
293
+ `node_modules`, or a Deno `node_modules` copy unless `nodeModulesDir` is
294
+ `"none"`), and for pnpm the lockfile must resolve Loom to it; otherwise it
295
+ says to run `loom dev sync`, or to commit the Loom changes and run
296
+ `loom dev sync --force`. The build's commit must then be reachable from
248
297
  `origin/main` and either included in a semver release tag or
249
298
  package-equivalent to the latest semver release because only non-package files
250
- changed after that tag. It then switches the app to the exact published
251
- `@gadicc/loom` version that covers the sync. If no recorded commit exists, the
252
- command preserves the older compatibility behavior and switches back to the
253
- existing published dependency with an explicit warning. The command also
254
- notices stale lockfiles that still resolve Loom to a local package even after
255
- the workspace override has been removed.
299
+ changed after that tag. The command switches the app to the exact published
300
+ `@gadicc/loom` version that covers it and removes every Loom override or link
301
+ it found. Dev state and the checkout's current git state play no part. A pnpm
302
+ link that was never installed needs no proof: when pnpm-lock.yaml and pnpm's
303
+ record of node_modules (`node_modules/.pnpm/lock.yaml`) still hold the
304
+ published Loom and `node_modules/@gadicc/loom` links pnpm's store entry for
305
+ that version, the command removes the overrides and keeps the pin. Anything
306
+ less certain gets the full proof: an interrupted install, or a layout without
307
+ a `node_modules/.pnpm` store entry to check (`node-linker=hoisted`,
308
+ `enableGlobalVirtualStore`, a custom `virtual-store-dir`). Deno links are
309
+ always proved, since Deno reads a linked directory or copies it into
310
+ node_modules on its next install or run. It also notices stale lockfiles that
311
+ still resolve Loom to a local package even after the workspace override has
312
+ been removed.
256
313
  - `loom check` verifies the recorded package/Deno configs, `loom.json`, the
257
314
  managed `AGENTS.md` block and `.agents/skills/*` links, and then runs
258
315
  feature-specific checks for active entries in `loom.json`, including
@@ -274,14 +331,22 @@ documented in [`docs/project-tooling.md`](docs/project-tooling.md).
274
331
  imports or DB/jobs tasks that bypass `loom env --`, warns when authoritative
275
332
  and secondary configs expose conflicting tasks, and warns when a Deno link or
276
333
  `pnpm-lock.yaml` still resolves Loom to local source. If
277
- `.loom/dev-state.json` records a synced Loom commit, `loom check` also
278
- explains whether that commit is unpublished or published in a newer exact Loom
279
- version than the app is pinned to. Pass `--strict-skills` to turn missing
280
- skill recommendations into check failures. Pass `--production` to make local
281
- Loom dev overrides, local lockfile resolutions, unresolved synced Loom
282
- commits, and DB migration release-flow gaps release-blocking failures. Pass
283
- `--network` to also run registered feature network checks after the local
284
- project checks.
334
+ `.loom/dev-state.json` records a synced Loom commit while local Loom may still
335
+ be in use (a local override, link or catalog entry, a local lockfile
336
+ resolution, or an installed copy that is not provably the published package),
337
+ `loom check` also explains whether that commit is unpublished or published in
338
+ a newer exact Loom version than the app is pinned to; with `--production` that
339
+ fails only while a link, override or local lockfile points at local Loom, not
340
+ for an unproven installed copy alone. (A Deno node_modules copy is proven
341
+ published when `deno.lock` records no Loom link and resolves the pinned
342
+ version from the registry.) Otherwise the record is stale: `loom check` notes
343
+ that it can be deleted and only advises a newer pin, and a recorded checkout
344
+ that no longer exists never fails the check on its own. Pass `--strict-skills`
345
+ to turn missing skill recommendations into check failures. Pass `--production`
346
+ to make local Loom dev overrides, local lockfile resolutions, unresolved
347
+ synced Loom commits, and DB migration release-flow gaps release-blocking
348
+ failures. Pass `--network` to also run registered feature network checks after
349
+ the local project checks.
285
350
 
286
351
  The current CLI scope is project bootstrap, validation, and feature-specific
287
352
  scaffolding. Extracted feature hooks are added behind the same `init`, `add`,
@@ -303,13 +368,21 @@ package and run the production gate:
303
368
 
304
369
  ```sh
305
370
  loom dev published
306
- pnpm update --no-save @gadicc/loom@<version-from-loom-output>
307
371
  pnpm install
308
372
  loom check --production
309
373
  ```
310
374
 
311
- For Deno-managed projects, replace the pnpm refresh commands with
312
- `deno install`; `loom dev published` prints the project-appropriate command.
375
+ For Deno-managed projects, replace the pnpm refresh command with `deno install`;
376
+ `loom dev published` prints the project-appropriate command. A lockfile linked
377
+ by earlier Loom versions through `pnpm update --no-save` keeps its local
378
+ resolution through a plain `pnpm install`; `loom dev published` detects that
379
+ case and explains how to restore it. Release-check suggestions move Loom between
380
+ published versions with a package.json edit plus `pnpm install` (or
381
+ `pnpm add --save-exact` for such a legacy lockfile), never `pnpm update`, which
382
+ would re-resolve Loom's dependencies. Apps that pin Loom through a pnpm catalog
383
+ (`"@gadicc/loom": "catalog:"`) keep that reference: Loom reads and pins the
384
+ version in the `pnpm-workspace.yaml` catalog entry and suggests editing it plus
385
+ `pnpm install`, since `pnpm add` would replace the reference.
313
386
 
314
387
  Publishing Loom is only required when the app was synced against
315
388
  package-relevant Loom changes that are not already covered by a published semver
@@ -414,24 +487,28 @@ includes `loom skills disable <name>` as the opt-out path.
414
487
  For local Loom package development, prefer `loom dev local` and the managed
415
488
  `file:` marker flow over `pnpm link`. `loom dev sync` owns the rebuild and pnpm
416
489
  refresh step for that local package. When it refreshes the installed package at
417
- the start of another Loom command, rerun that original command so the current
418
- process uses the refreshed CLI code. This keeps the committed dependency on the
419
- published version while still resolving peer dependencies correctly during local
420
- development. Treat this as a workaround for current pnpm behavior rather than a
421
- permanent preference; if pnpm's local-link behavior changes, this flow can be
422
- simplified or removed later.
490
+ the start of another Loom command, that command exits with status 75; rerun it
491
+ so the current process uses the refreshed CLI code. `loom env` is the exception:
492
+ it only loads env files before starting its wrapped command in a new process, so
493
+ it continues. This keeps the committed dependency on the published version while
494
+ still resolving peer dependencies correctly during local development. Treat this
495
+ as a workaround for current pnpm behavior rather than a permanent preference; if
496
+ pnpm's local-link behavior changes, this flow can be simplified or removed
497
+ later.
423
498
 
424
499
  The managed local-dev block also records the Loom source commit that was synced
425
500
  when the local package path points at a Loom git checkout, and the same state is
426
- persisted in gitignored `.loom/dev-state.json` so Loom can still diagnose stale
427
- local lockfiles after the workspace override has been removed.
428
- `loom dev published` uses that record as a release gate: clean commits that have
429
- reached `origin/main` and are either included in a semver release tag or have no
430
- package-relevant changes after the latest semver tag can be switched to the
431
- exact published version, while dirty or unreleased package changes block the
432
- switch. Existing apps with older local-dev blocks that lack this metadata can
433
- still switch back to their current published dependency, but new syncs should be
434
- used before relying on the release gate.
501
+ persisted in gitignored `.loom/dev-state.json` so `loom check` can still
502
+ diagnose stale local lockfiles after the workspace override has been removed.
503
+ That record is informational, and `loom dev published` deletes it once nothing
504
+ local is in use any more (for pnpm, typically when rerun after the
505
+ `pnpm install` it asks for). `loom dev published` gates on the provenance the
506
+ installed build itself records in `npm/.loom-build.json`: a build from a clean
507
+ commit that has reached `origin/main` and is either included in a semver release
508
+ tag or has no package-relevant changes after the latest semver tag can be
509
+ switched to the exact published version, while dirty, unreleased or unrecorded
510
+ builds block the switch. Builds from before Loom recorded provenance are rebuilt
511
+ by the next `loom dev sync`.
435
512
 
436
513
  Loom's external catalog currently recommends these defaults:
437
514
 
@@ -1 +1 @@
1
- {"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/authorize.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,yBAAyB,EAGzB,sBAAsB,EACvB,MAAM,YAAY,CAAC;AA2DpB,iFAAiF;AACjF,wBAAsB,eAAe,CACnC,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,yBAAyB,CAAC,CAgJpC"}
1
+ {"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/authorize.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,yBAAyB,EAIzB,sBAAsB,EACvB,MAAM,YAAY,CAAC;AAwFpB,iFAAiF;AACjF,wBAAsB,eAAe,CACnC,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,yBAAyB,CAAC,CA+LpC"}
@@ -38,6 +38,30 @@ async function recordDenied(options, event) {
38
38
  return undefined;
39
39
  }
40
40
  }
41
+ /**
42
+ * Audit attribution for a verifier denial: only an `insufficient_permission`
43
+ * denial with a well-formed principal names the key and its owner.
44
+ */
45
+ function deniedKeyAuditFields(verification) {
46
+ const principal = verification.principal;
47
+ if (verification.code !== "insufficient_permission" || !principal ||
48
+ typeof principal.keyId !== "string" || !principal.keyId ||
49
+ typeof principal.ownerId !== "string" || !principal.ownerId) {
50
+ return {};
51
+ }
52
+ // A custom verifier's snapshots are untrusted input to the audit insert;
53
+ // drop anything that is not a string rather than fail the denial's record.
54
+ return {
55
+ keyId: principal.keyId,
56
+ keyNameSnapshot: typeof principal.keyName === "string"
57
+ ? principal.keyName
58
+ : undefined,
59
+ keyStartSnapshot: typeof principal.keyStart === "string"
60
+ ? principal.keyStart
61
+ : undefined,
62
+ ownerId: principal.ownerId,
63
+ };
64
+ }
41
65
  function principalAuditFields(principal) {
42
66
  return {
43
67
  keyId: principal.keyId,
@@ -72,6 +96,52 @@ export async function authorizeApiKey(options) {
72
96
  status,
73
97
  };
74
98
  }
99
+ if (options.rejectCredential) {
100
+ let rejected;
101
+ try {
102
+ rejected = await options.rejectCredential(extracted.credential, {
103
+ descriptor: options.descriptor,
104
+ transport: extracted.transport,
105
+ }) !== false;
106
+ }
107
+ catch {
108
+ // Fail closed without fingerprinting a credential the app may have
109
+ // been about to reject.
110
+ const recorded = await recordDenied(options, {
111
+ ...auditBase,
112
+ authorizationOutcome: "error",
113
+ eventType: "authorization",
114
+ httpStatus: 500,
115
+ // Distinct from a verifier outage for operators; the response is not.
116
+ reasonCode: "credential_rejection_error",
117
+ transport: extracted.transport,
118
+ });
119
+ return {
120
+ authorizationEventId: recorded?.id,
121
+ code: "verification_error",
122
+ ok: false,
123
+ status: 500,
124
+ };
125
+ }
126
+ if (rejected) {
127
+ // Same result as an invalid key, so callers cannot tell a rejected
128
+ // value from a wrong one; only the audit reason differs.
129
+ const recorded = await recordDenied(options, {
130
+ ...auditBase,
131
+ authorizationOutcome: "denied",
132
+ eventType: "authorization",
133
+ httpStatus: 401,
134
+ reasonCode: "credential_rejected",
135
+ transport: extracted.transport,
136
+ });
137
+ return {
138
+ authorizationEventId: recorded?.id,
139
+ code: "invalid_credential",
140
+ ok: false,
141
+ status: 401,
142
+ };
143
+ }
144
+ }
75
145
  const credentialFingerprint = await fingerprintApiKeyCredential(extracted.credential);
76
146
  let verification;
77
147
  try {
@@ -106,6 +176,7 @@ export async function authorizeApiKey(options) {
106
176
  : 401);
107
177
  const recorded = await recordDenied(options, {
108
178
  ...auditBase,
179
+ ...deniedKeyAuditFields(verification),
109
180
  authorizationOutcome: "denied",
110
181
  credentialFingerprint,
111
182
  eventType: "authorization",
@@ -0,0 +1,123 @@
1
+ import type { ApiKeyScopeDefinitions, DefinedApiKeyScopes } from "./policy.js";
2
+ import type { ApiKeyVerifier } from "./types.js";
3
+ /**
4
+ * The part of a Better Auth instance with the api-key plugin that the shared
5
+ * verifier calls. Loom never imports Better Auth; pass the app's `auth`
6
+ * instance. Method syntax keeps the parameter check bivariant, so Better
7
+ * Auth's richer endpoint signature remains assignable.
8
+ */
9
+ export interface BetterAuthApiKeyVerifyApi {
10
+ api: {
11
+ verifyApiKey(input: {
12
+ body: {
13
+ configId?: string;
14
+ key: string;
15
+ };
16
+ }): Promise<unknown>;
17
+ };
18
+ }
19
+ /**
20
+ * A key record returned by a successful Better Auth `verifyApiKey` call, after
21
+ * Loom's shape checks. Fields beyond `id` are unvalidated plugin data.
22
+ */
23
+ export interface BetterAuthVerifiedApiKey {
24
+ readonly [field: string]: unknown;
25
+ /** Non-empty key ID. */
26
+ readonly id: string;
27
+ /** `false` for a revoked key; re-checked as defense in depth. */
28
+ readonly enabled?: unknown;
29
+ /** Expiry; a past or unparseable value is re-checked as expired. */
30
+ readonly expiresAt?: unknown;
31
+ /** Display name, when the plugin returned a string. */
32
+ readonly name?: unknown;
33
+ /** Permissions as decoded once by Better Auth. Never decoded again. */
34
+ readonly permissions?: unknown;
35
+ /** Owner reference in current Better Auth api-key schemas. */
36
+ readonly referenceId?: unknown;
37
+ /** Non-secret key prefix, when the plugin returned a string. */
38
+ readonly start?: unknown;
39
+ }
40
+ /** Options for `createBetterAuthApiKeyVerifier`. */
41
+ export interface CreateBetterAuthApiKeyVerifierOptions<TDefinitions extends ApiKeyScopeDefinitions = ApiKeyScopeDefinitions> {
42
+ /** The app's Better Auth instance, configured with the api-key plugin. */
43
+ auth: BetterAuthApiKeyVerifyApi;
44
+ /**
45
+ * The plugin configuration to verify against, always sent to Better Auth.
46
+ * Use `"default"` for a plugin configured without a `configId`.
47
+ */
48
+ configId: string;
49
+ /**
50
+ * Resolves the key owner. Defaults to `key.referenceId`. A missing or
51
+ * non-string owner fails closed as a verification error.
52
+ */
53
+ ownerId?: (key: BetterAuthVerifiedApiKey) => string | undefined;
54
+ /**
55
+ * The app's scope registry. When given, `principal.permissions` lists only
56
+ * registry permissions the key grants exactly; otherwise every exact grant
57
+ * stored on the key is listed.
58
+ */
59
+ scopes?: DefinedApiKeyScopes<TDefinitions>;
60
+ }
61
+ /**
62
+ * Creates a Loom `ApiKeyVerifier` that makes exactly one Better Auth
63
+ * `verifyApiKey` call per authorization and decides the requested permission
64
+ * locally.
65
+ *
66
+ * The plugin reports a valid key that lacks a requested permission as
67
+ * `KEY_NOT_FOUND`, indistinguishable from a forged or revoked key, so this
68
+ * verifier never sends `permissions`. Instead it checks the decoded grants
69
+ * with `hasApiKeyPermission` and reports a miss as `insufficient_permission`
70
+ * (403). Better Auth still owns hashing, config scoping, enablement, expiry,
71
+ * and usage accounting.
72
+ *
73
+ * Classification:
74
+ * - `valid: false` with code `RATE_LIMITED` (per-key rate limit) or
75
+ * `USAGE_EXCEEDED` (`remaining` quota spent; the plugin reports it as 429
76
+ * and deletes an exhausted key that has no refill) → `rate_limited` (429);
77
+ * - any other `valid: false`, `valid: true` without a key, or a returned key
78
+ * that is disabled or expired → `invalid_credential` (401);
79
+ * - a valid key without the exact permission → `insufficient_permission`
80
+ * (403), carrying the key's `principal` so Loom attributes the audit row
81
+ * to its owner;
82
+ * - a malformed result, key ID, or owner throws, which Loom records as
83
+ * `verification_error` (500). Exceptions from Better Auth propagate too.
84
+ *
85
+ * Caveats:
86
+ * - A scope miss now passes through the plugin's usage claim. It updates
87
+ * `lastRequest`/`requestCount`/`updatedAt` and, with per-key rate limits or
88
+ * `remaining` quotas enabled, would spend them and could delete an exhausted
89
+ * key. Keep those disabled or account for it.
90
+ * - The plugin catches internal failures such as a database outage and
91
+ * returns them as `INVALID_API_KEY`, so they deny as `invalid_credential`
92
+ * (fail closed) rather than `verification_error`. Monitor Better Auth's
93
+ * "Failed to validate API key" log to tell an outage from bad keys.
94
+ */
95
+ export declare function createBetterAuthApiKeyVerifier<const TDefinitions extends ApiKeyScopeDefinitions = ApiKeyScopeDefinitions>(options: CreateBetterAuthApiKeyVerifierOptions<TDefinitions>): ApiKeyVerifier;
96
+ /**
97
+ * Better Auth api-key plugin endpoints served over HTTP, relative to the auth
98
+ * base path.
99
+ *
100
+ * Each is session-authenticated, so any signed-in user can call it for their
101
+ * own keys: `update` can re-enable an administratively revoked key or remove
102
+ * its expiry, `delete` hard-deletes the key row instead of soft-revoking it,
103
+ * and `create` skips the app's own validation. `verifyApiKey` and expired-key
104
+ * cleanup are server-only and are not listed.
105
+ */
106
+ export declare const BETTER_AUTH_API_KEY_HTTP_PATHS: readonly ["/api-key/create", "/api-key/update", "/api-key/delete", "/api-key/get", "/api-key/list"];
107
+ /**
108
+ * Returns Better Auth `disabledPaths` that also block every api-key plugin
109
+ * HTTP endpoint, preserving `existing` entries first and removing duplicates.
110
+ *
111
+ * Use it in the app-owned `betterAuth()` options so key lifecycle only goes
112
+ * through server actions that call `auth.api.*`; server-side calls never pass
113
+ * through the HTTP router, so they keep working:
114
+ *
115
+ * ```ts
116
+ * export const auth = betterAuth({
117
+ * disabledPaths: withBetterAuthApiKeyHttpPathsDisabled(),
118
+ * plugins: [apiKey({ ... })],
119
+ * });
120
+ * ```
121
+ */
122
+ export declare function withBetterAuthApiKeyHttpPathsDisabled(existing?: readonly string[]): string[];
123
+ //# sourceMappingURL=betterAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAwB,MAAM,YAAY,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,WAAW,yBAAyB;IACxC,GAAG,EAAE;QACH,YAAY,CACV,KAAK,EAAE;YAAE,IAAI,EAAE;gBAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;gBAAC,GAAG,EAAE,MAAM,CAAA;aAAE,CAAA;SAAE,GAClD,OAAO,CAAC,OAAO,CAAC,CAAC;KACrB,CAAC;CACH;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IAClC,wBAAwB;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,iEAAiE;IACjE,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,uDAAuD;IACvD,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,uEAAuE;IACvE,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,8DAA8D;IAC9D,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,gEAAgE;IAChE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,oDAAoD;AACpD,MAAM,WAAW,qCAAqC,CACpD,YAAY,SAAS,sBAAsB,GAAG,sBAAsB;IAEpE,0EAA0E;IAC1E,IAAI,EAAE,yBAAyB,CAAC;IAChC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,wBAAwB,KAAK,MAAM,GAAG,SAAS,CAAC;IAChE;;;;OAIG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;CAC5C;AA0BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,8BAA8B,CAC5C,KAAK,CAAC,YAAY,SAAS,sBAAsB,GAAG,sBAAsB,EAE1E,OAAO,EAAE,qCAAqC,CAAC,YAAY,CAAC,GAC3D,cAAc,CA4EhB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,8BAA8B,qGAQ1C,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qCAAqC,CACnD,QAAQ,GAAE,SAAS,MAAM,EAAO,GAC/B,MAAM,EAAE,CAQV"}
@@ -0,0 +1,164 @@
1
+ import { apiKeyGrantedPermissions, apiKeyPrincipalPermissions, hasApiKeyPermission, } from "./permissions.js";
2
+ function isObject(value) {
3
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ function malformed(detail) {
6
+ return new Error(`Better Auth verifyApiKey returned ${detail}.`);
7
+ }
8
+ function optionalString(value) {
9
+ return typeof value === "string" ? value : undefined;
10
+ }
11
+ /** True for a parseable expiry at or before now; unparseable values expire. */
12
+ function isExpired(expiresAt) {
13
+ if (expiresAt === null || expiresAt === undefined)
14
+ return false;
15
+ // The tag check also accepts a Date from another realm.
16
+ const time = Object.prototype.toString.call(expiresAt) === "[object Date]"
17
+ ? expiresAt.valueOf()
18
+ : typeof expiresAt === "string" || typeof expiresAt === "number"
19
+ ? new Date(expiresAt).valueOf()
20
+ : Number.NaN;
21
+ return !Number.isFinite(time) || time <= Date.now();
22
+ }
23
+ /**
24
+ * Creates a Loom `ApiKeyVerifier` that makes exactly one Better Auth
25
+ * `verifyApiKey` call per authorization and decides the requested permission
26
+ * locally.
27
+ *
28
+ * The plugin reports a valid key that lacks a requested permission as
29
+ * `KEY_NOT_FOUND`, indistinguishable from a forged or revoked key, so this
30
+ * verifier never sends `permissions`. Instead it checks the decoded grants
31
+ * with `hasApiKeyPermission` and reports a miss as `insufficient_permission`
32
+ * (403). Better Auth still owns hashing, config scoping, enablement, expiry,
33
+ * and usage accounting.
34
+ *
35
+ * Classification:
36
+ * - `valid: false` with code `RATE_LIMITED` (per-key rate limit) or
37
+ * `USAGE_EXCEEDED` (`remaining` quota spent; the plugin reports it as 429
38
+ * and deletes an exhausted key that has no refill) → `rate_limited` (429);
39
+ * - any other `valid: false`, `valid: true` without a key, or a returned key
40
+ * that is disabled or expired → `invalid_credential` (401);
41
+ * - a valid key without the exact permission → `insufficient_permission`
42
+ * (403), carrying the key's `principal` so Loom attributes the audit row
43
+ * to its owner;
44
+ * - a malformed result, key ID, or owner throws, which Loom records as
45
+ * `verification_error` (500). Exceptions from Better Auth propagate too.
46
+ *
47
+ * Caveats:
48
+ * - A scope miss now passes through the plugin's usage claim. It updates
49
+ * `lastRequest`/`requestCount`/`updatedAt` and, with per-key rate limits or
50
+ * `remaining` quotas enabled, would spend them and could delete an exhausted
51
+ * key. Keep those disabled or account for it.
52
+ * - The plugin catches internal failures such as a database outage and
53
+ * returns them as `INVALID_API_KEY`, so they deny as `invalid_credential`
54
+ * (fail closed) rather than `verification_error`. Monitor Better Auth's
55
+ * "Failed to validate API key" log to tell an outage from bad keys.
56
+ */
57
+ export function createBetterAuthApiKeyVerifier(options) {
58
+ const { auth, configId, ownerId, scopes } = options;
59
+ if (typeof auth?.api?.verifyApiKey !== "function") {
60
+ throw new Error("createBetterAuthApiKeyVerifier requires a Better Auth instance with the api-key plugin.");
61
+ }
62
+ if (typeof configId !== "string" || configId.length === 0) {
63
+ throw new Error("createBetterAuthApiKeyVerifier requires a configId.");
64
+ }
65
+ if (ownerId !== undefined && typeof ownerId !== "function") {
66
+ throw new Error("createBetterAuthApiKeyVerifier ownerId must be a function.");
67
+ }
68
+ return {
69
+ async verify(request) {
70
+ // `permissions` is deliberately absent; see the JSDoc above.
71
+ const result = await auth.api.verifyApiKey({
72
+ body: { configId, key: request.credential },
73
+ });
74
+ if (!isObject(result))
75
+ throw malformed("a non-object result");
76
+ if (typeof result.valid !== "boolean") {
77
+ throw malformed("a result without a boolean `valid`");
78
+ }
79
+ if (result.valid !== true) {
80
+ const error = result.error;
81
+ if (isObject(error) &&
82
+ (error.code === "RATE_LIMITED" || error.code === "USAGE_EXCEEDED")) {
83
+ return { code: "rate_limited", ok: false };
84
+ }
85
+ return { code: "invalid_credential", ok: false };
86
+ }
87
+ if (result.error !== null && result.error !== undefined) {
88
+ throw malformed("a valid result that also carries an error");
89
+ }
90
+ const key = result.key;
91
+ if (key === null || key === undefined) {
92
+ return { code: "invalid_credential", ok: false };
93
+ }
94
+ if (!isObject(key))
95
+ throw malformed("a non-object key");
96
+ if (typeof key.id !== "string" || key.id.length === 0) {
97
+ throw malformed("a key without an ID");
98
+ }
99
+ const verifiedKey = key;
100
+ const owner = ownerId ? ownerId(verifiedKey) : verifiedKey.referenceId;
101
+ if (typeof owner !== "string" || owner.length === 0) {
102
+ throw malformed("a key without a resolvable owner");
103
+ }
104
+ // Better Auth already rejects these; re-checking keeps a plugin
105
+ // regression from granting a disabled or expired key.
106
+ if (verifiedKey.enabled === false || isExpired(verifiedKey.expiresAt)) {
107
+ return { code: "invalid_credential", ok: false };
108
+ }
109
+ const principal = {
110
+ keyId: verifiedKey.id,
111
+ keyName: optionalString(verifiedKey.name),
112
+ keyStart: optionalString(verifiedKey.start),
113
+ ownerId: owner,
114
+ permissions: scopes
115
+ ? apiKeyPrincipalPermissions(scopes, verifiedKey.permissions)
116
+ : apiKeyGrantedPermissions(verifiedKey.permissions),
117
+ };
118
+ if (!hasApiKeyPermission(verifiedKey.permissions, request.permission)) {
119
+ // The key is genuine, so the denial is attributed to its owner.
120
+ return { code: "insufficient_permission", ok: false, principal };
121
+ }
122
+ return { ok: true, principal };
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Better Auth api-key plugin endpoints served over HTTP, relative to the auth
128
+ * base path.
129
+ *
130
+ * Each is session-authenticated, so any signed-in user can call it for their
131
+ * own keys: `update` can re-enable an administratively revoked key or remove
132
+ * its expiry, `delete` hard-deletes the key row instead of soft-revoking it,
133
+ * and `create` skips the app's own validation. `verifyApiKey` and expired-key
134
+ * cleanup are server-only and are not listed.
135
+ */
136
+ export const BETTER_AUTH_API_KEY_HTTP_PATHS = Object.freeze([
137
+ "/api-key/create",
138
+ "/api-key/update",
139
+ "/api-key/delete",
140
+ "/api-key/get",
141
+ "/api-key/list",
142
+ ]);
143
+ /**
144
+ * Returns Better Auth `disabledPaths` that also block every api-key plugin
145
+ * HTTP endpoint, preserving `existing` entries first and removing duplicates.
146
+ *
147
+ * Use it in the app-owned `betterAuth()` options so key lifecycle only goes
148
+ * through server actions that call `auth.api.*`; server-side calls never pass
149
+ * through the HTTP router, so they keep working:
150
+ *
151
+ * ```ts
152
+ * export const auth = betterAuth({
153
+ * disabledPaths: withBetterAuthApiKeyHttpPathsDisabled(),
154
+ * plugins: [apiKey({ ... })],
155
+ * });
156
+ * ```
157
+ */
158
+ export function withBetterAuthApiKeyHttpPathsDisabled(existing = []) {
159
+ if (!Array.isArray(existing) ||
160
+ existing.some((path) => typeof path !== "string")) {
161
+ throw new Error("Better Auth disabledPaths must be an array of strings.");
162
+ }
163
+ return [...new Set([...existing, ...BETTER_AUTH_API_KEY_HTTP_PATHS])];
164
+ }