robisie 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +6 -2
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +65 -8
- package/dist/commands.d.ts +8 -0
- package/dist/commands.js +95 -8
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/delivery-local.d.ts +2 -2
- package/dist/delivery-local.js +26 -5
- package/dist/device-login.d.ts +48 -0
- package/dist/device-login.js +523 -0
- package/dist/engine/bundle-report.json +13 -7
- package/dist/engine/tick.cjs +269 -119
- package/dist/engine-inputs.d.ts +13 -0
- package/dist/engine-inputs.js +193 -0
- package/dist/git-commit.d.ts +5 -0
- package/dist/git-commit.js +23 -0
- package/dist/helpers.js +1 -1
- package/dist/login.d.ts +29 -0
- package/dist/login.js +153 -0
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js +9 -0
- package/dist/role-registry.d.ts +1 -1
- package/dist/role-registry.js +11 -8
- package/dist/roles.d.ts +1 -1
- package/docs/ENGINE-CONFIG.md +8 -0
- package/docs/README.en.md +24 -5
- package/docs/README.md +25 -6
- package/docs/RELEASE-0.1.0.md +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { chmodSync, closeSync, constants, lstatSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
import { agentPaths } from "./agents.js";
|
|
6
|
+
import { KEY_ENV, KEY_PATTERN } from "./constants.js";
|
|
7
|
+
import { RobisieError, errorMessage } from "./context.js";
|
|
8
|
+
import { ensurePrivateDir, readKey, refuseSymlink, writeKey, writePrivate } from "./manifest.js";
|
|
9
|
+
/**
|
|
10
|
+
* `npx robisie login` — RFC 8628 device-code pairing (CONTRACT.md §1.1, §3, §7.3–7.6). The server always
|
|
11
|
+
* issues the pair A (worker) + B (owner_validator); it goes from the token response straight into the
|
|
12
|
+
* installation's files through the pair journal — never through the screen, the clipboard or the environment.
|
|
13
|
+
*/
|
|
14
|
+
const CLIENT_ID = "robisie-cli";
|
|
15
|
+
const SCOPE = "worker owner_validator";
|
|
16
|
+
const GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
17
|
+
const REVIEW_KEY_ENV = "ROBISIE_REVIEW_KEY";
|
|
18
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
19
|
+
const MAX_BACKOFF_MS = 60_000;
|
|
20
|
+
const SLOW_DOWN_STEP_SECONDS = 5;
|
|
21
|
+
export const DEFAULT_LOGIN_TIMEOUT_SECONDS = 540;
|
|
22
|
+
const DEVICE_CODE = /^[A-Za-z0-9_-]{43}$/;
|
|
23
|
+
const USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;
|
|
24
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
25
|
+
const COMMAND = /^[a-z][a-z -]{0,31}$/;
|
|
26
|
+
const RETRY = "Ponów `npx robisie login`.";
|
|
27
|
+
const FINISH = "Sprawdź połączenie, miejsce na dysku i uprawnienia katalogu, potem ponów `npx robisie login` — dokończy zapis tej samej pary.";
|
|
28
|
+
const WAITING = "Parowanie oczekuje na zatwierdzenie — to jeszcze nie jest zalogowanie. Wznów: `npx robisie login`.";
|
|
29
|
+
const OWN_START = Math.round(performance.timeOrigin);
|
|
30
|
+
const defaultIo = {
|
|
31
|
+
now: () => Date.now(),
|
|
32
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
33
|
+
hostname: hostname(),
|
|
34
|
+
processAlive: () => true,
|
|
35
|
+
};
|
|
36
|
+
function loginPaths(dir) {
|
|
37
|
+
return {
|
|
38
|
+
dir,
|
|
39
|
+
lock: join(dir, "robisie.lock"),
|
|
40
|
+
mutex: join(dir, "robisie.lock.sqlite"),
|
|
41
|
+
pending: join(dir, "login-pending.json"),
|
|
42
|
+
journal: join(dir, "pair-journal.json"),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Owned login files for uninstall, derived from the same paths used by pairing. */
|
|
46
|
+
export function loginFiles(dir) {
|
|
47
|
+
const paths = loginPaths(dir);
|
|
48
|
+
return [paths.journal, paths.pending, paths.lock, paths.mutex,
|
|
49
|
+
`${paths.mutex}-journal`, `${paths.mutex}-wal`, `${paths.mutex}-shm`];
|
|
50
|
+
}
|
|
51
|
+
function isRecord(value) {
|
|
52
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
const isUuid = (value) => typeof value === "string" && UUID.test(value);
|
|
55
|
+
const isKey = (value) => typeof value === "string" && KEY_PATTERN.test(value);
|
|
56
|
+
const isPositiveInt = (value) => Number.isInteger(value) && value > 0;
|
|
57
|
+
function readOptional(path) {
|
|
58
|
+
refuseSymlink(path);
|
|
59
|
+
try {
|
|
60
|
+
return readFileSync(path, "utf8");
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error.code === "ENOENT")
|
|
64
|
+
return null;
|
|
65
|
+
throw new RobisieError(`Nie mogę odczytać ${path}: ${errorMessage(error)}`, `Sprawdź uprawnienia do pliku ${path}.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function removeFile(path) {
|
|
69
|
+
try {
|
|
70
|
+
unlinkSync(path);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (error.code === "ENOENT")
|
|
74
|
+
return;
|
|
75
|
+
throw new RobisieError(`Nie mogę usunąć ${path}: ${errorMessage(error)}`, `Sprawdź uprawnienia do katalogu ${dirname(path)}.`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function saveJson(paths, path, value) {
|
|
79
|
+
writePrivate(paths.dir, path, `${JSON.stringify(value, null, 2)}\n`);
|
|
80
|
+
}
|
|
81
|
+
function parseLockOwner(text) {
|
|
82
|
+
try {
|
|
83
|
+
const value = JSON.parse(text);
|
|
84
|
+
if (!isRecord(value))
|
|
85
|
+
return null;
|
|
86
|
+
const { pid, startedAt, host, command, createdAt } = value;
|
|
87
|
+
return isPositiveInt(pid) && typeof startedAt === "number" && typeof host === "string" &&
|
|
88
|
+
typeof command === "string" && COMMAND.test(command) && typeof createdAt === "string" && !Number.isNaN(Date.parse(createdAt))
|
|
89
|
+
? { pid, startedAt, host, command, createdAt: new Date(createdAt).toISOString() }
|
|
90
|
+
: null;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function busy(owner) {
|
|
97
|
+
return new RobisieError(`Inna operacja robisie trwa (${owner ? `${owner.command}, od ${owner.createdAt}` : "nieznana komenda"}).`, "Zakończ ją i spróbuj ponownie.");
|
|
98
|
+
}
|
|
99
|
+
function lockIoError() {
|
|
100
|
+
return new RobisieError("Nie mogę obsłużyć blokady instalacji robisie.", "Sprawdź miejsce na dysku i uprawnienia do katalogu instalacji, potem ponów polecenie.");
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A single persistent SQLite file identifies this installation's mutex. The open transaction owns it
|
|
104
|
+
* until close/process death; the file is never renamed or removed. JSON is only last-owner diagnostics.
|
|
105
|
+
*/
|
|
106
|
+
export function acquireInstallationLock(dir, command, io = defaultIo) {
|
|
107
|
+
const paths = loginPaths(dir);
|
|
108
|
+
ensurePrivateDir(dir);
|
|
109
|
+
let db = null;
|
|
110
|
+
try {
|
|
111
|
+
for (const path of [paths.mutex, `${paths.mutex}-journal`, `${paths.mutex}-wal`, `${paths.mutex}-shm`])
|
|
112
|
+
refuseSymlink(path);
|
|
113
|
+
// Never open/close an existing inode outside SQLite: POSIX close can drop this process's locks.
|
|
114
|
+
let fd = null;
|
|
115
|
+
try {
|
|
116
|
+
fd = openSync(paths.mutex, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (error.code !== "EEXIST")
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
if (fd !== null)
|
|
124
|
+
closeSync(fd);
|
|
125
|
+
}
|
|
126
|
+
if (!lstatSync(paths.mutex).isFile())
|
|
127
|
+
throw lockIoError();
|
|
128
|
+
chmodSync(paths.mutex, 0o600);
|
|
129
|
+
const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
|
|
130
|
+
db = new DatabaseSync(paths.mutex);
|
|
131
|
+
db.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE");
|
|
132
|
+
saveJson(paths, paths.lock, { pid: process.pid, startedAt: OWN_START, host: io.hostname, command, createdAt: new Date(io.now()).toISOString() });
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
try {
|
|
136
|
+
db?.close();
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw lockIoError();
|
|
140
|
+
}
|
|
141
|
+
// Node's native SQLite errors carry a numeric errcode (SQLITE_BUSY = 5).
|
|
142
|
+
if (isRecord(error) && error.code === "ERR_SQLITE_ERROR" && typeof error.errcode === "number" && (error.errcode & 0xff) === 5) {
|
|
143
|
+
let owner = null;
|
|
144
|
+
try {
|
|
145
|
+
owner = parseLockOwner(readOptional(paths.lock) ?? "");
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// Diagnostics may be missing, damaged or racing; SQLite alone decides busy.
|
|
149
|
+
}
|
|
150
|
+
throw busy(owner);
|
|
151
|
+
}
|
|
152
|
+
throw lockIoError();
|
|
153
|
+
}
|
|
154
|
+
const held = db;
|
|
155
|
+
let released = false;
|
|
156
|
+
return () => {
|
|
157
|
+
if (released)
|
|
158
|
+
return;
|
|
159
|
+
try {
|
|
160
|
+
held.close();
|
|
161
|
+
released = true;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw lockIoError();
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
// ── HTTP ────────────────────────────────────────────────────────────────────
|
|
169
|
+
/** null = no answer (network error, timeout, refused redirect). Bodies and errors are never echoed. */
|
|
170
|
+
async function post(ctx, path, request) {
|
|
171
|
+
const headers = { accept: "application/json" };
|
|
172
|
+
let body;
|
|
173
|
+
if (request.form) {
|
|
174
|
+
headers["content-type"] = "application/x-www-form-urlencoded";
|
|
175
|
+
body = new URLSearchParams(request.form).toString();
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
headers["content-type"] = "application/json";
|
|
179
|
+
body = JSON.stringify(request.json ?? {});
|
|
180
|
+
}
|
|
181
|
+
if (request.bearer)
|
|
182
|
+
headers.authorization = `Bearer ${request.bearer}`;
|
|
183
|
+
try {
|
|
184
|
+
const res = await ctx.fetch(`${ctx.origin}${path}`, {
|
|
185
|
+
method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
186
|
+
});
|
|
187
|
+
const text = await res.text();
|
|
188
|
+
let parsed = null;
|
|
189
|
+
try {
|
|
190
|
+
parsed = JSON.parse(text);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
// not JSON
|
|
194
|
+
}
|
|
195
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
196
|
+
return { status: res.status, body: isRecord(parsed) ? parsed : null, retryAfter: retryAfter > 0 ? retryAfter : null };
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function offlineError(ctx) {
|
|
203
|
+
return new RobisieError(`Brak połączenia z ${new URL(ctx.origin).host}.`, "Sprawdź internet (albo proxy/firewall) i spróbuj ponownie.");
|
|
204
|
+
}
|
|
205
|
+
function serverError(status) {
|
|
206
|
+
return status === 503
|
|
207
|
+
? new RobisieError("Serwer robisie jest chwilowo niedostępny.", "Spróbuj ponownie za kilka minut: `npx robisie login`.")
|
|
208
|
+
: new RobisieError(`Serwer robisie odpowiedział błędem ${status}.`, "Spróbuj ponownie za kilka minut; jeśli błąd zostaje, napisz do robisie.");
|
|
209
|
+
}
|
|
210
|
+
function formatError() {
|
|
211
|
+
return new RobisieError("Serwer robisie odpowiedział w nieznanym formacie.", "Zaktualizuj paczkę: `npm i robisie@latest`, potem `npx robisie login`.");
|
|
212
|
+
}
|
|
213
|
+
function expiredError() {
|
|
214
|
+
return new RobisieError("Kod parowania wygasł bez zatwierdzenia.", "Uruchom ponownie `npx robisie login` i zatwierdź nowy kod w ciągu 10 minut.");
|
|
215
|
+
}
|
|
216
|
+
// ── Pending pairing (§1.1 p. 3) ─────────────────────────────────────────────
|
|
217
|
+
function ownUrl(ctx, value) {
|
|
218
|
+
if (typeof value !== "string")
|
|
219
|
+
return false;
|
|
220
|
+
try {
|
|
221
|
+
return new URL(value).origin === ctx.origin;
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** From the server (expires_in) or from login-pending.json (expires_at); links must stay on our origin. */
|
|
228
|
+
function asPending(ctx, value, serverNow) {
|
|
229
|
+
if (!isRecord(value))
|
|
230
|
+
return null;
|
|
231
|
+
const { device_code, user_code, verification_uri, verification_uri_complete, interval } = value;
|
|
232
|
+
const expiresAt = serverNow === null ? value.expires_at
|
|
233
|
+
: isPositiveInt(value.expires_in) ? serverNow + value.expires_in * 1000 : null;
|
|
234
|
+
if (typeof device_code !== "string" || !DEVICE_CODE.test(device_code) || typeof user_code !== "string" ||
|
|
235
|
+
!USER_CODE.test(user_code) || !ownUrl(ctx, verification_uri) || !ownUrl(ctx, verification_uri_complete) ||
|
|
236
|
+
!isPositiveInt(interval) || typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
|
|
237
|
+
return null;
|
|
238
|
+
return { device_code, user_code, verification_uri, verification_uri_complete, expires_at: expiresAt, interval };
|
|
239
|
+
}
|
|
240
|
+
function readPending(ctx, paths, now) {
|
|
241
|
+
const text = readOptional(paths.pending);
|
|
242
|
+
if (text === null)
|
|
243
|
+
return null;
|
|
244
|
+
let parsed = null;
|
|
245
|
+
try {
|
|
246
|
+
parsed = JSON.parse(text);
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
// damaged state is discarded below
|
|
250
|
+
}
|
|
251
|
+
const pending = asPending(ctx, parsed, null);
|
|
252
|
+
if (pending && pending.expires_at > now)
|
|
253
|
+
return pending;
|
|
254
|
+
removeFile(paths.pending);
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
async function startPairing(ctx, paths, options, displayName, io) {
|
|
258
|
+
const form = { client_id: CLIENT_ID, scope: SCOPE };
|
|
259
|
+
if (options.installationHint)
|
|
260
|
+
form.installation_hint = options.installationHint;
|
|
261
|
+
if (displayName)
|
|
262
|
+
form.display_name = displayName;
|
|
263
|
+
const reply = await post(ctx, "/api/cli/device_authorization", { form });
|
|
264
|
+
if (!reply)
|
|
265
|
+
throw offlineError(ctx);
|
|
266
|
+
if (reply.status === 429) {
|
|
267
|
+
throw new RobisieError("Za dużo prób parowania z tego adresu.", `Odczekaj ${reply.retryAfter ?? 600} s i ponów \`npx robisie login\`.`);
|
|
268
|
+
}
|
|
269
|
+
if (reply.status !== 200)
|
|
270
|
+
throw serverError(reply.status);
|
|
271
|
+
const pending = asPending(ctx, reply.body, io.now());
|
|
272
|
+
if (!pending)
|
|
273
|
+
throw formatError();
|
|
274
|
+
saveJson(paths, paths.pending, pending);
|
|
275
|
+
return pending;
|
|
276
|
+
}
|
|
277
|
+
function parseIssued(body) {
|
|
278
|
+
if (!body)
|
|
279
|
+
return null;
|
|
280
|
+
const { access_token: A, review_access_token: B, installation_id, pair_id, token_type } = body;
|
|
281
|
+
return token_type === "Bearer" && isKey(A) && isKey(B) && A !== B && isUuid(installation_id) && isUuid(pair_id)
|
|
282
|
+
? { A, B, installation_id: installation_id.toLowerCase(), pair_id: pair_id.toLowerCase() }
|
|
283
|
+
: null;
|
|
284
|
+
}
|
|
285
|
+
/** RFC 8628 §3.4–3.5. null = local timeout (the pairing stays valid and resumable). */
|
|
286
|
+
async function pollForPair(ctx, paths, pending, timeoutAt, io) {
|
|
287
|
+
let backoffMs = null;
|
|
288
|
+
for (;;) {
|
|
289
|
+
const delay = backoffMs ?? pending.interval * 1000;
|
|
290
|
+
const at = io.now() + delay;
|
|
291
|
+
if (at >= pending.expires_at && pending.expires_at <= timeoutAt) {
|
|
292
|
+
removeFile(paths.pending);
|
|
293
|
+
throw expiredError();
|
|
294
|
+
}
|
|
295
|
+
if (at > timeoutAt)
|
|
296
|
+
return null;
|
|
297
|
+
await io.sleep(delay);
|
|
298
|
+
const reply = await post(ctx, "/api/cli/token", {
|
|
299
|
+
form: { grant_type: GRANT_TYPE, device_code: pending.device_code, client_id: CLIENT_ID },
|
|
300
|
+
});
|
|
301
|
+
if (!reply || reply.status >= 500) {
|
|
302
|
+
backoffMs = Math.min(delay * 2, MAX_BACKOFF_MS);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (reply.status === 429) {
|
|
306
|
+
backoffMs = Math.max(pending.interval, reply.retryAfter ?? 0) * 1000;
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
backoffMs = null;
|
|
310
|
+
if (reply.status === 200) {
|
|
311
|
+
const issued = parseIssued(reply.body);
|
|
312
|
+
if (issued)
|
|
313
|
+
return issued;
|
|
314
|
+
removeFile(paths.pending);
|
|
315
|
+
throw formatError();
|
|
316
|
+
}
|
|
317
|
+
switch (reply.body?.error) {
|
|
318
|
+
case "authorization_pending":
|
|
319
|
+
continue;
|
|
320
|
+
case "slow_down":
|
|
321
|
+
pending.interval += SLOW_DOWN_STEP_SECONDS;
|
|
322
|
+
saveJson(paths, paths.pending, pending);
|
|
323
|
+
continue;
|
|
324
|
+
case "access_denied":
|
|
325
|
+
removeFile(paths.pending);
|
|
326
|
+
throw new RobisieError("Parowanie zostało odrzucone w przeglądarce.", "Jeśli to Ty albo Twój agent uruchomiliście logowanie, ponów `npx robisie login` i zatwierdź kod.");
|
|
327
|
+
case "expired_token":
|
|
328
|
+
removeFile(paths.pending);
|
|
329
|
+
throw expiredError();
|
|
330
|
+
case "invalid_grant":
|
|
331
|
+
removeFile(paths.pending);
|
|
332
|
+
throw new RobisieError("Kod parowania nie jest już ważny (mógł zostać już użyty).", RETRY);
|
|
333
|
+
default:
|
|
334
|
+
throw serverError(reply.status);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// ── Pair journal (§7.3 J1–J7) and restoring the old generation (R) ──────────
|
|
339
|
+
function asJournal(value) {
|
|
340
|
+
if (!isRecord(value))
|
|
341
|
+
return null;
|
|
342
|
+
const { pair_id, installation_id, A, B, old_A, old_B, step } = value;
|
|
343
|
+
const optional = (v) => v === null || typeof v === "string";
|
|
344
|
+
return isUuid(pair_id) && isUuid(installation_id) && isKey(A) && isKey(B) && optional(old_A) && optional(old_B) && typeof step === "string"
|
|
345
|
+
? { pair_id, installation_id, A, B, old_A, old_B, old_copies: value.old_copies ?? null, step }
|
|
346
|
+
: null;
|
|
347
|
+
}
|
|
348
|
+
function readJournal(paths) {
|
|
349
|
+
const text = readOptional(paths.journal);
|
|
350
|
+
if (text === null)
|
|
351
|
+
return null;
|
|
352
|
+
let journal = null;
|
|
353
|
+
try {
|
|
354
|
+
journal = asJournal(JSON.parse(text));
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
// reported below
|
|
358
|
+
}
|
|
359
|
+
if (journal)
|
|
360
|
+
return journal;
|
|
361
|
+
throw new RobisieError(`Dziennik parowania ${paths.journal} jest uszkodzony — klucze tej instalacji są zablokowane.`, `Przenieś ${paths.journal} poza katalog instalacji (zawiera klucze — nikomu go nie udostępniaj), potem uruchom \`npx robisie login\`.`);
|
|
362
|
+
}
|
|
363
|
+
function beginJournal(dir, paths, issued, copies) {
|
|
364
|
+
const journal = {
|
|
365
|
+
...issued,
|
|
366
|
+
old_A: readKey(dir, "key"),
|
|
367
|
+
old_B: readKey(dir, "review-key"),
|
|
368
|
+
old_copies: copies ? (copies.capture() ?? null) : null,
|
|
369
|
+
step: "J1",
|
|
370
|
+
};
|
|
371
|
+
saveJson(paths, paths.journal, journal);
|
|
372
|
+
return journal;
|
|
373
|
+
}
|
|
374
|
+
/** J2 / §7.5: both keys answer for this very pair with their own roles. */
|
|
375
|
+
async function verifyPair(ctx, journal) {
|
|
376
|
+
for (const [key, role] of [[journal.A, "worker"], [journal.B, "owner_validator"]]) {
|
|
377
|
+
const reply = await post(ctx, "/api/cli/whoami", { bearer: key });
|
|
378
|
+
if (!reply)
|
|
379
|
+
return "unknown";
|
|
380
|
+
if (reply.status === 401)
|
|
381
|
+
return "revoked";
|
|
382
|
+
if (reply.status !== 200 || !reply.body)
|
|
383
|
+
return "unknown";
|
|
384
|
+
const { role: actual, pair_id, installation_id } = reply.body;
|
|
385
|
+
if (actual !== role || pair_id !== journal.pair_id || installation_id !== journal.installation_id)
|
|
386
|
+
return "revoked";
|
|
387
|
+
}
|
|
388
|
+
return "ok";
|
|
389
|
+
}
|
|
390
|
+
async function confirmPair(ctx, journal) {
|
|
391
|
+
const reply = await post(ctx, "/api/cli/confirm", { bearer: journal.A, json: { pair_id: journal.pair_id } });
|
|
392
|
+
if (!reply)
|
|
393
|
+
return "unknown";
|
|
394
|
+
if (reply.status === 401)
|
|
395
|
+
return "revoked";
|
|
396
|
+
return reply.status === 200 && reply.body?.confirmed === true && reply.body.pair_id === journal.pair_id ? "ok" : "unknown";
|
|
397
|
+
}
|
|
398
|
+
function putKey(dir, slot, value) {
|
|
399
|
+
if (value === null)
|
|
400
|
+
removeFile(join(dir, slot));
|
|
401
|
+
else
|
|
402
|
+
writeKey(dir, value, slot);
|
|
403
|
+
}
|
|
404
|
+
/** R: writes the old values back (idempotent, independent of `step`); the journal goes only after a control read. */
|
|
405
|
+
function restoreOldGeneration(dir, paths, journal, copies) {
|
|
406
|
+
try {
|
|
407
|
+
putKey(dir, "key", journal.old_A);
|
|
408
|
+
putKey(dir, "review-key", journal.old_B);
|
|
409
|
+
copies?.restore(journal.old_copies);
|
|
410
|
+
if (readKey(dir, "key") !== journal.old_A || readKey(dir, "review-key") !== journal.old_B)
|
|
411
|
+
throw new Error("odczyt kontrolny");
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
throw new RobisieError("Nie udało się przywrócić poprzednich kluczy instalacji.", "Sprawdź miejsce na dysku i uprawnienia katalogu, potem ponów polecenie.");
|
|
415
|
+
}
|
|
416
|
+
removeFile(paths.journal);
|
|
417
|
+
removeFile(paths.pending);
|
|
418
|
+
const firstInstall = journal.old_A === null && journal.old_B === null;
|
|
419
|
+
throw new RobisieError(firstInstall ? "Nowa para kluczy została unieważniona; instalacja wraca do stanu bez kluczy."
|
|
420
|
+
: "Nowa para kluczy została unieważniona — przywrócono poprzednie klucze instalacji.", firstInstall ? "Uruchom `npx robisie login`." : RETRY);
|
|
421
|
+
}
|
|
422
|
+
function ambiguous() {
|
|
423
|
+
return new RobisieError("Brak jednoznacznej odpowiedzi serwera o nowej parze kluczy.", FINISH);
|
|
424
|
+
}
|
|
425
|
+
function journalStep(paths, journal, step, write) {
|
|
426
|
+
try {
|
|
427
|
+
write();
|
|
428
|
+
journal.step = step;
|
|
429
|
+
saveJson(paths, paths.journal, journal);
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
throw new RobisieError("Zapis nowej pary kluczy został przerwany.", FINISH);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
async function completeJournal(ctx, dir, paths, journal, copies) {
|
|
436
|
+
const valid = await verifyPair(ctx, journal);
|
|
437
|
+
if (valid === "revoked")
|
|
438
|
+
restoreOldGeneration(dir, paths, journal, copies);
|
|
439
|
+
if (valid === "unknown")
|
|
440
|
+
throw ambiguous();
|
|
441
|
+
journalStep(paths, journal, "J3", () => writeKey(dir, journal.A, "key"));
|
|
442
|
+
journalStep(paths, journal, "J4", () => writeKey(dir, journal.B, "review-key"));
|
|
443
|
+
journalStep(paths, journal, "J5", () => copies?.apply({ key: journal.A, installationId: journal.installation_id, pairId: journal.pair_id }));
|
|
444
|
+
const confirmed = await confirmPair(ctx, journal);
|
|
445
|
+
if (confirmed === "revoked")
|
|
446
|
+
restoreOldGeneration(dir, paths, journal, copies);
|
|
447
|
+
if (confirmed === "unknown")
|
|
448
|
+
throw ambiguous();
|
|
449
|
+
removeFile(paths.journal);
|
|
450
|
+
removeFile(paths.pending);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Finishes (or rolls back) an interrupted pair write. Every command calls it under the installation lock
|
|
454
|
+
* before touching the key files; while it throws, the keys in the files must not be used.
|
|
455
|
+
* Returns true when a journal was found and the pair is now saved and confirmed.
|
|
456
|
+
*/
|
|
457
|
+
export async function resumePairJournal(ctx, dir, copies) {
|
|
458
|
+
const paths = loginPaths(dir);
|
|
459
|
+
const journal = readJournal(paths);
|
|
460
|
+
if (!journal)
|
|
461
|
+
return false;
|
|
462
|
+
await completeJournal(ctx, dir, paths, journal, copies);
|
|
463
|
+
return true;
|
|
464
|
+
}
|
|
465
|
+
// ── Command ─────────────────────────────────────────────────────────────────
|
|
466
|
+
/** B stays out of every inherited environment, as in maszynista/engine-context.ts. Values are never printed. */
|
|
467
|
+
function isolateReviewKey(ctx) {
|
|
468
|
+
for (const name of [KEY_ENV, REVIEW_KEY_ENV]) {
|
|
469
|
+
if (ctx.env[name] !== undefined || process.env[name] !== undefined) {
|
|
470
|
+
ctx.err(`Stara wartość ${name} w środowisku jest ignorowana — otwórz nowy terminal.`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
delete process.env[REVIEW_KEY_ENV];
|
|
474
|
+
}
|
|
475
|
+
/** Exit codes (F10): 0 = pair saved and confirmed, 2 = still waiting for approval, 1 = failure. */
|
|
476
|
+
export async function deviceLogin(ctx, options) {
|
|
477
|
+
const io = { ...defaultIo, ...options.io };
|
|
478
|
+
const dir = agentPaths(ctx).clientDir;
|
|
479
|
+
const paths = loginPaths(dir);
|
|
480
|
+
const displayName = options.displayName ?? io.hostname;
|
|
481
|
+
let release = null;
|
|
482
|
+
let result = 1;
|
|
483
|
+
try {
|
|
484
|
+
isolateReviewKey(ctx);
|
|
485
|
+
release = acquireInstallationLock(dir, "login", io);
|
|
486
|
+
if (!(await resumePairJournal(ctx, dir, options.copies))) {
|
|
487
|
+
const timeoutAt = io.now() + (options.timeoutSeconds ?? DEFAULT_LOGIN_TIMEOUT_SECONDS) * 1000;
|
|
488
|
+
const pending = readPending(ctx, paths, io.now()) ?? await startPairing(ctx, paths, options, displayName, io);
|
|
489
|
+
ctx.out(`Otwórz w przeglądarce zalogowanej do robisie.app: ${pending.verification_uri_complete}`);
|
|
490
|
+
ctx.out(`Albo wejdź na ${pending.verification_uri} i wpisz kod: ${pending.user_code}`);
|
|
491
|
+
const issued = options.wait ? await pollForPair(ctx, paths, pending, timeoutAt, io) : null;
|
|
492
|
+
if (!issued) {
|
|
493
|
+
ctx.out(WAITING);
|
|
494
|
+
result = 2;
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
await completeJournal(ctx, dir, paths, beginJournal(dir, paths, issued, options.copies), options.copies);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (result !== 2) {
|
|
501
|
+
ctx.out(`Zalogowano. Instalacja «${displayName}» ma nową parę kluczy.`);
|
|
502
|
+
result = 0;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
const known = error instanceof RobisieError ? error
|
|
507
|
+
: new RobisieError("Logowanie przerwał nieoczekiwany błąd.", "Ponów `npx robisie login` — dokończy zapis od miejsca przerwania.");
|
|
508
|
+
ctx.err(`✗ ${known.message}`);
|
|
509
|
+
ctx.err(`Następny krok: ${known.nextStep}`);
|
|
510
|
+
}
|
|
511
|
+
finally {
|
|
512
|
+
try {
|
|
513
|
+
release?.();
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
const error = lockIoError();
|
|
517
|
+
ctx.err(`✗ ${error.message}`);
|
|
518
|
+
ctx.err(`Następny krok: ${error.nextStep}`);
|
|
519
|
+
result = 1;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return result;
|
|
523
|
+
}
|
|
@@ -655,6 +655,12 @@
|
|
|
655
655
|
"kind": "import-statement",
|
|
656
656
|
"category": "builtin"
|
|
657
657
|
},
|
|
658
|
+
{
|
|
659
|
+
"module": "packages/client/src/git-commit.ts",
|
|
660
|
+
"path": "node:child_process",
|
|
661
|
+
"kind": "import-statement",
|
|
662
|
+
"category": "builtin"
|
|
663
|
+
},
|
|
658
664
|
{
|
|
659
665
|
"module": "packages/client/src/delivery-local.ts",
|
|
660
666
|
"path": "node:child_process",
|
|
@@ -1649,20 +1655,20 @@
|
|
|
1649
1655
|
"staticOperations": {
|
|
1650
1656
|
"beforePreflight": {
|
|
1651
1657
|
"module": "maszynista/tick.ts",
|
|
1652
|
-
"startLine":
|
|
1653
|
-
"endLine":
|
|
1658
|
+
"startLine": 9177,
|
|
1659
|
+
"endLine": 9289,
|
|
1654
1660
|
"text": "export async function main(): Promise<number> {\n const start = standaloneStartCheck({ filename: __filename, env: process.env });\n if (start.standalone && !start.ok) {\n console.error(start.message);\n process.exitCode = 78;\n return 78;\n }\n let installation: EngineContext;\n try { installation = createEngineContext(currentEngine(), {\n loadEnvironment: loadEnvFiles, preflight, baseRef: engineBaseRef, refreshBase: fetchMain,\n disk: defaultDiskPressureDependencies, workerContext: loadNorthStar,\n controlEnv: hostEnv, workerEnv: executionEnv, prepareWorktree: prepareHostWorktree, workerArtifacts: createWorkerTmpdir,\n notify: async (card, reason) => { decisionForReksio(card, reason, \"Rozstrzygnij na karcie\", \"\", \"\"); return { outcome: \"recorded\", ref: DECISIONS_REKSIO }; },\n hostOperations: hostOperationsPhase,\n activation: { confirmLoaded, finishHostActivation, readActivationState, recoverTickTimeout, runEnabledAuto },\n }, git, log); }\n catch (error) {\n if (!engineClient()) throw error;\n console.error(`HOLD kontekst klienta: ${clientTickFailure(error)}`);\n process.exitCode = 78;\n return 78;\n }\n const previousInstallation = tickInstallation;\n const hostErrorText = errorText;\n const client = engineClient();\n const result: { outcome: \"ok\" | \"retry\" | \"stop\"; reason: string; cleanup: boolean } = { outcome: \"ok\", reason: \"\", cleanup: false };\n const stopClient = (reason = clientTickFailure()): void => {\n if (client && result.outcome !== \"stop\") { result.outcome = \"stop\"; result.reason = reason; }\n };\n let code = 2;\n try { code = await q.withPlannerQueries(installation.planner, async () => {\n tickInstallation = installation;\n const errorText = client ? clientTickFailure : hostErrorText;\n const loadEnvFiles = installation.loadEnvironment;\n const preflight = () => {\n const actor = installation.preflight();\n return { uid: actor.kind === \"db\" ? actor.uid : API_ACTOR };\n };\n const { confirmLoaded, finishHostActivation, readActivationState, recoverTickTimeout, runEnabledAuto } = installation.activation;\n const smokeOnly = DRY && process.env.MASZYNISTA_SMOKE === \"1\";\n if (!DRY) {\n const acquire = (): boolean => tryCreateTickLock(LOCK);\n if (!acquire()) {\n const raw = readFileSync(LOCK, \"utf8\"), pid = Number(raw);\n if (!Number.isSafeInteger(pid) || pid <= 0) { console.log(\"tick lock bez poprawnego PID — HOLD\"); return 0; }\n try { process.kill(pid, 0); console.log(`tick już trwa (pid ${pid})`); return 0; }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error; }\n if (readFileSync(LOCK, \"utf8\") === raw) unlinkSync(LOCK);\n if (!acquire()) { console.log(\"tick już trwa\"); return 0; }\n }\n }\n skippedCardEvents.clear();\n let s = parseState(null).state;\n // Internal smoke handoff: the child cannot outlive the parent's reserved budget.\n const smokeLimit = DRY ? Number(process.env.MASZYNISTA_SMOKE_TIMEOUT_MS) : NaN;\n let stateLoaded = false;\n let tickStarted: string | undefined;\n let outcome: \"ok\" | \"failed\" = \"ok\";\n let runtimeFailed = false;\n let observedLoaded = \"UNKNOWN\";\n let tickPhase = \"startup\";\n const deadlineAlarm = armTickDeadline(() => s, Number.isSafeInteger(smokeLimit) && smokeLimit > 0\n ? Math.min(TICK_LIMIT_MS, smokeLimit) : TICK_LIMIT_MS, () => ({ phase: tickPhase, observedLoaded }));\n let hostReady = false;\n let hostBoard: { uid: string; projectId: string } | undefined;\n let activationCards: CardLike[] = [];\n let activationCardsKnown = false;\n let blockedBefore = 0;\n const clientStopped = (): boolean => {\n if (client && (outcome === \"failed\" || (!DRY && s.blocked > blockedBefore))) stopClient();\n if (client && result.outcome === \"stop\") outcome = \"failed\";\n return client && result.outcome === \"stop\";\n };\n let hostPhaseStarted = false;\n const hostPhase = async (): Promise<boolean> => {\n if (smokeOnly || !hostReady || hostPhaseStarted) return false;\n hostPhaseStarted = true;\n tickPhase = \"host\";\n if (hostBoard) {\n const { uid: boardUid, projectId: boardProject } = hostBoard;\n try {\n await runEnabledAuto({ state: s, loadedSha: observedLoaded, repo: REPO, logPath: LOG, tick: s.tick, stateDir: hostStateDir(),\n now: new Date().toISOString(), activation: readActivationState(hostStateDir()), dryRun: DRY }, {\n listCards: async () => scanTasks(boardUid, boardProject, { full: true, statuses: [\"delivered\"],\n detailsKeys: ENABLED_SCAN_DETAILS_KEYS }),\n getTask: id => q.getTask(boardUid, id),\n appendDetail: async (id, patch) => { await appendBoundedDetail(boardUid, id, patch); },\n saveState: writeState,\n alarm: hostActivationAlarm,\n log,\n });\n } catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL ENABLED auto: ${errorText(error)}`); }\n } else log(\"ENABLED auto: UNKNOWN — brak odczytu projektu; dowód karty czeka na dostęp do tablicy\");\n try {\n const result = await engineRunHostActivation({ repo: REPO, stateDir: hostStateDir(), cards: activationCards, cardsKnown: activationCardsKnown, tick: s.tick, dryRun: DRY }, {\n git, remainingTickMs, alarm: hostActivationAlarm, infrastructureChecks, infrastructurePullRequest, log: line => log(`host-activation: ${line}`),\n });\n log(`host-activation: code=${result.code} target=${result.target ?? \"UNKNOWN\"}${result.detail ? ` reason=${result.detail}` : \"\"}`);\n if (result.code === \"activate\" && result.target) {\n lastTick(s, \"activation\", `aktywacja ${result.target}; ogon odroczony`, outcome === \"ok\");\n return true;\n }\n } catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL aktywacja: ${errorText(error)}`); }\n return false;\n };\n try {\n observedLoaded = loadedSha = readLoadedSha(REPO);\n s = readState((await engineFjConfig()).enabled);\n stateLoaded = true; blockedBefore = s.blocked;\n s.tick++; tickStarted = new Date().toISOString(); s.lastTickAt = tickStarted;\n log(`tick_started tick=${s.tick} at=${tickStarted} duration=UNKNOWN loaded=${loadedSha}`);\n loadEnvFiles();\n const { uid } = preflight();"
|
|
1655
1661
|
},
|
|
1656
1662
|
"finalization": {
|
|
1657
1663
|
"module": "maszynista/tick.ts",
|
|
1658
|
-
"startLine":
|
|
1659
|
-
"endLine":
|
|
1664
|
+
"startLine": 9578,
|
|
1665
|
+
"endLine": 9630,
|
|
1660
1666
|
"text": " } finally {\n // A persisted terminal FAIL is a card result; every unexpected exception above\n // remains a runtime failure, including DB errors inside card handling.\n if (!DRY && s.blocked > blockedBefore) {\n outcome = \"failed\";\n try { log(`FAIL: licznik blocked wzrósł ${blockedBefore} → ${s.blocked}; outcome=failed`); }\n catch (error) { console.error(`zapis licznika blocked: ${errorText(error)}`); }\n }\n clientStopped();\n // Early board failure still reaches the same host phase, at most once per tick.\n await hostPhase();\n tickPhase = \"finalizing\";\n try { if (!DRY) await finishHostActivation({ stateDir: hostStateDir(), outcome, tick: s.tick, runtimeFailed, observedLoaded }, { alarm: hostActivationAlarm, log }); }\n catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL breaker aktywacji: ${errorText(error)}`); }\n clientStopped();\n try { if (stateLoaded) writeState(s); }\n catch (error) { runtimeFailed = true; outcome = \"failed\"; if (!client) throw error; stopClient(); result.cleanup = true; }\n finally {\n if (!DRY) {\n try { if (readFileSync(LOCK, \"utf8\") === String(process.pid)) unlinkSync(LOCK); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") { if (!client) throw error; stopClient(); result.cleanup = true; } }\n }\n const at = new Date().toISOString();\n const duration = tickStarted ? `${(Date.parse(at) - Date.parse(tickStarted)) / 1000}s` : \"UNKNOWN\";\n try {\n const { total, ops } = drainEgressCounters();\n const sorted = Object.entries(ops).sort(([, a], [, b]) => b.bytes - a.bytes);\n const summary = sorted.filter(([op]) => !op.includes(\":\")).slice(0, 12)\n .map(([op, counter]) => `${op}:${counter.calls}:${counter.bytes}`).join(\",\");\n const variants = sorted.filter(([op]) => op.includes(\":\")).slice(0, 6)\n .map(([op, counter]) => `${op}:${counter.calls}:${counter.bytes}`).join(\",\");\n log(`egress tick=${s.tick} total=${total} ops=${summary} variants=${variants}`);\n } catch { /* Optional metrics must never interrupt tick cleanup. */ }\n try { refreshTickReport(observedLoaded); log(`tick_finished tick=${s.tick} at=${at} outcome=${client && result.outcome === \"retry\" ? \"retry\" : outcome} duration=${duration} loaded=${loadedSha}`); }\n finally { clearTimeout(deadlineAlarm); tickDeadline = Number.POSITIVE_INFINITY; }\n }\n }\n }); } catch (error) {\n if (!client) throw error;\n stopClient(); result.cleanup = true;\n } finally {\n tickInstallation = previousInstallation;\n try { await installation.close(); }\n catch (error) {\n if (client) { stopClient(); result.cleanup = true; }\n else safeLog(`Zamknięcie instalacji nieudane: ${String(error)}`);\n }\n }\n if (client && result.outcome !== \"ok\") console.error(`Fabryka ${result.outcome === \"stop\" ? \"zatrzymana\" : \"retry\"}: ${result.reason}${result.cleanup ? \"; finalizacja niepotwierdzona — sprawdź stan i blokadę\" : \"\"}`);\n return client && result.outcome === \"stop\" ? 2 : code;\n}\n\nif (require.main === module && process.argv[2] !== \"--opencode-runner\") {"
|
|
1661
1667
|
},
|
|
1662
1668
|
"refreshTickReport": {
|
|
1663
1669
|
"module": "maszynista/tick.ts",
|
|
1664
|
-
"startLine":
|
|
1665
|
-
"endLine":
|
|
1670
|
+
"startLine": 813,
|
|
1671
|
+
"endLine": 824,
|
|
1666
1672
|
"text": "export function refreshTickReport(observedLoaded = readLoadedSha(REPO)): void {\n loadedSha = observedLoaded;\n try { mainSha = git([\"rev-parse\", engineBranchRef()]); }\n catch (error) { mainSha = \"UNKNOWN\"; log(`Nie można odczytać main SHA: ${errorText(error)}`); }\n if (DRY) return;\n try {\n const content = readFileSync(LAST_TICK, \"utf8\");\n writeFileSync(LAST_TICK, `${content.replace(/^- (?:loaded|main):.*\\n?/gm, \"\")}- loaded: ${loadedSha}\\n- main: ${mainSha}\\n`);\n } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n}\n\nfunction writeAtomic(file: string, content: string): void {"
|
|
1667
1673
|
},
|
|
1668
1674
|
"importTime": {
|
|
@@ -1682,6 +1688,6 @@
|
|
|
1682
1688
|
"status": 0,
|
|
1683
1689
|
"signal": null,
|
|
1684
1690
|
"stdout": "v24.3.0\n",
|
|
1685
|
-
"stderr": "(node:
|
|
1691
|
+
"stderr": "(node:14004) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n(Use `node --trace-warnings ...` to show where the warning was created)\n"
|
|
1686
1692
|
}
|
|
1687
1693
|
}
|