kalvium-worklog 1.4.4 → 1.6.8

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,11 +36,12 @@ 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 |
38
40
 
39
41
  ## Features
40
42
 
41
43
  - **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
44
+ - **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
45
  - **Token auto-refresh**: Refresh token rotates on each use, lasts 6 days
44
46
  - **Auto-discovers position ID**: Works for any user, no hardcoded IDs
45
47
  - **Weekend skipping**: Auto-submit skips Saturdays and Sundays
@@ -54,7 +56,7 @@ One-time setup:
54
56
 
55
57
  Daily auto-submit (scheduler):
56
58
  Refresh token → PUT worklog API → done
57
- If token expired → auto open browser → re-login → retry
59
+ If token expired → open persistent browser → capture a new token → retry
58
60
  If network fails → retry up to 5 times (1 min apart)
59
61
 
60
62
  Catch-up (on login/wake, every 30 min):
@@ -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,438 +1,185 @@
1
- import { PROFILE_DIR, TOKEN_FILE, ensureInstallDir, saveToken, } from "./config.js";
2
- import * as readline from "readline";
3
- import { createServer } from "http";
4
- import { request as httpRequest } from "https";
5
- import { execSync } from "child_process";
6
- /**
7
- * Check if Playwright is available on this platform.
8
- * Playwright doesn't support Android/Termux.
9
- */
10
- function isPlaywrightAvailable() {
11
- try {
12
- if (process.platform === "android")
13
- return false;
14
- require.resolve("playwright");
15
- return true;
16
- }
17
- catch {
18
- return false;
19
- }
20
- }
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;
21
4
  /**
22
5
  * Try headless mode first (fast — works if session is still valid).
23
6
  * If no session, opens a headed browser and waits for manual login.
24
- * On platforms without Playwright (e.g. Android/Termux), uses a
25
- * reverse proxy to capture the token automatically.
26
7
  */
27
- export async function captureToken() {
8
+ export async function captureToken(options = {}) {
28
9
  ensureInstallDir();
29
- if (!isPlaywrightAvailable()) {
30
- return captureTokenViaProxy();
31
- }
32
- const { chromium } = await import("playwright");
33
- console.log("Trying headless mode (existing session)...");
34
- let data = await tryCapture(chromium, true);
35
- if (data) {
36
- console.log(" Session still valid — token captured!");
37
- }
38
- else {
39
- console.log(" No valid session. Opening browser for manual login...");
40
- 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;
41
22
  }
42
- if (data) {
43
- saveToken(data);
44
- console.log(`\nToken saved to ${TOKEN_FILE}`);
45
- console.log(` Access token expires in: ${data.expires_in ?? "?"} seconds`);
46
- console.log(` Refresh token expires in: ${data.refresh_expires_in ?? "?"} seconds`);
47
- 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;
48
27
  }
49
- console.log("\nERROR: Could not capture token. Please log in and try again.");
50
- return false;
51
28
  }
52
29
  /**
53
- * Capture token via reverse proxy (for Android/Termux without Playwright).
54
- *
55
- * Starts a local server on port 4567 that proxies kalvium.community.
56
- * The user navigates to http://localhost:4567, logs in normally,
57
- * and the proxy intercepts the Keycloak token exchange automatically.
58
- *
59
- * No javascript: injection, no bookmarklets — just log in normally.
30
+ * Try to capture token by loading the page and extracting it from localStorage.
31
+ * Opens headed browser and waits for manual login.
60
32
  */
61
- async function captureTokenViaProxy() {
62
- const PORT = 4567;
63
- const TARGET = "kalvium.community";
64
- const AUTH_TARGET = "auth.kalvium.community";
65
- console.log("\n ========================================");
66
- console.log(" Reverse proxy token capture (no Playwright)");
67
- console.log(" ========================================\n");
68
- let capturedToken = null;
69
- const tokenPromise = new Promise((resolve) => {
70
- const server = createServer((req, res) => {
71
- // Handle CORS
72
- res.setHeader("Access-Control-Allow-Origin", "*");
73
- res.setHeader("Access-Control-Allow-Headers", "*");
74
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
75
- if (req.method === "OPTIONS") {
76
- res.writeHead(204);
77
- res.end();
78
- return;
79
- }
80
- const url = new URL(req.url ?? "/", `http://localhost:${PORT}`);
81
- // Check if we already captured the token — serve success page
82
- if (url.pathname === "/__done__") {
83
- res.writeHead(200, { "Content-Type": "text/html" });
84
- res.end(`<html><body style="font-family:sans-serif;text-align:center;padding:40px">
85
- <h2>✓ Token captured!</h2>
86
- <p>You can close this tab and go back to Termux.</p>
87
- </body></html>`);
88
- return;
89
- }
90
- // Determine which backend to proxy to
91
- let targetHost = TARGET;
92
- let targetPath = req.url ?? "/";
93
- // Route auth requests to auth.kalvium.community
94
- if (url.pathname.startsWith("/auth/") || url.pathname.startsWith("/realms/")) {
95
- targetHost = AUTH_TARGET;
96
- targetPath = req.url ?? "/";
97
- }
98
- // Intercept token exchange requests
99
- if (url.pathname.includes("openid-connect/token") &&
100
- req.method === "POST") {
101
- // Collect body
102
- let body = "";
103
- req.on("data", (chunk) => {
104
- body += chunk;
105
- });
106
- req.on("end", () => {
107
- // Forward to actual Keycloak
108
- const proxyReq = httpRequest({
109
- hostname: AUTH_TARGET,
110
- port: 443,
111
- path: url.pathname,
112
- method: "POST",
113
- headers: {
114
- "content-type": "application/x-www-form-urlencoded",
115
- "content-length": Buffer.byteLength(body),
116
- },
117
- }, (proxyRes) => {
118
- let responseBody = "";
119
- proxyRes.on("data", (chunk) => {
120
- responseBody += chunk;
121
- });
122
- proxyRes.on("end", () => {
123
- // Try to capture token from response
124
- try {
125
- const data = JSON.parse(responseBody);
126
- if (data.refresh_token) {
127
- console.log(" Refresh token captured from proxy!");
128
- capturedToken = data;
129
- resolve(data);
130
- }
131
- }
132
- catch {
133
- // not JSON, ignore
134
- }
135
- // Send response back to browser
136
- res.writeHead(proxyRes.statusCode ?? 200, {
137
- "content-type": proxyRes.headers["content-type"] ?? "application/json",
138
- "access-control-allow-origin": "*",
139
- });
140
- res.end(responseBody);
141
- });
142
- });
143
- proxyReq.on("error", () => {
144
- res.writeHead(502);
145
- res.end("Proxy error");
146
- });
147
- proxyReq.write(body);
148
- proxyReq.end();
149
- });
33
+ async function tryCapture(chromium, email, previousRefreshToken) {
34
+ const context = await chromium.launchPersistentContext(PROFILE_DIR, {
35
+ headless: false,
36
+ viewport: null,
37
+ });
38
+ let captured = null;
39
+ const selectedAccountPages = new Set();
40
+ try {
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"))
150
45
  return;
151
- }
152
- // Proxy all other requests to kalvium.community
153
- const proxyHeaders = {};
154
- for (const [key, value] of Object.entries(req.headers)) {
155
- if (key === "host")
156
- continue;
157
- if (Array.isArray(value)) {
158
- proxyHeaders[key] = value.join(", ");
159
- }
160
- else if (value) {
161
- proxyHeaders[key] = value;
46
+ void response.json().then((data) => {
47
+ const token = tokenFromUnknown(data);
48
+ if (token && isNewUsableToken(token, previousRefreshToken)) {
49
+ captured ??= token;
162
50
  }
163
- }
164
- proxyHeaders["host"] = targetHost;
165
- const proxyReq = httpRequest({
166
- hostname: targetHost,
167
- port: 443,
168
- path: targetPath,
169
- method: req.method ?? "GET",
170
- headers: proxyHeaders,
171
- }, (proxyRes) => {
172
- // Rewrite location headers to point back to proxy
173
- const headers = {};
174
- for (const [key, value] of Object.entries(proxyRes.headers)) {
175
- if (key === "location" && typeof value === "string") {
176
- // Rewrite kalvium.community URLs to localhost
177
- let rewritten = value
178
- .replace(/https:\/\/kalvium\.community/g, `http://localhost:${PORT}`)
179
- .replace(/https:\/\/auth\.kalvium\.community/g, `http://localhost:${PORT}`);
180
- headers[key] = rewritten;
181
- }
182
- else if (key === "content-security-policy") {
183
- // Relax CSP to allow the proxy to work
184
- headers[key] = value;
185
- }
186
- else if (key === "strict-transport-security") {
187
- // Skip HSTS
188
- continue;
189
- }
190
- else if (Array.isArray(value)) {
191
- headers[key] = value.join(", ");
192
- }
193
- else if (value) {
194
- headers[key] = value;
195
- }
196
- }
197
- // Rewrite set-cookie domains
198
- if (headers["set-cookie"]) {
199
- headers["set-cookie"] = headers["set-cookie"].replace(/domain=\.kalvium\.community/gi, `domain=localhost`);
200
- }
201
- res.writeHead(proxyRes.statusCode ?? 200, headers);
202
- // For HTML responses, rewrite URLs
203
- const contentType = proxyRes.headers["content-type"] ?? "";
204
- if (contentType.includes("text/html") || contentType.includes("javascript") || contentType.includes("css")) {
205
- let body = "";
206
- proxyRes.on("data", (chunk) => {
207
- body += chunk.toString();
208
- });
209
- proxyRes.on("end", () => {
210
- // Rewrite absolute URLs to go through proxy
211
- const rewritten = body
212
- .replace(/https:\/\/kalvium\.community/g, `http://localhost:${PORT}`)
213
- .replace(/https:\/\/auth\.kalvium\.community/g, `http://localhost:${PORT}`)
214
- .replace(/https:\/\/student-api\.kalvium\.community/g, `http://localhost:${PORT}/api`);
215
- res.end(rewritten);
216
- });
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.
65
+ }
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);
217
75
  }
218
- else {
219
- proxyRes.pipe(res);
76
+ const token = await readStoredToken(openPage);
77
+ if (token && isNewUsableToken(token, previousRefreshToken)) {
78
+ captured ??= token;
220
79
  }
221
- });
222
- proxyReq.on("error", () => {
223
- res.writeHead(502);
224
- res.end("Proxy error — check your internet connection");
225
- });
226
- // Forward request body for POST/PUT
227
- if (req.method === "POST" || req.method === "PUT") {
228
- req.pipe(proxyReq);
229
- }
230
- else {
231
- proxyReq.end();
232
- }
233
- });
234
- server.listen(PORT, () => {
235
- console.log(` Proxy server running on http://localhost:${PORT}`);
236
- });
237
- // Timeout after 5 minutes
238
- setTimeout(() => {
239
- if (!capturedToken) {
240
- server.close();
241
- resolve(null);
80
+ if (captured)
81
+ return captured;
242
82
  }
243
- }, 300000);
244
- });
245
- // Open the proxy URL in the phone's default browser
246
- const proxyUrl = `http://localhost:${PORT}/internships`;
247
- try {
248
- if (process.platform === "android") {
249
- execSync(`termux-open-url ${proxyUrl}`, { stdio: "ignore" });
83
+ await new Promise((resolve) => setTimeout(resolve, 1000));
250
84
  }
251
- else {
252
- execSync(`xdg-open ${proxyUrl} || open ${proxyUrl}`, {
253
- stdio: "ignore",
254
- });
255
- }
256
- console.log(` Opened ${proxyUrl} in your browser.`);
85
+ return null;
257
86
  }
258
- catch {
259
- console.log(` Could not auto-open browser. Please open: ${proxyUrl}`);
87
+ finally {
88
+ await context.close().catch(() => undefined);
260
89
  }
261
- console.log("\n ────────────────────────────────────────────");
262
- console.log(" A page opened in your browser.");
263
- console.log(" Just log in with Google normally.");
264
- console.log(" The token is captured automatically — no");
265
- console.log(" javascript: or bookmarks needed.");
266
- console.log(" ────────────────────────────────────────────");
267
- console.log("\n Waiting for login (up to 5 minutes)...\n");
268
- const data = await tokenPromise;
269
- if (data) {
270
- saveToken(data);
271
- console.log(`\n✓ Token captured and saved to ${TOKEN_FILE}`);
272
- console.log(` Access token expires in: ${data.expires_in ?? "?"} seconds`);
273
- console.log(` Refresh token expires in: ${data.refresh_expires_in ?? "?"} seconds`);
274
- return true;
275
- }
276
- // Fallback: manual paste
277
- console.log("\n Proxy capture failed. Let's try manual paste.");
278
- return captureTokenManual();
279
90
  }
280
- /**
281
- * Manual token capture — fallback.
282
- * Prompts the user to paste a refresh token JSON.
283
- */
284
- async function captureTokenManual() {
285
- console.log("\n ========================================");
286
- console.log(" Manual token setup");
287
- console.log(" ========================================\n");
288
- console.log(" To get your token:");
289
- console.log(" 1. Run `kalvium-worklog login` on a desktop/laptop");
290
- console.log(" 2. Copy the contents of ~/.kalvium/refresh_token.json");
291
- console.log(" 3. Paste it below\n");
292
- const rl = readline.createInterface({
293
- input: process.stdin,
294
- output: process.stdout,
295
- });
296
- const ask = (q) => new Promise((resolve) => rl.question(q, resolve));
297
- const input = await ask("Paste token JSON here: ");
298
- rl.close();
91
+ async function selectGoogleAccount(page, email) {
92
+ if (!email || !page.url().includes("accounts.google.com"))
93
+ return false;
299
94
  try {
300
- const data = JSON.parse(input.trim());
301
- if (!data.refresh_token) {
302
- console.log("ERROR: Invalid token JSON — missing refresh_token field.");
303
- return false;
304
- }
305
- saveToken(data);
306
- console.log(`\nToken saved to ${TOKEN_FILE}`);
95
+ await page
96
+ .locator("[data-identifier]")
97
+ .filter({ hasText: email })
98
+ .first()
99
+ .click({ timeout: 500 });
100
+ console.log(` Selected ${email}.`);
307
101
  return true;
308
102
  }
309
103
  catch {
310
- 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.
311
105
  return false;
312
106
  }
313
107
  }
314
- async function tryCapture(chromium, headless) {
315
- const tokenData = {};
316
- const context = await chromium.launchPersistentContext(PROFILE_DIR, {
317
- headless: false,
318
- args: [
319
- "--disable-blink-features=AutomationControlled",
320
- ...(headless ? ["--headless=new"] : []),
321
- ],
322
- });
323
- const page = context.pages()[0] ?? (await context.newPage());
324
- context.route("**/openid-connect/token", (route) => {
325
- if (route.request().method() === "POST") {
326
- route.fetch().then((response) => {
327
- response
328
- .text()
329
- .then((text) => {
330
- try {
331
- const data = JSON.parse(text);
332
- if (data.refresh_token) {
333
- if (!headless)
334
- console.log(" Refresh token captured!");
335
- tokenData.data = data;
336
- }
337
- }
338
- catch {
339
- // ignore
340
- }
341
- })
342
- .catch(() => { });
343
- route.fulfill({ response }).catch(() => { });
344
- });
345
- }
346
- else {
347
- route.continue().catch(() => { });
348
- }
349
- });
350
- if (headless) {
351
- console.log("Loading kalvium.community/internships (headless)...");
352
- try {
353
- await page.goto("https://kalvium.community/internships", {
354
- waitUntil: "domcontentloaded",
355
- timeout: 30000,
356
- });
357
- await page
358
- .waitForLoadState("networkidle", { timeout: 10000 })
359
- .catch(() => { });
360
- const googleBtn = page.locator("text=Continue with Google").first();
361
- const isVisible = await googleBtn.isVisible().catch(() => false);
362
- if (isVisible) {
363
- await googleBtn.click();
364
- console.log(" Clicked 'Continue with Google' (headless)...");
365
- for (let i = 0; i < 15; i++) {
366
- if (tokenData.data)
367
- break;
368
- 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) ?? "");
369
119
  }
370
- }
371
- if (!tokenData.data) {
372
- await page.waitForTimeout(5000);
373
- }
374
- }
375
- catch {
376
- // 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;
377
128
  }
378
129
  }
379
- else {
380
- console.log("\n ========================================");
381
- console.log(" Browser opened. Auto-clicking 'Continue with Google'...");
382
- console.log(" Please complete 2FA if prompted.");
383
- console.log(" ========================================\n");
384
- await page.goto("https://kalvium.community/internships", {
385
- waitUntil: "domcontentloaded",
386
- timeout: 120000,
387
- });
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") {
388
138
  try {
389
- const googleBtn = page.locator("text=Continue with Google").first();
390
- const isVisible = await googleBtn.isVisible().catch(() => false);
391
- if (isVisible) {
392
- await googleBtn.click();
393
- console.log(" Clicked 'Continue with Google'.");
394
- }
395
- else {
396
- await page
397
- .locator("button:has-text('Google'), a:has-text('Google')")
398
- .first()
399
- .click({ timeout: 5000 })
400
- .catch(() => { });
401
- console.log(" Clicked Google login button.");
402
- }
139
+ parsed = JSON.parse(value);
403
140
  }
404
141
  catch {
405
- console.log(" Could not auto-click. Please click 'Continue with Google' manually.");
406
- }
407
- console.log(" Waiting for login to complete (up to 5 minutes)...");
408
- for (let i = 0; i < 300; i++) {
409
- if (tokenData.data)
410
- break;
411
- await page.waitForTimeout(1000);
412
- if (i > 0 && i % 30 === 0) {
413
- const url = page.url();
414
- if (url.includes("kalvium.community/internships") &&
415
- !url.includes("error")) {
416
- await page
417
- .waitForLoadState("networkidle", { timeout: 5000 })
418
- .catch(() => { });
419
- }
420
- }
421
- }
422
- if (!tokenData.data) {
423
- console.log(" Trying page reload to trigger token exchange...");
424
- try {
425
- await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 });
426
- await page
427
- .waitForLoadState("networkidle", { timeout: 15000 })
428
- .catch(() => { });
429
- await page.waitForTimeout(8000);
430
- }
431
- catch {
432
- // ignore
433
- }
142
+ return null;
434
143
  }
435
144
  }
436
- await context.close();
437
- 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
+ }
438
185
  }
package/dist/cli.js CHANGED
@@ -23,8 +23,9 @@ program
23
23
  program
24
24
  .command("login")
25
25
  .description("Log in to Kalvium and capture refresh token (opens browser)")
26
- .action(async () => {
27
- const ok = await captureToken();
26
+ .option("--email <email>", "Google account to select when the account chooser appears")
27
+ .action(async (opts) => {
28
+ const ok = await captureToken({ email: opts.email });
28
29
  if (!ok)
29
30
  process.exit(1);
30
31
  });
@@ -83,6 +84,15 @@ program
83
84
  if (!ok)
84
85
  process.exit(1);
85
86
  });
87
+ // ─── trigger ───────────────────────────────────────────────────────────────
88
+ program
89
+ .command("trigger")
90
+ .description("Run the safe catch-up check now (submits only if today's worklog is missing)")
91
+ .action(async () => {
92
+ const ok = await catchUpSubmit();
93
+ if (!ok)
94
+ process.exit(1);
95
+ });
86
96
  // ─── schedule ──────────────────────────────────────────────────────────────
87
97
  program
88
98
  .command("schedule [time]")
package/dist/config.d.ts CHANGED
@@ -23,6 +23,7 @@ export declare function loadToken(): TokenData | null;
23
23
  export declare function saveToken(data: TokenData): void;
24
24
  export declare function loadConfig(): ConfigData | null;
25
25
  export declare function saveConfig(config: ConfigData): void;
26
+ export declare function getLocalDate(date?: Date): string;
26
27
  export declare function getWorklogApi(): string | null;
27
28
  export declare function log(message: string): void;
28
29
  export declare function decodeJwt(token: string): Record<string, unknown> | null;
package/dist/config.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "os";
2
2
  import { join } from "path";
3
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "fs";
4
4
  export const INSTALL_DIR = join(homedir(), ".kalvium");
5
5
  export const PROFILE_DIR = join(homedir(), ".kalvium_profile");
6
6
  export const TOKEN_FILE = join(INSTALL_DIR, "refresh_token.json");
@@ -11,7 +11,13 @@ export const CLIENT_ID = "login_client";
11
11
  export const API_BASE = "https://student-api.kalvium.community/api/internships/worklogs";
12
12
  export function ensureInstallDir() {
13
13
  if (!existsSync(INSTALL_DIR)) {
14
- mkdirSync(INSTALL_DIR, { recursive: true });
14
+ mkdirSync(INSTALL_DIR, { recursive: true, mode: 0o700 });
15
+ }
16
+ try {
17
+ chmodSync(INSTALL_DIR, 0o700);
18
+ }
19
+ catch {
20
+ // Permissions are best effort on platforms without POSIX file modes.
15
21
  }
16
22
  }
17
23
  export function loadToken() {
@@ -27,6 +33,12 @@ export function loadToken() {
27
33
  export function saveToken(data) {
28
34
  ensureInstallDir();
29
35
  writeFileSync(TOKEN_FILE, JSON.stringify(data, null, 2));
36
+ try {
37
+ chmodSync(TOKEN_FILE, 0o600);
38
+ }
39
+ catch {
40
+ // Permissions are best effort on platforms without POSIX file modes.
41
+ }
30
42
  }
31
43
  export function loadConfig() {
32
44
  if (!existsSync(CONFIG_FILE))
@@ -41,6 +53,18 @@ export function loadConfig() {
41
53
  export function saveConfig(config) {
42
54
  ensureInstallDir();
43
55
  writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
56
+ try {
57
+ chmodSync(CONFIG_FILE, 0o600);
58
+ }
59
+ catch {
60
+ // Permissions are best effort on platforms without POSIX file modes.
61
+ }
62
+ }
63
+ export function getLocalDate(date = new Date()) {
64
+ const year = date.getFullYear();
65
+ const month = String(date.getMonth() + 1).padStart(2, "0");
66
+ const day = String(date.getDate()).padStart(2, "0");
67
+ return `${year}-${month}-${day}`;
44
68
  }
45
69
  export function getWorklogApi() {
46
70
  const config = loadConfig();
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * Discover the user's internship position ID.
3
3
  * Tries JWT extraction first (no browser needed).
4
- * Falls back to browser-based discovery via Playwright if available.
5
- * On Android, uses JWT extraction only.
4
+ * Falls back to browser-based discovery via Playwright.
6
5
  */
7
6
  export declare function discoverPosition(): Promise<boolean>;
@@ -1,23 +1,8 @@
1
1
  import { PROFILE_DIR, CONFIG_FILE, ensureInstallDir, saveConfig, loadToken, getPositionIdFromToken, } from "./config.js";
2
- /**
3
- * Check if Playwright is available on this platform.
4
- */
5
- function isPlaywrightAvailable() {
6
- try {
7
- if (process.platform === "android")
8
- return false;
9
- require.resolve("playwright");
10
- return true;
11
- }
12
- catch {
13
- return false;
14
- }
15
- }
16
2
  /**
17
3
  * Discover the user's internship position ID.
18
4
  * Tries JWT extraction first (no browser needed).
19
- * Falls back to browser-based discovery via Playwright if available.
20
- * On Android, uses JWT extraction only.
5
+ * Falls back to browser-based discovery via Playwright.
21
6
  */
22
7
  export async function discoverPosition() {
23
8
  ensureInstallDir();
@@ -40,20 +25,10 @@ export async function discoverPosition() {
40
25
  else {
41
26
  console.log(" No token found. Run `kalvium-worklog login` first.");
42
27
  }
43
- // Step 2: Fall back to browser-based discovery (if Playwright available)
44
- if (!isPlaywrightAvailable()) {
45
- console.log("\nERROR: Could not discover position ID.");
46
- console.log("Playwright is not available on this platform.");
47
- console.log("Make sure you have a valid token (run `kalvium-worklog login`).");
48
- return false;
49
- }
28
+ // Step 2: Fall back to browser-based discovery
50
29
  const { chromium } = await import("playwright");
51
- console.log("\n1. Trying headless mode (existing session)...");
52
- let captured = await discoverViaBrowser(chromium, true);
53
- if (!captured.token) {
54
- console.log(" No valid session. Opening browser for manual login...");
55
- captured = await discoverViaBrowser(chromium, false);
56
- }
30
+ console.log("\nOpening browser for manual login...");
31
+ const captured = await discoverViaBrowser(chromium, false);
57
32
  if (!captured.token) {
58
33
  console.log("\nERROR: Could not capture token. Please log in and try again.");
59
34
  return false;
package/dist/refresh.js CHANGED
@@ -29,14 +29,21 @@ export async function refreshToken() {
29
29
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
30
30
  body,
31
31
  });
32
- const data = await res.json();
33
- if (data.error) {
34
- return { success: false, error: data.error };
32
+ const data = await res.json().catch(() => null);
33
+ if (!res.ok || !data || typeof data !== "object") {
34
+ const error = data && typeof data === "object" && "error" in data
35
+ ? String(data.error)
36
+ : `HTTP ${res.status}`;
37
+ return { success: false, error };
38
+ }
39
+ const token = data;
40
+ if (typeof token.access_token !== "string" || typeof token.refresh_token !== "string") {
41
+ return { success: false, error: "Invalid token response" };
35
42
  }
36
43
  saveToken(data);
37
- return { success: true, accessToken: data.access_token };
44
+ return { success: true, accessToken: token.access_token };
38
45
  }
39
46
  catch (e) {
40
- return { success: false, error: String(e) };
47
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
41
48
  }
42
49
  }
package/dist/scheduler.js CHANGED
@@ -9,6 +9,13 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
9
9
  const IS_MAC = platform() === "darwin";
10
10
  const IS_WINDOWS = platform() === "win32";
11
11
  const IS_LINUX = platform() === "linux";
12
+ const LAUNCHD_DOMAIN = `gui/${process.getuid?.() ?? 0}`;
13
+ function nodeExecutable() {
14
+ const stablePaths = IS_MAC
15
+ ? ["/opt/homebrew/bin/node", "/usr/local/bin/node"]
16
+ : [];
17
+ return stablePaths.find((path) => existsSync(path)) ?? process.execPath;
18
+ }
12
19
  /**
13
20
  * Set up daily auto-submit scheduler.
14
21
  * macOS: launchd
@@ -43,6 +50,8 @@ function formatTime(hour, minute) {
43
50
  function copyDailyScript() {
44
51
  ensureInstallDir();
45
52
  const distDir = __dirname;
53
+ // Generated wrappers are ESM but live outside the npm package.
54
+ writeFileSync(join(INSTALL_DIR, "package.json"), '{"type":"module"}\n');
46
55
  // Daily submit wrapper
47
56
  const dailyDst = join(INSTALL_DIR, "daily_submit.js");
48
57
  const dailyWrapper = `#!/usr/bin/env node
@@ -68,8 +77,21 @@ function setupLaunchd(hour, minute) {
68
77
  }
69
78
  const dailyScript = copyDailyScript();
70
79
  const catchupScript = join(INSTALL_DIR, "catchup_submit.js");
80
+ const nodePath = nodeExecutable();
71
81
  // ─── 1. Scheduled daily plist (fires at chosen time) ────────────────────
72
82
  const plistPath = join(launchAgentsDir, "com.kalvium.worklog.plist");
83
+ // launchd uses 1 for Sunday, so Monday through Friday are 2 through 6.
84
+ const weekdayIntervals = [2, 3, 4, 5, 6]
85
+ .map((weekday) => `
86
+ <dict>
87
+ <key>Hour</key>
88
+ <integer>${hour}</integer>
89
+ <key>Minute</key>
90
+ <integer>${minute}</integer>
91
+ <key>Weekday</key>
92
+ <integer>${weekday}</integer>
93
+ </dict>`)
94
+ .join("");
73
95
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
74
96
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
75
97
  <plist version="1.0">
@@ -78,24 +100,12 @@ function setupLaunchd(hour, minute) {
78
100
  <string>com.kalvium.worklog</string>
79
101
  <key>ProgramArguments</key>
80
102
  <array>
81
- <string>${process.execPath}</string>
103
+ <string>${nodePath}</string>
82
104
  <string>${dailyScript}</string>
83
105
  </array>
84
106
  <key>StartCalendarInterval</key>
85
- <dict>
86
- <key>Hour</key>
87
- <integer>${hour}</integer>
88
- <key>Minute</key>
89
- <integer>${minute}</integer>
90
- <key>Weekday</key>
91
- <array>
92
- <integer>1</integer>
93
- <integer>2</integer>
94
- <integer>3</integer>
95
- <integer>4</integer>
96
- <integer>5</integer>
97
- </array>
98
- </dict>
107
+ <array>${weekdayIntervals}
108
+ </array>
99
109
  <key>StandardOutPath</key>
100
110
  <string>${LOG_FILE}</string>
101
111
  <key>StandardErrorPath</key>
@@ -110,8 +120,16 @@ function setupLaunchd(hour, minute) {
110
120
  </dict>
111
121
  </plist>`;
112
122
  writeFileSync(plistPath, plist);
113
- execSync(`launchctl unload "${plistPath}"`, { stdio: "ignore" });
114
- execSync(`launchctl load "${plistPath}"`, { stdio: "ignore" });
123
+ unloadLaunchAgent(plistPath);
124
+ try {
125
+ execSync(`launchctl bootstrap ${LAUNCHD_DOMAIN} "${plistPath}"`, {
126
+ stdio: "ignore",
127
+ });
128
+ }
129
+ catch (error) {
130
+ console.log(`Failed to load daily scheduler: ${String(error)}`);
131
+ return false;
132
+ }
115
133
  // ─── 2. Catch-up plist (fires on login/wake — RunAtLoad) ────────────────
116
134
  // This checks if today's worklog was already submitted. If not, submits it.
117
135
  // Handles the case where the scheduled time was missed (laptop asleep/offline).
@@ -124,7 +142,7 @@ function setupLaunchd(hour, minute) {
124
142
  <string>com.kalvium.worklog.catchup</string>
125
143
  <key>ProgramArguments</key>
126
144
  <array>
127
- <string>${process.execPath}</string>
145
+ <string>${nodePath}</string>
128
146
  <string>${catchupScript}</string>
129
147
  </array>
130
148
  <key>RunAtLoad</key>
@@ -145,17 +163,36 @@ function setupLaunchd(hour, minute) {
145
163
  </dict>
146
164
  </plist>`;
147
165
  writeFileSync(catchupPlistPath, catchupPlist);
148
- execSync(`launchctl unload "${catchupPlistPath}"`, { stdio: "ignore" });
149
- execSync(`launchctl load "${catchupPlistPath}"`, { stdio: "ignore" });
150
- console.log(`Daily auto-submit installed (${formatTime(hour, minute)} every weekday)`);
166
+ unloadLaunchAgent(catchupPlistPath);
167
+ try {
168
+ execSync(`launchctl bootstrap ${LAUNCHD_DOMAIN} "${catchupPlistPath}"`, {
169
+ stdio: "ignore",
170
+ });
171
+ }
172
+ catch (error) {
173
+ console.log(`Failed to load catch-up scheduler: ${String(error)}`);
174
+ return false;
175
+ }
176
+ console.log(`Daily auto-submit installed (${formatTime(hour, minute)} Monday-Friday)`);
151
177
  console.log(" + Catch-up check on login/wake (every 30 min)");
152
178
  return true;
153
179
  }
180
+ function unloadLaunchAgent(plistPath) {
181
+ try {
182
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${plistPath}"`, {
183
+ stdio: "ignore",
184
+ });
185
+ }
186
+ catch {
187
+ // The task might not have been loaded yet.
188
+ }
189
+ }
154
190
  function setupTaskScheduler(hour, minute) {
155
191
  const dailyScript = copyDailyScript();
192
+ const nodePath = nodeExecutable();
156
193
  const batPath = join(INSTALL_DIR, "daily_submit.bat");
157
194
  // Create batch wrapper
158
- writeFileSync(batPath, `@echo off\r\n"${process.execPath}" "${dailyScript}"\r\n`);
195
+ writeFileSync(batPath, `@echo off\r\n"${nodePath}" "${dailyScript}"\r\n`);
159
196
  // Remove existing task
160
197
  try {
161
198
  execSync('schtasks /Delete /TN "KalviumWorklog" /F', { stdio: "ignore" });
@@ -178,7 +215,7 @@ function setupTaskScheduler(hour, minute) {
178
215
  }
179
216
  function setupCron(hour, minute) {
180
217
  const dailyScript = copyDailyScript();
181
- const cronLine = `${minute} ${hour} * * 1-5 ${process.execPath} ${dailyScript} >> ${LOG_FILE} 2>&1`;
218
+ const cronLine = `${minute} ${hour} * * 1-5 ${nodeExecutable()} ${dailyScript} >> ${LOG_FILE} 2>&1`;
182
219
  // Read existing crontab
183
220
  let crontab = "";
184
221
  try {
@@ -207,7 +244,7 @@ export async function removeScheduler() {
207
244
  // Remove daily plist
208
245
  const plistPath = join(homedir(), "Library/LaunchAgents/com.kalvium.worklog.plist");
209
246
  try {
210
- execSync(`launchctl unload "${plistPath}"`, { stdio: "ignore" });
247
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${plistPath}"`, { stdio: "ignore" });
211
248
  }
212
249
  catch {
213
250
  // ignore
@@ -218,7 +255,7 @@ export async function removeScheduler() {
218
255
  // Remove catch-up plist
219
256
  const catchupPlistPath = join(homedir(), "Library/LaunchAgents/com.kalvium.worklog.catchup.plist");
220
257
  try {
221
- execSync(`launchctl unload "${catchupPlistPath}"`, { stdio: "ignore" });
258
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${catchupPlistPath}"`, { stdio: "ignore" });
222
259
  }
223
260
  catch {
224
261
  // ignore
package/dist/submit.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export interface SubmitOptions {
2
2
  text?: string;
3
3
  dryRun?: boolean;
4
+ allowInteractiveLogin?: boolean;
4
5
  }
5
6
  export interface SubmitResult {
6
7
  success: boolean;
package/dist/submit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getWorklogApi, log } from "./config.js";
1
+ import { getLocalDate, getWorklogApi, log } 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";
@@ -11,6 +11,7 @@ const STATUS_LABEL = "Working on-site (Company location)";
11
11
  export async function submitWorklog(options = {}) {
12
12
  const text = options.text ?? "Working on assigned task";
13
13
  const dryRun = options.dryRun ?? false;
14
+ const allowInteractiveLogin = options.allowInteractiveLogin ?? true;
14
15
  const worklogApi = getWorklogApi();
15
16
  if (!worklogApi) {
16
17
  return {
@@ -25,7 +26,7 @@ export async function submitWorklog(options = {}) {
25
26
  timeSpent: 0,
26
27
  priorityLevel: "medium",
27
28
  blockers: "",
28
- worklogs: JSON.stringify({ content: `<p>${text}</p>` }),
29
+ worklogs: JSON.stringify({ content: `<p>${escapeHtml(text)}</p>` }),
29
30
  });
30
31
  if (dryRun) {
31
32
  console.log(`[DRY RUN] Would submit to ${worklogApi}`);
@@ -41,17 +42,14 @@ export async function submitWorklog(options = {}) {
41
42
  // Step 1: Refresh token
42
43
  const refreshResult = await refreshToken();
43
44
  if (!refreshResult.success || !refreshResult.accessToken) {
44
- if (attempt === 0) {
45
+ if (attempt === 0 && allowInteractiveLogin) {
45
46
  console.log("Token expired. Auto re-logging in via browser...");
46
47
  const reloginOk = await captureToken();
47
48
  if (reloginOk)
48
49
  continue;
49
50
  return { success: false, message: "Re-login failed" };
50
51
  }
51
- return {
52
- success: false,
53
- message: refreshResult.error ?? "Token refresh failed",
54
- };
52
+ return { success: false, message: authenticationMessage(refreshResult.error) };
55
53
  }
56
54
  // Step 2: Submit worklog
57
55
  console.log(`Submitting worklog: '${text}'...`);
@@ -78,7 +76,7 @@ export async function submitWorklog(options = {}) {
78
76
  };
79
77
  }
80
78
  // 401/403 = token invalid — try re-login
81
- if ((res.status === 401 || res.status === 403) && attempt === 0) {
79
+ if ((res.status === 401 || res.status === 403) && attempt === 0 && allowInteractiveLogin) {
82
80
  console.log(`Got HTTP ${res.status}. Token may be invalid. Trying re-login...`);
83
81
  const reloginOk = await captureToken();
84
82
  if (reloginOk)
@@ -146,7 +144,7 @@ export async function checkStatus() {
146
144
  console.log("ERROR: Invalid response");
147
145
  return;
148
146
  }
149
- const today = new Date().toISOString().slice(0, 10);
147
+ const today = getLocalDate();
150
148
  for (const w of worklogs.slice(0, 5)) {
151
149
  const date = (w.worklogDate ?? "").slice(0, 10);
152
150
  const status = w.status ?? "?";
@@ -189,19 +187,25 @@ export async function dailySubmit() {
189
187
  }
190
188
  const result = await submitWorklog({
191
189
  text: "Working on assigned task",
190
+ // A persistent Google session can restore an expired Kalvium token
191
+ // without user input. If Google needs a password or 2FA, the browser
192
+ // remains available for the user to complete that security check.
193
+ allowInteractiveLogin: true,
192
194
  });
193
195
  if (result.success) {
194
196
  log(`[INFO] SUCCESS: ${result.message}`);
195
197
  return true;
196
198
  }
197
199
  // Check if it's a network error (retry) vs a real error (give up)
198
- const isNetworkError = result.message.includes("fetch") ||
199
- result.message.includes("ECONNREFUSED") ||
200
- result.message.includes("ENOTFOUND") ||
201
- result.message.includes("ETIMEDOUT") ||
202
- result.message.includes("network") ||
203
- result.message.includes("Failed to fetch") ||
204
- result.message.includes("refresh failed");
200
+ const isAuthenticationError = result.message.startsWith("Authentication expired");
201
+ const isNetworkError = !isAuthenticationError &&
202
+ (result.message.includes("fetch") ||
203
+ result.message.includes("ECONNREFUSED") ||
204
+ result.message.includes("ENOTFOUND") ||
205
+ result.message.includes("ETIMEDOUT") ||
206
+ result.message.includes("network") ||
207
+ result.message.includes("Failed to fetch") ||
208
+ result.message.includes("refresh failed"));
205
209
  // "Already submitted" is a success, not an error
206
210
  if (result.message.includes("Already submitted")) {
207
211
  log(`[INFO] ${result.message}`);
@@ -218,6 +222,16 @@ export async function dailySubmit() {
218
222
  }
219
223
  return false;
220
224
  }
225
+ function authenticationMessage(reason) {
226
+ const detail = reason ? ` (${reason})` : "";
227
+ return `Authentication expired${detail}. Run \`kalvium-worklog login\` while you are at your computer, then retry.`;
228
+ }
229
+ function escapeHtml(value) {
230
+ const entities = {
231
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
232
+ };
233
+ return value.replace(/[&<>\"']/g, (character) => entities[character]);
234
+ }
221
235
  function sleep(ms) {
222
236
  return new Promise((resolve) => setTimeout(resolve, ms));
223
237
  }
@@ -251,7 +265,7 @@ export async function catchUpSubmit() {
251
265
  if (res.ok) {
252
266
  const worklogs = await res.json();
253
267
  if (Array.isArray(worklogs)) {
254
- const today = new Date().toISOString().slice(0, 10);
268
+ const today = getLocalDate();
255
269
  const todayEntry = worklogs.find((w) => (w.worklogDate ?? "").slice(0, 10) === today &&
256
270
  w.status === "complete");
257
271
  if (todayEntry) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kalvium-worklog",
3
- "version": "1.4.4",
3
+ "version": "1.6.8",
4
4
  "description": "Auto-submit your daily Kalvium worklog without opening the website",
5
5
  "keywords": [
6
6
  "kalvium",
@@ -37,10 +37,8 @@
37
37
  "postinstall": "node dist/postinstall.js"
38
38
  },
39
39
  "dependencies": {
40
- "commander": "^12.1.0"
41
- },
42
- "optionalDependencies": {
43
- "playwright": "^1.48.0"
40
+ "commander": "^12.1.0",
41
+ "playwright": "^1.64.1"
44
42
  },
45
43
  "devDependencies": {
46
44
  "@types/node": "^22.0.0",