@platforma-sdk/pl-cli 0.13.5 → 0.14.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.
Files changed (45) hide show
  1. package/README.md +208 -0
  2. package/dist/address.d.ts +6 -0
  3. package/dist/base_command.d.ts +10 -3
  4. package/dist/cli.js +649 -230
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cmd/login.d.ts +21 -0
  7. package/dist/cmd/logout.d.ts +7 -0
  8. package/dist/cmd/session/list.d.ts +6 -0
  9. package/dist/cmd/session/remove.d.ts +7 -0
  10. package/dist/cmd/session/select.d.ts +9 -0
  11. package/dist/cmd-opts.d.ts +8 -3
  12. package/dist/connection.d.ts +59 -3
  13. package/dist/index.js +1 -1
  14. package/dist/instance.d.ts +7 -0
  15. package/dist/jwt.d.ts +12 -0
  16. package/dist/lib.d.ts +2 -1
  17. package/dist/project_ops-CHhJu5k5.js +524 -0
  18. package/dist/project_ops-CHhJu5k5.js.map +1 -0
  19. package/dist/prompt.d.ts +5 -0
  20. package/dist/session_store.d.ts +112 -0
  21. package/dist/sso.d.ts +30 -0
  22. package/package.json +3 -3
  23. package/src/address.ts +15 -0
  24. package/src/base_command.ts +24 -6
  25. package/src/cli.ts +74 -3
  26. package/src/cmd/admin/delete-user.ts +7 -0
  27. package/src/cmd/login.ts +262 -0
  28. package/src/cmd/logout.ts +55 -0
  29. package/src/cmd/session/list.ts +71 -0
  30. package/src/cmd/session/remove.ts +29 -0
  31. package/src/cmd/session/select.ts +36 -0
  32. package/src/cmd-opts.ts +24 -15
  33. package/src/commands.test.ts +637 -0
  34. package/src/connection.ts +275 -15
  35. package/src/instance.ts +19 -0
  36. package/src/jwt.ts +36 -0
  37. package/src/lib.ts +12 -0
  38. package/src/prompt.ts +54 -0
  39. package/src/session_store.test.ts +237 -0
  40. package/src/session_store.ts +315 -0
  41. package/src/sso.test.ts +269 -0
  42. package/src/sso.ts +336 -0
  43. package/src/test_backend.ts +151 -0
  44. package/dist/output-D41Wn0wM.js +0 -229
  45. package/dist/output-D41Wn0wM.js.map +0 -1
@@ -0,0 +1,237 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ mkdtempSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ statSync,
10
+ utimesSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
16
+ import { SessionStore, type StoredSession } from "./session_store";
17
+
18
+ const posix = process.platform !== "win32";
19
+
20
+ function session(login: string, address = "http://127.0.0.1:6345"): StoredSession {
21
+ return {
22
+ login,
23
+ address,
24
+ token: `token-of-${login}`,
25
+ loginMethod: { id: "sso", kind: "sso" },
26
+ createdAt: "2026-12-01T00:00:00.000Z",
27
+ updatedAt: "2026-12-01T00:00:00.000Z",
28
+ };
29
+ }
30
+
31
+ describe("SessionStore", () => {
32
+ let dir: string;
33
+ let path: string;
34
+
35
+ beforeEach(() => {
36
+ dir = mkdtempSync(join(tmpdir(), "pl-cli-sessions-"));
37
+ path = join(dir, "nested", "pl-cli.sessions");
38
+ });
39
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
40
+
41
+ test("missing file reads as empty", () => {
42
+ const store = new SessionStore(path);
43
+ expect(store.list()).toEqual([]);
44
+ expect(store.get("i1")).toBeUndefined();
45
+ });
46
+
47
+ test.runIf(posix)("creates the directory with mode 0700 and the file with mode 0600", () => {
48
+ const store = new SessionStore(path);
49
+ store.put("i1", session("alice"));
50
+ expect(statSync(join(dir, "nested")).mode & 0o777).toBe(0o700);
51
+ expect(statSync(path).mode & 0o777).toBe(0o600);
52
+ });
53
+
54
+ test.runIf(posix)("tightens a file that others can read", () => {
55
+ const store = new SessionStore(path);
56
+ store.put("i1", session("alice"));
57
+ chmodSync(path, 0o644);
58
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
59
+ try {
60
+ expect(store.get("i1")?.login).toBe("alice");
61
+ } finally {
62
+ warn.mockRestore();
63
+ }
64
+ expect(statSync(path).mode & 0o777).toBe(0o600);
65
+ });
66
+
67
+ test("keeps sessions of several instances apart", () => {
68
+ const store = new SessionStore(path);
69
+ // The same address for both: as through an SSH tunnel to two Backends.
70
+ store.put("i1", session("alice"));
71
+ store.put("i2", session("bob"));
72
+ expect(store.get("i1")?.login).toBe("alice");
73
+ expect(store.get("i2")?.login).toBe("bob");
74
+ expect(store.get("i1", "bob")).toBeUndefined();
75
+ expect(store.list().map((r) => [r.instanceId, r.session.login, r.current])).toEqual([
76
+ ["i1", "alice", true],
77
+ ["i2", "bob", true],
78
+ ]);
79
+ });
80
+
81
+ test("a new sign-in becomes current; select changes current", () => {
82
+ const store = new SessionStore(path);
83
+ store.put("i1", session("alice"));
84
+ store.put("i1", session("bob"));
85
+ expect(store.get("i1")?.login).toBe("bob");
86
+ expect(store.logins("i1")).toEqual(["alice", "bob"]);
87
+
88
+ store.select("i1", "alice");
89
+ expect(store.get("i1")?.login).toBe("alice");
90
+ expect(store.get("i1", "bob")?.login).toBe("bob");
91
+ expect(() => store.select("i1", "carol")).toThrow(/No stored session/);
92
+ expect(() => store.select("i9", "alice")).toThrow(/No stored session/);
93
+ });
94
+
95
+ test("a sign-in of the same login replaces its session", () => {
96
+ const store = new SessionStore(path);
97
+ store.put("i1", session("alice"));
98
+ store.put("i1", { ...session("alice"), token: "new" });
99
+ expect(store.logins("i1")).toEqual(["alice"]);
100
+ expect(store.get("i1")?.token).toBe("new");
101
+ });
102
+
103
+ test("remove: current, by login, and the last one of an instance", () => {
104
+ const store = new SessionStore(path);
105
+ store.put("i1", session("alice"));
106
+ store.put("i1", session("bob"));
107
+
108
+ expect(store.remove("i1")?.login).toBe("bob");
109
+ // No silent switch to another login after the current one is removed.
110
+ expect(store.get("i1")).toBeUndefined();
111
+ expect(store.get("i1", "alice")?.login).toBe("alice");
112
+
113
+ expect(store.remove("i1", "nobody")).toBeUndefined();
114
+ expect(store.remove("i1", "alice")?.login).toBe("alice");
115
+ expect(store.list()).toEqual([]);
116
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual({ version: 1, instances: {} });
117
+ });
118
+
119
+ test("updateToken changes only the token and the update time", () => {
120
+ const store = new SessionStore(path);
121
+ store.put("i1", session("alice"));
122
+ store.updateToken("i1", "alice", "renewed");
123
+ store.updateToken("i1", "gone", "ignored");
124
+ const s = store.get("i1");
125
+ expect(s?.token).toBe("renewed");
126
+ expect(s?.createdAt).toBe("2026-12-01T00:00:00.000Z");
127
+ expect(s?.updatedAt).not.toBe("2026-12-01T00:00:00.000Z");
128
+ expect(store.logins("i1")).toEqual(["alice"]);
129
+ });
130
+
131
+ test("rejects a file that is not a sessions file", () => {
132
+ const store = new SessionStore(join(dir, "bad"));
133
+ writeFileSync(join(dir, "bad"), "{not json", { mode: 0o600 });
134
+ expect(() => store.list()).toThrow(/not valid JSON/);
135
+ writeFileSync(join(dir, "bad"), '{"version":7}', { mode: 0o600 });
136
+ expect(() => store.list()).toThrow(/unknown format/);
137
+ });
138
+
139
+ test("keys such as __proto__ and constructor are ordinary keys", () => {
140
+ const store = new SessionStore(path);
141
+ expect(store.get("constructor")).toBeUndefined();
142
+ expect(store.get("i1", "constructor")).toBeUndefined();
143
+ store.put("__proto__", session("__proto__"));
144
+ store.put("i1", session("constructor"));
145
+ expect(store.get("__proto__")?.login).toBe("__proto__");
146
+ expect(store.get("i1", "toString")).toBeUndefined();
147
+ expect(store.list().map((r) => [r.instanceId, r.session.login])).toEqual([
148
+ ["__proto__", "__proto__"],
149
+ ["i1", "constructor"],
150
+ ]);
151
+ // Reading the file again gives the same keys, and Object.prototype stays clean.
152
+ expect(new SessionStore(path).get("__proto__")?.login).toBe("__proto__");
153
+ expect(Object.prototype).not.toHaveProperty("sessions");
154
+ expect(store.remove("__proto__")?.login).toBe("__proto__");
155
+ });
156
+
157
+ test("writes leave no lock or temporary files", () => {
158
+ const store = new SessionStore(path);
159
+ store.put("i1", session("alice"));
160
+ store.put("i1", session("bob"));
161
+ expect(readdirSync(join(dir, "nested"))).toEqual(["pl-cli.sessions"]);
162
+ });
163
+
164
+ test("waits for a lock; removes a stale lock", () => {
165
+ const store = new SessionStore(path);
166
+ store.put("i1", session("alice"));
167
+ const lock = `${path}.lock`;
168
+ writeFileSync(lock, "");
169
+ const old = (Date.now() - 60_000) / 1000;
170
+ utimesSync(lock, old, old);
171
+ store.put("i1", session("bob"));
172
+ expect(store.logins("i1")).toEqual(["alice", "bob"]);
173
+ expect(existsSync(lock)).toBe(false);
174
+ });
175
+
176
+ test.runIf(posix)("warns when the directory is writable by others", () => {
177
+ const shared = join(dir, "shared");
178
+ mkdirSync(shared, { mode: 0o777 });
179
+ chmodSync(shared, 0o777);
180
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
181
+ try {
182
+ new SessionStore(join(shared, "s")).put("i1", session("alice"));
183
+ expect(warn.mock.calls.flat().join("")).toMatch(/writable by other users/);
184
+ } finally {
185
+ warn.mockRestore();
186
+ }
187
+ });
188
+
189
+ test("default session: set by put and select, cleared by remove, ignored when stale", () => {
190
+ const store = new SessionStore(path);
191
+ expect(store.getDefault()).toBeUndefined();
192
+ store.put("i1", session("alice"));
193
+ store.put("i2", session("bob"));
194
+ expect(store.getDefault()).toEqual({ instanceId: "i2", session: session("bob") });
195
+ store.select("i1", "alice");
196
+ expect(store.getDefault()?.instanceId).toBe("i1");
197
+ expect(store.list().map((r) => [r.session.login, r.default, r.current])).toEqual([
198
+ ["alice", true, true],
199
+ ["bob", false, true],
200
+ ]);
201
+ store.remove("i2", "bob");
202
+ expect(store.getDefault()?.session.login).toBe("alice");
203
+ store.remove("i1", "alice");
204
+ expect(store.getDefault()).toBeUndefined();
205
+
206
+ writeFileSync(
207
+ path,
208
+ JSON.stringify({ version: 1, default: { instanceId: "gone", login: "x" }, instances: {} }),
209
+ { mode: 0o600 },
210
+ );
211
+ expect(store.getDefault()).toBeUndefined();
212
+
213
+ // null, a string or an incomplete object: no default, no crash.
214
+ for (const bad of [null, "i1", 7, { instanceId: "i1" }]) {
215
+ writeFileSync(
216
+ path,
217
+ JSON.stringify({
218
+ version: 1,
219
+ default: bad,
220
+ instances: { i1: { current: "alice", sessions: { alice: session("alice") } } },
221
+ }),
222
+ { mode: 0o600 },
223
+ );
224
+ expect(store.getDefault()).toBeUndefined();
225
+ expect(store.list().map((r) => r.default)).toEqual([false]);
226
+ }
227
+ });
228
+
229
+ test('the file stores the default session under the key "default"', () => {
230
+ const store = new SessionStore(path);
231
+ store.put("i1", session("alice"));
232
+ const raw = JSON.parse(readFileSync(path, "utf8"));
233
+ expect(raw.default).toEqual({ instanceId: "i1", login: "alice" });
234
+ expect(raw).not.toHaveProperty("current");
235
+ expect(raw.instances.i1.current).toBe("alice");
236
+ });
237
+ });
@@ -0,0 +1,315 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ openSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { dirname, join } from "node:path";
16
+
17
+ /** Environment variable that overrides the location of the sessions file. */
18
+ export const SessionsFileEnv = "PL_CLI_SESSIONS_FILE";
19
+
20
+ /** Kind of the login method that issued a stored token. */
21
+ export type SessionLoginKind = "sso" | "basic" | "token";
22
+
23
+ /** One stored sign-in: the token that the Backend issued for one login on one Backend instance.
24
+ * The store never holds a password or a token of the identity provider. */
25
+ export interface StoredSession {
26
+ /** The login that the token is for. */
27
+ login: string;
28
+ /** The address that was used to sign in. For information only: the instance ID selects the session. */
29
+ address: string;
30
+ /** The Platforma token (JWT) that the Backend issued. */
31
+ token: string;
32
+ /** The login method that issued the token, as the Backend advertises it. */
33
+ loginMethod?: { id: string; kind: SessionLoginKind };
34
+ /** Time of the sign-in, ISO 8601. */
35
+ createdAt: string;
36
+ /** Time of the last token change (sign-in or renewal), ISO 8601. */
37
+ updatedAt: string;
38
+ }
39
+
40
+ interface InstanceEntry {
41
+ /** The login of the session that commands use when no login is given. */
42
+ current?: string;
43
+ /** Sessions of this instance, by login. */
44
+ sessions: Record<string, StoredSession>;
45
+ }
46
+
47
+ /** Content of the sessions file. */
48
+ /** The session that commands without an address use. */
49
+ export interface DefaultSessionRef {
50
+ instanceId: string;
51
+ login: string;
52
+ }
53
+
54
+ export interface SessionsFileData {
55
+ version: 1;
56
+ /** The default session: commands without `--address` use its stored address. It is also the
57
+ * current session of its instance. Absent when no session is the default. */
58
+ default?: DefaultSessionRef;
59
+ /** Sessions by the instance ID that the Backend returns in its ping answer. */
60
+ instances: Record<string, InstanceEntry>;
61
+ }
62
+
63
+ /** One row of {@link SessionStore.list}. */
64
+ export interface SessionListEntry {
65
+ instanceId: string;
66
+ /** The current session of its instance: used when the address selects this instance. */
67
+ current: boolean;
68
+ /** The default session: used when no address is given. */
69
+ default: boolean;
70
+ session: StoredSession;
71
+ }
72
+
73
+ /** Default location of the sessions file: `$PL_CLI_SESSIONS_FILE`, else `~/.platforma/pl-cli.sessions`. */
74
+ export function defaultSessionsPath(): string {
75
+ const fromEnv = process.env[SessionsFileEnv];
76
+ if (fromEnv !== undefined && fromEnv !== "") return fromEnv;
77
+ return join(homedir(), ".platforma", "pl-cli.sessions");
78
+ }
79
+
80
+ const isPosix = process.platform !== "win32";
81
+
82
+ /**
83
+ * Stores Backend sessions of pl-cli in one JSON file.
84
+ *
85
+ * Sessions are keyed by the instance ID of the Backend, not by its address: several Backends
86
+ * can answer on the same local address (for example, through SSH tunnels). Each instance can
87
+ * hold sessions of several logins; one of them is current.
88
+ *
89
+ * File protection: on POSIX systems the file has mode 0600 and a directory that the store
90
+ * creates has mode 0700. On Windows, Node.js cannot set these modes; the file is protected by
91
+ * the access rules of the user profile directory, where only the user and administrators can
92
+ * read it by default.
93
+ *
94
+ * Each change takes a lock file (`<path>.lock`), reads the file, changes it and writes it again
95
+ * through a temporary file and a rename. So a reader never sees a partly written file, and two
96
+ * pl-cli processes that change the file at the same time do not lose a change.
97
+ *
98
+ * Instance IDs and logins are keys of objects without a prototype, so a key such as `__proto__`
99
+ * is an ordinary key.
100
+ */
101
+ export class SessionStore {
102
+ constructor(public readonly path: string = defaultSessionsPath()) {}
103
+
104
+ /** Reads the file. A missing file gives an empty store. */
105
+ read(): SessionsFileData {
106
+ if (!existsSync(this.path)) return { version: 1, instances: Object.create(null) };
107
+ this.tightenFileMode();
108
+ let parsed: unknown;
109
+ try {
110
+ parsed = JSON.parse(readFileSync(this.path, "utf8"));
111
+ } catch (err) {
112
+ throw new Error(
113
+ `The sessions file ${this.path} is not valid JSON. Remove it and sign in again.`,
114
+ { cause: err },
115
+ );
116
+ }
117
+ const data = parsed as Partial<SessionsFileData>;
118
+ if (data?.version !== 1 || typeof data.instances !== "object" || data.instances === null)
119
+ throw new Error(
120
+ `The sessions file ${this.path} has an unknown format. Remove it and sign in again.`,
121
+ );
122
+ // Copy into objects without a prototype: lookups by key then never find inherited members.
123
+ const instances: Record<string, InstanceEntry> = Object.create(null);
124
+ for (const [instanceId, entry] of Object.entries(data.instances)) {
125
+ const sessions: Record<string, StoredSession> = Object.create(null);
126
+ for (const [login, session] of Object.entries(entry.sessions ?? {}))
127
+ sessions[login] = session;
128
+ instances[instanceId] =
129
+ entry.current === undefined ? { sessions } : { current: entry.current, sessions };
130
+ }
131
+ // A missing, null or malformed entry, or one that names a removed session, means no default.
132
+ const cur: unknown = data.default;
133
+ const def =
134
+ cur !== null &&
135
+ typeof cur === "object" &&
136
+ "instanceId" in cur &&
137
+ "login" in cur &&
138
+ typeof cur.instanceId === "string" &&
139
+ typeof cur.login === "string" &&
140
+ Object.hasOwn(instances, cur.instanceId) &&
141
+ Object.hasOwn(instances[cur.instanceId].sessions, cur.login)
142
+ ? { instanceId: cur.instanceId, login: cur.login }
143
+ : undefined;
144
+ return def === undefined ? { version: 1, instances } : { version: 1, default: def, instances };
145
+ }
146
+
147
+ /** Returns the default session (for commands without an address), if any. */
148
+ getDefault(): { instanceId: string; session: StoredSession } | undefined {
149
+ const data = this.read();
150
+ if (data.default === undefined) return undefined;
151
+ const { instanceId, login } = data.default;
152
+ return { instanceId, session: data.instances[instanceId].sessions[login] };
153
+ }
154
+
155
+ /** Returns the session of `login` on the instance, or the current session when `login` is not given. */
156
+ get(instanceId: string, login?: string): StoredSession | undefined {
157
+ const entry = this.read().instances[instanceId];
158
+ if (entry === undefined) return undefined;
159
+ const key = login ?? entry.current;
160
+ return key === undefined ? undefined : entry.sessions[key];
161
+ }
162
+
163
+ /** Returns the logins that have sessions on the instance. */
164
+ logins(instanceId: string): string[] {
165
+ return Object.keys(this.read().instances[instanceId]?.sessions ?? {}).sort();
166
+ }
167
+
168
+ /** Returns all sessions, sorted by instance ID and login. */
169
+ list(): SessionListEntry[] {
170
+ const data = this.read();
171
+ const rows: SessionListEntry[] = [];
172
+ for (const instanceId of Object.keys(data.instances).sort()) {
173
+ const entry = data.instances[instanceId];
174
+ for (const login of Object.keys(entry.sessions).sort())
175
+ rows.push({
176
+ instanceId,
177
+ current: entry.current === login,
178
+ default: data.default?.instanceId === instanceId && data.default.login === login,
179
+ session: entry.sessions[login],
180
+ });
181
+ }
182
+ return rows;
183
+ }
184
+
185
+ /** Adds the session, or replaces the session of the same login on the instance.
186
+ * The session becomes current on its instance and the default session. */
187
+ put(instanceId: string, session: StoredSession): void {
188
+ this.update((data) => {
189
+ const entry = (data.instances[instanceId] ??= { sessions: Object.create(null) });
190
+ entry.sessions[session.login] = session;
191
+ entry.current = session.login;
192
+ data.default = { instanceId, login: session.login };
193
+ });
194
+ }
195
+
196
+ /** Replaces the token of an existing session after a renewal. Does nothing if the session is gone. */
197
+ updateToken(instanceId: string, login: string, token: string): void {
198
+ this.update((data) => {
199
+ const session = data.instances[instanceId]?.sessions[login];
200
+ if (session === undefined) return;
201
+ session.token = token;
202
+ session.updatedAt = new Date().toISOString();
203
+ });
204
+ }
205
+
206
+ /** Makes the session of `login` current on the instance and the default session. */
207
+ select(instanceId: string, login: string): void {
208
+ this.update((data) => {
209
+ const entry = data.instances[instanceId];
210
+ if (entry?.sessions[login] === undefined)
211
+ throw new Error(`No stored session for login "${login}" on instance ${instanceId}.`);
212
+ entry.current = login;
213
+ data.default = { instanceId, login };
214
+ });
215
+ }
216
+
217
+ /** Removes the session of `login`, or the current session when `login` is not given.
218
+ * Returns the removed session. When the current session is removed, the instance has no
219
+ * current session until the next sign-in or `select`. When the default session is removed,
220
+ * there is no default session until then. */
221
+ remove(instanceId: string, login?: string): StoredSession | undefined {
222
+ let removed: StoredSession | undefined;
223
+ this.update((data) => {
224
+ const entry = data.instances[instanceId];
225
+ if (entry === undefined) return;
226
+ const key = login ?? entry.current;
227
+ if (key === undefined) return;
228
+ removed = entry.sessions[key];
229
+ if (removed === undefined) return;
230
+ delete entry.sessions[key];
231
+ if (entry.current === key) delete entry.current;
232
+ if (data.default?.instanceId === instanceId && data.default.login === key)
233
+ delete data.default;
234
+ if (Object.keys(entry.sessions).length === 0) delete data.instances[instanceId];
235
+ });
236
+ return removed;
237
+ }
238
+
239
+ private update(change: (data: SessionsFileData) => void): void {
240
+ this.prepareDir();
241
+ const release = this.lock();
242
+ try {
243
+ const data = this.read();
244
+ change(data);
245
+ this.write(data);
246
+ } finally {
247
+ release();
248
+ }
249
+ }
250
+
251
+ /** Creates the directory (mode 0700). Warns when an existing directory is writable by others:
252
+ * they could replace the file. */
253
+ private prepareDir(): void {
254
+ const dir = dirname(this.path);
255
+ if (existsSync(dir)) {
256
+ if (isPosix && (statSync(dir).mode & 0o022) !== 0)
257
+ console.error(
258
+ `warning: the directory ${dir} is writable by other users; they can replace the ` +
259
+ "sessions file. Run: chmod go-w " +
260
+ dir,
261
+ );
262
+ return;
263
+ }
264
+ // `mode` applies only to directories that mkdir creates.
265
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
266
+ }
267
+
268
+ /** Takes the lock file. Waits up to 5 s; removes a lock older than 30 s (a stopped process). */
269
+ private lock(): () => void {
270
+ const lockPath = `${this.path}.lock`;
271
+ const deadline = Date.now() + 5000;
272
+ for (;;) {
273
+ try {
274
+ closeSync(openSync(lockPath, "wx", 0o600));
275
+ return () => rmSync(lockPath, { force: true });
276
+ } catch (err) {
277
+ if (!(err instanceof Error && "code" in err && err.code === "EEXIST")) throw err;
278
+ }
279
+ try {
280
+ if (Date.now() - statSync(lockPath).mtimeMs > 30_000) rmSync(lockPath, { force: true });
281
+ } catch {
282
+ // The other process removed the lock.
283
+ }
284
+ if (Date.now() > deadline)
285
+ throw new Error(
286
+ `The sessions file is locked by another pl-cli process. If no other pl-cli runs, ` +
287
+ `remove ${lockPath}.`,
288
+ );
289
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
290
+ }
291
+ }
292
+
293
+ private write(data: SessionsFileData): void {
294
+ const tmp = `${this.path}.${randomBytes(8).toString("hex")}.tmp`;
295
+ try {
296
+ // "wx": never write through a file (or a link) that someone created at this name.
297
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600, flag: "wx" });
298
+ renameSync(tmp, this.path);
299
+ } catch (err) {
300
+ rmSync(tmp, { force: true });
301
+ throw err;
302
+ }
303
+ }
304
+
305
+ /** On POSIX, removes group and other access from a file that has it, and tells the user. */
306
+ private tightenFileMode(): void {
307
+ if (!isPosix) return;
308
+ const mode = statSync(this.path).mode & 0o777;
309
+ if ((mode & 0o077) === 0) return;
310
+ chmodSync(this.path, 0o600);
311
+ console.error(
312
+ `warning: the sessions file ${this.path} had mode ${mode.toString(8)}; changed it to 600.`,
313
+ );
314
+ }
315
+ }