@cortexkit/common-auth 0.11.5 → 0.11.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/README.md CHANGED
@@ -11,10 +11,10 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
11
11
 
12
12
  A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
13
13
 
14
- The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/46cc166b0df2edcfd14b3eb54ed6eeac588fed69/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
14
+ The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/73c7e66145e131eadffdd874c82d93548868b668/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
15
15
 
16
16
  ```sh
17
- cargo install --locked --git https://github.com/cortexkit/commons --rev 46cc166b0df2edcfd14b3eb54ed6eeac588fed69 cortexkit-mutate
17
+ cargo install --locked --git https://github.com/cortexkit/commons --rev 73c7e66145e131eadffdd874c82d93548868b668 cortexkit-mutate
18
18
  ckdev-mutate check
19
19
  ckdev-mutate run --all
20
20
  ckdev-mutate run --diff origin/main
@@ -1,6 +1,6 @@
1
1
  export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, } from './builtins.js';
2
2
  export { MENU_DISABLED_REASON } from './builtins.js';
3
- export type { CommandMenu, CommandMenuOptions } from './menu.js';
3
+ export type { CommandMenu, CommandMenuOptions, StoreSectionSlot, } from './menu.js';
4
4
  export { createCommandMenu, parseApplyRequest } from './menu.js';
5
5
  export type { ActionDefinition, ActionInput, ActionOutcome, CommandApplyRequest, CommandApplyResult, CommandDialogPayload, CommandInvocation, CommandMenuModel, ItemDefinition, KnobValue, KnobValues, MenuAccount, MenuAction, MenuChoice, MenuConfirmation, MenuItem, MenuKnob, MenuSection, NotifyKind, PluginExtraSection, PluginSection, SectionContent, SectionSlot, } from './model.js';
6
6
  export { SECTION_SLOTS } from './model.js';
@@ -3,12 +3,26 @@ import type { PoolLockSpec, PoolStore } from '../store/index.js';
3
3
  import { type AccountsSectionOptions, type LimitsSectionOptions, type QuotaSectionOptions, type RoutingSectionOptions } from './builtins.js';
4
4
  import type { CommandApplyRequest, CommandApplyResult, CommandDialogPayload, CommandInvocation, PluginExtraSection, PluginSection } from './model.js';
5
5
  import { type SeamLogger } from './seam.js';
6
+ /** The four slots the library can build from a pool store. */
7
+ export type StoreSectionSlot = 'accounts' | 'quota' | 'routing' | 'limits';
6
8
  export interface CommandMenuOptions {
7
9
  /** The slash command's name without the slash (`openai`, `claude`). */
8
10
  command: string;
9
11
  /** The dialog title. */
10
12
  title: string;
11
- store: PoolStore;
13
+ /**
14
+ * The pool store the built-in Accounts, Quota, Routing and Limits sections
15
+ * read and write. Required unless `replace` supplies all four.
16
+ */
17
+ store?: PoolStore;
18
+ /**
19
+ * Plugin sections that take the place of built-in ones, keeping their slot
20
+ * and the fixed order. For a plugin whose accounts are not pool rows (a
21
+ * single host login, or rows it must not expose by id), so it renders its
22
+ * own items and actions without a store. A replaced slot's built-in
23
+ * options (`accounts`, `quota`, ...) must not be given.
24
+ */
25
+ replace?: Partial<Record<StoreSectionSlot, PluginSection>>;
12
26
  /** The plugin's legacy locks, passed to every store write the menu makes. */
13
27
  extraLocks?: readonly PoolLockSpec[];
14
28
  accounts?: AccountsSectionOptions;
@@ -13,6 +13,12 @@ const BUILTIN_IDS = new Set([
13
13
  'cache',
14
14
  'diagnostics',
15
15
  ]);
16
+ const STORE_SLOTS = [
17
+ 'accounts',
18
+ 'quota',
19
+ 'routing',
20
+ 'limits',
21
+ ];
16
22
  /**
17
23
  * A private copy of the caller's context, taken before the first await. Work
18
24
  * an invocation leaves running reports through this copy, so a host that
@@ -102,6 +108,15 @@ export function createCommandMenu(options) {
102
108
  const seam = { logger, redact };
103
109
  const now = options.now ?? Date.now;
104
110
  const extras = options.extras ?? [];
111
+ const replaced = options.replace ?? {};
112
+ const builtSlots = STORE_SLOTS.filter((slot) => !replaced[slot]);
113
+ for (const slot of STORE_SLOTS) {
114
+ if (replaced[slot] && options[slot] !== undefined)
115
+ throw new Error(`the ${slot} section is replaced; its built-in options cannot also be given`);
116
+ }
117
+ const store = options.store;
118
+ if (builtSlots.length > 0 && !store)
119
+ throw new Error(`a store is required for the built-in ${builtSlots.join(', ')} section${builtSlots.length > 1 ? 's' : ''}`);
105
120
  const seen = new Set();
106
121
  for (const extra of extras) {
107
122
  if (BUILTIN_IDS.has(extra.id) || seen.has(extra.id))
@@ -134,15 +149,30 @@ export function createCommandMenu(options) {
134
149
  }
135
150
  /** Every section, in the fixed slot order. */
136
151
  async function sections(invocation) {
137
- const out = await builtinSections({
138
- store: options.store,
139
- now,
140
- ...(options.extraLocks ? { extraLocks: options.extraLocks } : {}),
141
- ...(options.accounts ? { accounts: options.accounts } : {}),
142
- ...(options.quota ? { quota: options.quota } : {}),
143
- ...(options.routing ? { routing: options.routing } : {}),
144
- ...(options.limits ? { limits: options.limits } : {}),
145
- });
152
+ // Built-in sections read the store once; a fully replaced menu never
153
+ // touches it.
154
+ const built = store && builtSlots.length > 0
155
+ ? await builtinSections({
156
+ store,
157
+ now,
158
+ ...(options.extraLocks ? { extraLocks: options.extraLocks } : {}),
159
+ ...(options.accounts ? { accounts: options.accounts } : {}),
160
+ ...(options.quota ? { quota: options.quota } : {}),
161
+ ...(options.routing ? { routing: options.routing } : {}),
162
+ ...(options.limits ? { limits: options.limits } : {}),
163
+ })
164
+ : [];
165
+ const out = [];
166
+ for (const slot of STORE_SLOTS) {
167
+ const replacement = replaced[slot];
168
+ if (replacement)
169
+ out.push(await plugin(slot, slot, replacement, invocation));
170
+ else {
171
+ const section = built.find((entry) => entry.slot === slot);
172
+ if (section)
173
+ out.push(section);
174
+ }
175
+ }
146
176
  if (options.cache)
147
177
  out.push(await plugin('cache', 'cache', options.cache, invocation));
148
178
  if (options.diagnostics)
@@ -55,6 +55,28 @@ export interface RemoveView {
55
55
  state: Readonly<Record<string, unknown>>;
56
56
  }
57
57
  export interface RemoveOptions extends RowToggleOptions {
58
+ /**
59
+ * The credential the removal was decided for (since 0.11.7). Checked under
60
+ * every lock, before `protect` and before anything is written or repaired:
61
+ * - a roster row must be bound to its credential stamp, not torn, and hold
62
+ * exactly this epoch and recorded identity (absence included);
63
+ * - an orphan (only a state-file entry left, by a removal or add
64
+ * interrupted between its writes) must carry a stamp this store can bind
65
+ * to the credential beside it, and that stamp must name exactly this
66
+ * epoch and identity.
67
+ * Epochs only grow per id (a removal records the dropped epoch, and a later
68
+ * add of the id starts past it), so an orphan an interrupted later add
69
+ * left under the same id never matches the epoch of the row the caller
70
+ * meant to remove. A mismatch refuses with kind `attribution`, an orphan
71
+ * or row with no bindable stamp with kind `unbound-credential`; both leave
72
+ * the files byte for byte unchanged. Without it, `remove` drops whatever
73
+ * the id holds, as before.
74
+ *
75
+ * The epoch survives a refresh or `rotate`, so it names a credential
76
+ * lineage, not one token: a caller that must remove only an exact token
77
+ * still checks the loaded credential in `protect`.
78
+ */
79
+ attribution?: Attribution;
58
80
  /**
59
81
  * Awaited under every lock before anything is written; a reason refuses
60
82
  * the removal (kind `row-protected`) with both files unchanged. The store
@@ -710,6 +710,8 @@ export async function removeRow(rt, id, options = {}) {
710
710
  // older readers would trim is invalid, and removing it is a repair.
711
711
  if (typeof id !== 'string' || id.length === 0)
712
712
  throw refusal('remove', id, 'invalid-input', 'id must be non-empty');
713
+ const fence = options.attribution;
714
+ validateAttribution('remove', id, fence);
713
715
  const result = await readPool(ctx);
714
716
  if (result.status !== 'ready')
715
717
  throw notReadyError(result, 'remove', id);
@@ -727,6 +729,12 @@ export async function removeRow(rt, id, options = {}) {
727
729
  throw unknownRow('remove', id);
728
730
  if (rowLockKey(row ?? { id }) !== seenKey)
729
731
  throw keyChanged('remove', id);
732
+ if (fence !== undefined) {
733
+ if (row)
734
+ assertBoundRowAttribution(id, row, fence);
735
+ else
736
+ assertOrphanAttribution(rt, tx, id, fence);
737
+ }
730
738
  const protect = options.protect;
731
739
  if (protect) {
732
740
  const view = {
@@ -747,9 +755,76 @@ export async function removeRow(rt, id, options = {}) {
747
755
  await tx.commitState();
748
756
  }
749
757
  return { id, outcome: row ? 'removed' : 'completed' };
750
- });
758
+ },
759
+ // An attributed removal is refused, when it is, with nothing written:
760
+ // completing another row's interrupted write first would be a write.
761
+ { completeTorn: fence === undefined });
751
762
  });
752
763
  }
764
+ /** An attributed removal of a roster row: bound, not torn, same epoch and identity. */
765
+ function assertBoundRowAttribution(id, row, fence) {
766
+ assertRowAttribution('remove', id, row, fence);
767
+ // A torn row is between the two writes of another operation; which
768
+ // credential it holds is not settled, so no attribution can match it.
769
+ if (row.torn)
770
+ throw refusal('remove', id, 'attribution', `row ${id} is between the writes of another operation; retry once it completes`, true);
771
+ if (row.stamp !== 'bound')
772
+ throw refusal('remove', id, 'unbound-credential', `row ${id}'s credential is not bound to its stamp, so the removal cannot be attributed to it`);
773
+ }
774
+ /**
775
+ * An attributed removal of an orphan. The orphan is loaded the way an
776
+ * interrupted add's replay loads it (`matchingInterruptedAdd`): its stamp
777
+ * supplies the identity and endpoint the missing roster row would have held,
778
+ * and the credential beside it must be the one that stamp names (status
779
+ * `bound`). Only then does the stamp's epoch and identity mean anything.
780
+ */
781
+ function assertOrphanAttribution(rt, tx, id, fence) {
782
+ const unbound = () => refusal('remove', id, 'unbound-credential', `orphan ${id} has no credential stamp this store can bind, so the removal cannot be attributed to it`);
783
+ const account = tx.stateAccount(id);
784
+ const stamp = parseStamp(account?.[CREDENTIAL_STAMP_KEY]);
785
+ // A replace's stamp only ever sits beside a roster row; one left without
786
+ // a row is not a state this store writes.
787
+ if (!account ||
788
+ !stamp?.binding ||
789
+ stamp.dispatch === undefined ||
790
+ stamp.replace)
791
+ throw unbound();
792
+ let descriptor;
793
+ if (typeof account.apiKey === 'string') {
794
+ if (stamp.binding.baseURL === undefined ||
795
+ stamp.binding.authHeader === undefined)
796
+ throw unbound();
797
+ descriptor = {
798
+ type: 'api',
799
+ apiKey: account.apiKey,
800
+ baseURL: stamp.binding.baseURL,
801
+ authHeader: stamp.binding.authHeader,
802
+ };
803
+ }
804
+ else if (typeof account.refresh === 'string') {
805
+ descriptor = { type: 'oauth', refresh: account.refresh };
806
+ }
807
+ else
808
+ throw unbound();
809
+ const [orphan] = buildRawRows({
810
+ accounts: [
811
+ rosterRowFor({
812
+ id,
813
+ credential: descriptor,
814
+ identity: stamp.binding.identity,
815
+ addedAt: 0,
816
+ }),
817
+ ],
818
+ [POOL_KEY]: {
819
+ rows: { [id]: { credentialEpoch: stamp.credentialEpoch } },
820
+ },
821
+ }, tx.state, rt.ctx.codec, rt.ctx.providerState);
822
+ if (!orphan?.credential || orphan.invalid || orphan.stamp !== 'bound')
823
+ throw unbound();
824
+ if (stamp.credentialEpoch !== fence.credentialEpoch ||
825
+ stamp.binding.identity !== fence.identity)
826
+ throw refusal('remove', id, 'attribution', `orphan ${id} was written for a credential or account other than the one this removal was decided for`, true);
827
+ }
753
828
  function hasStateAccount(state, id) {
754
829
  const accounts = state.accounts;
755
830
  return isRecord(accounts) && Object.hasOwn(accounts, id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.11.5",
3
+ "version": "0.11.7",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {