@ouro.bot/cli 0.1.0-alpha.1010 → 0.1.0-alpha.1013
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 +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/auth/auth-flow.js +60 -0
- package/dist/heart/core.js +5 -3
- package/dist/heart/provider-credentials.js +2 -2
- package/dist/heart/providers/account-pool.js +549 -0
- package/dist/heart/providers/github-copilot.js +71 -6
- package/dist/heart/quota/fleet-readings.js +222 -0
- package/dist/heart/quota/tranche.js +59 -0
- package/dist/repertoire/bitwarden-native.js +349 -0
- package/dist/repertoire/bitwarden-store.js +49 -4
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.LOCAL_BALANCER_STATE = void 0;
|
|
37
|
+
exports.readingsFromBalancerState = readingsFromBalancerState;
|
|
38
|
+
exports.mergeReadings = mergeReadings;
|
|
39
|
+
exports.readFleetQuota = readFleetQuota;
|
|
40
|
+
exports.directReading = directReading;
|
|
41
|
+
exports.agentBurnFileName = agentBurnFileName;
|
|
42
|
+
exports.agentBurnContent = agentBurnContent;
|
|
43
|
+
exports.loadFleetQuota = loadFleetQuota;
|
|
44
|
+
exports.publishAgentBurn = publishAgentBurn;
|
|
45
|
+
const fs = __importStar(require("fs"));
|
|
46
|
+
const os = __importStar(require("os"));
|
|
47
|
+
const path = __importStar(require("path"));
|
|
48
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
49
|
+
/**
|
|
50
|
+
* Quota readings for agents, from the same places the Copilot app balancer (`quota-balance.mjs`) keeps them:
|
|
51
|
+
* its local state first (`~/.config/mac-fleet/quota-balance.json`), then the fleet gist (`<machine>.quota.txt`).
|
|
52
|
+
* Agents publish their own burn to the same gist as `<machine>.<agent>.quota.txt`.
|
|
53
|
+
*/
|
|
54
|
+
exports.LOCAL_BALANCER_STATE = path.join(".config", "mac-fleet", "quota-balance.json");
|
|
55
|
+
function isRecord(value) {
|
|
56
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
57
|
+
}
|
|
58
|
+
const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
|
|
59
|
+
const str = (value) => (typeof value === "string" && value ? value : null);
|
|
60
|
+
/** Readings from one balancer state object: `{ readings: { "login@host": { pct, overage_permitted, at, reset } } }`. */
|
|
61
|
+
function readingsFromBalancerState(state, source) {
|
|
62
|
+
if (!isRecord(state) || !isRecord(state.readings))
|
|
63
|
+
return [];
|
|
64
|
+
const out = [];
|
|
65
|
+
for (const [key, raw] of Object.entries(state.readings)) {
|
|
66
|
+
if (!isRecord(raw) || num(raw.pct) === null)
|
|
67
|
+
continue;
|
|
68
|
+
out.push({
|
|
69
|
+
key,
|
|
70
|
+
leftPct: num(raw.pct),
|
|
71
|
+
burnPerH: num(raw.burn_per_h),
|
|
72
|
+
dryAt: str(raw.dry_at),
|
|
73
|
+
overageOk: raw.overage_permitted === true,
|
|
74
|
+
at: str(raw.at),
|
|
75
|
+
reset: str(raw.reset),
|
|
76
|
+
remaining: num(raw.remaining),
|
|
77
|
+
entitlement: num(raw.entitlement),
|
|
78
|
+
source,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
const timeOf = (reading) => {
|
|
84
|
+
const at = Date.parse(reading.at ?? "");
|
|
85
|
+
return Number.isNaN(at) ? -Infinity : at;
|
|
86
|
+
};
|
|
87
|
+
/** Freshest reading per account. On a tie the earlier list wins, so pass local readings first. */
|
|
88
|
+
function mergeReadings(...lists) {
|
|
89
|
+
const out = new Map();
|
|
90
|
+
for (const list of lists) {
|
|
91
|
+
for (const reading of list) {
|
|
92
|
+
const prev = out.get(reading.key);
|
|
93
|
+
if (!prev || timeOf(reading) > timeOf(prev))
|
|
94
|
+
out.set(reading.key, reading);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return [...out.values()];
|
|
98
|
+
}
|
|
99
|
+
/** Every reading in the fleet: local balancer state first, then each other Mac's `<machine>.quota.txt` in the gist. */
|
|
100
|
+
function readFleetQuota(sources) {
|
|
101
|
+
const local = readingsFromBalancerState(sources.localState, "local");
|
|
102
|
+
const fleet = [];
|
|
103
|
+
const files = isRecord(sources.gist) && isRecord(sources.gist.files) ? sources.gist.files : {};
|
|
104
|
+
for (const [name, file] of Object.entries(files)) {
|
|
105
|
+
const match = /^([^.]+)\.quota\.txt$/.exec(name);
|
|
106
|
+
if (!match || !isRecord(file) || typeof file.content !== "string")
|
|
107
|
+
continue;
|
|
108
|
+
try {
|
|
109
|
+
fleet.push(readingsFromBalancerState(JSON.parse(file.content), `fleet:${match[1]}`));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// A half-written file is skipped; the next read picks it up.
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const readings = mergeReadings(local, ...fleet);
|
|
116
|
+
(0, runtime_1.emitNervesEvent)({
|
|
117
|
+
component: "engine",
|
|
118
|
+
event: "engine.fleet_quota_read",
|
|
119
|
+
message: "read fleet quota readings",
|
|
120
|
+
meta: { local: local.length, gistFiles: fleet.length, accounts: readings.length },
|
|
121
|
+
});
|
|
122
|
+
return readings;
|
|
123
|
+
}
|
|
124
|
+
/** A reading from an account's own `/copilot_internal/user` answer. */
|
|
125
|
+
function directReading(key, body, at) {
|
|
126
|
+
if (!isRecord(body) || !isRecord(body.quota_snapshots) || !isRecord(body.quota_snapshots.premium_interactions))
|
|
127
|
+
return null;
|
|
128
|
+
const snap = body.quota_snapshots.premium_interactions;
|
|
129
|
+
const leftPct = snap.unlimited === true ? 100 : num(snap.percent_remaining);
|
|
130
|
+
if (leftPct === null)
|
|
131
|
+
return null;
|
|
132
|
+
return {
|
|
133
|
+
key,
|
|
134
|
+
leftPct,
|
|
135
|
+
burnPerH: null,
|
|
136
|
+
dryAt: null,
|
|
137
|
+
overageOk: snap.overage_permitted === true,
|
|
138
|
+
at,
|
|
139
|
+
reset: str(body.quota_reset_date_utc),
|
|
140
|
+
remaining: num(snap.remaining),
|
|
141
|
+
entitlement: num(snap.entitlement),
|
|
142
|
+
source: "direct",
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function agentBurnFileName(machine, agent) {
|
|
146
|
+
return `${machine}.${agent}.quota.txt`;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The agent's file, in the shape the Copilot app balancer reads (`parseAgentQuota` in quota-balance.mjs):
|
|
150
|
+
* `{machine, agent, at, readings: [{key, leftPct, burnPerH, dryAt, overageOk, at, remaining, entitlement, reset}]}`.
|
|
151
|
+
* `burnPerH` is this agent's own requests an hour on that account.
|
|
152
|
+
*/
|
|
153
|
+
function agentBurnContent(burn) {
|
|
154
|
+
const keys = [...new Set([...burn.readings.map((reading) => reading.key), ...Object.keys(burn.requestsPerH)])];
|
|
155
|
+
const readings = keys.map((key) => {
|
|
156
|
+
const reading = burn.readings.find((candidate) => candidate.key === key);
|
|
157
|
+
return {
|
|
158
|
+
key,
|
|
159
|
+
leftPct: reading?.leftPct ?? null,
|
|
160
|
+
burnPerH: burn.requestsPerH[key] ?? 0,
|
|
161
|
+
dryAt: reading?.dryAt ?? null,
|
|
162
|
+
overageOk: reading?.overageOk ?? false,
|
|
163
|
+
at: reading?.at ?? burn.at,
|
|
164
|
+
...(reading?.remaining != null ? { remaining: reading.remaining } : {}),
|
|
165
|
+
...(reading?.entitlement != null ? { entitlement: reading.entitlement } : {}),
|
|
166
|
+
...(reading?.reset ? { reset: reading.reset } : {}),
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
return `${JSON.stringify({ machine: burn.machine, agent: burn.agent, at: burn.at, current: burn.current, readings }, null, 2)}\n`;
|
|
170
|
+
}
|
|
171
|
+
const gistUrl = (gistId) => `https://api.github.com/gists/${gistId}`;
|
|
172
|
+
const gistHeaders = (token) => ({
|
|
173
|
+
Authorization: `token ${token}`,
|
|
174
|
+
Accept: "application/vnd.github+json",
|
|
175
|
+
"User-Agent": "ouro-account-pool",
|
|
176
|
+
});
|
|
177
|
+
/** Load local balancer state and the fleet gist; either may be missing. */
|
|
178
|
+
async function loadFleetQuota(gist, io = {}) {
|
|
179
|
+
const readFile = io.readFile ?? ((file) => fs.readFileSync(file, "utf8"));
|
|
180
|
+
let localState;
|
|
181
|
+
try {
|
|
182
|
+
localState = JSON.parse(readFile(path.join(io.homeDir ?? os.homedir(), exports.LOCAL_BALANCER_STATE)));
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
localState = undefined;
|
|
186
|
+
}
|
|
187
|
+
let gistBody;
|
|
188
|
+
if (gist) {
|
|
189
|
+
try {
|
|
190
|
+
const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), { headers: gistHeaders(gist.token), signal: AbortSignal.timeout(15000) });
|
|
191
|
+
gistBody = response.ok ? await response.json() : undefined;
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
gistBody = undefined;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return readFleetQuota({ localState, gist: gistBody });
|
|
198
|
+
}
|
|
199
|
+
/** Write this agent's burn to the fleet gist. Returns false (never throws) when the gist can't be written. */
|
|
200
|
+
async function publishAgentBurn(gist, burn, io = {}) {
|
|
201
|
+
let ok = false;
|
|
202
|
+
try {
|
|
203
|
+
const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), {
|
|
204
|
+
method: "PATCH",
|
|
205
|
+
headers: { ...gistHeaders(gist.token), "Content-Type": "application/json" },
|
|
206
|
+
body: JSON.stringify({ files: { [agentBurnFileName(burn.machine, burn.agent)]: { content: agentBurnContent(burn) } } }),
|
|
207
|
+
signal: AbortSignal.timeout(15000),
|
|
208
|
+
});
|
|
209
|
+
ok = response.ok;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
ok = false;
|
|
213
|
+
}
|
|
214
|
+
(0, runtime_1.emitNervesEvent)({
|
|
215
|
+
level: ok ? "info" : "warn",
|
|
216
|
+
component: "engine",
|
|
217
|
+
event: "engine.agent_burn_published",
|
|
218
|
+
message: ok ? "published agent burn to the fleet gist" : "could not publish agent burn to the fleet gist",
|
|
219
|
+
meta: { agent: burn.agent, machine: burn.machine, ok },
|
|
220
|
+
});
|
|
221
|
+
return ok;
|
|
222
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_TRANCHE_CAPS = void 0;
|
|
4
|
+
exports.usedPct = usedPct;
|
|
5
|
+
exports.trancheCap = trancheCap;
|
|
6
|
+
exports.pickByTranche = pickByTranche;
|
|
7
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
8
|
+
/** Fill every account to 30% used, then 60%, then 90%, then squeeze the last 10% from each (Ari, 2026-11-09). */
|
|
9
|
+
exports.DEFAULT_TRANCHE_CAPS = [30, 60, 90, 100];
|
|
10
|
+
/**
|
|
11
|
+
* These mirror `usedPct`, `trancheCap` and `pickByTranche` in the Copilot app balancer
|
|
12
|
+
* (desk `setup/quota-balance.mjs`), so agents and the app fill accounts the same way.
|
|
13
|
+
*/
|
|
14
|
+
/** Percent of included requests used, or null with no reading. */
|
|
15
|
+
function usedPct(reading) {
|
|
16
|
+
if (!reading || reading.leftPct === null)
|
|
17
|
+
return null;
|
|
18
|
+
return Math.max(0, Math.min(100, 100 - reading.leftPct));
|
|
19
|
+
}
|
|
20
|
+
function byKey(readings) {
|
|
21
|
+
return new Map(readings.map((reading) => [reading.key, reading]));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The current cap: the lowest cap that some eligible account with a reading is still below. It rises only once
|
|
25
|
+
* every eligible account has reached it. When every one is at 100 it stays 100.
|
|
26
|
+
*/
|
|
27
|
+
function trancheCap(readings, eligible, caps = exports.DEFAULT_TRANCHE_CAPS) {
|
|
28
|
+
const map = byKey(readings);
|
|
29
|
+
const used = eligible.map((key) => usedPct(map.get(key))).filter((value) => value !== null);
|
|
30
|
+
const cap = caps.find((candidate) => used.some((value) => value < candidate)) ?? caps[caps.length - 1];
|
|
31
|
+
(0, runtime_1.emitNervesEvent)({
|
|
32
|
+
component: "engine",
|
|
33
|
+
event: "engine.quota_tranche_cap",
|
|
34
|
+
message: "computed the quota tranche cap",
|
|
35
|
+
meta: { cap, eligible: eligible.length },
|
|
36
|
+
});
|
|
37
|
+
return cap;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Stay on `current` while it is eligible and below the cap; else the first account in `order` that is eligible
|
|
41
|
+
* and below it, then any eligible one; null when none is (included requests spent everywhere: overage).
|
|
42
|
+
*/
|
|
43
|
+
function pickByTranche(current, readings, eligible, order, cap) {
|
|
44
|
+
const map = byKey(readings);
|
|
45
|
+
const below = (key) => {
|
|
46
|
+
if (key === null || !eligible.includes(key))
|
|
47
|
+
return false;
|
|
48
|
+
const used = usedPct(map.get(key));
|
|
49
|
+
return used !== null && used < cap;
|
|
50
|
+
};
|
|
51
|
+
const picked = below(current) ? current : order.find(below) ?? eligible.find(below) ?? null;
|
|
52
|
+
(0, runtime_1.emitNervesEvent)({
|
|
53
|
+
component: "engine",
|
|
54
|
+
event: "engine.quota_tranche_pick",
|
|
55
|
+
message: "picked an account by quota tranche",
|
|
56
|
+
meta: { current, picked, cap },
|
|
57
|
+
});
|
|
58
|
+
return picked;
|
|
59
|
+
}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Reads an agent's Bitwarden/Vaultwarden vault over HTTPS with Node's own crypto, so a daemon
|
|
4
|
+
* reading its runtime config and provider credentials never runs the `bw` CLI.
|
|
5
|
+
*
|
|
6
|
+
* Protocol (Bitwarden security whitepaper): prelogin for the KDF, PBKDF2-SHA256 master key,
|
|
7
|
+
* a password-grant login with the master password hash, the user key unwrapped with the
|
|
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`.
|
|
11
|
+
*/
|
|
12
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
15
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
16
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
17
|
+
}
|
|
18
|
+
Object.defineProperty(o, k2, desc);
|
|
19
|
+
}) : (function(o, m, k, k2) {
|
|
20
|
+
if (k2 === undefined) k2 = k;
|
|
21
|
+
o[k2] = m[k];
|
|
22
|
+
}));
|
|
23
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
24
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
25
|
+
}) : function(o, v) {
|
|
26
|
+
o["default"] = v;
|
|
27
|
+
});
|
|
28
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
29
|
+
var ownKeys = function(o) {
|
|
30
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
31
|
+
var ar = [];
|
|
32
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
33
|
+
return ar;
|
|
34
|
+
};
|
|
35
|
+
return ownKeys(o);
|
|
36
|
+
};
|
|
37
|
+
return function (mod) {
|
|
38
|
+
if (mod && mod.__esModule) return mod;
|
|
39
|
+
var result = {};
|
|
40
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
41
|
+
__setModuleDefault(result, mod);
|
|
42
|
+
return result;
|
|
43
|
+
};
|
|
44
|
+
})();
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.NativeVaultReader = exports.NATIVE_VAULT_LOGIN_FAILURE_RETRY_MS = exports.NATIVE_VAULT_ITEMS_FRESH_MS = exports.NativeVaultUnsupportedError = void 0;
|
|
47
|
+
exports.nodeVaultRequest = nodeVaultRequest;
|
|
48
|
+
exports.decryptCipherString = decryptCipherString;
|
|
49
|
+
exports.decryptSyncItems = decryptSyncItems;
|
|
50
|
+
exports.sharedNativeVaultReader = sharedNativeVaultReader;
|
|
51
|
+
const crypto = __importStar(require("node:crypto"));
|
|
52
|
+
const http = __importStar(require("node:http"));
|
|
53
|
+
const https = __importStar(require("node:https"));
|
|
54
|
+
const os = __importStar(require("node:os"));
|
|
55
|
+
const runtime_1 = require("../nerves/runtime");
|
|
56
|
+
const vault_setup_1 = require("./vault-setup");
|
|
57
|
+
/** The vault uses something this reader does not implement; `bw` may still read it. */
|
|
58
|
+
class NativeVaultUnsupportedError extends Error {
|
|
59
|
+
constructor(reason) {
|
|
60
|
+
super(`native vault reads do not support ${reason}`);
|
|
61
|
+
this.name = "NativeVaultUnsupportedError";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
exports.NativeVaultUnsupportedError = NativeVaultUnsupportedError;
|
|
65
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
66
|
+
/** One request with node:http(s): global fetch would load undici, about 7 MB more per process. */
|
|
67
|
+
function nodeVaultRequest(url, init, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
const client = url.startsWith("https:") ? https : http;
|
|
70
|
+
const request = client.request(url, { method: init.method, headers: init.headers }, (response) => {
|
|
71
|
+
const chunks = [];
|
|
72
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
73
|
+
response.on("end", () => resolve({ status: Number(response.statusCode), body: Buffer.concat(chunks).toString("utf8") }));
|
|
74
|
+
response.on("error", reject);
|
|
75
|
+
});
|
|
76
|
+
request.setTimeout(timeoutMs, () => request.destroy(Object.assign(new Error("request timed out"), { name: "TimeoutError" })));
|
|
77
|
+
request.on("error", reject);
|
|
78
|
+
request.end(init.body);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const defaultDeps = {
|
|
82
|
+
request: (url, init) => nodeVaultRequest(url, init),
|
|
83
|
+
now: () => Date.now(),
|
|
84
|
+
hostname: () => os.hostname(),
|
|
85
|
+
platform: process.platform,
|
|
86
|
+
};
|
|
87
|
+
const KDF_PBKDF2 = 0;
|
|
88
|
+
/** How long one sync answers reads before the next read syncs again. */
|
|
89
|
+
exports.NATIVE_VAULT_ITEMS_FRESH_MS = 30_000;
|
|
90
|
+
/** A rejected secret is not retried against the server for this long, as the bw path does. */
|
|
91
|
+
exports.NATIVE_VAULT_LOGIN_FAILURE_RETRY_MS = 5 * 60_000;
|
|
92
|
+
const TOKEN_EXPIRY_MARGIN_MS = 60_000;
|
|
93
|
+
/** Bitwarden answers some objects in PascalCase and Vaultwarden in camelCase; read either. */
|
|
94
|
+
function field(source, name) {
|
|
95
|
+
if (!source || typeof source !== "object")
|
|
96
|
+
return undefined;
|
|
97
|
+
const record = source;
|
|
98
|
+
return record[name] ?? record[name.charAt(0).toUpperCase() + name.slice(1)];
|
|
99
|
+
}
|
|
100
|
+
function stringField(source, name) {
|
|
101
|
+
const value = field(source, name);
|
|
102
|
+
return typeof value === "string" ? value : undefined;
|
|
103
|
+
}
|
|
104
|
+
function deviceType(platform) {
|
|
105
|
+
// Bitwarden's DeviceType: WindowsCLI 23, MacOsCLI 24, LinuxCLI 25.
|
|
106
|
+
if (platform === "win32")
|
|
107
|
+
return "23";
|
|
108
|
+
if (platform === "darwin")
|
|
109
|
+
return "24";
|
|
110
|
+
return "25";
|
|
111
|
+
}
|
|
112
|
+
/** One stable device per agent and host, so the server does not see a new device on every start. */
|
|
113
|
+
function deviceIdentifier(email, serverUrl, hostname) {
|
|
114
|
+
const hex = crypto.createHash("sha256").update(`ouro-native-vault\n${email.toLowerCase()}\n${serverUrl}\n${hostname}`).digest("hex");
|
|
115
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
116
|
+
}
|
|
117
|
+
/** Decrypt a type-2 cipher string ("2.<iv>|<ct>|<mac>") with a 64-byte key (32 enc + 32 mac). */
|
|
118
|
+
function decryptCipherString(value, key) {
|
|
119
|
+
const dot = value.indexOf(".");
|
|
120
|
+
const type = dot > 0 ? value.slice(0, dot) : "";
|
|
121
|
+
if (type !== "2")
|
|
122
|
+
throw new NativeVaultUnsupportedError(`cipher strings of type ${type || "unknown"}`);
|
|
123
|
+
const parts = value.slice(dot + 1).split("|");
|
|
124
|
+
if (parts.length !== 3)
|
|
125
|
+
throw new Error("malformed cipher string");
|
|
126
|
+
const [iv, ct, mac] = parts.map((part) => Buffer.from(part, "base64"));
|
|
127
|
+
if (iv.length !== 16 || mac.length !== 32 || ct.length === 0)
|
|
128
|
+
throw new Error("malformed cipher string");
|
|
129
|
+
const expected = crypto.createHmac("sha256", key.subarray(32, 64)).update(iv).update(ct).digest();
|
|
130
|
+
if (!crypto.timingSafeEqual(expected, mac))
|
|
131
|
+
throw new Error("cipher string failed its integrity check");
|
|
132
|
+
const decipher = crypto.createDecipheriv("aes-256-cbc", key.subarray(0, 32), iv);
|
|
133
|
+
return Buffer.concat([decipher.update(ct), decipher.final()]);
|
|
134
|
+
}
|
|
135
|
+
function decryptText(value, key) {
|
|
136
|
+
return typeof value === "string" && value.length > 0 ? decryptCipherString(value, key).toString("utf8") : undefined;
|
|
137
|
+
}
|
|
138
|
+
function decryptKey(value, key, what) {
|
|
139
|
+
const decrypted = decryptCipherString(value, key);
|
|
140
|
+
if (decrypted.length !== 64)
|
|
141
|
+
throw new NativeVaultUnsupportedError(`a ${decrypted.length}-byte ${what}`);
|
|
142
|
+
return decrypted;
|
|
143
|
+
}
|
|
144
|
+
/** Decrypt the personal, non-deleted items of a sync response; items in organizations are left out. */
|
|
145
|
+
function decryptSyncItems(sync, userKey) {
|
|
146
|
+
const ciphers = field(sync, "ciphers");
|
|
147
|
+
if (!Array.isArray(ciphers))
|
|
148
|
+
throw new Error("vault sync returned no item list");
|
|
149
|
+
const items = [];
|
|
150
|
+
let skipped = 0;
|
|
151
|
+
let unreadable = 0;
|
|
152
|
+
for (const cipher of ciphers) {
|
|
153
|
+
if (field(cipher, "organizationId") || field(cipher, "deletedDate")) {
|
|
154
|
+
skipped += 1;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
const itemKeyString = stringField(cipher, "key");
|
|
159
|
+
const key = itemKeyString ? decryptKey(itemKeyString, userKey, "item key") : userKey;
|
|
160
|
+
const login = field(cipher, "login");
|
|
161
|
+
const uris = field(login, "uris");
|
|
162
|
+
items.push({
|
|
163
|
+
id: String(field(cipher, "id")),
|
|
164
|
+
name: decryptText(field(cipher, "name"), key) ?? "",
|
|
165
|
+
...(login
|
|
166
|
+
? {
|
|
167
|
+
login: {
|
|
168
|
+
username: decryptText(field(login, "username"), key),
|
|
169
|
+
password: decryptText(field(login, "password"), key),
|
|
170
|
+
uris: Array.isArray(uris)
|
|
171
|
+
? uris.map((entry) => decryptText(field(entry, "uri"), key)).filter((uri) => uri !== undefined).map((uri) => ({ uri }))
|
|
172
|
+
: [],
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
: {}),
|
|
176
|
+
notes: decryptText(field(cipher, "notes"), key) ?? null,
|
|
177
|
+
revisionDate: stringField(cipher, "revisionDate"),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
if (error instanceof NativeVaultUnsupportedError)
|
|
182
|
+
throw error;
|
|
183
|
+
unreadable += 1;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return { items, skipped, unreadable };
|
|
187
|
+
}
|
|
188
|
+
class NativeVaultReader {
|
|
189
|
+
email;
|
|
190
|
+
masterPassword;
|
|
191
|
+
deps;
|
|
192
|
+
serverUrl;
|
|
193
|
+
keys = null;
|
|
194
|
+
session = null;
|
|
195
|
+
cache = null;
|
|
196
|
+
loginFailure = null;
|
|
197
|
+
constructor(serverUrl, email, masterPassword, deps = defaultDeps) {
|
|
198
|
+
this.email = email;
|
|
199
|
+
this.masterPassword = masterPassword;
|
|
200
|
+
this.deps = deps;
|
|
201
|
+
this.serverUrl = serverUrl.replace(/\/+$/, "");
|
|
202
|
+
}
|
|
203
|
+
/** Forget the synced items, so the next read syncs (after this process wrote to the vault). */
|
|
204
|
+
invalidate() {
|
|
205
|
+
this.cache = null;
|
|
206
|
+
}
|
|
207
|
+
async items() {
|
|
208
|
+
if (this.cache && this.deps.now() - this.cache.at < exports.NATIVE_VAULT_ITEMS_FRESH_MS)
|
|
209
|
+
return this.cache.items;
|
|
210
|
+
(0, runtime_1.emitNervesEvent)({
|
|
211
|
+
component: "repertoire",
|
|
212
|
+
event: "repertoire.native_vault_sync_start",
|
|
213
|
+
message: "reading the vault natively",
|
|
214
|
+
meta: { email: this.email, serverUrl: this.serverUrl },
|
|
215
|
+
});
|
|
216
|
+
let session = await this.ensureSession();
|
|
217
|
+
let sync = await this.requestSync(session);
|
|
218
|
+
if (sync === null) {
|
|
219
|
+
// The token was revoked or expired early: one fresh login, then give up.
|
|
220
|
+
this.session = null;
|
|
221
|
+
session = await this.ensureSession();
|
|
222
|
+
sync = await this.requestSync(session);
|
|
223
|
+
if (sync === null)
|
|
224
|
+
throw new Error("vault sync rejected a fresh access token (HTTP 401)");
|
|
225
|
+
}
|
|
226
|
+
const { items, skipped, unreadable } = decryptSyncItems(sync, session.userKey);
|
|
227
|
+
this.cache = { items, at: this.deps.now() };
|
|
228
|
+
(0, runtime_1.emitNervesEvent)({
|
|
229
|
+
component: "repertoire",
|
|
230
|
+
event: "repertoire.native_vault_sync_end",
|
|
231
|
+
message: "read the vault natively",
|
|
232
|
+
meta: { email: this.email, items: items.length, skipped, unreadable },
|
|
233
|
+
});
|
|
234
|
+
return items;
|
|
235
|
+
}
|
|
236
|
+
async ensureSession() {
|
|
237
|
+
if (this.session && this.deps.now() < this.session.expiresAt - TOKEN_EXPIRY_MARGIN_MS)
|
|
238
|
+
return this.session;
|
|
239
|
+
if (this.loginFailure && this.deps.now() - this.loginFailure.at < exports.NATIVE_VAULT_LOGIN_FAILURE_RETRY_MS)
|
|
240
|
+
throw this.loginFailure.error;
|
|
241
|
+
this.loginFailure = null;
|
|
242
|
+
const keys = this.keys ?? (this.keys = await this.deriveKeys());
|
|
243
|
+
const body = new URLSearchParams({
|
|
244
|
+
grant_type: "password",
|
|
245
|
+
username: this.email,
|
|
246
|
+
password: keys.hash,
|
|
247
|
+
scope: "api offline_access",
|
|
248
|
+
client_id: "cli",
|
|
249
|
+
deviceType: deviceType(this.deps.platform),
|
|
250
|
+
deviceIdentifier: deviceIdentifier(this.email, this.serverUrl, this.deps.hostname()),
|
|
251
|
+
deviceName: "ouro",
|
|
252
|
+
});
|
|
253
|
+
const response = await this.request("/identity/connect/token", {
|
|
254
|
+
method: "POST",
|
|
255
|
+
headers: {
|
|
256
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
257
|
+
"auth-email": Buffer.from(this.email).toString("base64url"),
|
|
258
|
+
},
|
|
259
|
+
body: body.toString(),
|
|
260
|
+
});
|
|
261
|
+
const token = readJson(response);
|
|
262
|
+
if (!ok(response)) {
|
|
263
|
+
if (field(token, "twoFactorProviders") || field(token, "twoFactorProviders2"))
|
|
264
|
+
throw new NativeVaultUnsupportedError("two-step login");
|
|
265
|
+
const message = stringField(field(token, "errorModel"), "message") ?? stringField(token, "error_description") ?? stringField(token, "error") ?? "";
|
|
266
|
+
if (/device/i.test(message))
|
|
267
|
+
throw new NativeVaultUnsupportedError("new-device verification");
|
|
268
|
+
const error = response.status === 400 && (stringField(token, "error") === "invalid_grant" || /username or password is incorrect/i.test(message))
|
|
269
|
+
? new Error(`vault login for ${this.email} failed: username or password is incorrect (the saved vault unlock secret was rejected)`)
|
|
270
|
+
: new Error(`vault login for ${this.email} failed: HTTP ${response.status}${message ? ` ${message}` : ""}`);
|
|
271
|
+
if (response.status === 400)
|
|
272
|
+
this.loginFailure = { error, at: this.deps.now() };
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
const accessToken = stringField(token, "access_token");
|
|
276
|
+
const protectedKey = stringField(token, "key");
|
|
277
|
+
if (!accessToken || !protectedKey)
|
|
278
|
+
throw new Error("vault login returned no access token or user key");
|
|
279
|
+
const expiresIn = Number(field(token, "expires_in"));
|
|
280
|
+
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 };
|
|
282
|
+
return this.session;
|
|
283
|
+
}
|
|
284
|
+
async deriveKeys() {
|
|
285
|
+
const response = await this.request("/identity/accounts/prelogin", {
|
|
286
|
+
method: "POST",
|
|
287
|
+
headers: { "content-type": "application/json" },
|
|
288
|
+
body: JSON.stringify({ email: this.email }),
|
|
289
|
+
});
|
|
290
|
+
if (!ok(response))
|
|
291
|
+
throw new Error(`vault prelogin for ${this.email} failed: HTTP ${response.status}`);
|
|
292
|
+
const prelogin = readJson(response);
|
|
293
|
+
const kdf = Number(field(prelogin, "kdf"));
|
|
294
|
+
const iterations = Number(field(prelogin, "kdfIterations"));
|
|
295
|
+
if (kdf !== KDF_PBKDF2)
|
|
296
|
+
throw new NativeVaultUnsupportedError(`KDF ${Number.isFinite(kdf) ? kdf : "unknown"} (only PBKDF2-SHA256)`);
|
|
297
|
+
if (!Number.isInteger(iterations) || iterations < 1)
|
|
298
|
+
throw new Error("vault prelogin returned no KDF iteration count");
|
|
299
|
+
const masterKey = await (0, vault_setup_1.deriveMasterKey)(this.masterPassword, this.email, iterations);
|
|
300
|
+
return { hash: await (0, vault_setup_1.deriveMasterPasswordHash)(masterKey, this.masterPassword), stretched: (0, vault_setup_1.deriveStretchedMasterKey)(masterKey) };
|
|
301
|
+
}
|
|
302
|
+
/** The sync body, or null when the server rejected the access token. */
|
|
303
|
+
async requestSync(session) {
|
|
304
|
+
const response = await this.request("/api/sync?excludeDomains=true", {
|
|
305
|
+
method: "GET",
|
|
306
|
+
headers: { authorization: `Bearer ${session.accessToken}` },
|
|
307
|
+
});
|
|
308
|
+
if (response.status === 401)
|
|
309
|
+
return null;
|
|
310
|
+
if (!ok(response))
|
|
311
|
+
throw new Error(`vault sync for ${this.email} failed: HTTP ${response.status}`);
|
|
312
|
+
return readJson(response);
|
|
313
|
+
}
|
|
314
|
+
async request(pathname, init) {
|
|
315
|
+
const endpoint = pathname.split("?")[0];
|
|
316
|
+
try {
|
|
317
|
+
return await this.deps.request(`${this.serverUrl}${pathname}`, init);
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
// Worded so the store's transient-error check retries it.
|
|
321
|
+
if (error instanceof Error && error.name === "TimeoutError")
|
|
322
|
+
throw new Error(`vault request to ${endpoint} timed out`);
|
|
323
|
+
const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : "";
|
|
324
|
+
throw new Error(`vault request to ${endpoint} failed: ${error instanceof Error ? error.message : String(error)}${cause}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
exports.NativeVaultReader = NativeVaultReader;
|
|
329
|
+
function readJson(response) {
|
|
330
|
+
try {
|
|
331
|
+
const parsed = JSON.parse(response.body);
|
|
332
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return {};
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const ok = (response) => response.status >= 200 && response.status < 300;
|
|
339
|
+
const sharedReaders = new Map();
|
|
340
|
+
/** One reader per vault account and secret in a process, so its stores share one login and one sync. */
|
|
341
|
+
function sharedNativeVaultReader(serverUrl, email, masterPassword) {
|
|
342
|
+
const key = crypto.createHash("sha256").update(`${serverUrl.replace(/\/+$/, "")}\n${email.toLowerCase()}\n${masterPassword}`).digest("hex");
|
|
343
|
+
let reader = sharedReaders.get(key);
|
|
344
|
+
if (!reader) {
|
|
345
|
+
reader = new NativeVaultReader(serverUrl, email, masterPassword);
|
|
346
|
+
sharedReaders.set(key, reader);
|
|
347
|
+
}
|
|
348
|
+
return reader;
|
|
349
|
+
}
|