@ouro.bot/cli 0.1.0-alpha.1014 → 0.1.0-alpha.1016

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.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1016",
6
+ "changes": [
7
+ "An agent with a Copilot account pool writes its fleet gist file only when it changed, at most every 30 minutes and at least every 5 hours, to stay inside GitHub's shared gist write budget."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1015",
12
+ "changes": [
13
+ "ouro auth, ouro vault config set and every other vault write go through Ouro's own Bitwarden client too: it creates, updates or trashes the login item over HTTPS with Node's crypto, keeps an existing item's own key, folder, custom fields and history as stored, refuses to overwrite a newer copy, and reads the item back to check it. Nothing on the vault path runs bw any more unless the vault needs it (Argon2id, two-step login) or OURO_VAULT_NATIVE_READS=0."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1014",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1014",
2
+ "runtimeVersion": "0.1.0-alpha.1016",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1014</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1016</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -270,6 +270,7 @@ class AccountPool {
270
270
  requests = [];
271
271
  lastRefresh = -Infinity;
272
272
  lastPublish = -Infinity;
273
+ lastPublished = "";
273
274
  loadedReadings = false;
274
275
  refreshing = null;
275
276
  options;
@@ -371,26 +372,36 @@ class AccountPool {
371
372
  this.publishIfDue();
372
373
  }
373
374
  /**
374
- * Rewrite this agent's file in the fleet gist every few minutes while it runs, once readings have loaded
375
- * (so a process that just started never blanks the agent's published readings).
375
+ * Rewrite this agent's file in the fleet gist when it has changed, at most every 30 minutes (GitHub allows
376
+ * 100 gist writes an hour per user, shared by the whole fleet), and at least every 5 hours so the balancer,
377
+ * which trusts a reading for 6 hours, keeps it. Never before readings have loaded, so a process that just
378
+ * started never blanks the agent's published readings. Switching accounts never waits on this.
376
379
  */
377
380
  publishIfDue() {
378
381
  const now = this.now();
379
382
  const publish = this.options.publishBurn;
380
383
  const loaded = this.loadedReadings || !this.options.loadReadings;
381
- if (!publish || !loaded || now - this.lastPublish < (this.options.publishMs ?? 5 * 60 * 1000))
384
+ if (!publish || !loaded || now - this.lastPublish < (this.options.publishMs ?? 30 * 60 * 1000))
382
385
  return;
383
- this.lastPublish = now;
384
- void publish({
385
- agent: this.options.agent,
386
- machine: this.options.machine ?? os.hostname().split(".")[0].toLowerCase().replace(/\./g, "-"),
387
- at: new Date(now).toISOString(),
386
+ const content = {
388
387
  current: this.currentKey,
389
388
  requestsPerH: this.agentBurnPerH(now),
390
389
  readings: this.accounts.map(exports.accountKey).flatMap((key) => {
391
390
  const found = this.readings.find((reading) => reading.key === key);
392
391
  return found ? [found] : [];
393
392
  }),
393
+ };
394
+ const signature = JSON.stringify(content);
395
+ const stale = now - this.lastPublish >= (this.options.republishMs ?? 5 * 60 * 60 * 1000);
396
+ if (signature === this.lastPublished && !stale)
397
+ return;
398
+ this.lastPublish = now;
399
+ this.lastPublished = signature;
400
+ void publish({
401
+ agent: this.options.agent,
402
+ machine: this.options.machine ?? os.hostname().split(".")[0].toLowerCase().replace(/\./g, "-"),
403
+ at: new Date(now).toISOString(),
404
+ ...content,
394
405
  });
395
406
  }
396
407
  /** Share this process's last-hour request times with the agent's other processes. */
@@ -6,8 +6,10 @@
6
6
  * Protocol (Bitwarden security whitepaper): prelogin for the KDF, PBKDF2-SHA256 master key,
7
7
  * a password-grant login with the master password hash, the user key unwrapped with the
8
8
  * HKDF-stretched master key, then /api/sync and AES-256-CBC + HMAC-SHA256 decryption of each item.
9
- * Reads only: writes stay on `bw`. Anything this reader does not handle (Argon2id, two-step login,
10
- * other cipher types) raises NativeVaultUnsupportedError so the caller can fall back to `bw`.
9
+ * It also creates, updates and trashes login items (POST/PUT /api/ciphers), re-encrypting only the
10
+ * name, notes and login and replaying every other encrypted field from the last sync unchanged.
11
+ * Anything this client does not handle (Argon2id, two-step login, other cipher types) raises
12
+ * NativeVaultUnsupportedError so the caller can fall back to `bw`.
11
13
  */
12
14
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
15
  if (k2 === undefined) k2 = k;
@@ -46,6 +48,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
46
48
  exports.NativeVaultReader = exports.NATIVE_VAULT_LOGIN_FAILURE_RETRY_MS = exports.NATIVE_VAULT_ITEMS_FRESH_MS = exports.NativeVaultUnsupportedError = void 0;
47
49
  exports.nodeVaultRequest = nodeVaultRequest;
48
50
  exports.decryptCipherString = decryptCipherString;
51
+ exports.encryptCipherString = encryptCipherString;
49
52
  exports.decryptSyncItems = decryptSyncItems;
50
53
  exports.sharedNativeVaultReader = sharedNativeVaultReader;
51
54
  const crypto = __importStar(require("node:crypto"));
@@ -132,6 +135,14 @@ function decryptCipherString(value, key) {
132
135
  const decipher = crypto.createDecipheriv("aes-256-cbc", key.subarray(0, 32), iv);
133
136
  return Buffer.concat([decipher.update(ct), decipher.final()]);
134
137
  }
138
+ /** Encrypt into a type-2 cipher string with a 64-byte key (32 enc + 32 mac). */
139
+ function encryptCipherString(data, key) {
140
+ const iv = crypto.randomBytes(16);
141
+ const cipher = crypto.createCipheriv("aes-256-cbc", key.subarray(0, 32), iv);
142
+ const ct = Buffer.concat([cipher.update(typeof data === "string" ? Buffer.from(data, "utf8") : data), cipher.final()]);
143
+ const mac = crypto.createHmac("sha256", key.subarray(32, 64)).update(iv).update(ct).digest();
144
+ return `2.${iv.toString("base64")}|${ct.toString("base64")}|${mac.toString("base64")}`;
145
+ }
135
146
  function decryptText(value, key) {
136
147
  return typeof value === "string" && value.length > 0 ? decryptCipherString(value, key).toString("utf8") : undefined;
137
148
  }
@@ -147,6 +158,7 @@ function decryptSyncItems(sync, userKey) {
147
158
  if (!Array.isArray(ciphers))
148
159
  throw new Error("vault sync returned no item list");
149
160
  const items = [];
161
+ const raw = new Map();
150
162
  let skipped = 0;
151
163
  let unreadable = 0;
152
164
  for (const cipher of ciphers) {
@@ -159,6 +171,7 @@ function decryptSyncItems(sync, userKey) {
159
171
  const key = itemKeyString ? decryptKey(itemKeyString, userKey, "item key") : userKey;
160
172
  const login = field(cipher, "login");
161
173
  const uris = field(login, "uris");
174
+ raw.set(String(field(cipher, "id")), cipher);
162
175
  items.push({
163
176
  id: String(field(cipher, "id")),
164
177
  name: decryptText(field(cipher, "name"), key) ?? "",
@@ -183,8 +196,21 @@ function decryptSyncItems(sync, userKey) {
183
196
  unreadable += 1;
184
197
  }
185
198
  }
186
- return { items, skipped, unreadable };
199
+ return { items, skipped, unreadable, raw };
200
+ }
201
+ /** The user id (`sub`) in a JWT access token, or null when the token is not a JWT. */
202
+ function tokenUserId(accessToken) {
203
+ try {
204
+ const payload = JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString("utf8"));
205
+ const sub = field(payload, "sub");
206
+ return typeof sub === "string" && sub.length > 0 ? sub : null;
207
+ }
208
+ catch {
209
+ return null;
210
+ }
187
211
  }
212
+ /** The fields of an item that a write keeps as they are: still encrypted, so never decrypted here. */
213
+ const PRESERVED_CIPHER_FIELDS = ["folderId", "favorite", "reprompt", "fields", "passwordHistory"];
188
214
  class NativeVaultReader {
189
215
  email;
190
216
  masterPassword;
@@ -223,8 +249,8 @@ class NativeVaultReader {
223
249
  if (sync === null)
224
250
  throw new Error("vault sync rejected a fresh access token (HTTP 401)");
225
251
  }
226
- const { items, skipped, unreadable } = decryptSyncItems(sync, session.userKey);
227
- this.cache = { items, at: this.deps.now() };
252
+ const { items, skipped, unreadable, raw } = decryptSyncItems(sync, session.userKey);
253
+ this.cache = { items, raw, at: this.deps.now() };
228
254
  (0, runtime_1.emitNervesEvent)({
229
255
  component: "repertoire",
230
256
  event: "repertoire.native_vault_sync_end",
@@ -233,6 +259,80 @@ class NativeVaultReader {
233
259
  });
234
260
  return items;
235
261
  }
262
+ /**
263
+ * Create a login item, or update the item `existingId` names. An update needs that item in the
264
+ * latest sync (read items() first): it keeps the item's own key, folder, favorite, custom fields,
265
+ * password history and other login data exactly as stored, and the server refuses it if the item
266
+ * changed since that sync. Returns the item id. Does not retry, so a lost answer never writes twice.
267
+ */
268
+ async saveLogin(write, existingId) {
269
+ const existing = existingId === undefined ? undefined : this.cache?.raw.get(existingId);
270
+ if (existingId !== undefined && !existing)
271
+ throw new Error(`vault item ${existingId} is not in the latest sync; read the vault before updating it`);
272
+ (0, runtime_1.emitNervesEvent)({
273
+ component: "repertoire",
274
+ event: "repertoire.native_vault_write_start",
275
+ message: existingId ? "updating a vault item natively" : "creating a vault item natively",
276
+ meta: { email: this.email, update: existingId !== undefined },
277
+ });
278
+ const answer = await this.withSession(async (session) => {
279
+ const itemKeyString = existing ? stringField(existing, "key") : undefined;
280
+ const key = itemKeyString ? decryptKey(itemKeyString, session.userKey, "item key") : session.userKey;
281
+ const login = field(existing, "login");
282
+ const body = {
283
+ ...(existing ? Object.fromEntries(PRESERVED_CIPHER_FIELDS.map((name) => [name, field(existing, name) ?? null])) : { folderId: null, favorite: false, reprompt: 0, fields: null, passwordHistory: null }),
284
+ type: 1,
285
+ organizationId: null,
286
+ key: itemKeyString ?? null,
287
+ name: encryptCipherString(write.name, key),
288
+ notes: write.notes === null ? null : encryptCipherString(write.notes, key),
289
+ login: {
290
+ ...(login && typeof login === "object" ? login : {}),
291
+ username: encryptCipherString(write.username, key),
292
+ password: encryptCipherString(write.password, key),
293
+ uris: [{ uri: encryptCipherString(write.uri, key), match: null }],
294
+ },
295
+ encryptedFor: session.userId,
296
+ lastKnownRevisionDate: existing ? stringField(existing, "revisionDate") ?? null : null,
297
+ };
298
+ return this.request(existingId ? `/api/ciphers/${encodeURIComponent(existingId)}` : "/api/ciphers", {
299
+ method: existingId ? "PUT" : "POST",
300
+ headers: { authorization: `Bearer ${session.accessToken}`, "content-type": "application/json" },
301
+ body: JSON.stringify(body),
302
+ });
303
+ });
304
+ this.cache = null;
305
+ if (!ok(answer))
306
+ throw new Error(`vault ${existingId ? "update" : "create"} for ${this.email} failed: HTTP ${answer.status}${serverMessage(answer)}`);
307
+ const id = stringField(readJson(answer), "id");
308
+ if (!id)
309
+ throw new Error(`vault ${existingId ? "update" : "create"} for ${this.email} returned no item id`);
310
+ (0, runtime_1.emitNervesEvent)({
311
+ component: "repertoire",
312
+ event: "repertoire.native_vault_write_end",
313
+ message: "wrote a vault item natively",
314
+ meta: { email: this.email, update: existingId !== undefined },
315
+ });
316
+ return id;
317
+ }
318
+ /** Move an item to the trash, as `bw delete item` does. */
319
+ async deleteItem(id) {
320
+ const answer = await this.withSession((session) => this.request(`/api/ciphers/${encodeURIComponent(id)}/delete`, {
321
+ method: "PUT",
322
+ headers: { authorization: `Bearer ${session.accessToken}` },
323
+ }));
324
+ this.cache = null;
325
+ if (!ok(answer))
326
+ throw new Error(`vault delete for ${this.email} failed: HTTP ${answer.status}${serverMessage(answer)}`);
327
+ }
328
+ /** Run one request with a session, logging in once more if the server rejects the access token. */
329
+ async withSession(send) {
330
+ const answer = await send(await this.ensureSession());
331
+ if (answer.status !== 401)
332
+ return answer;
333
+ this.session = null;
334
+ return send(await this.ensureSession());
335
+ }
236
336
  async ensureSession() {
237
337
  if (this.session && this.deps.now() < this.session.expiresAt - TOKEN_EXPIRY_MARGIN_MS)
238
338
  return this.session;
@@ -278,7 +378,10 @@ class NativeVaultReader {
278
378
  throw new Error("vault login returned no access token or user key");
279
379
  const expiresIn = Number(field(token, "expires_in"));
280
380
  const userKey = decryptKey(protectedKey, keys.stretched, "user key");
281
- this.session = { accessToken, expiresAt: this.deps.now() + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600) * 1000, userKey };
381
+ const userId = tokenUserId(accessToken);
382
+ if (!userId)
383
+ throw new NativeVaultUnsupportedError("an access token without a user id");
384
+ this.session = { accessToken, expiresAt: this.deps.now() + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600) * 1000, userKey, userId };
282
385
  return this.session;
283
386
  }
284
387
  async deriveKeys() {
@@ -336,6 +439,12 @@ function readJson(response) {
336
439
  }
337
440
  }
338
441
  const ok = (response) => response.status >= 200 && response.status < 300;
442
+ /** The server's own explanation of a refused request, when it gave one. */
443
+ function serverMessage(response) {
444
+ const body = readJson(response);
445
+ const message = stringField(field(body, "errorModel"), "message") ?? stringField(body, "message");
446
+ return message ? ` ${message}` : "";
447
+ }
339
448
  const sharedReaders = new Map();
340
449
  /** One reader per vault account and secret in a process, so its stores share one login and one sync. */
341
450
  function sharedNativeVaultReader(serverUrl, email, masterPassword) {
@@ -1055,39 +1055,40 @@ class BitwardenCredentialStore {
1055
1055
  message: `storing credential via bw for ${domain}`,
1056
1056
  meta: { domain, backend: "bitwarden" },
1057
1057
  });
1058
- await this.withSessionRetry(async (session) => {
1059
- if (shouldUseStructuredItemLookup(domain)) {
1058
+ if (!(await this.storeNatively(domain, data)))
1059
+ await this.withSessionRetry(async (session) => {
1060
+ if (shouldUseStructuredItemLookup(domain)) {
1061
+ this.structuredItemCache = null;
1062
+ }
1063
+ const existing = await this.findItemByDomain(domain, session);
1064
+ const item = {
1065
+ ...(existing ?? {}),
1066
+ type: 1, // Login type
1067
+ name: domain,
1068
+ login: {
1069
+ username: data.username ?? "",
1070
+ password: data.password,
1071
+ uris: [{ uri: `https://${domain}` }],
1072
+ },
1073
+ notes: data.notes ?? null,
1074
+ };
1075
+ const encoded = Buffer.from(JSON.stringify(item)).toString("base64");
1060
1076
  this.structuredItemCache = null;
1061
- }
1062
- const existing = await this.findItemByDomain(domain, session);
1063
- const item = {
1064
- ...(existing ?? {}),
1065
- type: 1, // Login type
1066
- name: domain,
1067
- login: {
1068
- username: data.username ?? "",
1069
- password: data.password,
1070
- uris: [{ uri: `https://${domain}` }],
1071
- },
1072
- notes: data.notes ?? null,
1073
- };
1074
- const encoded = Buffer.from(JSON.stringify(item)).toString("base64");
1075
- this.structuredItemCache = null;
1076
- let savedItem;
1077
- if (existing) {
1078
- const stdout = await this.execBw(["edit", "item", existing.id], session, encoded);
1079
- const savedItemId = parseBwItemId(stdout) ?? existing.id;
1080
- savedItem = await this.findItemById(savedItemId, session);
1081
- }
1082
- else {
1083
- const stdout = await this.execBw(["create", "item"], session, encoded);
1084
- const savedItemId = parseBwItemId(stdout);
1085
- savedItem = savedItemId
1086
- ? await this.findItemById(savedItemId, session)
1087
- : await this.findItemByDomain(domain, session);
1088
- }
1089
- this.assertStoredCredentialMatches(domain, data, savedItem);
1090
- });
1077
+ let savedItem;
1078
+ if (existing) {
1079
+ const stdout = await this.execBw(["edit", "item", existing.id], session, encoded);
1080
+ const savedItemId = parseBwItemId(stdout) ?? existing.id;
1081
+ savedItem = await this.findItemById(savedItemId, session);
1082
+ }
1083
+ else {
1084
+ const stdout = await this.execBw(["create", "item"], session, encoded);
1085
+ const savedItemId = parseBwItemId(stdout);
1086
+ savedItem = savedItemId
1087
+ ? await this.findItemById(savedItemId, session)
1088
+ : await this.findItemByDomain(domain, session);
1089
+ }
1090
+ this.assertStoredCredentialMatches(domain, data, savedItem);
1091
+ });
1091
1092
  this.structuredItemCache = null;
1092
1093
  this.nativeReader?.invalidate();
1093
1094
  (0, runtime_1.emitNervesEvent)({
@@ -1126,7 +1127,8 @@ class BitwardenCredentialStore {
1126
1127
  message: `deleting credential via bw for ${domain}`,
1127
1128
  meta: { domain, backend: "bitwarden" },
1128
1129
  });
1129
- const item = await this.withSessionRetry((session) => this.findItemByDomain(domain, session));
1130
+ const native = await this.deleteNatively(domain);
1131
+ const item = native === null ? await this.withSessionRetry((session) => this.findItemByDomain(domain, session)) : native;
1130
1132
  if (!item) {
1131
1133
  (0, runtime_1.emitNervesEvent)({
1132
1134
  event: "repertoire.bw_credential_delete_end",
@@ -1136,7 +1138,8 @@ class BitwardenCredentialStore {
1136
1138
  });
1137
1139
  return false;
1138
1140
  }
1139
- await this.withSessionRetry((session) => this.execBw(["delete", "item", item.id], session));
1141
+ if (native === null)
1142
+ await this.withSessionRetry((session) => this.execBw(["delete", "item", item.id], session));
1140
1143
  this.structuredItemCache = null;
1141
1144
  this.nativeReader?.invalidate();
1142
1145
  (0, runtime_1.emitNervesEvent)({
@@ -1155,13 +1158,42 @@ class BitwardenCredentialStore {
1155
1158
  return native.find((item) => item.name === domain) ?? null;
1156
1159
  return this.withSessionRetry((session) => this.findItemByDomain(domain, session));
1157
1160
  }
1161
+ /**
1162
+ * Write one credential through the native client, reading it back to verify. False when this
1163
+ * vault goes through bw instead (no native client, or one that does not support this vault).
1164
+ */
1165
+ async storeNatively(domain, data) {
1166
+ return this.withNativeClient(async (client) => {
1167
+ client.invalidate();
1168
+ const existing = (await client.items()).find((item) => item.name === domain);
1169
+ await client.saveLogin({ name: domain, username: data.username ?? "", password: data.password, notes: data.notes ?? null, uri: `https://${domain}` }, existing?.id);
1170
+ const saved = (await client.items()).find((item) => item.name === domain) ?? null;
1171
+ this.assertStoredCredentialMatches(domain, data, saved);
1172
+ return true;
1173
+ }, false);
1174
+ }
1175
+ /** Trash one credential through the native client: the item it trashed, false when there was none, null for bw. */
1176
+ async deleteNatively(domain) {
1177
+ return this.withNativeClient(async (client) => {
1178
+ client.invalidate();
1179
+ const existing = (await client.items()).find((item) => item.name === domain);
1180
+ if (!existing)
1181
+ return false;
1182
+ await client.deleteItem(existing.id);
1183
+ return existing;
1184
+ }, null);
1185
+ }
1158
1186
  /** Every item through the native reader, or null when reads go through bw. */
1159
1187
  async nativeItems() {
1188
+ return this.withNativeClient((client) => client.items(), null);
1189
+ }
1190
+ /** Run with the native client, or return `viaBw` when this vault goes through bw. */
1191
+ async withNativeClient(operation, viaBw) {
1160
1192
  const reader = this.nativeReader;
1161
1193
  if (!reader)
1162
- return null;
1194
+ return viaBw;
1163
1195
  try {
1164
- return await reader.items();
1196
+ return await operation(reader);
1165
1197
  }
1166
1198
  catch (error) {
1167
1199
  /* v8 ignore next -- defensive: the reader always throws Error instances @preserve */
@@ -1172,10 +1204,10 @@ class BitwardenCredentialStore {
1172
1204
  level: "warn",
1173
1205
  event: "repertoire.native_vault_fallback",
1174
1206
  component: "repertoire",
1175
- message: "reading this vault through bw instead",
1207
+ message: "using bw for this vault instead",
1176
1208
  meta: { email: this.email, serverUrl: this.serverUrl, reason: err.message },
1177
1209
  });
1178
- return null;
1210
+ return viaBw;
1179
1211
  }
1180
1212
  if (isBwInvalidUnlockSecretMessage(err.message))
1181
1213
  await this.notifyInvalidUnlockSecret(err);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1014",
3
+ "version": "0.1.0-alpha.1016",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1014",
9
+ "version": "0.1.0-alpha.1016",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@bitwarden/cli": "2026.9.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1014",
3
+ "version": "0.1.0-alpha.1016",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },