@hackersbaby/plugin 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __commonJS = (cb, mod) => function __require() {
10
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
14
  };
@@ -26,6 +29,41 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
29
  mod
27
30
  ));
28
31
 
32
+ // src/config.ts
33
+ function sessionStateFile(source) {
34
+ return import_path.default.join(CONFIG_DIR, `active-session-${source}.json`);
35
+ }
36
+ function ensureConfigDir() {
37
+ if (!import_fs.default.existsSync(CONFIG_DIR)) {
38
+ import_fs.default.mkdirSync(CONFIG_DIR, { recursive: true });
39
+ }
40
+ }
41
+ function loadConfig() {
42
+ try {
43
+ if (!import_fs.default.existsSync(CONFIG_FILE)) return null;
44
+ const raw = import_fs.default.readFileSync(CONFIG_FILE, "utf-8");
45
+ return JSON.parse(raw);
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ function saveConfig(config) {
51
+ ensureConfigDir();
52
+ import_fs.default.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
53
+ }
54
+ var import_fs, import_path, import_os, CONFIG_DIR, CONFIG_FILE, QUEUE_FILE;
55
+ var init_config = __esm({
56
+ "src/config.ts"() {
57
+ "use strict";
58
+ import_fs = __toESM(require("fs"));
59
+ import_path = __toESM(require("path"));
60
+ import_os = __toESM(require("os"));
61
+ CONFIG_DIR = import_path.default.join(import_os.default.homedir(), ".hackersbaby");
62
+ CONFIG_FILE = import_path.default.join(CONFIG_DIR, "config.json");
63
+ QUEUE_FILE = import_path.default.join(CONFIG_DIR, "queue.jsonl");
64
+ }
65
+ });
66
+
29
67
  // ../shared/dist/types.js
30
68
  var require_types = __commonJS({
31
69
  "../shared/dist/types.js"(exports2) {
@@ -164,185 +202,175 @@ var require_dist = __commonJS({
164
202
  }
165
203
  });
166
204
 
167
- // src/collector.ts
168
- var import_uuid = require("uuid");
169
-
170
- // src/config.ts
171
- var import_fs = __toESM(require("fs"));
172
- var import_path = __toESM(require("path"));
173
- var import_os = __toESM(require("os"));
174
- var CONFIG_DIR = import_path.default.join(import_os.default.homedir(), ".hackersbaby");
175
- var CONFIG_FILE = import_path.default.join(CONFIG_DIR, "config.json");
176
- var QUEUE_FILE = import_path.default.join(CONFIG_DIR, "queue.jsonl");
177
- function sessionStateFile(source) {
178
- return import_path.default.join(CONFIG_DIR, `active-session-${source}.json`);
179
- }
180
- function ensureConfigDir() {
181
- if (!import_fs.default.existsSync(CONFIG_DIR)) {
182
- import_fs.default.mkdirSync(CONFIG_DIR, { recursive: true });
183
- }
184
- }
185
- function loadConfig() {
186
- try {
187
- if (!import_fs.default.existsSync(CONFIG_FILE)) return null;
188
- const raw = import_fs.default.readFileSync(CONFIG_FILE, "utf-8");
189
- return JSON.parse(raw);
190
- } catch {
191
- return null;
192
- }
193
- }
194
- function saveConfig(config) {
195
- ensureConfigDir();
196
- import_fs.default.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
197
- }
198
-
199
205
  // src/api-client.ts
200
- var import_shared = __toESM(require_dist());
201
- var APIClient = class {
202
- config = loadConfig();
203
- sessionSecret = null;
204
- chainHash = "0000000000000000";
205
- get headers() {
206
- return {
207
- "Content-Type": "application/json",
208
- Authorization: `Bearer ${this.config?.token || ""}`
209
- };
210
- }
211
- /** Register session with server and get cryptographic secret */
212
- async startSession(sessionId) {
213
- try {
214
- const server = this.config?.server || "https://hackers.baby";
215
- const res = await fetch(`${server}/api/sessions/start`, {
216
- method: "POST",
217
- headers: this.headers,
218
- body: JSON.stringify({ session_id: sessionId })
219
- });
220
- if (res.ok) {
221
- const data = await res.json();
222
- this.sessionSecret = data.session_secret;
223
- this.chainHash = data.initial_chain_hash;
224
- return true;
206
+ var import_shared, APIClient;
207
+ var init_api_client = __esm({
208
+ "src/api-client.ts"() {
209
+ "use strict";
210
+ init_config();
211
+ import_shared = __toESM(require_dist());
212
+ APIClient = class {
213
+ config = loadConfig();
214
+ sessionSecret = null;
215
+ chainHash = "0000000000000000";
216
+ onChainUpdate = null;
217
+ /** Set callback to persist chain state between hook processes */
218
+ setChainUpdateCallback(cb) {
219
+ this.onChainUpdate = cb;
225
220
  }
226
- return false;
227
- } catch {
228
- return false;
229
- }
230
- }
231
- async sendBatch(batch) {
232
- try {
233
- const server = this.config?.server || "https://hackers.baby";
234
- if (this.sessionSecret) {
235
- const prevChainHash = this.chainHash;
236
- const newChainHash = (0, import_shared.computeChainHash)(batch.events, prevChainHash);
237
- const signature = (0, import_shared.signBatch)(batch.session_id, batch.events, newChainHash, this.sessionSecret);
238
- batch.signature = signature;
239
- batch.chain_hash = newChainHash;
240
- batch.prev_chain_hash = prevChainHash;
241
- this.chainHash = newChainHash;
221
+ /** Restore crypto state from a previous session */
222
+ restoreCryptoState(secret, chainHash) {
223
+ this.sessionSecret = secret;
224
+ this.chainHash = chainHash;
242
225
  }
243
- const res = await fetch(`${server}/api/scores/batch`, {
244
- method: "POST",
245
- headers: this.headers,
246
- body: JSON.stringify(batch)
247
- });
248
- return res.ok;
249
- } catch {
250
- return false;
251
- }
252
- }
253
- async refreshTokenIfNeeded() {
254
- if (!this.config) return;
255
- try {
256
- const parts = this.config.token.split(".");
257
- if (parts.length !== 3) return;
258
- const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
259
- const expMs = payload.exp * 1e3;
260
- const oneDayMs = 24 * 60 * 60 * 1e3;
261
- if (Date.now() + oneDayMs < expMs) return;
262
- const res = await fetch(`${this.config.server}/api/auth/cli-token/refresh`, {
263
- method: "POST",
264
- headers: this.headers,
265
- body: JSON.stringify({ refresh_token: this.config.refresh_token })
266
- });
267
- if (res.ok) {
268
- const data = await res.json();
269
- if (data.token) {
270
- this.config.token = data.token;
271
- if (data.refresh_token) this.config.refresh_token = data.refresh_token;
272
- saveConfig(this.config);
226
+ get headers() {
227
+ return {
228
+ "Content-Type": "application/json",
229
+ Authorization: `Bearer ${this.config?.token || ""}`
230
+ };
231
+ }
232
+ /** Get current crypto state for persistence */
233
+ getCryptoState() {
234
+ if (!this.sessionSecret) return null;
235
+ return { secret: this.sessionSecret, chainHash: this.chainHash };
236
+ }
237
+ /** Register session with server and get cryptographic secret */
238
+ async startSession(sessionId) {
239
+ try {
240
+ const server = this.config?.server || "https://hackers.baby";
241
+ const res = await fetch(`${server}/api/sessions/start`, {
242
+ method: "POST",
243
+ headers: this.headers,
244
+ body: JSON.stringify({ session_id: sessionId })
245
+ });
246
+ if (res.ok) {
247
+ const data = await res.json();
248
+ this.sessionSecret = data.session_secret;
249
+ this.chainHash = data.initial_chain_hash;
250
+ return true;
251
+ }
252
+ return false;
253
+ } catch {
254
+ return false;
273
255
  }
274
256
  }
275
- } catch {
276
- }
277
- }
278
- async getStatus() {
279
- const server = this.config?.server || "https://hackers.baby";
280
- const res = await fetch(`${server}/api/users/me`, { headers: this.headers });
281
- if (!res.ok) throw new Error(`getStatus failed: ${res.status}`);
282
- return res.json();
283
- }
284
- async getRank() {
285
- const server = this.config?.server || "https://hackers.baby";
286
- const res = await fetch(`${server}/api/users/me/rank`, { headers: this.headers });
287
- if (!res.ok) throw new Error(`getRank failed: ${res.status}`);
288
- return res.json();
289
- }
290
- async getLeaderboard() {
291
- const server = this.config?.server || "https://hackers.baby";
292
- const res = await fetch(`${server}/api/leaderboard/global?limit=10`, { headers: this.headers });
293
- if (!res.ok) throw new Error(`getLeaderboard failed: ${res.status}`);
294
- return res.json();
295
- }
296
- async getPublicStats() {
297
- try {
298
- const server = this.config?.server || "https://hackers.baby";
299
- const res = await fetch(`${server}/api/stats/public`);
300
- if (!res.ok) return null;
301
- return res.json();
302
- } catch {
303
- return null;
304
- }
305
- }
306
- async getNotifications() {
307
- try {
308
- const server = this.config?.server || "https://hackers.baby";
309
- const res = await fetch(`${server}/api/users/me/notifications`, { headers: this.headers });
310
- if (!res.ok) return null;
311
- return res.json();
312
- } catch {
313
- return null;
314
- }
315
- }
316
- async claimReferral(code) {
317
- try {
318
- const server = this.config?.server || "https://hackers.baby";
319
- const res = await fetch(`${server}/api/referral/claim`, {
320
- method: "POST",
321
- headers: this.headers,
322
- body: JSON.stringify({ referral_code: code })
323
- });
324
- if (!res.ok) return null;
325
- return res.json();
326
- } catch {
327
- return null;
328
- }
329
- }
330
- async getReferralStats() {
331
- try {
332
- const server = this.config?.server || "https://hackers.baby";
333
- const res = await fetch(`${server}/api/referral/stats`, { headers: this.headers });
334
- if (!res.ok) return null;
335
- return res.json();
336
- } catch {
337
- return null;
338
- }
257
+ async sendBatch(batch) {
258
+ try {
259
+ const server = this.config?.server || "https://hackers.baby";
260
+ if (this.sessionSecret) {
261
+ const prevChainHash = this.chainHash;
262
+ const newChainHash = (0, import_shared.computeChainHash)(batch.events, prevChainHash);
263
+ const signature = (0, import_shared.signBatch)(batch.session_id, batch.events, newChainHash, this.sessionSecret);
264
+ batch.signature = signature;
265
+ batch.chain_hash = newChainHash;
266
+ batch.prev_chain_hash = prevChainHash;
267
+ this.chainHash = newChainHash;
268
+ if (this.onChainUpdate) {
269
+ this.onChainUpdate(this.chainHash, this.sessionSecret);
270
+ }
271
+ }
272
+ const res = await fetch(`${server}/api/scores/batch`, {
273
+ method: "POST",
274
+ headers: this.headers,
275
+ body: JSON.stringify(batch)
276
+ });
277
+ return res.ok;
278
+ } catch {
279
+ return false;
280
+ }
281
+ }
282
+ async refreshTokenIfNeeded() {
283
+ if (!this.config) return;
284
+ try {
285
+ const parts = this.config.token.split(".");
286
+ if (parts.length !== 3) return;
287
+ const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
288
+ const expMs = payload.exp * 1e3;
289
+ const oneDayMs = 24 * 60 * 60 * 1e3;
290
+ if (Date.now() + oneDayMs < expMs) return;
291
+ const res = await fetch(`${this.config.server}/api/auth/cli-token/refresh`, {
292
+ method: "POST",
293
+ headers: this.headers,
294
+ body: JSON.stringify({ refresh_token: this.config.refresh_token })
295
+ });
296
+ if (res.ok) {
297
+ const data = await res.json();
298
+ if (data.token) {
299
+ this.config.token = data.token;
300
+ if (data.refresh_token) this.config.refresh_token = data.refresh_token;
301
+ saveConfig(this.config);
302
+ }
303
+ }
304
+ } catch {
305
+ }
306
+ }
307
+ async getStatus() {
308
+ const server = this.config?.server || "https://hackers.baby";
309
+ const res = await fetch(`${server}/api/users/me`, { headers: this.headers });
310
+ if (!res.ok) throw new Error(`getStatus failed: ${res.status}`);
311
+ return res.json();
312
+ }
313
+ async getRank() {
314
+ const server = this.config?.server || "https://hackers.baby";
315
+ const res = await fetch(`${server}/api/users/me/rank`, { headers: this.headers });
316
+ if (!res.ok) throw new Error(`getRank failed: ${res.status}`);
317
+ return res.json();
318
+ }
319
+ async getLeaderboard() {
320
+ const server = this.config?.server || "https://hackers.baby";
321
+ const res = await fetch(`${server}/api/leaderboard/global?limit=10`, { headers: this.headers });
322
+ if (!res.ok) throw new Error(`getLeaderboard failed: ${res.status}`);
323
+ return res.json();
324
+ }
325
+ async getPublicStats() {
326
+ try {
327
+ const server = this.config?.server || "https://hackers.baby";
328
+ const res = await fetch(`${server}/api/stats/public`);
329
+ if (!res.ok) return null;
330
+ return res.json();
331
+ } catch {
332
+ return null;
333
+ }
334
+ }
335
+ async getNotifications() {
336
+ try {
337
+ const server = this.config?.server || "https://hackers.baby";
338
+ const res = await fetch(`${server}/api/users/me/notifications`, { headers: this.headers });
339
+ if (!res.ok) return null;
340
+ return res.json();
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ async claimReferral(code) {
346
+ try {
347
+ const server = this.config?.server || "https://hackers.baby";
348
+ const res = await fetch(`${server}/api/referral/claim`, {
349
+ method: "POST",
350
+ headers: this.headers,
351
+ body: JSON.stringify({ referral_code: code })
352
+ });
353
+ if (!res.ok) return null;
354
+ return res.json();
355
+ } catch {
356
+ return null;
357
+ }
358
+ }
359
+ async getReferralStats() {
360
+ try {
361
+ const server = this.config?.server || "https://hackers.baby";
362
+ const res = await fetch(`${server}/api/referral/stats`, { headers: this.headers });
363
+ if (!res.ok) return null;
364
+ return res.json();
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ };
339
370
  }
340
- };
371
+ });
341
372
 
342
373
  // src/queue.ts
343
- var import_fs2 = __toESM(require("fs"));
344
- var MAX_QUEUE_SIZE = 1e4;
345
- var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
346
374
  function enqueueEvents(events) {
347
375
  ensureConfigDir();
348
376
  const lines = events.map((e) => JSON.stringify(e)).join("\n");
@@ -380,66 +408,100 @@ function drainQueue() {
380
408
  return [];
381
409
  }
382
410
  }
411
+ var import_fs2, MAX_QUEUE_SIZE, MAX_AGE_MS;
412
+ var init_queue = __esm({
413
+ "src/queue.ts"() {
414
+ "use strict";
415
+ import_fs2 = __toESM(require("fs"));
416
+ init_config();
417
+ MAX_QUEUE_SIZE = 1e4;
418
+ MAX_AGE_MS = 24 * 60 * 60 * 1e3;
419
+ }
420
+ });
383
421
 
384
422
  // src/collector.ts
385
- var EventCollector = class {
386
- sessionId;
387
- buffer = [];
388
- flushInterval = null;
389
- client;
390
- source;
391
- constructor(sessionId, source) {
392
- this.sessionId = sessionId ?? (0, import_uuid.v4)();
393
- this.client = new APIClient();
394
- this.source = source;
395
- }
396
- addEvent(event) {
397
- const metadata = this.source ? { ...event.metadata, source: this.source } : event.metadata;
398
- this.buffer.push({
399
- ...event,
400
- metadata,
401
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
402
- });
403
- }
404
- async start() {
405
- await this.client.refreshTokenIfNeeded();
406
- await this.client.startSession(this.sessionId);
407
- const queued = drainQueue();
408
- if (queued.length > 0) {
409
- const batch = { session_id: this.sessionId, events: queued };
410
- const ok = await this.client.sendBatch(batch);
411
- if (!ok) {
412
- enqueueEvents(queued);
423
+ var import_uuid, EventCollector;
424
+ var init_collector = __esm({
425
+ "src/collector.ts"() {
426
+ "use strict";
427
+ import_uuid = require("uuid");
428
+ init_api_client();
429
+ init_queue();
430
+ init_config();
431
+ EventCollector = class {
432
+ sessionId;
433
+ buffer = [];
434
+ flushInterval = null;
435
+ client;
436
+ source;
437
+ constructor(sessionId, source) {
438
+ this.sessionId = sessionId ?? (0, import_uuid.v4)();
439
+ this.client = new APIClient();
440
+ this.source = source;
413
441
  }
414
- }
415
- const config = loadConfig();
416
- const intervalMs = config?.preferences?.batch_interval_ms ?? 1e4;
417
- this.flushInterval = setInterval(() => {
418
- this.flush().catch(() => {
419
- });
420
- }, intervalMs);
421
- }
422
- async flush() {
423
- if (this.buffer.length === 0) return;
424
- const events = this.buffer.splice(0);
425
- const batch = { session_id: this.sessionId, events };
426
- const ok = await this.client.sendBatch(batch);
427
- if (!ok) {
428
- enqueueEvents(events);
429
- }
430
- }
431
- async stop() {
432
- if (this.flushInterval !== null) {
433
- clearInterval(this.flushInterval);
434
- this.flushInterval = null;
435
- }
436
- this.addEvent({ action_type: "session_completed", value: 1, metadata: {} });
437
- await this.flush();
442
+ /** Restore crypto state from persisted session data */
443
+ restoreCrypto(secret, chainHash) {
444
+ this.client.restoreCryptoState(secret, chainHash);
445
+ }
446
+ /** Set callback to persist crypto state after each batch */
447
+ setCryptoUpdateCallback(cb) {
448
+ this.client.setChainUpdateCallback(cb);
449
+ }
450
+ addEvent(event) {
451
+ const metadata = this.source ? { ...event.metadata, source: this.source } : event.metadata;
452
+ this.buffer.push({
453
+ ...event,
454
+ metadata,
455
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
456
+ });
457
+ }
458
+ async start() {
459
+ await this.client.refreshTokenIfNeeded();
460
+ await this.client.startSession(this.sessionId);
461
+ const queued = drainQueue();
462
+ if (queued.length > 0) {
463
+ const batch = { session_id: this.sessionId, events: queued };
464
+ const ok = await this.client.sendBatch(batch);
465
+ if (!ok) {
466
+ enqueueEvents(queued);
467
+ }
468
+ }
469
+ const config = loadConfig();
470
+ const intervalMs = config?.preferences?.batch_interval_ms ?? 1e4;
471
+ this.flushInterval = setInterval(() => {
472
+ this.flush().catch(() => {
473
+ });
474
+ }, intervalMs);
475
+ }
476
+ async flush() {
477
+ if (this.buffer.length === 0) return;
478
+ const events = this.buffer.splice(0);
479
+ const batch = { session_id: this.sessionId, events };
480
+ const ok = await this.client.sendBatch(batch);
481
+ if (!ok) {
482
+ enqueueEvents(events);
483
+ }
484
+ }
485
+ async stop() {
486
+ if (this.flushInterval !== null) {
487
+ clearInterval(this.flushInterval);
488
+ this.flushInterval = null;
489
+ }
490
+ this.addEvent({ action_type: "session_completed", value: 1, metadata: {} });
491
+ await this.flush();
492
+ }
493
+ };
438
494
  }
439
- };
495
+ });
496
+
497
+ // src/hooks/shared/session-start.ts
498
+ init_collector();
499
+ init_api_client();
500
+ init_config();
440
501
 
441
502
  // src/hooks/shared/utils.ts
442
503
  var import_fs3 = __toESM(require("fs"));
504
+ init_config();
443
505
  function saveSessionState(state) {
444
506
  const file = sessionStateFile(state.source);
445
507
  import_fs3.default.writeFileSync(file, JSON.stringify(state));
@@ -454,8 +516,24 @@ function detectSource(payload) {
454
516
  async function handleSessionStart(source) {
455
517
  const detected = detectSource();
456
518
  const collector = new EventCollector(void 0, detected);
519
+ collector.setCryptoUpdateCallback((chainHash, secret) => {
520
+ saveSessionState({
521
+ sessionId: collector.sessionId,
522
+ pid: process.pid,
523
+ source: detected,
524
+ sessionSecret: secret,
525
+ chainHash
526
+ });
527
+ });
457
528
  await collector.start();
458
- saveSessionState({ sessionId: collector.sessionId, pid: process.pid, source: detected });
529
+ const crypto = collector.client.getCryptoState();
530
+ saveSessionState({
531
+ sessionId: collector.sessionId,
532
+ pid: process.pid,
533
+ source: detected,
534
+ sessionSecret: crypto?.secret,
535
+ chainHash: crypto?.chainHash
536
+ });
459
537
  try {
460
538
  const config = loadConfig();
461
539
  if (config?.token) {