kalvium-worklog 1.6.8 → 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 +25 -0
- package/dist/cli.js +39 -0
- package/dist/cloud.d.ts +27 -0
- package/dist/cloud.js +368 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.js +32 -2
- package/dist/refresh.d.ts +1 -0
- package/dist/refresh.js +5 -1
- package/dist/scheduler.d.ts +3 -0
- package/dist/scheduler.js +72 -1
- package/dist/submit.d.ts +3 -1
- package/dist/submit.js +29 -5
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -37,6 +37,11 @@ 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 |
|
|
44
|
+
| `kalvium-worklog cloud monitor --remove` | Remove the macOS cloud-login recovery monitor |
|
|
40
45
|
|
|
41
46
|
## Features
|
|
42
47
|
|
|
@@ -47,6 +52,8 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
|
|
|
47
52
|
- **Weekend skipping**: Auto-submit skips Saturdays and Sundays
|
|
48
53
|
- **Network retry**: Retries up to 5 times on network failure (covers laptop waking up, internet reconnecting)
|
|
49
54
|
- **Catch-up on wake**: If the scheduled time was missed (laptop asleep/offline), submits when the device wakes up
|
|
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
|
|
50
57
|
|
|
51
58
|
## How It Works
|
|
52
59
|
|
|
@@ -61,8 +68,26 @@ Daily auto-submit (scheduler):
|
|
|
61
68
|
|
|
62
69
|
Catch-up (on login/wake, every 30 min):
|
|
63
70
|
Check if today's worklog is submitted → if not, submit it
|
|
71
|
+
|
|
72
|
+
Cloud mode (optional):
|
|
73
|
+
GitHub Actions checks every 30 min around the chosen time
|
|
74
|
+
Transient network failures retry up to 5 times (1 min apart)
|
|
75
|
+
Rotated refresh token is written back to the private repo's KATTEND_TOKEN secret
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## GitHub Actions mode
|
|
79
|
+
|
|
80
|
+
Install and configure the local login, position, and schedule first. Then authenticate the GitHub CLI and run:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
gh auth login
|
|
84
|
+
kalvium-worklog cloud init --repo owner/kalvium-attendance-cloud
|
|
64
85
|
```
|
|
65
86
|
|
|
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`.
|
|
88
|
+
|
|
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`.
|
|
90
|
+
|
|
66
91
|
## Token Lifecycle
|
|
67
92
|
|
|
68
93
|
- **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, cloudMonitorRemove, 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,44 @@ 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("--email <email>", "Google account for unattended account-chooser selection")
|
|
103
|
+
.option("--reuse", "reuse the separately saved cloud login")
|
|
104
|
+
.option("--login", "refresh the separate cloud login during sync")
|
|
105
|
+
.option("--remove", "remove the local cloud recovery monitor (for cloud monitor)")
|
|
106
|
+
.action(async (action, opts) => {
|
|
107
|
+
const cliPath = join(__dirname, "cli.js");
|
|
108
|
+
switch (action) {
|
|
109
|
+
case "init":
|
|
110
|
+
await cloudInit({ cliPath, version: VERSION, repoName: opts.repo, reuse: opts.reuse, email: opts.email });
|
|
111
|
+
return;
|
|
112
|
+
case "run":
|
|
113
|
+
await cloudRun();
|
|
114
|
+
return;
|
|
115
|
+
case "sync":
|
|
116
|
+
await cloudSync({ cliPath, version: VERSION, login: opts.login, email: opts.email });
|
|
117
|
+
return;
|
|
118
|
+
case "status":
|
|
119
|
+
cloudStatus();
|
|
120
|
+
return;
|
|
121
|
+
case "test":
|
|
122
|
+
cloudTest();
|
|
123
|
+
return;
|
|
124
|
+
case "monitor":
|
|
125
|
+
if (opts.remove)
|
|
126
|
+
cloudMonitorRemove();
|
|
127
|
+
else
|
|
128
|
+
await cloudSync({ cliPath, version: VERSION, email: opts.email });
|
|
129
|
+
return;
|
|
130
|
+
default:
|
|
131
|
+
console.error("Use: kalvium-worklog cloud init | run | sync [--login] | status | test | monitor [--remove]");
|
|
132
|
+
process.exitCode = 1;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
96
135
|
// ─── schedule ──────────────────────────────────────────────────────────────
|
|
97
136
|
program
|
|
98
137
|
.command("schedule [time]")
|
package/dist/cloud.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
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
|
+
email?: string;
|
|
8
|
+
}): Promise<void>;
|
|
9
|
+
export declare function cloudSync(options: {
|
|
10
|
+
cliPath: string;
|
|
11
|
+
version: string;
|
|
12
|
+
login?: boolean;
|
|
13
|
+
email?: string;
|
|
14
|
+
}): Promise<void>;
|
|
15
|
+
export declare function cloudStatus(): void;
|
|
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;
|
|
27
|
+
export declare function cloudRun(): Promise<void>;
|
package/dist/cloud.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
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
|
+
import { log } from "./config.js";
|
|
9
|
+
import { setupCloudRepairScheduler, removeCloudRepairScheduler } from "./scheduler.js";
|
|
10
|
+
// Reuse the browser profile already created by kalvium-attendance, but keep
|
|
11
|
+
// Worklog's rotated refresh token in its own file to avoid token races.
|
|
12
|
+
const CLOUD_HOME = path.join(os.homedir(), ".kalvium-attendance-cloud");
|
|
13
|
+
const CLOUD_CONFIG = path.join(INSTALL_DIR, "cloud.json");
|
|
14
|
+
const WORKFLOW_PATH = ".github/workflows/attendance.yml";
|
|
15
|
+
const SECRET_TOKEN = "KATTEND_TOKEN";
|
|
16
|
+
const SECRET_CONFIG = "KATTEND_CONFIG";
|
|
17
|
+
const SECRET_PAT = "KATTEND_PAT";
|
|
18
|
+
function gh(args, input) {
|
|
19
|
+
const result = spawnSync("gh", args, {
|
|
20
|
+
encoding: "utf8",
|
|
21
|
+
input,
|
|
22
|
+
windowsHide: true,
|
|
23
|
+
});
|
|
24
|
+
if (result.error?.code === "ENOENT") {
|
|
25
|
+
throw new Error("GitHub CLI is required. Install gh, then run: gh auth login");
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
function requireGh() {
|
|
30
|
+
if (gh(["auth", "status"]).status !== 0) {
|
|
31
|
+
throw new Error("Not logged in to GitHub. Run: gh auth login");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function runGh(args, input) {
|
|
35
|
+
const result = gh(args, input);
|
|
36
|
+
if (result.status !== 0) {
|
|
37
|
+
throw new Error((result.stderr || result.stdout || "GitHub CLI command failed").trim());
|
|
38
|
+
}
|
|
39
|
+
return result.stdout.trim();
|
|
40
|
+
}
|
|
41
|
+
async function ask(prompt, defaultValue) {
|
|
42
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
43
|
+
try {
|
|
44
|
+
const suffix = defaultValue ? ` (${defaultValue})` : "";
|
|
45
|
+
return (await rl.question(`${prompt}${suffix}: `)).trim() || defaultValue || "";
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
rl.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function askHidden(prompt) {
|
|
52
|
+
process.stdout.write(prompt);
|
|
53
|
+
if (!process.stdin.isTTY || !process.stdin.setRawMode) {
|
|
54
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
55
|
+
try {
|
|
56
|
+
return (await rl.question("")).trim();
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
rl.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const stdin = process.stdin;
|
|
63
|
+
stdin.setRawMode(true);
|
|
64
|
+
stdin.resume();
|
|
65
|
+
stdin.setEncoding("utf8");
|
|
66
|
+
return new Promise((resolve) => {
|
|
67
|
+
let value = "";
|
|
68
|
+
const onData = (chunk) => {
|
|
69
|
+
for (const char of chunk) {
|
|
70
|
+
if (char === "\r" || char === "\n") {
|
|
71
|
+
stdin.setRawMode(false);
|
|
72
|
+
stdin.pause();
|
|
73
|
+
stdin.off("data", onData);
|
|
74
|
+
process.stdout.write("\n");
|
|
75
|
+
resolve(value.trim());
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (char === "\u0003")
|
|
79
|
+
process.exit(130);
|
|
80
|
+
if (char === "\u007f" || char === "\b")
|
|
81
|
+
value = value.slice(0, -1);
|
|
82
|
+
else
|
|
83
|
+
value += char;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
stdin.on("data", onData);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function readCloudConfig() {
|
|
90
|
+
try {
|
|
91
|
+
return JSON.parse(fs.readFileSync(CLOUD_CONFIG, "utf8"));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
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
|
+
}
|
|
103
|
+
function requireRepo() {
|
|
104
|
+
const repo = readCloudConfig()?.cloudRepo;
|
|
105
|
+
if (!repo)
|
|
106
|
+
throw new Error("Cloud mode is not set up. Run: kalvium-worklog cloud init");
|
|
107
|
+
return repo;
|
|
108
|
+
}
|
|
109
|
+
function cloudLogin(cliPath, email) {
|
|
110
|
+
fs.mkdirSync(CLOUD_HOME, { recursive: true, mode: 0o700 });
|
|
111
|
+
console.log("Opening a separate Kalvium login for GitHub Actions.");
|
|
112
|
+
const args = [cliPath, "login"];
|
|
113
|
+
if (email)
|
|
114
|
+
args.push("--email", email);
|
|
115
|
+
const result = spawnSync(process.execPath, args, {
|
|
116
|
+
stdio: "inherit",
|
|
117
|
+
env: {
|
|
118
|
+
...process.env,
|
|
119
|
+
KWORKLOG_HOME: CLOUD_HOME,
|
|
120
|
+
KWORKLOG_PROFILE_DIR: path.join(CLOUD_HOME, "browser-profile"),
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
if (result.status !== 0 || !fs.existsSync(path.join(CLOUD_HOME, "refresh_token.json"))) {
|
|
124
|
+
throw new Error("Cloud login did not complete.");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export function cronFor(time, offsetMin = new Date().getTimezoneOffset()) {
|
|
128
|
+
const match = /^(\d{1,2}):(\d{2})$/.exec(time);
|
|
129
|
+
if (!match)
|
|
130
|
+
throw new Error(`Invalid time "${time}". Use HH:MM, e.g. 12:30`);
|
|
131
|
+
const hour = Number(match[1]);
|
|
132
|
+
const minute = Number(match[2]);
|
|
133
|
+
if (hour > 23 || minute > 59)
|
|
134
|
+
throw new Error(`Invalid time "${time}".`);
|
|
135
|
+
const hours = new Set();
|
|
136
|
+
const base = hour * 60 + minute + offsetMin;
|
|
137
|
+
for (let offset = -30; offset <= 240; offset += 30) {
|
|
138
|
+
const utcMinutes = ((base + offset) % 1440 + 1440) % 1440;
|
|
139
|
+
hours.add(Math.floor(utcMinutes / 60));
|
|
140
|
+
}
|
|
141
|
+
return `7,37 ${[...hours].sort((a, b) => a - b).join(",")} * * *`;
|
|
142
|
+
}
|
|
143
|
+
function workflowYaml(config, version) {
|
|
144
|
+
return `# Generated by kalvium-worklog. Run kalvium-worklog cloud sync to update.
|
|
145
|
+
name: Kalvium worklog
|
|
146
|
+
on:
|
|
147
|
+
schedule:
|
|
148
|
+
- cron: "${cronFor(config.time)}"
|
|
149
|
+
workflow_dispatch:
|
|
150
|
+
concurrency:
|
|
151
|
+
group: kalvium-worklog
|
|
152
|
+
cancel-in-progress: false
|
|
153
|
+
permissions: {}
|
|
154
|
+
jobs:
|
|
155
|
+
submit:
|
|
156
|
+
runs-on: ubuntu-latest
|
|
157
|
+
timeout-minutes: 15
|
|
158
|
+
env:
|
|
159
|
+
TZ: ${config.timezone}
|
|
160
|
+
KWORKLOG_HOME: /tmp/kalvium-worklog
|
|
161
|
+
KATTEND_TOKEN_JSON: \${{ secrets.${SECRET_TOKEN} }}
|
|
162
|
+
KATTEND_CONFIG_JSON: \${{ secrets.${SECRET_CONFIG} }}
|
|
163
|
+
GH_TOKEN: \${{ secrets.${SECRET_PAT} }}
|
|
164
|
+
steps:
|
|
165
|
+
- uses: actions/setup-node@v4
|
|
166
|
+
with:
|
|
167
|
+
node-version: 20
|
|
168
|
+
- name: Submit daily worklog
|
|
169
|
+
run: npx --yes kalvium-worklog@${version} cloud run
|
|
170
|
+
`;
|
|
171
|
+
}
|
|
172
|
+
function putWorkflow(repo, content) {
|
|
173
|
+
const api = `repos/${repo}/contents/${WORKFLOW_PATH}`;
|
|
174
|
+
const existingSha = gh(["api", api, "--jq", ".sha"]);
|
|
175
|
+
const args = [
|
|
176
|
+
"api", "-X", "PUT", api,
|
|
177
|
+
"-f", "message=Update Kalvium worklog workflow",
|
|
178
|
+
"-f", `content=${Buffer.from(content).toString("base64")}`,
|
|
179
|
+
];
|
|
180
|
+
if (existingSha.status === 0 && existingSha.stdout.trim()) {
|
|
181
|
+
args.push("-f", `sha=${existingSha.stdout.trim()}`);
|
|
182
|
+
}
|
|
183
|
+
runGh(args);
|
|
184
|
+
}
|
|
185
|
+
function setSecret(repo, name, value) {
|
|
186
|
+
runGh(["secret", "set", name, "--repo", repo], value);
|
|
187
|
+
}
|
|
188
|
+
function currentCloudConfig(repo) {
|
|
189
|
+
const local = loadConfig();
|
|
190
|
+
if (!local?.position_id || !local.worklog_api_url) {
|
|
191
|
+
throw new Error("Run kalvium-worklog discover before setting up cloud mode.");
|
|
192
|
+
}
|
|
193
|
+
const schedule = loadSchedule() ?? { hour: 12, minute: 30 };
|
|
194
|
+
return {
|
|
195
|
+
position_id: local.position_id,
|
|
196
|
+
worklog_api_url: local.worklog_api_url,
|
|
197
|
+
time: `${String(schedule.hour).padStart(2, "0")}:${String(schedule.minute).padStart(2, "0")}`,
|
|
198
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
199
|
+
cloudRepo: repo,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function secretConfig(config) {
|
|
203
|
+
return JSON.stringify({
|
|
204
|
+
position_id: config.position_id,
|
|
205
|
+
worklog_api_url: config.worklog_api_url,
|
|
206
|
+
time: config.time,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
export async function cloudInit(options) {
|
|
210
|
+
requireGh();
|
|
211
|
+
const owner = runGh(["api", "user", "--jq", ".login"]);
|
|
212
|
+
const requested = options.repoName || await ask("Private GitHub repo name", "kalvium-attendance-cloud");
|
|
213
|
+
const repo = requested.includes("/") ? requested : `${owner}/${requested}`;
|
|
214
|
+
const cloudTokenFile = path.join(CLOUD_HOME, "refresh_token.json");
|
|
215
|
+
if (!(options.reuse && fs.existsSync(cloudTokenFile)))
|
|
216
|
+
cloudLogin(options.cliPath, options.email);
|
|
217
|
+
const config = currentCloudConfig(repo);
|
|
218
|
+
console.log(`This will configure the private repo ${repo} to run at ${config.time} ${config.timezone}.`);
|
|
219
|
+
if ((await ask("Continue? (yes/no)", "no")).toLowerCase() !== "yes")
|
|
220
|
+
throw new Error("Cancelled.");
|
|
221
|
+
const created = gh(["repo", "create", repo, "--private", "--description", "Daily Kalvium worklog automation"]);
|
|
222
|
+
if (created.status !== 0 && !/already exists/i.test(created.stderr)) {
|
|
223
|
+
throw new Error((created.stderr || "Could not create the GitHub repository.").trim());
|
|
224
|
+
}
|
|
225
|
+
const pat = process.env.KATTEND_PAT || await askHidden("Fine-grained PAT (repo Secrets: read/write; input hidden): ");
|
|
226
|
+
if (!pat)
|
|
227
|
+
throw new Error("A GitHub token is required to save rotated refresh tokens.");
|
|
228
|
+
setSecret(repo, SECRET_TOKEN, fs.readFileSync(cloudTokenFile, "utf8"));
|
|
229
|
+
setSecret(repo, SECRET_CONFIG, secretConfig(config));
|
|
230
|
+
setSecret(repo, SECRET_PAT, pat);
|
|
231
|
+
putWorkflow(repo, workflowYaml(config, options.version));
|
|
232
|
+
saveCloudMetadata(repo, options.email);
|
|
233
|
+
setupCloudRepairScheduler(options.cliPath, options.version);
|
|
234
|
+
console.log(`Cloud worklog enabled for ${repo} at ${config.time} ${config.timezone}.`);
|
|
235
|
+
}
|
|
236
|
+
export async function cloudSync(options) {
|
|
237
|
+
requireGh();
|
|
238
|
+
const repo = requireRepo();
|
|
239
|
+
if (options.login) {
|
|
240
|
+
cloudLogin(options.cliPath, options.email || readCloudConfig()?.email);
|
|
241
|
+
const tokenFile = path.join(CLOUD_HOME, "refresh_token.json");
|
|
242
|
+
setSecret(repo, SECRET_TOKEN, fs.readFileSync(tokenFile, "utf8"));
|
|
243
|
+
}
|
|
244
|
+
const config = currentCloudConfig(repo);
|
|
245
|
+
setSecret(repo, SECRET_CONFIG, secretConfig(config));
|
|
246
|
+
putWorkflow(repo, workflowYaml(config, options.version));
|
|
247
|
+
saveCloudMetadata(repo, options.email);
|
|
248
|
+
setupCloudRepairScheduler(options.cliPath, options.version);
|
|
249
|
+
console.log(`Synced cloud worklog settings${options.login ? " and refreshed its login" : ""}.`);
|
|
250
|
+
}
|
|
251
|
+
export function cloudStatus() {
|
|
252
|
+
requireGh();
|
|
253
|
+
const repo = requireRepo();
|
|
254
|
+
console.log(`Repo: https://github.com/${repo}`);
|
|
255
|
+
const result = gh(["run", "list", "--repo", repo, "--limit", "8"]);
|
|
256
|
+
if (result.status !== 0)
|
|
257
|
+
throw new Error((result.stderr || "Could not read workflow runs.").trim());
|
|
258
|
+
console.log(result.stdout.trim() || "No runs yet.");
|
|
259
|
+
}
|
|
260
|
+
export function cloudTest() {
|
|
261
|
+
requireGh();
|
|
262
|
+
const repo = requireRepo();
|
|
263
|
+
runGh(["workflow", "run", "attendance.yml", "--repo", repo]);
|
|
264
|
+
console.log(`Started a run. Check https://github.com/${repo}/actions`);
|
|
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
|
+
}
|
|
332
|
+
export async function cloudRun() {
|
|
333
|
+
const tokenJson = process.env.KATTEND_TOKEN_JSON;
|
|
334
|
+
const configJson = process.env.KATTEND_CONFIG_JSON;
|
|
335
|
+
if (!tokenJson || !configJson)
|
|
336
|
+
throw new Error("Cloud token/config secrets are missing. Run cloud sync --login.");
|
|
337
|
+
const config = JSON.parse(configJson);
|
|
338
|
+
const mappedConfig = {
|
|
339
|
+
position_id: config.position_id,
|
|
340
|
+
worklog_api_url: config.worklog_api_url,
|
|
341
|
+
};
|
|
342
|
+
if (!mappedConfig.position_id || !mappedConfig.worklog_api_url) {
|
|
343
|
+
throw new Error("Cloud config is missing the internship position or worklog URL.");
|
|
344
|
+
}
|
|
345
|
+
ensureInstallDir();
|
|
346
|
+
fs.writeFileSync(TOKEN_FILE, tokenJson, { mode: 0o600 });
|
|
347
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify(mappedConfig), { mode: 0o600 });
|
|
348
|
+
const scheduled = /^(\d{1,2}):(\d{2})$/.exec(config.time || "12:30");
|
|
349
|
+
if (scheduled) {
|
|
350
|
+
const now = new Date();
|
|
351
|
+
const due = Number(scheduled[1]) * 60 + Number(scheduled[2]);
|
|
352
|
+
if (now.getHours() * 60 + now.getMinutes() < due) {
|
|
353
|
+
console.log("Not due yet; the next scheduled check will retry.");
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const submitted = await dailySubmit({ allowInteractiveLogin: false });
|
|
358
|
+
const updatedToken = fs.readFileSync(TOKEN_FILE, "utf8");
|
|
359
|
+
if (updatedToken !== tokenJson) {
|
|
360
|
+
const repo = process.env.GITHUB_REPOSITORY || requireRepo();
|
|
361
|
+
if (!process.env.GH_TOKEN)
|
|
362
|
+
throw new Error(`Token rotated but cannot be saved; configure ${SECRET_PAT}.`);
|
|
363
|
+
setSecret(repo, SECRET_TOKEN, updatedToken);
|
|
364
|
+
console.log("Saved rotated Kalvium token.");
|
|
365
|
+
}
|
|
366
|
+
if (!submitted)
|
|
367
|
+
throw new Error("Worklog cloud run failed; see the log output above.");
|
|
368
|
+
}
|
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 =
|
|
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
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 {
|
|
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.d.ts
CHANGED
|
@@ -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
|
@@ -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));
|
|
@@ -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"]
|
|
@@ -24,6 +25,7 @@ function nodeExecutable() {
|
|
|
24
25
|
*/
|
|
25
26
|
export async function setupScheduler(options) {
|
|
26
27
|
const { hour, minute } = options;
|
|
28
|
+
saveSchedule({ hour, minute });
|
|
27
29
|
if (IS_MAC) {
|
|
28
30
|
return setupLaunchd(hour, minute);
|
|
29
31
|
}
|
|
@@ -173,6 +175,15 @@ function setupLaunchd(hour, minute) {
|
|
|
173
175
|
console.log(`Failed to load catch-up scheduler: ${String(error)}`);
|
|
174
176
|
return false;
|
|
175
177
|
}
|
|
178
|
+
// Start one check immediately. RunAtLoad is not reliable when an agent is
|
|
179
|
+
// registered after the user session has already started.
|
|
180
|
+
try {
|
|
181
|
+
execSync(`launchctl kickstart -k ${LAUNCHD_DOMAIN}/com.kalvium.worklog.catchup`, { stdio: "ignore" });
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
console.log(`Failed to start catch-up check: ${String(error)}`);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
176
187
|
console.log(`Daily auto-submit installed (${formatTime(hour, minute)} Monday-Friday)`);
|
|
177
188
|
console.log(" + Catch-up check on login/wake (every 30 min)");
|
|
178
189
|
return true;
|
|
@@ -187,6 +198,66 @@ function unloadLaunchAgent(plistPath) {
|
|
|
187
198
|
// The task might not have been loaded yet.
|
|
188
199
|
}
|
|
189
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
|
+
}
|
|
190
261
|
function setupTaskScheduler(hour, minute) {
|
|
191
262
|
const dailyScript = copyDailyScript();
|
|
192
263
|
const nodePath = nodeExecutable();
|
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(
|
|
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
|
-
|
|
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.
|
|
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/
|
|
16
|
+
"url": "git+https://github.com/EmperorKP/kalvium-worklog.git"
|
|
17
17
|
},
|
|
18
|
-
"homepage": "https://github.com/
|
|
18
|
+
"homepage": "https://github.com/EmperorKP/kalvium-worklog#readme",
|
|
19
19
|
"bugs": {
|
|
20
|
-
"url": "https://github.com/
|
|
20
|
+
"url": "https://github.com/EmperorKP/kalvium-worklog/issues"
|
|
21
21
|
},
|
|
22
22
|
"type": "module",
|
|
23
23
|
"main": "dist/index.js",
|