kalvium-worklog 1.7.0 → 1.8.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/README.md CHANGED
@@ -41,6 +41,7 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
41
41
  | `kalvium-worklog cloud sync [--login]` | Update cloud settings; `--login` captures a fresh cloud token |
42
42
  | `kalvium-worklog cloud status` | Show recent GitHub Actions runs |
43
43
  | `kalvium-worklog cloud test` | Start a manual cloud run |
44
+ | `kalvium-worklog cloud monitor --remove` | Remove the macOS cloud-login recovery monitor |
44
45
 
45
46
  ## Features
46
47
 
@@ -52,6 +53,7 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
52
53
  - **Network retry**: Retries up to 5 times on network failure (covers laptop waking up, internet reconnecting)
53
54
  - **Catch-up on wake**: If the scheduled time was missed (laptop asleep/offline), submits when the device wakes up
54
55
  - **GitHub Actions mode**: Runs while your Mac is off and saves rotated refresh tokens back to GitHub Secrets
56
+ - **Cloud login recovery**: A macOS LaunchAgent checks failed cloud runs every 30 minutes and attempts a browser re-login when the refresh token is rejected
55
57
 
56
58
  ## How It Works
57
59
 
@@ -84,7 +86,7 @@ kalvium-worklog cloud init --repo owner/kalvium-attendance-cloud
84
86
 
85
87
  Cloud setup performs a separate Kalvium login and creates or updates a private repository workflow. It prompts for a fine-grained GitHub token restricted to that repository with **Secrets: read and write** permission. The token is entered in a hidden prompt and stored as `KATTEND_PAT`; the Kalvium refresh token and worklog configuration are stored as `KATTEND_TOKEN` and `KATTEND_CONFIG`.
86
88
 
87
- Use `kalvium-worklog cloud sync` after changing the local schedule or configuration. Use `kalvium-worklog cloud sync --login` to refresh the cloud login and replace its token secret. If Google requires a password, two-step verification, or consent, finish that in the opened browser window.
89
+ Use `kalvium-worklog cloud sync` after changing the local schedule or configuration. Use `kalvium-worklog cloud sync --login` to refresh the cloud login and replace its token secret. When you sync, macOS installs a local monitor that watches for failed cloud authentication and attempts a browser re-login with the saved Google session. If Google requires a password, two-step verification, or consent, finish that in the opened browser window. Remove the monitor with `kalvium-worklog cloud monitor --remove`.
88
90
 
89
91
  ## Token Lifecycle
90
92
 
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import { join, dirname } from "path";
10
10
  import { homedir } from "os";
11
11
  import { fileURLToPath } from "url";
12
12
  import { readFileSync } from "fs";
13
- import { cloudInit, cloudRun, cloudStatus, cloudSync, cloudTest } from "./cloud.js";
13
+ import { cloudInit, cloudMonitorRemove, cloudRun, cloudStatus, cloudSync, cloudTest } from "./cloud.js";
14
14
  // Read version from package.json
15
15
  const __dirname = dirname(fileURLToPath(import.meta.url));
16
16
  const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"));
@@ -99,19 +99,21 @@ program
99
99
  .command("cloud <action>")
100
100
  .description("Run worklog automation from GitHub Actions while your Mac is off")
101
101
  .option("--repo <name>", "private GitHub repository name or owner/name")
102
+ .option("--email <email>", "Google account for unattended account-chooser selection")
102
103
  .option("--reuse", "reuse the separately saved cloud login")
103
104
  .option("--login", "refresh the separate cloud login during sync")
105
+ .option("--remove", "remove the local cloud recovery monitor (for cloud monitor)")
104
106
  .action(async (action, opts) => {
105
107
  const cliPath = join(__dirname, "cli.js");
106
108
  switch (action) {
107
109
  case "init":
108
- await cloudInit({ cliPath, version: VERSION, repoName: opts.repo, reuse: opts.reuse });
110
+ await cloudInit({ cliPath, version: VERSION, repoName: opts.repo, reuse: opts.reuse, email: opts.email });
109
111
  return;
110
112
  case "run":
111
113
  await cloudRun();
112
114
  return;
113
115
  case "sync":
114
- await cloudSync({ cliPath, version: VERSION, login: opts.login });
116
+ await cloudSync({ cliPath, version: VERSION, login: opts.login, email: opts.email });
115
117
  return;
116
118
  case "status":
117
119
  cloudStatus();
@@ -119,8 +121,14 @@ program
119
121
  case "test":
120
122
  cloudTest();
121
123
  return;
124
+ case "monitor":
125
+ if (opts.remove)
126
+ cloudMonitorRemove();
127
+ else
128
+ await cloudSync({ cliPath, version: VERSION, email: opts.email });
129
+ return;
122
130
  default:
123
- console.error("Use: kalvium-worklog cloud init | run | sync [--login] | status | test");
131
+ console.error("Use: kalvium-worklog cloud init | run | sync [--login] | status | test | monitor [--remove]");
124
132
  process.exitCode = 1;
125
133
  }
126
134
  });
package/dist/cloud.d.ts CHANGED
@@ -4,12 +4,24 @@ export declare function cloudInit(options: {
4
4
  version: string;
5
5
  repoName?: string;
6
6
  reuse?: boolean;
7
+ email?: string;
7
8
  }): Promise<void>;
8
9
  export declare function cloudSync(options: {
9
10
  cliPath: string;
10
11
  version: string;
11
12
  login?: boolean;
13
+ email?: string;
12
14
  }): Promise<void>;
13
15
  export declare function cloudStatus(): void;
14
16
  export declare function cloudTest(): void;
17
+ /**
18
+ * Called by the Mac LaunchAgent. If a cloud run failed specifically because
19
+ * Kalvium rejected its refresh token, reuse the saved Google browser session
20
+ * and replace the cloud token secret. A six-hour cooldown prevents login loops.
21
+ */
22
+ export declare function cloudMonitor(options: {
23
+ cliPath: string;
24
+ version: string;
25
+ }): Promise<void>;
26
+ export declare function cloudMonitorRemove(): void;
15
27
  export declare function cloudRun(): Promise<void>;
package/dist/cloud.js CHANGED
@@ -5,6 +5,8 @@ import { spawnSync } from "child_process";
5
5
  import { createInterface } from "readline/promises";
6
6
  import { CONFIG_FILE, INSTALL_DIR, TOKEN_FILE, ensureInstallDir, loadConfig, loadSchedule, } from "./config.js";
7
7
  import { dailySubmit } from "./submit.js";
8
+ import { log } from "./config.js";
9
+ import { setupCloudRepairScheduler, removeCloudRepairScheduler } from "./scheduler.js";
8
10
  // Reuse the browser profile already created by kalvium-attendance, but keep
9
11
  // Worklog's rotated refresh token in its own file to avoid token races.
10
12
  const CLOUD_HOME = path.join(os.homedir(), ".kalvium-attendance-cloud");
@@ -92,16 +94,25 @@ function readCloudConfig() {
92
94
  return null;
93
95
  }
94
96
  }
97
+ function saveCloudMetadata(repo, email) {
98
+ fs.mkdirSync(INSTALL_DIR, { recursive: true, mode: 0o700 });
99
+ const previous = readCloudConfig();
100
+ const value = { ...previous, cloudRepo: repo, ...(email ? { email } : {}) };
101
+ fs.writeFileSync(CLOUD_CONFIG, JSON.stringify(value, null, 2), { mode: 0o600 });
102
+ }
95
103
  function requireRepo() {
96
104
  const repo = readCloudConfig()?.cloudRepo;
97
105
  if (!repo)
98
106
  throw new Error("Cloud mode is not set up. Run: kalvium-worklog cloud init");
99
107
  return repo;
100
108
  }
101
- function cloudLogin(cliPath) {
109
+ function cloudLogin(cliPath, email) {
102
110
  fs.mkdirSync(CLOUD_HOME, { recursive: true, mode: 0o700 });
103
111
  console.log("Opening a separate Kalvium login for GitHub Actions.");
104
- const result = spawnSync(process.execPath, [cliPath, "login"], {
112
+ const args = [cliPath, "login"];
113
+ if (email)
114
+ args.push("--email", email);
115
+ const result = spawnSync(process.execPath, args, {
105
116
  stdio: "inherit",
106
117
  env: {
107
118
  ...process.env,
@@ -202,7 +213,7 @@ export async function cloudInit(options) {
202
213
  const repo = requested.includes("/") ? requested : `${owner}/${requested}`;
203
214
  const cloudTokenFile = path.join(CLOUD_HOME, "refresh_token.json");
204
215
  if (!(options.reuse && fs.existsSync(cloudTokenFile)))
205
- cloudLogin(options.cliPath);
216
+ cloudLogin(options.cliPath, options.email);
206
217
  const config = currentCloudConfig(repo);
207
218
  console.log(`This will configure the private repo ${repo} to run at ${config.time} ${config.timezone}.`);
208
219
  if ((await ask("Continue? (yes/no)", "no")).toLowerCase() !== "yes")
@@ -218,20 +229,23 @@ export async function cloudInit(options) {
218
229
  setSecret(repo, SECRET_CONFIG, secretConfig(config));
219
230
  setSecret(repo, SECRET_PAT, pat);
220
231
  putWorkflow(repo, workflowYaml(config, options.version));
221
- fs.writeFileSync(CLOUD_CONFIG, JSON.stringify({ cloudRepo: repo }, null, 2), { mode: 0o600 });
232
+ saveCloudMetadata(repo, options.email);
233
+ setupCloudRepairScheduler(options.cliPath, options.version);
222
234
  console.log(`Cloud worklog enabled for ${repo} at ${config.time} ${config.timezone}.`);
223
235
  }
224
236
  export async function cloudSync(options) {
225
237
  requireGh();
226
238
  const repo = requireRepo();
227
239
  if (options.login) {
228
- cloudLogin(options.cliPath);
240
+ cloudLogin(options.cliPath, options.email || readCloudConfig()?.email);
229
241
  const tokenFile = path.join(CLOUD_HOME, "refresh_token.json");
230
242
  setSecret(repo, SECRET_TOKEN, fs.readFileSync(tokenFile, "utf8"));
231
243
  }
232
244
  const config = currentCloudConfig(repo);
233
245
  setSecret(repo, SECRET_CONFIG, secretConfig(config));
234
246
  putWorkflow(repo, workflowYaml(config, options.version));
247
+ saveCloudMetadata(repo, options.email);
248
+ setupCloudRepairScheduler(options.cliPath, options.version);
235
249
  console.log(`Synced cloud worklog settings${options.login ? " and refreshed its login" : ""}.`);
236
250
  }
237
251
  export function cloudStatus() {
@@ -249,6 +263,72 @@ export function cloudTest() {
249
263
  runGh(["workflow", "run", "attendance.yml", "--repo", repo]);
250
264
  console.log(`Started a run. Check https://github.com/${repo}/actions`);
251
265
  }
266
+ function recoveryStatePath() {
267
+ return path.join(INSTALL_DIR, "cloud-recovery.json");
268
+ }
269
+ function readRecoveryState() {
270
+ try {
271
+ return JSON.parse(fs.readFileSync(recoveryStatePath(), "utf8"));
272
+ }
273
+ catch {
274
+ return {};
275
+ }
276
+ }
277
+ function saveRecoveryState(state) {
278
+ fs.writeFileSync(recoveryStatePath(), JSON.stringify(state, null, 2), { mode: 0o600 });
279
+ }
280
+ /**
281
+ * Called by the Mac LaunchAgent. If a cloud run failed specifically because
282
+ * Kalvium rejected its refresh token, reuse the saved Google browser session
283
+ * and replace the cloud token secret. A six-hour cooldown prevents login loops.
284
+ */
285
+ export async function cloudMonitor(options) {
286
+ const repo = readCloudConfig()?.cloudRepo;
287
+ if (!repo)
288
+ return;
289
+ requireGh();
290
+ const list = gh([
291
+ "run", "list", "--repo", repo, "--workflow", "attendance.yml", "--limit", "1",
292
+ "--json", "databaseId,status,conclusion",
293
+ ]);
294
+ if (list.status !== 0)
295
+ throw new Error((list.stderr || "Could not read recent cloud runs.").trim());
296
+ const runs = JSON.parse(list.stdout || "[]");
297
+ const latest = runs[0];
298
+ if (!latest || latest.status !== "completed" || latest.conclusion !== "failure")
299
+ return;
300
+ const runLog = gh(["run", "view", String(latest.databaseId), "--repo", repo, "--log-failed"]);
301
+ if (runLog.status !== 0)
302
+ return;
303
+ const authFailure = /authentication expired|session expired or invalid|refresh token.{0,40}(invalid|expired)|HTTP 401|HTTP 403/i.test(runLog.stdout);
304
+ if (!authFailure)
305
+ return;
306
+ const state = readRecoveryState();
307
+ const attemptedAt = state.attemptedAt ? Date.parse(state.attemptedAt) : 0;
308
+ if (state.attemptedRunId === latest.databaseId || Date.now() - attemptedAt < 6 * 60 * 60 * 1000) {
309
+ return;
310
+ }
311
+ ensureInstallDir();
312
+ saveRecoveryState({ attemptedRunId: latest.databaseId, attemptedAt: new Date().toISOString() });
313
+ log(`Cloud login failed in GitHub run ${latest.databaseId}; attempting browser re-login.`);
314
+ try {
315
+ cloudLogin(options.cliPath, readCloudConfig()?.email);
316
+ const tokenFile = path.join(CLOUD_HOME, "refresh_token.json");
317
+ const token = fs.readFileSync(tokenFile, "utf8");
318
+ setSecret(repo, SECRET_TOKEN, token);
319
+ const config = currentCloudConfig(repo);
320
+ setSecret(repo, SECRET_CONFIG, secretConfig(config));
321
+ putWorkflow(repo, workflowYaml(config, options.version));
322
+ saveRecoveryState({});
323
+ log("Cloud login refreshed and saved. GitHub Actions will retry on its next scheduled check.");
324
+ }
325
+ catch (error) {
326
+ log(`Cloud re-login could not complete: ${error instanceof Error ? error.message : String(error)}. Google may need you to finish sign-in in the browser.`);
327
+ }
328
+ }
329
+ export function cloudMonitorRemove() {
330
+ removeCloudRepairScheduler();
331
+ }
252
332
  export async function cloudRun() {
253
333
  const tokenJson = process.env.KATTEND_TOKEN_JSON;
254
334
  const configJson = process.env.KATTEND_CONFIG_JSON;
@@ -9,6 +9,9 @@ export interface ScheduleOptions {
9
9
  * Linux: cron
10
10
  */
11
11
  export declare function setupScheduler(options: ScheduleOptions): Promise<boolean>;
12
+ /** Poll GitHub Actions while the user session is active and repair cloud auth if needed. */
13
+ export declare function setupCloudRepairScheduler(cliPath: string, version: string): boolean;
14
+ export declare function removeCloudRepairScheduler(): void;
12
15
  /**
13
16
  * Remove the scheduled task.
14
17
  */
package/dist/scheduler.js CHANGED
@@ -10,6 +10,7 @@ const IS_MAC = platform() === "darwin";
10
10
  const IS_WINDOWS = platform() === "win32";
11
11
  const IS_LINUX = platform() === "linux";
12
12
  const LAUNCHD_DOMAIN = `gui/${process.getuid?.() ?? 0}`;
13
+ const CLOUD_REPAIR_LABEL = "com.kalvium.worklog.cloud-repair";
13
14
  function nodeExecutable() {
14
15
  const stablePaths = IS_MAC
15
16
  ? ["/opt/homebrew/bin/node", "/usr/local/bin/node"]
@@ -197,6 +198,66 @@ function unloadLaunchAgent(plistPath) {
197
198
  // The task might not have been loaded yet.
198
199
  }
199
200
  }
201
+ /** Poll GitHub Actions while the user session is active and repair cloud auth if needed. */
202
+ export function setupCloudRepairScheduler(cliPath, version) {
203
+ if (!IS_MAC) {
204
+ console.log("Automatic cloud-login recovery is currently available on macOS only.");
205
+ return false;
206
+ }
207
+ ensureInstallDir();
208
+ const scriptPath = join(INSTALL_DIR, "cloud_repair.js");
209
+ const script = `#!/usr/bin/env node
210
+ // Auto-generated by kalvium-worklog. Do not edit.
211
+ import { cloudMonitor } from "${join(dirname(fileURLToPath(import.meta.url)), "cloud.js")}";
212
+ cloudMonitor({ cliPath: "${cliPath}", version: "${version}" }).catch((error) => {
213
+ console.error("Cloud recovery check failed:", error instanceof Error ? error.message : String(error));
214
+ process.exitCode = 1;
215
+ });
216
+ `;
217
+ writeFileSync(scriptPath, script, { mode: 0o700 });
218
+ const agentsDir = join(homedir(), "Library", "LaunchAgents");
219
+ if (!existsSync(agentsDir))
220
+ mkdirSync(agentsDir, { recursive: true });
221
+ const plistPath = join(agentsDir, `${CLOUD_REPAIR_LABEL}.plist`);
222
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
223
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
224
+ <plist version="1.0"><dict>
225
+ <key>Label</key><string>${CLOUD_REPAIR_LABEL}</string>
226
+ <key>ProgramArguments</key><array><string>${nodeExecutable()}</string><string>${scriptPath}</string></array>
227
+ <key>RunAtLoad</key><true/>
228
+ <key>StartInterval</key><integer>1800</integer>
229
+ <key>StandardOutPath</key><string>${LOG_FILE}</string>
230
+ <key>StandardErrorPath</key><string>${LOG_FILE}</string>
231
+ <key>EnvironmentVariables</key><dict>
232
+ <key>HOME</key><string>${homedir()}</string>
233
+ <key>PATH</key><string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin</string>
234
+ </dict>
235
+ </dict></plist>`;
236
+ writeFileSync(plistPath, plist, { mode: 0o600 });
237
+ unloadLaunchAgent(plistPath);
238
+ try {
239
+ execSync(`launchctl bootstrap ${LAUNCHD_DOMAIN} "${plistPath}"`, { stdio: "ignore" });
240
+ execSync(`launchctl kickstart -k ${LAUNCHD_DOMAIN}/${CLOUD_REPAIR_LABEL}`, { stdio: "ignore" });
241
+ console.log("Cloud auth recovery monitor installed (checks every 30 minutes).");
242
+ return true;
243
+ }
244
+ catch (error) {
245
+ console.log(`Failed to install cloud recovery monitor: ${String(error)}`);
246
+ return false;
247
+ }
248
+ }
249
+ export function removeCloudRepairScheduler() {
250
+ if (!IS_MAC)
251
+ return;
252
+ const plistPath = join(homedir(), "Library", "LaunchAgents", `${CLOUD_REPAIR_LABEL}.plist`);
253
+ unloadLaunchAgent(plistPath);
254
+ if (existsSync(plistPath))
255
+ execSync(`rm "${plistPath}"`);
256
+ const scriptPath = join(INSTALL_DIR, "cloud_repair.js");
257
+ if (existsSync(scriptPath))
258
+ execSync(`rm "${scriptPath}"`);
259
+ console.log("Cloud auth recovery monitor removed.");
260
+ }
200
261
  function setupTaskScheduler(hour, minute) {
201
262
  const dailyScript = copyDailyScript();
202
263
  const nodePath = nodeExecutable();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kalvium-worklog",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Auto-submit your daily Kalvium worklog without opening the website",
5
5
  "keywords": [
6
6
  "kalvium",
@@ -13,11 +13,11 @@
13
13
  "author": "",
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://github.com/kp/kalvium-worklog.git"
16
+ "url": "git+https://github.com/EmperorKP/kalvium-worklog.git"
17
17
  },
18
- "homepage": "https://github.com/kp/kalvium-worklog#readme",
18
+ "homepage": "https://github.com/EmperorKP/kalvium-worklog#readme",
19
19
  "bugs": {
20
- "url": "https://github.com/kp/kalvium-worklog/issues"
20
+ "url": "https://github.com/EmperorKP/kalvium-worklog/issues"
21
21
  },
22
22
  "type": "module",
23
23
  "main": "dist/index.js",