sil-openclaw 0.2.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.
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Persistent credential + identity storage for the sil plugin — the SOLE owner
3
+ * of on-disk auth state.
4
+ *
5
+ * After a successful claim the plugin writes two files under the resolved data
6
+ * directory:
7
+ * - `tokens.json` → { access_token, refresh_token } (the bearer pair)
8
+ * - `config.json` → { user: { id, name? } } (identity, for whoami)
9
+ *
10
+ * The PKCE verifier is NEVER written here — it is the claim bearer secret and
11
+ * lives only in memory (see `pkce.ts`). Only the post-claim tokens + identity
12
+ * touch disk.
13
+ *
14
+ * Resolution order for the data dir (no host `dataDir` accessor exists in the
15
+ * declared SDK, so we compute it deterministically; the env override is what
16
+ * makes the credential tests hermetic — each points at its own temp dir):
17
+ * 1. `$SIL_DATA_DIR` (test/override — highest precedence)
18
+ * 2. `$XDG_DATA_HOME/sil` (XDG Base Directory spec)
19
+ * 3. `~/.local/share/sil` (XDG default)
20
+ *
21
+ * Writes are atomic (temp file in the same dir + rename) so a crash mid-write
22
+ * never leaves a half-written token file, and the files are `0600` (owner-only)
23
+ * so the bearer pair is never group/world-readable. Reads tolerate a missing
24
+ * dir/file by returning null (the already-registered short-circuit treats
25
+ * "no tokens" as "not registered").
26
+ */
27
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
28
+ import { homedir } from "node:os";
29
+ import { dirname, join } from "node:path";
30
+ import { randomBytes } from "node:crypto";
31
+ /** Owner read/write only. The bearer pair must never be group/world-readable. */
32
+ const FILE_MODE = 0o600;
33
+ /** Owner read/write/execute only on the data dir itself. */
34
+ const DIR_MODE = 0o700;
35
+ const TOKENS_FILE = "tokens.json";
36
+ const CONFIG_FILE = "config.json";
37
+ /**
38
+ * Resolve the plugin's data directory at call time (never cached — tests flip
39
+ * `$SIL_DATA_DIR` between cases, and a deployment could relocate `$XDG_DATA_HOME`
40
+ * between calls). See the module header for the precedence order.
41
+ */
42
+ export function getDataDir() {
43
+ const override = process.env["SIL_DATA_DIR"];
44
+ if (override !== undefined && override !== "")
45
+ return override;
46
+ const xdg = process.env["XDG_DATA_HOME"];
47
+ if (xdg !== undefined && xdg !== "")
48
+ return join(xdg, "sil");
49
+ return join(homedir(), ".local", "share", "sil");
50
+ }
51
+ export function getTokensPath() {
52
+ return join(getDataDir(), TOKENS_FILE);
53
+ }
54
+ export function getConfigPath() {
55
+ return join(getDataDir(), CONFIG_FILE);
56
+ }
57
+ /**
58
+ * True iff a `tokens.json` exists on disk. This is the already-registered
59
+ * short-circuit's gate — it is PRESENCE-based, not freshness-based: an expired
60
+ * access token still counts as "registered" for this card (refresh is SC7, the
61
+ * sil_whoami card). Note carried forward in the card body.
62
+ */
63
+ export function hasTokens() {
64
+ return existsSync(getTokensPath());
65
+ }
66
+ /**
67
+ * Persist the bearer pair atomically with owner-only perms.
68
+ *
69
+ * Async signature (returns a Promise) but SYNCHRONOUS fs internals (temp+rename
70
+ * via the *Sync calls). The async wrapper is the public contract (callers await
71
+ * it); the sync internals guarantee the file is fully on disk by the time the
72
+ * returned promise resolves — important under the fake-timer poll loop, where a
73
+ * threadpool-backed `fs/promises` write would NOT settle within the test's
74
+ * microtask flush and the persisted file would race the assertion.
75
+ */
76
+ export async function writeTokens(tokens) {
77
+ writeJsonAtomic(getTokensPath(), tokens);
78
+ }
79
+ /** Persist the identity atomically with owner-only perms. See `writeTokens`
80
+ * for why this is an async wrapper over synchronous fs internals. */
81
+ export async function writeConfig(config) {
82
+ writeJsonAtomic(getConfigPath(), config);
83
+ }
84
+ /** Read the bearer pair, or null if absent/unreadable/malformed. */
85
+ export function readTokens() {
86
+ return readJson(getTokensPath());
87
+ }
88
+ /** Read the identity, or null if absent/unreadable/malformed. */
89
+ export function readConfig() {
90
+ return readJson(getConfigPath());
91
+ }
92
+ /**
93
+ * Delete `tokens.json` if present (tolerant of absence — a no-op when the file
94
+ * is already gone). Called on a CONFIRMED terminal auth failure (a refresh that
95
+ * came back invalid_grant) so a known-dead bearer pair never lingers on disk:
96
+ * the product invariant is "a dead session never masquerades as live". Because
97
+ * the sil_register short-circuit is PRESENCE-based, leaving a dead tokens.json
98
+ * would wrongly short-circuit the user's re-registration recovery; clearing it
99
+ * lets the next sil_register mint a fresh session. Only ever called for a
100
+ * confirmed-dead pair — never on a transient/retryable blip (the token may be
101
+ * fine). The config.json identity is left untouched (it is not a credential and
102
+ * is overwritten on the next successful claim).
103
+ */
104
+ export function clearTokens() {
105
+ const path = getTokensPath();
106
+ if (!existsSync(path))
107
+ return;
108
+ unlinkSync(path);
109
+ }
110
+ /**
111
+ * Write `data` as pretty JSON to `path` atomically: serialize to a uniquely
112
+ * named temp file in the SAME directory (rename is only atomic within a
113
+ * filesystem), fsync-free `writeFileSync`, then `renameSync` over the target.
114
+ * The temp file is created `0600` and the final file is re-`chmod`'d to `0600`
115
+ * in case the rename inherited a different mode on some filesystems.
116
+ *
117
+ * Creating the dir first (recursive, `0700`) makes first-run on a clean machine
118
+ * a non-error. The temp name carries random bytes so two concurrent writers (a
119
+ * pathological double-register sharing a data dir) don't collide on the temp.
120
+ */
121
+ function writeJsonAtomic(path, data) {
122
+ const dir = dirname(path);
123
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
124
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
125
+ writeFileSync(tmp, JSON.stringify(data, null, 2), {
126
+ encoding: "utf-8",
127
+ mode: FILE_MODE,
128
+ });
129
+ renameSync(tmp, path);
130
+ // Belt-and-braces: some filesystems drop the temp's mode on rename.
131
+ chmodSync(path, FILE_MODE);
132
+ }
133
+ function readJson(path) {
134
+ if (!existsSync(path))
135
+ return null;
136
+ try {
137
+ return JSON.parse(readFileSync(path, "utf-8"));
138
+ }
139
+ catch {
140
+ // A corrupt/half-written file reads as "absent" — the caller falls back to
141
+ // the not-registered path rather than crashing on a SyntaxError.
142
+ return null;
143
+ }
144
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * PKCE primitives for the sil-web auth flow (proof system A — agent ↔ sil-web).
3
+ *
4
+ * The plugin mints a session id + a code verifier, holds the verifier as a
5
+ * secret IN MEMORY, and sends only the S256 CHALLENGE to `/authorize`. This is
6
+ * load-bearing: sil-web stores what the agent sends (already a digest) and the
7
+ * claim CAS compares digest-to-digest — so the derivation here MUST match
8
+ * sil-web's `src/lib/pkce.ts` byte-for-byte, or every claim returns a uniform
9
+ * 404 (wrong-verifier ≡ unknown-session by construction, no existence oracle).
10
+ *
11
+ * `deriveChallenge` / `isValidCodeChallenge` / `isValidSessionId` are ported
12
+ * verbatim from sil-services/apps/sil-web/src/lib/pkce.ts so the two sides agree.
13
+ * `newSessionId` / `newVerifier` are the plugin-side minters (sil-web never
14
+ * mints — it only validates the incoming params).
15
+ *
16
+ * node:crypto only; base64url; no dependency.
17
+ */
18
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
19
+ /** A base64url S256 digest is exactly 43 chars, no padding ([A-Za-z0-9_-]). */
20
+ const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
21
+ /** RFC 4122 UUID (any version/variant); the session id is minted by the agent. */
22
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ /**
24
+ * The verifier is 32 random bytes, base64url-encoded. 32 bytes → a 43-char
25
+ * base64url string, comfortably inside RFC 7636's 43–128 char range; the same
26
+ * width sil-web's own test vectors use.
27
+ */
28
+ const VERIFIER_BYTES = 32;
29
+ /**
30
+ * Derive the PKCE S256 code challenge from a verifier:
31
+ * BASE64URL( SHA256( ASCII(verifier) ) )
32
+ * Pure; no I/O. The result is a 43-char base64url string.
33
+ *
34
+ * Identical to sil-web's `deriveChallenge` — pinned by a shared test vector so
35
+ * any drift fails in CI rather than silently as a runtime 404.
36
+ */
37
+ export function deriveChallenge(verifier) {
38
+ return createHash("sha256").update(verifier).digest("base64url");
39
+ }
40
+ /**
41
+ * True iff `value` is a well-formed S256 code challenge: exactly 43 characters,
42
+ * base64url charset only ([A-Za-z0-9_-], no padding). This is the format gate
43
+ * sil-web's `/authorize` applies to the incoming `code_challenge`.
44
+ */
45
+ export function isValidCodeChallenge(value) {
46
+ return CODE_CHALLENGE_RE.test(value);
47
+ }
48
+ /**
49
+ * True iff `value` is a well-formed session id (UUID). This is the format gate
50
+ * sil-web's `/authorize` and `/claim` apply to the incoming `session` param.
51
+ */
52
+ export function isValidSessionId(value) {
53
+ return UUID_RE.test(value);
54
+ }
55
+ /** Mint a fresh session id (UUID v4). The agent owns it for the whole flow. */
56
+ export function newSessionId() {
57
+ return randomUUID();
58
+ }
59
+ /**
60
+ * Mint a fresh PKCE code verifier — 32 cryptographically-random bytes as a
61
+ * base64url string. NEVER written to disk: it is the bearer secret for the
62
+ * claim CAS; only its digest (the challenge) ever leaves the process, and only
63
+ * inside the auth URL.
64
+ */
65
+ export function newVerifier() {
66
+ return randomBytes(VERIFIER_BYTES).toString("base64url");
67
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Generic bounded interval-with-deadline poll loop.
3
+ *
4
+ * Lifecycle (the whole reason this is its own module — so the timer behaviour is
5
+ * unit-testable with fake timers, in isolation from the claim taxonomy):
6
+ * - `startPoll` arms a `setInterval` and returns a handle with `stop()`.
7
+ * - Each tick calls the injected `poll()` step. It returns `{ done: false }`
8
+ * to keep polling or `{ done: true, ... }` to terminate.
9
+ * - The FIRST terminal step stops the loop and fires `onDone` EXACTLY once
10
+ * with that step result.
11
+ * - If the overall deadline passes with no terminal step, the loop stops and
12
+ * fires `onDone` with a synthetic timeout result `{ done, timedOut, outcome:
13
+ * "timeout" }`, so no run ends in silence.
14
+ * - The interval timer is cleared on EVERY exit path (terminal, deadline,
15
+ * explicit `stop()`). The architect's "poll loop leak" risk: a missed
16
+ * `clearInterval` leaks a timer per `sil_register` call in a reused process.
17
+ * `vi.getTimerCount()` must be 0 after any exit — enforced by poller.test.ts.
18
+ *
19
+ * The loop is deliberately GENERIC over the step result: it knows only `done`.
20
+ * The claim-status → done mapping lives in the caller (the tool), keeping the
21
+ * HTTP taxonomy (sil-client) and the timer lifecycle (here) independently
22
+ * testable. No system event / wake is fired — the declared OpenClaw SDK has no
23
+ * such member; success is observed by the credential file landing on disk.
24
+ */
25
+ /** Poll cadence: how often a tick fires a `poll()` step. ~3s (architect default). */
26
+ export const POLL_INTERVAL_MS = 3_000;
27
+ /** Overall budget: must not outlive sil-web's 30-min session TTL. ~30 min. */
28
+ export const POLL_DEADLINE_MS = 30 * 60 * 1_000;
29
+ /**
30
+ * Arm the bounded poll. Returns immediately with a handle — the caller (the
31
+ * tool's `execute`) does NOT await it; that is what keeps the tool non-blocking.
32
+ */
33
+ export function startPoll(opts) {
34
+ const now = opts.now ?? Date.now;
35
+ const startedAt = now();
36
+ let settled = false;
37
+ let inFlight = false;
38
+ let timer = null;
39
+ const clearTimer = () => {
40
+ if (timer !== null) {
41
+ clearInterval(timer);
42
+ timer = null;
43
+ }
44
+ };
45
+ // Single exit point: clear the timer once, fire onDone once. Every terminal
46
+ // branch routes through here so a timer can never be left armed.
47
+ const settle = (result) => {
48
+ if (settled)
49
+ return;
50
+ settled = true;
51
+ clearTimer();
52
+ opts.onDone(result);
53
+ };
54
+ const tick = async () => {
55
+ if (settled)
56
+ return;
57
+ // Deadline check FIRST: if the budget is spent, stop before another poll.
58
+ if (now() - startedAt >= opts.deadlineMs) {
59
+ settle({ done: true, timedOut: true, outcome: "timeout" });
60
+ return;
61
+ }
62
+ // Skip overlapping ticks — a slow poll step must not stack a second
63
+ // in-flight call on the next interval.
64
+ if (inFlight)
65
+ return;
66
+ inFlight = true;
67
+ let result;
68
+ try {
69
+ result = await opts.poll();
70
+ }
71
+ catch {
72
+ // A throw from the injected step is treated as non-terminal: the
73
+ // sil-client wrapper already maps network errors to a retryable result,
74
+ // so this is belt-and-braces; let the next tick (within budget) retry.
75
+ result = { done: false };
76
+ }
77
+ finally {
78
+ inFlight = false;
79
+ }
80
+ if (settled)
81
+ return; // a concurrent stop() landed during the await.
82
+ if (result.done)
83
+ settle(result);
84
+ };
85
+ timer = setInterval(() => void tick(), opts.intervalMs);
86
+ return {
87
+ stop() {
88
+ if (settled)
89
+ return;
90
+ settled = true;
91
+ clearTimer();
92
+ },
93
+ };
94
+ }