kalvium-worklog 1.4.5 → 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
@@ -16,6 +16,7 @@ kalvium-worklog install
16
16
 
17
17
  # Or step by step:
18
18
  kalvium-worklog login # log in via browser (Google + 2FA)
19
+ kalvium-worklog login --email you@example.com # select an account at Google's chooser
19
20
  kalvium-worklog discover # auto-discover your position ID
20
21
  kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
21
22
  ```
@@ -35,16 +36,22 @@ kalvium-worklog schedule 14:00 # daily auto-submit at 2 PM
35
36
  | `kalvium-worklog schedule --remove` | Remove daily auto-submit |
36
37
  | `kalvium-worklog daily` | Run daily submit (used by scheduler) |
37
38
  | `kalvium-worklog catchup` | Check if today's worklog is missing and submit if needed |
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 |
38
44
 
39
45
  ## Features
40
46
 
41
47
  - **Cross-platform**: macOS (launchd), Windows (Task Scheduler), Linux (cron)
42
- - **Auto re-login**: If the token expires, automatically opens browser, waits for login, and retries
48
+ - **Automatic re-login attempt**: If a refresh token expires, the scheduled task opens the persistent browser profile and retries automatically when the existing Google session is still valid
43
49
  - **Token auto-refresh**: Refresh token rotates on each use, lasts 6 days
44
50
  - **Auto-discovers position ID**: Works for any user, no hardcoded IDs
45
51
  - **Weekend skipping**: Auto-submit skips Saturdays and Sundays
46
52
  - **Network retry**: Retries up to 5 times on network failure (covers laptop waking up, internet reconnecting)
47
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
48
55
 
49
56
  ## How It Works
50
57
 
@@ -54,13 +61,31 @@ One-time setup:
54
61
 
55
62
  Daily auto-submit (scheduler):
56
63
  Refresh token → PUT worklog API → done
57
- If token expired → auto open browser → re-login → retry
64
+ If token expired → open persistent browser → capture a new token → retry
58
65
  If network fails → retry up to 5 times (1 min apart)
59
66
 
60
67
  Catch-up (on login/wake, every 30 min):
61
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
62
83
  ```
63
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
+
64
89
  ## Token Lifecycle
65
90
 
66
91
  - **Access token**: 3 days
@@ -1,7 +1,8 @@
1
+ export interface CaptureTokenOptions {
2
+ email?: string;
3
+ }
1
4
  /**
2
5
  * Try headless mode first (fast — works if session is still valid).
3
6
  * If no session, opens a headed browser and waits for manual login.
4
- * On platforms without Playwright (e.g. Android/Termux), uses a
5
- * reverse proxy to capture the token automatically.
6
7
  */
7
- export declare function captureToken(): Promise<boolean>;
8
+ export declare function captureToken(options?: CaptureTokenOptions): Promise<boolean>;
@@ -1,231 +1,185 @@
1
- import { PROFILE_DIR, TOKEN_FILE, ensureInstallDir, saveToken, } from "./config.js";
2
- import * as readline from "readline";
3
- /**
4
- * Check if Playwright is available on this platform.
5
- * Playwright doesn't support Android/Termux.
6
- */
7
- function isPlaywrightAvailable() {
8
- try {
9
- if (process.platform === "android")
10
- return false;
11
- require.resolve("playwright");
12
- return true;
13
- }
14
- catch {
15
- return false;
16
- }
17
- }
1
+ import { PROFILE_DIR, ensureInstallDir, loadToken, saveToken, } from "./config.js";
2
+ const LOGIN_URL = "https://kalvium.community/internships";
3
+ const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
18
4
  /**
19
5
  * Try headless mode first (fast — works if session is still valid).
20
6
  * If no session, opens a headed browser and waits for manual login.
21
- * On platforms without Playwright (e.g. Android/Termux), uses a
22
- * reverse proxy to capture the token automatically.
23
7
  */
24
- export async function captureToken() {
8
+ export async function captureToken(options = {}) {
25
9
  ensureInstallDir();
26
- if (!isPlaywrightAvailable()) {
27
- return captureTokenViaProxy();
28
- }
29
- const { chromium } = await import("playwright");
30
- console.log("Trying headless mode (existing session)...");
31
- let data = await tryCapture(chromium, true);
32
- if (data) {
33
- console.log(" Session still valid — token captured!");
34
- }
35
- else {
36
- console.log(" No valid session. Opening browser for manual login...");
37
- data = await tryCapture(chromium, false);
10
+ try {
11
+ const { chromium } = await import("playwright");
12
+ console.log("Opening browser for login...");
13
+ const previousRefreshToken = loadToken()?.refresh_token;
14
+ const data = await tryCapture(chromium, options.email, previousRefreshToken);
15
+ if (data) {
16
+ saveToken(data);
17
+ console.log("Login complete. Secure refresh token saved.");
18
+ return true;
19
+ }
20
+ console.log("Login did not complete before the timeout. Please try again.");
21
+ return false;
38
22
  }
39
- if (data) {
40
- saveToken(data);
41
- console.log(`\nToken saved to ${TOKEN_FILE}`);
42
- console.log(` Access token expires in: ${data.expires_in ?? "?"} seconds`);
43
- console.log(` Refresh token expires in: ${data.refresh_expires_in ?? "?"} seconds`);
44
- return true;
23
+ catch (error) {
24
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
25
+ console.log(`Could not open the login browser: ${message}`);
26
+ return false;
45
27
  }
46
- console.log("\nERROR: Could not capture token. Please log in and try again.");
47
- return false;
48
28
  }
49
29
  /**
50
- * Capture token on platforms without Playwright (Android/Termux).
51
- * Simple manual paste — user gets token from desktop and pastes it.
30
+ * Try to capture token by loading the page and extracting it from localStorage.
31
+ * Opens headed browser and waits for manual login.
52
32
  */
53
- async function captureTokenViaProxy() {
54
- console.log("\n ========================================");
55
- console.log(" Token Setup (Android/Termux)");
56
- console.log(" ========================================\n");
57
- console.log(" Playwright doesn't work on Android, so you");
58
- console.log(" need to get your token from a desktop.\n");
59
- console.log(" ────────────────────────────────────────────");
60
- console.log(" ON YOUR DESKTOP/LAPTOP:");
61
- console.log(" ────────────────────────────────────────────");
62
- console.log(" 1. Install: npm install -g kalvium-worklog");
63
- console.log(" 2. Run: kalvium-worklog login");
64
- console.log(" 3. Log in with Google");
65
- console.log(" 4. Run: cat ~/.kalvium/refresh_token.json");
66
- console.log(" 5. Copy the entire JSON output\n");
67
- console.log(" ────────────────────────────────────────────");
68
- console.log(" THEN ON YOUR PHONE:");
69
- console.log(" ────────────────────────────────────────────");
70
- console.log(" 6. Paste the JSON below\n");
71
- return captureTokenManual();
72
- }
73
- /**
74
- * Manual token capture — fallback.
75
- * Prompts the user to paste a refresh token JSON.
76
- */
77
- async function captureTokenManual() {
78
- console.log("\n ========================================");
79
- console.log(" Manual token setup");
80
- console.log(" ========================================\n");
81
- console.log(" To get your token:");
82
- console.log(" 1. Run `kalvium-worklog login` on a desktop/laptop");
83
- console.log(" 2. Copy the contents of ~/.kalvium/refresh_token.json");
84
- console.log(" 3. Paste it below\n");
85
- const rl = readline.createInterface({
86
- input: process.stdin,
87
- output: process.stdout,
33
+ async function tryCapture(chromium, email, previousRefreshToken) {
34
+ const context = await chromium.launchPersistentContext(PROFILE_DIR, {
35
+ headless: false,
36
+ viewport: null,
88
37
  });
89
- const ask = (q) => new Promise((resolve) => rl.question(q, resolve));
90
- const input = await ask("Paste token JSON here: ");
91
- rl.close();
38
+ let captured = null;
39
+ const selectedAccountPages = new Set();
92
40
  try {
93
- const data = JSON.parse(input.trim());
94
- if (!data.refresh_token) {
95
- console.log("ERROR: Invalid token JSON — missing refresh_token field.");
96
- return false;
41
+ // Catch the Keycloak token exchange directly. This is more reliable than
42
+ // relying on a Kalvium localStorage key that can change after deployments.
43
+ context.on("response", (response) => {
44
+ if (!response.url().includes("/openid-connect/token"))
45
+ return;
46
+ void response.json().then((data) => {
47
+ const token = tokenFromUnknown(data);
48
+ if (token && isNewUsableToken(token, previousRefreshToken)) {
49
+ captured ??= token;
50
+ }
51
+ }).catch(() => undefined);
52
+ });
53
+ const page = context.pages()[0] || await context.newPage();
54
+ console.log(" ========================================");
55
+ console.log(" Browser opened. Complete Google login and 2FA if prompted.");
56
+ console.log(" This command will finish automatically after Kalvium loads.");
57
+ console.log(" ========================================");
58
+ await page.goto(LOGIN_URL, { waitUntil: "domcontentloaded", timeout: 120000 });
59
+ try {
60
+ await page.getByRole("button", { name: /continue with google/i }).first().click({ timeout: 5000 });
61
+ console.log(" Clicked 'Continue with Google'.");
62
+ }
63
+ catch {
64
+ // An existing session may bypass this button.
97
65
  }
98
- saveToken(data);
99
- console.log(`\nToken saved to ${TOKEN_FILE}`);
66
+ const deadline = Date.now() + LOGIN_TIMEOUT_MS;
67
+ while (Date.now() < deadline) {
68
+ if (captured)
69
+ return captured;
70
+ for (const openPage of context.pages()) {
71
+ if (!selectedAccountPages.has(openPage)) {
72
+ const selected = await selectGoogleAccount(openPage, email);
73
+ if (selected)
74
+ selectedAccountPages.add(openPage);
75
+ }
76
+ const token = await readStoredToken(openPage);
77
+ if (token && isNewUsableToken(token, previousRefreshToken)) {
78
+ captured ??= token;
79
+ }
80
+ if (captured)
81
+ return captured;
82
+ }
83
+ await new Promise((resolve) => setTimeout(resolve, 1000));
84
+ }
85
+ return null;
86
+ }
87
+ finally {
88
+ await context.close().catch(() => undefined);
89
+ }
90
+ }
91
+ async function selectGoogleAccount(page, email) {
92
+ if (!email || !page.url().includes("accounts.google.com"))
93
+ return false;
94
+ try {
95
+ await page
96
+ .locator("[data-identifier]")
97
+ .filter({ hasText: email })
98
+ .first()
99
+ .click({ timeout: 500 });
100
+ console.log(` Selected ${email}.`);
100
101
  return true;
101
102
  }
102
103
  catch {
103
- console.log("ERROR: Invalid JSON. Please paste the full token JSON.");
104
+ // The page may be on password/2FA or not have loaded its account list yet.
104
105
  return false;
105
106
  }
106
107
  }
107
- async function tryCapture(chromium, headless) {
108
- const tokenData = {};
109
- const context = await chromium.launchPersistentContext(PROFILE_DIR, {
110
- headless: false,
111
- args: [
112
- "--disable-blink-features=AutomationControlled",
113
- ...(headless ? ["--headless=new"] : []),
114
- ],
115
- });
116
- const page = context.pages()[0] ?? (await context.newPage());
117
- context.route("**/openid-connect/token", (route) => {
118
- if (route.request().method() === "POST") {
119
- route.fetch().then((response) => {
120
- response
121
- .text()
122
- .then((text) => {
123
- try {
124
- const data = JSON.parse(text);
125
- if (data.refresh_token) {
126
- if (!headless)
127
- console.log(" Refresh token captured!");
128
- tokenData.data = data;
129
- }
130
- }
131
- catch {
132
- // ignore
133
- }
134
- })
135
- .catch(() => { });
136
- route.fulfill({ response }).catch(() => { });
137
- });
138
- }
139
- else {
140
- route.continue().catch(() => { });
141
- }
142
- });
143
- if (headless) {
144
- console.log("Loading kalvium.community/internships (headless)...");
145
- try {
146
- await page.goto("https://kalvium.community/internships", {
147
- waitUntil: "domcontentloaded",
148
- timeout: 30000,
149
- });
150
- await page
151
- .waitForLoadState("networkidle", { timeout: 10000 })
152
- .catch(() => { });
153
- const googleBtn = page.locator("text=Continue with Google").first();
154
- const isVisible = await googleBtn.isVisible().catch(() => false);
155
- if (isVisible) {
156
- await googleBtn.click();
157
- console.log(" Clicked 'Continue with Google' (headless)...");
158
- for (let i = 0; i < 15; i++) {
159
- if (tokenData.data)
160
- break;
161
- await page.waitForTimeout(1000);
108
+ async function readStoredToken(page) {
109
+ if (!page.url().includes("kalvium.community"))
110
+ return null;
111
+ try {
112
+ const values = await page.evaluate(() => {
113
+ const read = (storage) => {
114
+ const values = [];
115
+ for (let index = 0; index < storage.length; index += 1) {
116
+ const key = storage.key(index);
117
+ if (key)
118
+ values.push(storage.getItem(key) ?? "");
162
119
  }
163
- }
164
- if (!tokenData.data) {
165
- await page.waitForTimeout(5000);
166
- }
167
- }
168
- catch {
169
- // ignore
120
+ return values;
121
+ };
122
+ return [...read(localStorage), ...read(sessionStorage)];
123
+ });
124
+ for (const value of values) {
125
+ const token = tokenFromUnknown(value);
126
+ if (token)
127
+ return token;
170
128
  }
171
129
  }
172
- else {
173
- console.log("\n ========================================");
174
- console.log(" Browser opened. Auto-clicking 'Continue with Google'...");
175
- console.log(" Please complete 2FA if prompted.");
176
- console.log(" ========================================\n");
177
- await page.goto("https://kalvium.community/internships", {
178
- waitUntil: "domcontentloaded",
179
- timeout: 120000,
180
- });
130
+ catch {
131
+ // The browser can be changing origins while Google redirects back.
132
+ }
133
+ return null;
134
+ }
135
+ function tokenFromUnknown(value) {
136
+ let parsed = value;
137
+ if (typeof value === "string") {
181
138
  try {
182
- const googleBtn = page.locator("text=Continue with Google").first();
183
- const isVisible = await googleBtn.isVisible().catch(() => false);
184
- if (isVisible) {
185
- await googleBtn.click();
186
- console.log(" Clicked 'Continue with Google'.");
187
- }
188
- else {
189
- await page
190
- .locator("button:has-text('Google'), a:has-text('Google')")
191
- .first()
192
- .click({ timeout: 5000 })
193
- .catch(() => { });
194
- console.log(" Clicked Google login button.");
195
- }
139
+ parsed = JSON.parse(value);
196
140
  }
197
141
  catch {
198
- console.log(" Could not auto-click. Please click 'Continue with Google' manually.");
199
- }
200
- console.log(" Waiting for login to complete (up to 5 minutes)...");
201
- for (let i = 0; i < 300; i++) {
202
- if (tokenData.data)
203
- break;
204
- await page.waitForTimeout(1000);
205
- if (i > 0 && i % 30 === 0) {
206
- const url = page.url();
207
- if (url.includes("kalvium.community/internships") &&
208
- !url.includes("error")) {
209
- await page
210
- .waitForLoadState("networkidle", { timeout: 5000 })
211
- .catch(() => { });
212
- }
213
- }
214
- }
215
- if (!tokenData.data) {
216
- console.log(" Trying page reload to trigger token exchange...");
217
- try {
218
- await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 });
219
- await page
220
- .waitForLoadState("networkidle", { timeout: 15000 })
221
- .catch(() => { });
222
- await page.waitForTimeout(8000);
223
- }
224
- catch {
225
- // ignore
226
- }
142
+ return null;
227
143
  }
228
144
  }
229
- await context.close();
230
- return tokenData.data ?? null;
145
+ if (!parsed || typeof parsed !== "object")
146
+ return null;
147
+ const data = parsed;
148
+ const accessToken = data.access_token ?? data.accessToken;
149
+ const refreshToken = data.refresh_token ?? data.refreshToken;
150
+ if (typeof accessToken === "string" && typeof refreshToken === "string") {
151
+ return {
152
+ access_token: accessToken,
153
+ refresh_token: refreshToken,
154
+ expires_in: typeof data.expires_in === "number" ? data.expires_in : undefined,
155
+ refresh_expires_in: typeof data.refresh_expires_in === "number" ? data.refresh_expires_in : undefined,
156
+ token_type: typeof data.token_type === "string" ? data.token_type : undefined,
157
+ session_state: typeof data.session_state === "string" ? data.session_state : undefined,
158
+ };
159
+ }
160
+ for (const nestedValue of Object.values(data)) {
161
+ const token = tokenFromUnknown(nestedValue);
162
+ if (token)
163
+ return token;
164
+ }
165
+ return null;
166
+ }
167
+ function isNewUsableToken(token, previousRefreshToken) {
168
+ if (token.refresh_token === previousRefreshToken)
169
+ return false;
170
+ const payload = decodeJwtPayload(token.refresh_token);
171
+ if (!payload || typeof payload.exp !== "number")
172
+ return true;
173
+ return payload.exp > Math.floor(Date.now() / 1000);
174
+ }
175
+ function decodeJwtPayload(token) {
176
+ try {
177
+ const payload = token.split(".")[1];
178
+ if (!payload)
179
+ return null;
180
+ return JSON.parse(Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf-8"));
181
+ }
182
+ catch {
183
+ return null;
184
+ }
231
185
  }
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"));
@@ -23,8 +24,9 @@ program
23
24
  program
24
25
  .command("login")
25
26
  .description("Log in to Kalvium and capture refresh token (opens browser)")
26
- .action(async () => {
27
- const ok = await captureToken();
27
+ .option("--email <email>", "Google account to select when the account chooser appears")
28
+ .action(async (opts) => {
29
+ const ok = await captureToken({ email: opts.email });
28
30
  if (!ok)
29
31
  process.exit(1);
30
32
  });
@@ -83,6 +85,45 @@ program
83
85
  if (!ok)
84
86
  process.exit(1);
85
87
  });
88
+ // ─── trigger ───────────────────────────────────────────────────────────────
89
+ program
90
+ .command("trigger")
91
+ .description("Run the safe catch-up check now (submits only if today's worklog is missing)")
92
+ .action(async () => {
93
+ const ok = await catchUpSubmit();
94
+ if (!ok)
95
+ process.exit(1);
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
+ });
86
127
  // ─── schedule ──────────────────────────────────────────────────────────────
87
128
  program
88
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>;