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/dist/cloud.js ADDED
@@ -0,0 +1,288 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { spawnSync } from "child_process";
5
+ import { createInterface } from "readline/promises";
6
+ import { CONFIG_FILE, INSTALL_DIR, TOKEN_FILE, ensureInstallDir, loadConfig, loadSchedule, } from "./config.js";
7
+ import { dailySubmit } from "./submit.js";
8
+ // Reuse the browser profile already created by kalvium-attendance, but keep
9
+ // Worklog's rotated refresh token in its own file to avoid token races.
10
+ const CLOUD_HOME = path.join(os.homedir(), ".kalvium-attendance-cloud");
11
+ const CLOUD_CONFIG = path.join(INSTALL_DIR, "cloud.json");
12
+ const WORKFLOW_PATH = ".github/workflows/attendance.yml";
13
+ const SECRET_TOKEN = "KATTEND_TOKEN";
14
+ const SECRET_CONFIG = "KATTEND_CONFIG";
15
+ const SECRET_PAT = "KATTEND_PAT";
16
+ function gh(args, input) {
17
+ const result = spawnSync("gh", args, {
18
+ encoding: "utf8",
19
+ input,
20
+ windowsHide: true,
21
+ });
22
+ if (result.error?.code === "ENOENT") {
23
+ throw new Error("GitHub CLI is required. Install gh, then run: gh auth login");
24
+ }
25
+ return result;
26
+ }
27
+ function requireGh() {
28
+ if (gh(["auth", "status"]).status !== 0) {
29
+ throw new Error("Not logged in to GitHub. Run: gh auth login");
30
+ }
31
+ }
32
+ function runGh(args, input) {
33
+ const result = gh(args, input);
34
+ if (result.status !== 0) {
35
+ throw new Error((result.stderr || result.stdout || "GitHub CLI command failed").trim());
36
+ }
37
+ return result.stdout.trim();
38
+ }
39
+ async function ask(prompt, defaultValue) {
40
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
41
+ try {
42
+ const suffix = defaultValue ? ` (${defaultValue})` : "";
43
+ return (await rl.question(`${prompt}${suffix}: `)).trim() || defaultValue || "";
44
+ }
45
+ finally {
46
+ rl.close();
47
+ }
48
+ }
49
+ async function askHidden(prompt) {
50
+ process.stdout.write(prompt);
51
+ if (!process.stdin.isTTY || !process.stdin.setRawMode) {
52
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
53
+ try {
54
+ return (await rl.question("")).trim();
55
+ }
56
+ finally {
57
+ rl.close();
58
+ }
59
+ }
60
+ const stdin = process.stdin;
61
+ stdin.setRawMode(true);
62
+ stdin.resume();
63
+ stdin.setEncoding("utf8");
64
+ return new Promise((resolve) => {
65
+ let value = "";
66
+ const onData = (chunk) => {
67
+ for (const char of chunk) {
68
+ if (char === "\r" || char === "\n") {
69
+ stdin.setRawMode(false);
70
+ stdin.pause();
71
+ stdin.off("data", onData);
72
+ process.stdout.write("\n");
73
+ resolve(value.trim());
74
+ return;
75
+ }
76
+ if (char === "\u0003")
77
+ process.exit(130);
78
+ if (char === "\u007f" || char === "\b")
79
+ value = value.slice(0, -1);
80
+ else
81
+ value += char;
82
+ }
83
+ };
84
+ stdin.on("data", onData);
85
+ });
86
+ }
87
+ function readCloudConfig() {
88
+ try {
89
+ return JSON.parse(fs.readFileSync(CLOUD_CONFIG, "utf8"));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ function requireRepo() {
96
+ const repo = readCloudConfig()?.cloudRepo;
97
+ if (!repo)
98
+ throw new Error("Cloud mode is not set up. Run: kalvium-worklog cloud init");
99
+ return repo;
100
+ }
101
+ function cloudLogin(cliPath) {
102
+ fs.mkdirSync(CLOUD_HOME, { recursive: true, mode: 0o700 });
103
+ console.log("Opening a separate Kalvium login for GitHub Actions.");
104
+ const result = spawnSync(process.execPath, [cliPath, "login"], {
105
+ stdio: "inherit",
106
+ env: {
107
+ ...process.env,
108
+ KWORKLOG_HOME: CLOUD_HOME,
109
+ KWORKLOG_PROFILE_DIR: path.join(CLOUD_HOME, "browser-profile"),
110
+ },
111
+ });
112
+ if (result.status !== 0 || !fs.existsSync(path.join(CLOUD_HOME, "refresh_token.json"))) {
113
+ throw new Error("Cloud login did not complete.");
114
+ }
115
+ }
116
+ export function cronFor(time, offsetMin = new Date().getTimezoneOffset()) {
117
+ const match = /^(\d{1,2}):(\d{2})$/.exec(time);
118
+ if (!match)
119
+ throw new Error(`Invalid time "${time}". Use HH:MM, e.g. 12:30`);
120
+ const hour = Number(match[1]);
121
+ const minute = Number(match[2]);
122
+ if (hour > 23 || minute > 59)
123
+ throw new Error(`Invalid time "${time}".`);
124
+ const hours = new Set();
125
+ const base = hour * 60 + minute + offsetMin;
126
+ for (let offset = -30; offset <= 240; offset += 30) {
127
+ const utcMinutes = ((base + offset) % 1440 + 1440) % 1440;
128
+ hours.add(Math.floor(utcMinutes / 60));
129
+ }
130
+ return `7,37 ${[...hours].sort((a, b) => a - b).join(",")} * * *`;
131
+ }
132
+ function workflowYaml(config, version) {
133
+ return `# Generated by kalvium-worklog. Run kalvium-worklog cloud sync to update.
134
+ name: Kalvium worklog
135
+ on:
136
+ schedule:
137
+ - cron: "${cronFor(config.time)}"
138
+ workflow_dispatch:
139
+ concurrency:
140
+ group: kalvium-worklog
141
+ cancel-in-progress: false
142
+ permissions: {}
143
+ jobs:
144
+ submit:
145
+ runs-on: ubuntu-latest
146
+ timeout-minutes: 15
147
+ env:
148
+ TZ: ${config.timezone}
149
+ KWORKLOG_HOME: /tmp/kalvium-worklog
150
+ KATTEND_TOKEN_JSON: \${{ secrets.${SECRET_TOKEN} }}
151
+ KATTEND_CONFIG_JSON: \${{ secrets.${SECRET_CONFIG} }}
152
+ GH_TOKEN: \${{ secrets.${SECRET_PAT} }}
153
+ steps:
154
+ - uses: actions/setup-node@v4
155
+ with:
156
+ node-version: 20
157
+ - name: Submit daily worklog
158
+ run: npx --yes kalvium-worklog@${version} cloud run
159
+ `;
160
+ }
161
+ function putWorkflow(repo, content) {
162
+ const api = `repos/${repo}/contents/${WORKFLOW_PATH}`;
163
+ const existingSha = gh(["api", api, "--jq", ".sha"]);
164
+ const args = [
165
+ "api", "-X", "PUT", api,
166
+ "-f", "message=Update Kalvium worklog workflow",
167
+ "-f", `content=${Buffer.from(content).toString("base64")}`,
168
+ ];
169
+ if (existingSha.status === 0 && existingSha.stdout.trim()) {
170
+ args.push("-f", `sha=${existingSha.stdout.trim()}`);
171
+ }
172
+ runGh(args);
173
+ }
174
+ function setSecret(repo, name, value) {
175
+ runGh(["secret", "set", name, "--repo", repo], value);
176
+ }
177
+ function currentCloudConfig(repo) {
178
+ const local = loadConfig();
179
+ if (!local?.position_id || !local.worklog_api_url) {
180
+ throw new Error("Run kalvium-worklog discover before setting up cloud mode.");
181
+ }
182
+ const schedule = loadSchedule() ?? { hour: 12, minute: 30 };
183
+ return {
184
+ position_id: local.position_id,
185
+ worklog_api_url: local.worklog_api_url,
186
+ time: `${String(schedule.hour).padStart(2, "0")}:${String(schedule.minute).padStart(2, "0")}`,
187
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
188
+ cloudRepo: repo,
189
+ };
190
+ }
191
+ function secretConfig(config) {
192
+ return JSON.stringify({
193
+ position_id: config.position_id,
194
+ worklog_api_url: config.worklog_api_url,
195
+ time: config.time,
196
+ });
197
+ }
198
+ export async function cloudInit(options) {
199
+ requireGh();
200
+ const owner = runGh(["api", "user", "--jq", ".login"]);
201
+ const requested = options.repoName || await ask("Private GitHub repo name", "kalvium-attendance-cloud");
202
+ const repo = requested.includes("/") ? requested : `${owner}/${requested}`;
203
+ const cloudTokenFile = path.join(CLOUD_HOME, "refresh_token.json");
204
+ if (!(options.reuse && fs.existsSync(cloudTokenFile)))
205
+ cloudLogin(options.cliPath);
206
+ const config = currentCloudConfig(repo);
207
+ console.log(`This will configure the private repo ${repo} to run at ${config.time} ${config.timezone}.`);
208
+ if ((await ask("Continue? (yes/no)", "no")).toLowerCase() !== "yes")
209
+ throw new Error("Cancelled.");
210
+ const created = gh(["repo", "create", repo, "--private", "--description", "Daily Kalvium worklog automation"]);
211
+ if (created.status !== 0 && !/already exists/i.test(created.stderr)) {
212
+ throw new Error((created.stderr || "Could not create the GitHub repository.").trim());
213
+ }
214
+ const pat = process.env.KATTEND_PAT || await askHidden("Fine-grained PAT (repo Secrets: read/write; input hidden): ");
215
+ if (!pat)
216
+ throw new Error("A GitHub token is required to save rotated refresh tokens.");
217
+ setSecret(repo, SECRET_TOKEN, fs.readFileSync(cloudTokenFile, "utf8"));
218
+ setSecret(repo, SECRET_CONFIG, secretConfig(config));
219
+ setSecret(repo, SECRET_PAT, pat);
220
+ putWorkflow(repo, workflowYaml(config, options.version));
221
+ fs.writeFileSync(CLOUD_CONFIG, JSON.stringify({ cloudRepo: repo }, null, 2), { mode: 0o600 });
222
+ console.log(`Cloud worklog enabled for ${repo} at ${config.time} ${config.timezone}.`);
223
+ }
224
+ export async function cloudSync(options) {
225
+ requireGh();
226
+ const repo = requireRepo();
227
+ if (options.login) {
228
+ cloudLogin(options.cliPath);
229
+ const tokenFile = path.join(CLOUD_HOME, "refresh_token.json");
230
+ setSecret(repo, SECRET_TOKEN, fs.readFileSync(tokenFile, "utf8"));
231
+ }
232
+ const config = currentCloudConfig(repo);
233
+ setSecret(repo, SECRET_CONFIG, secretConfig(config));
234
+ putWorkflow(repo, workflowYaml(config, options.version));
235
+ console.log(`Synced cloud worklog settings${options.login ? " and refreshed its login" : ""}.`);
236
+ }
237
+ export function cloudStatus() {
238
+ requireGh();
239
+ const repo = requireRepo();
240
+ console.log(`Repo: https://github.com/${repo}`);
241
+ const result = gh(["run", "list", "--repo", repo, "--limit", "8"]);
242
+ if (result.status !== 0)
243
+ throw new Error((result.stderr || "Could not read workflow runs.").trim());
244
+ console.log(result.stdout.trim() || "No runs yet.");
245
+ }
246
+ export function cloudTest() {
247
+ requireGh();
248
+ const repo = requireRepo();
249
+ runGh(["workflow", "run", "attendance.yml", "--repo", repo]);
250
+ console.log(`Started a run. Check https://github.com/${repo}/actions`);
251
+ }
252
+ export async function cloudRun() {
253
+ const tokenJson = process.env.KATTEND_TOKEN_JSON;
254
+ const configJson = process.env.KATTEND_CONFIG_JSON;
255
+ if (!tokenJson || !configJson)
256
+ throw new Error("Cloud token/config secrets are missing. Run cloud sync --login.");
257
+ const config = JSON.parse(configJson);
258
+ const mappedConfig = {
259
+ position_id: config.position_id,
260
+ worklog_api_url: config.worklog_api_url,
261
+ };
262
+ if (!mappedConfig.position_id || !mappedConfig.worklog_api_url) {
263
+ throw new Error("Cloud config is missing the internship position or worklog URL.");
264
+ }
265
+ ensureInstallDir();
266
+ fs.writeFileSync(TOKEN_FILE, tokenJson, { mode: 0o600 });
267
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(mappedConfig), { mode: 0o600 });
268
+ const scheduled = /^(\d{1,2}):(\d{2})$/.exec(config.time || "12:30");
269
+ if (scheduled) {
270
+ const now = new Date();
271
+ const due = Number(scheduled[1]) * 60 + Number(scheduled[2]);
272
+ if (now.getHours() * 60 + now.getMinutes() < due) {
273
+ console.log("Not due yet; the next scheduled check will retry.");
274
+ return;
275
+ }
276
+ }
277
+ const submitted = await dailySubmit({ allowInteractiveLogin: false });
278
+ const updatedToken = fs.readFileSync(TOKEN_FILE, "utf8");
279
+ if (updatedToken !== tokenJson) {
280
+ const repo = process.env.GITHUB_REPOSITORY || requireRepo();
281
+ if (!process.env.GH_TOKEN)
282
+ throw new Error(`Token rotated but cannot be saved; configure ${SECRET_PAT}.`);
283
+ setSecret(repo, SECRET_TOKEN, updatedToken);
284
+ console.log("Saved rotated Kalvium token.");
285
+ }
286
+ if (!submitted)
287
+ throw new Error("Worklog cloud run failed; see the log output above.");
288
+ }
package/dist/config.d.ts CHANGED
@@ -3,6 +3,8 @@ export declare const PROFILE_DIR: string;
3
3
  export declare const TOKEN_FILE: string;
4
4
  export declare const CONFIG_FILE: string;
5
5
  export declare const LOG_FILE: string;
6
+ export declare const SCHEDULE_FILE: string;
7
+ export declare const CATCHUP_STATE_FILE: string;
6
8
  export declare const KEYCLOAK_URL = "https://auth.kalvium.community/auth/realms/kalvium/protocol/openid-connect/token";
7
9
  export declare const CLIENT_ID = "login_client";
8
10
  export declare const API_BASE = "https://student-api.kalvium.community/api/internships/worklogs";
@@ -23,6 +25,15 @@ export declare function loadToken(): TokenData | null;
23
25
  export declare function saveToken(data: TokenData): void;
24
26
  export declare function loadConfig(): ConfigData | null;
25
27
  export declare function saveConfig(config: ConfigData): void;
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;
26
37
  export declare function getWorklogApi(): string | null;
27
38
  export declare function log(message: string): void;
28
39
  export declare function decodeJwt(token: string): Record<string, unknown> | null;
package/dist/config.js CHANGED
@@ -1,17 +1,28 @@
1
1
  import { homedir } from "os";
2
2
  import { join } from "path";
3
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
4
- export const INSTALL_DIR = join(homedir(), ".kalvium");
5
- export const PROFILE_DIR = join(homedir(), ".kalvium_profile");
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "fs";
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";
12
17
  export function ensureInstallDir() {
13
18
  if (!existsSync(INSTALL_DIR)) {
14
- mkdirSync(INSTALL_DIR, { recursive: true });
19
+ mkdirSync(INSTALL_DIR, { recursive: true, mode: 0o700 });
20
+ }
21
+ try {
22
+ chmodSync(INSTALL_DIR, 0o700);
23
+ }
24
+ catch {
25
+ // Permissions are best effort on platforms without POSIX file modes.
15
26
  }
16
27
  }
17
28
  export function loadToken() {
@@ -27,6 +38,12 @@ export function loadToken() {
27
38
  export function saveToken(data) {
28
39
  ensureInstallDir();
29
40
  writeFileSync(TOKEN_FILE, JSON.stringify(data, null, 2));
41
+ try {
42
+ chmodSync(TOKEN_FILE, 0o600);
43
+ }
44
+ catch {
45
+ // Permissions are best effort on platforms without POSIX file modes.
46
+ }
30
47
  }
31
48
  export function loadConfig() {
32
49
  if (!existsSync(CONFIG_FILE))
@@ -41,6 +58,43 @@ export function loadConfig() {
41
58
  export function saveConfig(config) {
42
59
  ensureInstallDir();
43
60
  writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
61
+ try {
62
+ chmodSync(CONFIG_FILE, 0o600);
63
+ }
64
+ catch {
65
+ // Permissions are best effort on platforms without POSIX file modes.
66
+ }
67
+ }
68
+ export function getLocalDate(date = new Date()) {
69
+ const year = date.getFullYear();
70
+ const month = String(date.getMonth() + 1).padStart(2, "0");
71
+ const day = String(date.getDate()).padStart(2, "0");
72
+ return `${year}-${month}-${day}`;
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 });
44
98
  }
45
99
  export function getWorklogApi() {
46
100
  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.d.ts CHANGED
@@ -3,5 +3,6 @@ export interface RefreshResult {
3
3
  success: boolean;
4
4
  accessToken?: string;
5
5
  error?: string;
6
+ networkError?: boolean;
6
7
  }
7
8
  export declare function refreshToken(): Promise<RefreshResult>;
package/dist/refresh.js CHANGED
@@ -29,14 +29,25 @@ 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 {
48
+ success: false,
49
+ error: e instanceof Error ? e.message : String(e),
50
+ networkError: true,
51
+ };
41
52
  }
42
53
  }