kalvium-worklog 1.6.8 → 1.7.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
@@ -37,6 +37,10 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
37
37
  | `kalvium-worklog daily` | Run daily submit (used by scheduler) |
38
38
  | `kalvium-worklog catchup` | Check if today's worklog is missing and submit if needed |
39
39
  | `kalvium-worklog trigger` | Run the safe catch-up check immediately |
40
+ | `kalvium-worklog cloud init` | Set up the GitHub Actions runner in a private repo |
41
+ | `kalvium-worklog cloud sync [--login]` | Update cloud settings; `--login` captures a fresh cloud token |
42
+ | `kalvium-worklog cloud status` | Show recent GitHub Actions runs |
43
+ | `kalvium-worklog cloud test` | Start a manual cloud run |
40
44
 
41
45
  ## Features
42
46
 
@@ -47,6 +51,7 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
47
51
  - **Weekend skipping**: Auto-submit skips Saturdays and Sundays
48
52
  - **Network retry**: Retries up to 5 times on network failure (covers laptop waking up, internet reconnecting)
49
53
  - **Catch-up on wake**: If the scheduled time was missed (laptop asleep/offline), submits when the device wakes up
54
+ - **GitHub Actions mode**: Runs while your Mac is off and saves rotated refresh tokens back to GitHub Secrets
50
55
 
51
56
  ## How It Works
52
57
 
@@ -61,8 +66,26 @@ Daily auto-submit (scheduler):
61
66
 
62
67
  Catch-up (on login/wake, every 30 min):
63
68
  Check if today's worklog is submitted → if not, submit it
69
+
70
+ Cloud mode (optional):
71
+ GitHub Actions checks every 30 min around the chosen time
72
+ Transient network failures retry up to 5 times (1 min apart)
73
+ Rotated refresh token is written back to the private repo's KATTEND_TOKEN secret
74
+ ```
75
+
76
+ ## GitHub Actions mode
77
+
78
+ Install and configure the local login, position, and schedule first. Then authenticate the GitHub CLI and run:
79
+
80
+ ```bash
81
+ gh auth login
82
+ kalvium-worklog cloud init --repo owner/kalvium-attendance-cloud
64
83
  ```
65
84
 
85
+ 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
+
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.
88
+
66
89
  ## Token Lifecycle
67
90
 
68
91
  - **Access token**: 3 days
package/dist/cli.js CHANGED
@@ -10,6 +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
14
  // Read version from package.json
14
15
  const __dirname = dirname(fileURLToPath(import.meta.url));
15
16
  const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"));
@@ -93,6 +94,36 @@ program
93
94
  if (!ok)
94
95
  process.exit(1);
95
96
  });
97
+ // ─── cloud ────────────────────────────────────────────────────────────────
98
+ program
99
+ .command("cloud <action>")
100
+ .description("Run worklog automation from GitHub Actions while your Mac is off")
101
+ .option("--repo <name>", "private GitHub repository name or owner/name")
102
+ .option("--reuse", "reuse the separately saved cloud login")
103
+ .option("--login", "refresh the separate cloud login during sync")
104
+ .action(async (action, opts) => {
105
+ const cliPath = join(__dirname, "cli.js");
106
+ switch (action) {
107
+ case "init":
108
+ await cloudInit({ cliPath, version: VERSION, repoName: opts.repo, reuse: opts.reuse });
109
+ return;
110
+ case "run":
111
+ await cloudRun();
112
+ return;
113
+ case "sync":
114
+ await cloudSync({ cliPath, version: VERSION, login: opts.login });
115
+ return;
116
+ case "status":
117
+ cloudStatus();
118
+ return;
119
+ case "test":
120
+ cloudTest();
121
+ return;
122
+ default:
123
+ console.error("Use: kalvium-worklog cloud init | run | sync [--login] | status | test");
124
+ process.exitCode = 1;
125
+ }
126
+ });
96
127
  // ─── schedule ──────────────────────────────────────────────────────────────
97
128
  program
98
129
  .command("schedule [time]")
@@ -0,0 +1,15 @@
1
+ export declare function cronFor(time: string, offsetMin?: number): string;
2
+ export declare function cloudInit(options: {
3
+ cliPath: string;
4
+ version: string;
5
+ repoName?: string;
6
+ reuse?: boolean;
7
+ }): Promise<void>;
8
+ export declare function cloudSync(options: {
9
+ cliPath: string;
10
+ version: string;
11
+ login?: boolean;
12
+ }): Promise<void>;
13
+ export declare function cloudStatus(): void;
14
+ export declare function cloudTest(): void;
15
+ export declare function cloudRun(): Promise<void>;
package/dist/cloud.js ADDED
@@ -0,0 +1,288 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { spawnSync } from "child_process";
5
+ import { createInterface } from "readline/promises";
6
+ import { CONFIG_FILE, INSTALL_DIR, TOKEN_FILE, ensureInstallDir, loadConfig, loadSchedule, } from "./config.js";
7
+ import { dailySubmit } from "./submit.js";
8
+ // Reuse the browser profile already created by kalvium-attendance, but keep
9
+ // Worklog's rotated refresh token in its own file to avoid token races.
10
+ const CLOUD_HOME = path.join(os.homedir(), ".kalvium-attendance-cloud");
11
+ const CLOUD_CONFIG = path.join(INSTALL_DIR, "cloud.json");
12
+ const WORKFLOW_PATH = ".github/workflows/attendance.yml";
13
+ const SECRET_TOKEN = "KATTEND_TOKEN";
14
+ const SECRET_CONFIG = "KATTEND_CONFIG";
15
+ const SECRET_PAT = "KATTEND_PAT";
16
+ function gh(args, input) {
17
+ const result = spawnSync("gh", args, {
18
+ encoding: "utf8",
19
+ input,
20
+ windowsHide: true,
21
+ });
22
+ if (result.error?.code === "ENOENT") {
23
+ throw new Error("GitHub CLI is required. Install gh, then run: gh auth login");
24
+ }
25
+ return result;
26
+ }
27
+ function requireGh() {
28
+ if (gh(["auth", "status"]).status !== 0) {
29
+ throw new Error("Not logged in to GitHub. Run: gh auth login");
30
+ }
31
+ }
32
+ function runGh(args, input) {
33
+ const result = gh(args, input);
34
+ if (result.status !== 0) {
35
+ throw new Error((result.stderr || result.stdout || "GitHub CLI command failed").trim());
36
+ }
37
+ return result.stdout.trim();
38
+ }
39
+ async function ask(prompt, defaultValue) {
40
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
41
+ try {
42
+ const suffix = defaultValue ? ` (${defaultValue})` : "";
43
+ return (await rl.question(`${prompt}${suffix}: `)).trim() || defaultValue || "";
44
+ }
45
+ finally {
46
+ rl.close();
47
+ }
48
+ }
49
+ async function askHidden(prompt) {
50
+ process.stdout.write(prompt);
51
+ if (!process.stdin.isTTY || !process.stdin.setRawMode) {
52
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
53
+ try {
54
+ return (await rl.question("")).trim();
55
+ }
56
+ finally {
57
+ rl.close();
58
+ }
59
+ }
60
+ const stdin = process.stdin;
61
+ stdin.setRawMode(true);
62
+ stdin.resume();
63
+ stdin.setEncoding("utf8");
64
+ return new Promise((resolve) => {
65
+ let value = "";
66
+ const onData = (chunk) => {
67
+ for (const char of chunk) {
68
+ if (char === "\r" || char === "\n") {
69
+ stdin.setRawMode(false);
70
+ stdin.pause();
71
+ stdin.off("data", onData);
72
+ process.stdout.write("\n");
73
+ resolve(value.trim());
74
+ return;
75
+ }
76
+ if (char === "\u0003")
77
+ process.exit(130);
78
+ if (char === "\u007f" || char === "\b")
79
+ value = value.slice(0, -1);
80
+ else
81
+ value += char;
82
+ }
83
+ };
84
+ stdin.on("data", onData);
85
+ });
86
+ }
87
+ function readCloudConfig() {
88
+ try {
89
+ return JSON.parse(fs.readFileSync(CLOUD_CONFIG, "utf8"));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ function requireRepo() {
96
+ const repo = readCloudConfig()?.cloudRepo;
97
+ if (!repo)
98
+ throw new Error("Cloud mode is not set up. Run: kalvium-worklog cloud init");
99
+ return repo;
100
+ }
101
+ function cloudLogin(cliPath) {
102
+ fs.mkdirSync(CLOUD_HOME, { recursive: true, mode: 0o700 });
103
+ console.log("Opening a separate Kalvium login for GitHub Actions.");
104
+ const result = spawnSync(process.execPath, [cliPath, "login"], {
105
+ stdio: "inherit",
106
+ env: {
107
+ ...process.env,
108
+ KWORKLOG_HOME: CLOUD_HOME,
109
+ KWORKLOG_PROFILE_DIR: path.join(CLOUD_HOME, "browser-profile"),
110
+ },
111
+ });
112
+ if (result.status !== 0 || !fs.existsSync(path.join(CLOUD_HOME, "refresh_token.json"))) {
113
+ throw new Error("Cloud login did not complete.");
114
+ }
115
+ }
116
+ export function cronFor(time, offsetMin = new Date().getTimezoneOffset()) {
117
+ const match = /^(\d{1,2}):(\d{2})$/.exec(time);
118
+ if (!match)
119
+ throw new Error(`Invalid time "${time}". Use HH:MM, e.g. 12:30`);
120
+ const hour = Number(match[1]);
121
+ const minute = Number(match[2]);
122
+ if (hour > 23 || minute > 59)
123
+ throw new Error(`Invalid time "${time}".`);
124
+ const hours = new Set();
125
+ const base = hour * 60 + minute + offsetMin;
126
+ for (let offset = -30; offset <= 240; offset += 30) {
127
+ const utcMinutes = ((base + offset) % 1440 + 1440) % 1440;
128
+ hours.add(Math.floor(utcMinutes / 60));
129
+ }
130
+ return `7,37 ${[...hours].sort((a, b) => a - b).join(",")} * * *`;
131
+ }
132
+ function workflowYaml(config, version) {
133
+ return `# Generated by kalvium-worklog. Run kalvium-worklog cloud sync to update.
134
+ name: Kalvium worklog
135
+ on:
136
+ schedule:
137
+ - cron: "${cronFor(config.time)}"
138
+ workflow_dispatch:
139
+ concurrency:
140
+ group: kalvium-worklog
141
+ cancel-in-progress: false
142
+ permissions: {}
143
+ jobs:
144
+ submit:
145
+ runs-on: ubuntu-latest
146
+ timeout-minutes: 15
147
+ env:
148
+ TZ: ${config.timezone}
149
+ KWORKLOG_HOME: /tmp/kalvium-worklog
150
+ KATTEND_TOKEN_JSON: \${{ secrets.${SECRET_TOKEN} }}
151
+ KATTEND_CONFIG_JSON: \${{ secrets.${SECRET_CONFIG} }}
152
+ GH_TOKEN: \${{ secrets.${SECRET_PAT} }}
153
+ steps:
154
+ - uses: actions/setup-node@v4
155
+ with:
156
+ node-version: 20
157
+ - name: Submit daily worklog
158
+ run: npx --yes kalvium-worklog@${version} cloud run
159
+ `;
160
+ }
161
+ function putWorkflow(repo, content) {
162
+ const api = `repos/${repo}/contents/${WORKFLOW_PATH}`;
163
+ const existingSha = gh(["api", api, "--jq", ".sha"]);
164
+ const args = [
165
+ "api", "-X", "PUT", api,
166
+ "-f", "message=Update Kalvium worklog workflow",
167
+ "-f", `content=${Buffer.from(content).toString("base64")}`,
168
+ ];
169
+ if (existingSha.status === 0 && existingSha.stdout.trim()) {
170
+ args.push("-f", `sha=${existingSha.stdout.trim()}`);
171
+ }
172
+ runGh(args);
173
+ }
174
+ function setSecret(repo, name, value) {
175
+ runGh(["secret", "set", name, "--repo", repo], value);
176
+ }
177
+ function currentCloudConfig(repo) {
178
+ const local = loadConfig();
179
+ if (!local?.position_id || !local.worklog_api_url) {
180
+ throw new Error("Run kalvium-worklog discover before setting up cloud mode.");
181
+ }
182
+ const schedule = loadSchedule() ?? { hour: 12, minute: 30 };
183
+ return {
184
+ position_id: local.position_id,
185
+ worklog_api_url: local.worklog_api_url,
186
+ time: `${String(schedule.hour).padStart(2, "0")}:${String(schedule.minute).padStart(2, "0")}`,
187
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
188
+ cloudRepo: repo,
189
+ };
190
+ }
191
+ function secretConfig(config) {
192
+ return JSON.stringify({
193
+ position_id: config.position_id,
194
+ worklog_api_url: config.worklog_api_url,
195
+ time: config.time,
196
+ });
197
+ }
198
+ export async function cloudInit(options) {
199
+ requireGh();
200
+ const owner = runGh(["api", "user", "--jq", ".login"]);
201
+ const requested = options.repoName || await ask("Private GitHub repo name", "kalvium-attendance-cloud");
202
+ const repo = requested.includes("/") ? requested : `${owner}/${requested}`;
203
+ const cloudTokenFile = path.join(CLOUD_HOME, "refresh_token.json");
204
+ if (!(options.reuse && fs.existsSync(cloudTokenFile)))
205
+ cloudLogin(options.cliPath);
206
+ const config = currentCloudConfig(repo);
207
+ console.log(`This will configure the private repo ${repo} to run at ${config.time} ${config.timezone}.`);
208
+ if ((await ask("Continue? (yes/no)", "no")).toLowerCase() !== "yes")
209
+ throw new Error("Cancelled.");
210
+ const created = gh(["repo", "create", repo, "--private", "--description", "Daily Kalvium worklog automation"]);
211
+ if (created.status !== 0 && !/already exists/i.test(created.stderr)) {
212
+ throw new Error((created.stderr || "Could not create the GitHub repository.").trim());
213
+ }
214
+ const pat = process.env.KATTEND_PAT || await askHidden("Fine-grained PAT (repo Secrets: read/write; input hidden): ");
215
+ if (!pat)
216
+ throw new Error("A GitHub token is required to save rotated refresh tokens.");
217
+ setSecret(repo, SECRET_TOKEN, fs.readFileSync(cloudTokenFile, "utf8"));
218
+ setSecret(repo, SECRET_CONFIG, secretConfig(config));
219
+ setSecret(repo, SECRET_PAT, pat);
220
+ putWorkflow(repo, workflowYaml(config, options.version));
221
+ fs.writeFileSync(CLOUD_CONFIG, JSON.stringify({ cloudRepo: repo }, null, 2), { mode: 0o600 });
222
+ console.log(`Cloud worklog enabled for ${repo} at ${config.time} ${config.timezone}.`);
223
+ }
224
+ export async function cloudSync(options) {
225
+ requireGh();
226
+ const repo = requireRepo();
227
+ if (options.login) {
228
+ cloudLogin(options.cliPath);
229
+ const tokenFile = path.join(CLOUD_HOME, "refresh_token.json");
230
+ setSecret(repo, SECRET_TOKEN, fs.readFileSync(tokenFile, "utf8"));
231
+ }
232
+ const config = currentCloudConfig(repo);
233
+ setSecret(repo, SECRET_CONFIG, secretConfig(config));
234
+ putWorkflow(repo, workflowYaml(config, options.version));
235
+ console.log(`Synced cloud worklog settings${options.login ? " and refreshed its login" : ""}.`);
236
+ }
237
+ export function cloudStatus() {
238
+ requireGh();
239
+ const repo = requireRepo();
240
+ console.log(`Repo: https://github.com/${repo}`);
241
+ const result = gh(["run", "list", "--repo", repo, "--limit", "8"]);
242
+ if (result.status !== 0)
243
+ throw new Error((result.stderr || "Could not read workflow runs.").trim());
244
+ console.log(result.stdout.trim() || "No runs yet.");
245
+ }
246
+ export function cloudTest() {
247
+ requireGh();
248
+ const repo = requireRepo();
249
+ runGh(["workflow", "run", "attendance.yml", "--repo", repo]);
250
+ console.log(`Started a run. Check https://github.com/${repo}/actions`);
251
+ }
252
+ export async function cloudRun() {
253
+ const tokenJson = process.env.KATTEND_TOKEN_JSON;
254
+ const configJson = process.env.KATTEND_CONFIG_JSON;
255
+ if (!tokenJson || !configJson)
256
+ throw new Error("Cloud token/config secrets are missing. Run cloud sync --login.");
257
+ const config = JSON.parse(configJson);
258
+ const mappedConfig = {
259
+ position_id: config.position_id,
260
+ worklog_api_url: config.worklog_api_url,
261
+ };
262
+ if (!mappedConfig.position_id || !mappedConfig.worklog_api_url) {
263
+ throw new Error("Cloud config is missing the internship position or worklog URL.");
264
+ }
265
+ ensureInstallDir();
266
+ fs.writeFileSync(TOKEN_FILE, tokenJson, { mode: 0o600 });
267
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(mappedConfig), { mode: 0o600 });
268
+ const scheduled = /^(\d{1,2}):(\d{2})$/.exec(config.time || "12:30");
269
+ if (scheduled) {
270
+ const now = new Date();
271
+ const due = Number(scheduled[1]) * 60 + Number(scheduled[2]);
272
+ if (now.getHours() * 60 + now.getMinutes() < due) {
273
+ console.log("Not due yet; the next scheduled check will retry.");
274
+ return;
275
+ }
276
+ }
277
+ const submitted = await dailySubmit({ allowInteractiveLogin: false });
278
+ const updatedToken = fs.readFileSync(TOKEN_FILE, "utf8");
279
+ if (updatedToken !== tokenJson) {
280
+ const repo = process.env.GITHUB_REPOSITORY || requireRepo();
281
+ if (!process.env.GH_TOKEN)
282
+ throw new Error(`Token rotated but cannot be saved; configure ${SECRET_PAT}.`);
283
+ setSecret(repo, SECRET_TOKEN, updatedToken);
284
+ console.log("Saved rotated Kalvium token.");
285
+ }
286
+ if (!submitted)
287
+ throw new Error("Worklog cloud run failed; see the log output above.");
288
+ }
package/dist/config.d.ts CHANGED
@@ -3,6 +3,8 @@ export declare const PROFILE_DIR: string;
3
3
  export declare const TOKEN_FILE: string;
4
4
  export declare const CONFIG_FILE: string;
5
5
  export declare const LOG_FILE: string;
6
+ export declare const SCHEDULE_FILE: string;
7
+ export declare const CATCHUP_STATE_FILE: string;
6
8
  export declare const KEYCLOAK_URL = "https://auth.kalvium.community/auth/realms/kalvium/protocol/openid-connect/token";
7
9
  export declare const CLIENT_ID = "login_client";
8
10
  export declare const API_BASE = "https://student-api.kalvium.community/api/internships/worklogs";
@@ -24,6 +26,14 @@ export declare function saveToken(data: TokenData): void;
24
26
  export declare function loadConfig(): ConfigData | null;
25
27
  export declare function saveConfig(config: ConfigData): void;
26
28
  export declare function getLocalDate(date?: Date): string;
29
+ export interface ScheduleData {
30
+ hour: number;
31
+ minute: number;
32
+ }
33
+ export declare function loadSchedule(): ScheduleData | null;
34
+ export declare function saveSchedule(schedule: ScheduleData): void;
35
+ export declare function getCatchupDate(): string | null;
36
+ export declare function setCatchupDate(date: string): void;
27
37
  export declare function getWorklogApi(): string | null;
28
38
  export declare function log(message: string): void;
29
39
  export declare function decodeJwt(token: string): Record<string, unknown> | null;
package/dist/config.js CHANGED
@@ -1,11 +1,16 @@
1
1
  import { homedir } from "os";
2
2
  import { join } from "path";
3
3
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "fs";
4
- export const INSTALL_DIR = join(homedir(), ".kalvium");
5
- export const PROFILE_DIR = join(homedir(), ".kalvium_profile");
4
+ export const INSTALL_DIR = process.env.KWORKLOG_HOME || join(homedir(), ".kalvium");
5
+ export const PROFILE_DIR = process.env.KWORKLOG_PROFILE_DIR ||
6
+ (process.env.KWORKLOG_HOME
7
+ ? join(INSTALL_DIR, "browser-profile")
8
+ : join(homedir(), ".kalvium_profile"));
6
9
  export const TOKEN_FILE = join(INSTALL_DIR, "refresh_token.json");
7
10
  export const CONFIG_FILE = join(INSTALL_DIR, "config.json");
8
11
  export const LOG_FILE = join(INSTALL_DIR, "worklog.log");
12
+ export const SCHEDULE_FILE = join(INSTALL_DIR, "schedule.json");
13
+ export const CATCHUP_STATE_FILE = join(INSTALL_DIR, "catchup-state.json");
9
14
  export const KEYCLOAK_URL = "https://auth.kalvium.community/auth/realms/kalvium/protocol/openid-connect/token";
10
15
  export const CLIENT_ID = "login_client";
11
16
  export const API_BASE = "https://student-api.kalvium.community/api/internships/worklogs";
@@ -66,6 +71,31 @@ export function getLocalDate(date = new Date()) {
66
71
  const day = String(date.getDate()).padStart(2, "0");
67
72
  return `${year}-${month}-${day}`;
68
73
  }
74
+ export function loadSchedule() {
75
+ try {
76
+ return JSON.parse(readFileSync(SCHEDULE_FILE, "utf-8"));
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ export function saveSchedule(schedule) {
83
+ ensureInstallDir();
84
+ writeFileSync(SCHEDULE_FILE, JSON.stringify(schedule, null, 2), { mode: 0o600 });
85
+ }
86
+ export function getCatchupDate() {
87
+ try {
88
+ const state = JSON.parse(readFileSync(CATCHUP_STATE_FILE, "utf-8"));
89
+ return state.date ?? null;
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ export function setCatchupDate(date) {
96
+ ensureInstallDir();
97
+ writeFileSync(CATCHUP_STATE_FILE, JSON.stringify({ date }), { mode: 0o600 });
98
+ }
69
99
  export function getWorklogApi() {
70
100
  const config = loadConfig();
71
101
  return config?.worklog_api_url ?? null;
package/dist/refresh.d.ts CHANGED
@@ -3,5 +3,6 @@ export interface RefreshResult {
3
3
  success: boolean;
4
4
  accessToken?: string;
5
5
  error?: string;
6
+ networkError?: boolean;
6
7
  }
7
8
  export declare function refreshToken(): Promise<RefreshResult>;
package/dist/refresh.js CHANGED
@@ -44,6 +44,10 @@ export async function refreshToken() {
44
44
  return { success: true, accessToken: token.access_token };
45
45
  }
46
46
  catch (e) {
47
- return { success: false, error: e instanceof Error ? e.message : String(e) };
47
+ return {
48
+ success: false,
49
+ error: e instanceof Error ? e.message : String(e),
50
+ networkError: true,
51
+ };
48
52
  }
49
53
  }
package/dist/scheduler.js CHANGED
@@ -2,7 +2,7 @@ import { homedir, platform } from "os";
2
2
  import { join } from "path";
3
3
  import { writeFileSync, existsSync, mkdirSync } from "fs";
4
4
  import { execSync } from "child_process";
5
- import { INSTALL_DIR, LOG_FILE, ensureInstallDir } from "./config.js";
5
+ import { INSTALL_DIR, LOG_FILE, ensureInstallDir, saveSchedule } from "./config.js";
6
6
  import { dirname } from "path";
7
7
  import { fileURLToPath } from "url";
8
8
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -24,6 +24,7 @@ function nodeExecutable() {
24
24
  */
25
25
  export async function setupScheduler(options) {
26
26
  const { hour, minute } = options;
27
+ saveSchedule({ hour, minute });
27
28
  if (IS_MAC) {
28
29
  return setupLaunchd(hour, minute);
29
30
  }
@@ -173,6 +174,15 @@ function setupLaunchd(hour, minute) {
173
174
  console.log(`Failed to load catch-up scheduler: ${String(error)}`);
174
175
  return false;
175
176
  }
177
+ // Start one check immediately. RunAtLoad is not reliable when an agent is
178
+ // registered after the user session has already started.
179
+ try {
180
+ execSync(`launchctl kickstart -k ${LAUNCHD_DOMAIN}/com.kalvium.worklog.catchup`, { stdio: "ignore" });
181
+ }
182
+ catch (error) {
183
+ console.log(`Failed to start catch-up check: ${String(error)}`);
184
+ return false;
185
+ }
176
186
  console.log(`Daily auto-submit installed (${formatTime(hour, minute)} Monday-Friday)`);
177
187
  console.log(" + Catch-up check on login/wake (every 30 min)");
178
188
  return true;
package/dist/submit.d.ts CHANGED
@@ -23,7 +23,9 @@ export declare function checkStatus(): Promise<void>;
23
23
  * Skips weekends. Logs to file.
24
24
  * Retries on network failure (up to 5 times with 60s delay).
25
25
  */
26
- export declare function dailySubmit(): Promise<boolean>;
26
+ export declare function dailySubmit(options?: {
27
+ allowInteractiveLogin?: boolean;
28
+ }): Promise<boolean>;
27
29
  /**
28
30
  * Catch-up check: if it's a weekday and today's worklog hasn't been
29
31
  * submitted yet, submit it. Used on login/wake to handle missed runs.
package/dist/submit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getLocalDate, getWorklogApi, log } from "./config.js";
1
+ import { getCatchupDate, getLocalDate, getWorklogApi, loadSchedule, log, setCatchupDate, } from "./config.js";
2
2
  import { refreshToken } from "./refresh.js";
3
3
  import { captureToken } from "./capture-token.js";
4
4
  const STATUS_KEY = "on_site";
@@ -42,6 +42,12 @@ export async function submitWorklog(options = {}) {
42
42
  // Step 1: Refresh token
43
43
  const refreshResult = await refreshToken();
44
44
  if (!refreshResult.success || !refreshResult.accessToken) {
45
+ if (refreshResult.networkError) {
46
+ return {
47
+ success: false,
48
+ message: `Network error while refreshing token: ${refreshResult.error ?? "connection failed"}`,
49
+ };
50
+ }
45
51
  if (attempt === 0 && allowInteractiveLogin) {
46
52
  console.log("Token expired. Auto re-logging in via browser...");
47
53
  const reloginOk = await captureToken();
@@ -114,6 +120,10 @@ export async function checkStatus() {
114
120
  for (let attempt = 0; attempt < 2; attempt++) {
115
121
  const refreshResult = await refreshToken();
116
122
  if (!refreshResult.success || !refreshResult.accessToken) {
123
+ if (refreshResult.networkError) {
124
+ console.log(`ERROR: Network error while refreshing token: ${refreshResult.error}`);
125
+ return;
126
+ }
117
127
  if (attempt === 0) {
118
128
  console.log("Token expired. Auto re-logging in via browser...");
119
129
  const reloginOk = await captureToken();
@@ -170,7 +180,7 @@ export async function checkStatus() {
170
180
  * Skips weekends. Logs to file.
171
181
  * Retries on network failure (up to 5 times with 60s delay).
172
182
  */
173
- export async function dailySubmit() {
183
+ export async function dailySubmit(options = {}) {
174
184
  const day = new Date().getDay();
175
185
  if (day === 0 || day === 6) {
176
186
  log("[INFO] Weekend - skipping");
@@ -190,7 +200,7 @@ export async function dailySubmit() {
190
200
  // A persistent Google session can restore an expired Kalvium token
191
201
  // without user input. If Google needs a password or 2FA, the browser
192
202
  // remains available for the user to complete that security check.
193
- allowInteractiveLogin: true,
203
+ allowInteractiveLogin: options.allowInteractiveLogin ?? true,
194
204
  });
195
205
  if (result.success) {
196
206
  log(`[INFO] SUCCESS: ${result.message}`);
@@ -244,6 +254,17 @@ export async function catchUpSubmit() {
244
254
  if (day === 0 || day === 6) {
245
255
  return true; // weekend, nothing to do
246
256
  }
257
+ const today = getLocalDate();
258
+ if (getCatchupDate() === today)
259
+ return true;
260
+ const schedule = loadSchedule();
261
+ if (schedule) {
262
+ const now = new Date();
263
+ if (now.getHours() * 60 + now.getMinutes() <
264
+ schedule.hour * 60 + schedule.minute) {
265
+ return true;
266
+ }
267
+ }
247
268
  log("[INFO] Catch-up check: verifying today's worklog...");
248
269
  // Check if today's worklog was already submitted
249
270
  const worklogApi = getWorklogApi();
@@ -265,11 +286,11 @@ export async function catchUpSubmit() {
265
286
  if (res.ok) {
266
287
  const worklogs = await res.json();
267
288
  if (Array.isArray(worklogs)) {
268
- const today = getLocalDate();
269
289
  const todayEntry = worklogs.find((w) => (w.worklogDate ?? "").slice(0, 10) === today &&
270
290
  w.status === "complete");
271
291
  if (todayEntry) {
272
292
  log("[INFO] Today's worklog already submitted. No catch-up needed.");
293
+ setCatchupDate(today);
273
294
  return true;
274
295
  }
275
296
  }
@@ -282,5 +303,8 @@ export async function catchUpSubmit() {
282
303
  }
283
304
  // Today's worklog is missing — submit it
284
305
  log("[INFO] Today's worklog is missing. Running catch-up submit...");
285
- return dailySubmit();
306
+ const submitted = await dailySubmit();
307
+ if (submitted)
308
+ setCatchupDate(today);
309
+ return submitted;
286
310
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kalvium-worklog",
3
- "version": "1.6.8",
3
+ "version": "1.7.0",
4
4
  "description": "Auto-submit your daily Kalvium worklog without opening the website",
5
5
  "keywords": [
6
6
  "kalvium",