worktrust 0.10.24 → 0.10.26
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/AGENTS.md +1 -1
- package/README.md +46 -20
- package/SECURITY.md +38 -8
- package/credential-store.mjs +109 -0
- package/credential-vault-scripts.mjs +82 -0
- package/credential-vault.mjs +49 -0
- package/engine-release.json +1 -1
- package/log-session.mjs +19 -84
- package/package-integrity.mjs +83 -6
- package/package-release.json +1 -1
- package/package.json +5 -2
- package/preserve-lines.mjs +2 -1
- package/preserve.mjs +16 -17
- package/runtime-install.mjs +48 -6
- package/setup-mcp.mjs +20 -18
- package/worktrust-launch.mjs +90 -8
- package/worktrust.mjs +69 -62
package/AGENTS.md
CHANGED
|
@@ -7,7 +7,7 @@ the rules of this package.
|
|
|
7
7
|
|
|
8
8
|
## Do not run it for the person
|
|
9
9
|
|
|
10
|
-
The bare `worktrust` command, `connect`, `update`, `history` (and `--rebuild`), `disconnect`, `preserve`, `codex`, `antigravity` and the
|
|
10
|
+
The bare `worktrust` command, `connect`, `update`, `history` (and `--rebuild`), `disconnect`, `protect-key`, `preserve`, `codex`, `antigravity` and the
|
|
11
11
|
import commands change what this computer sends or couples. **Only the person runs them, in their own terminal.** In an
|
|
12
12
|
agent's shell the CLI refuses these actions, `--yes` included. Version 0.10.12 adds the missing default-command
|
|
13
13
|
guard and tests both fresh and coupled synthetic homes. Do not work around the policy: do not unset
|
package/README.md
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
# worktrust
|
|
2
2
|
|
|
3
|
-
## Candidate 0.10.
|
|
3
|
+
## Candidate 0.10.26: OS credential storage
|
|
4
4
|
|
|
5
|
-
Not published yet.
|
|
5
|
+
Not published yet; 0.10.25 is the preceding live release. This candidate adds explicit
|
|
6
|
+
`worktrust protect-key` migration: an OS-vault wrapping key protects the locally encrypted
|
|
7
|
+
coupling credentials. It does not attest that local activity is truthful. See
|
|
8
|
+
[credential protection](#credential-protection) before enabling it.
|
|
9
|
+
|
|
10
|
+
After an approved update, WorkTrust receives the running version without
|
|
6
11
|
an activity upload. Pending metadata batches can be resumed with `worktrust history --resume`,
|
|
7
12
|
even after an AI app removed the original session files. Review-held revisions need review;
|
|
8
13
|
reconnecting does not approve them. Keep archives for work that was never queued.
|
|
9
14
|
|
|
10
|
-
The
|
|
15
|
+
The server limits new personal registrations to five active device
|
|
11
16
|
identities. AI apps sharing one key share one slot; cloned keys share account upload capacity.
|
|
12
17
|
Retiring a device preserves earlier data. Existing accounts above the limit are preserved but
|
|
13
18
|
cannot add another identity. Version labels and device signatures are not independent evidence
|
|
@@ -24,8 +29,8 @@ npx worktrust@latest
|
|
|
24
29
|
**The official npm package** is `worktrust`, published by the npm account **worktrustio** with
|
|
25
30
|
provenance from this repository (github.com/fhomey/worktrust-cli). Check it on npmjs.com before you run
|
|
26
31
|
it; a package of another name or from another publisher is not ours. Use the complete package:
|
|
27
|
-
individual support scripts are no longer downloaded and executed during setup.
|
|
28
|
-
|
|
32
|
+
individual support scripts are no longer downloaded and executed during setup. The live 0.10.25
|
|
33
|
+
release includes signed startup checks; 0.10.21 does not include this guard.
|
|
29
34
|
|
|
30
35
|
**Python tool runners:** this repository also builds `worktrust` for `uvx` and `pipx` from the
|
|
31
36
|
same measurement modules. Native wheels (0.10.13+) include a pinned official Node runtime,
|
|
@@ -381,20 +386,33 @@ a day it sealed before), but such a day reaches WorkTrust as reconstructed. It i
|
|
|
381
386
|
pairing: `connect` always mints a fresh pair, because a private key that lived on disk before the pairing would weaken
|
|
382
387
|
the proof of possession the pairing binds, for nothing your record would gain.
|
|
383
388
|
|
|
384
|
-
##
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
389
|
+
## Credential protection
|
|
390
|
+
|
|
391
|
+
Existing installations keep private file storage until the person opts in. In the 0.10.26
|
|
392
|
+
candidate, run `worktrust update`, quit the AI apps, then run `worktrust protect-key` and restart
|
|
393
|
+
those apps. A new computer can run `worktrust protect-key` before connecting. `worktrust status`
|
|
394
|
+
shows the storage mode. This command is local and does not publish or change a Passport.
|
|
395
|
+
|
|
396
|
+
Protected mode encrypts the token, pending renewal token, device private key and coupling metadata
|
|
397
|
+
with AES-256-GCM in `~/.worktrust/key.json`. Its random encryption key lives in macOS Keychain,
|
|
398
|
+
Windows Credential Manager, or Linux Secret Service (`/usr/bin/secret-tool` from libsecret-tools,
|
|
399
|
+
with a running, unlocked desktop secret service). No keychain reset is performed. First-time
|
|
400
|
+
protection may require OS approval; background reads never request an unlock prompt. An unavailable
|
|
401
|
+
vault stops uploads without advancing their checkpoints. There is no plaintext fallback.
|
|
402
|
+
|
|
403
|
+
Migration verifies the vault write before atomically replacing the old file. No plaintext backup
|
|
404
|
+
is created. Existing backups and already running processes can still hold the old secrets; this
|
|
405
|
+
is not secure erasure of an SSD or revocation of previously copied credentials. The local archive's
|
|
406
|
+
separate continuity key (`archive-key.json`) is not migrated by this command. `preserve` remains
|
|
407
|
+
offline and refuses to silently change signing identity when protected credentials are unavailable.
|
|
408
|
+
|
|
409
|
+
- **AI apps use the bridge.** The bridge and hooks read the protected credentials as the OS user;
|
|
410
|
+
their settings contain a launcher command, not the credentials. Update every installed bridge
|
|
411
|
+
first: older releases cannot read the encrypted format. Protected mode refuses `--direct`.
|
|
412
|
+
- **A device signature proves possession.** The server stores the public key and checks fresh
|
|
413
|
+
signed requests and single-use nonces. Neither file encryption nor an OS vault proves genuine
|
|
414
|
+
local activity. Software authorized as the same OS user may still obtain or use these secrets.
|
|
415
|
+
This is not a hardware-bound, non-exportable key. Revoke the connection if it may be compromised.
|
|
398
416
|
- **The key renews itself every week.** A new secret is made here, only its hash is sent, signed,
|
|
399
417
|
and last week's key stops working.
|
|
400
418
|
- `npx worktrust --direct` writes a plain key into the apps' settings instead, for an app
|
|
@@ -467,7 +485,8 @@ never as proof.
|
|
|
467
485
|
## Undo
|
|
468
486
|
|
|
469
487
|
`npx worktrust@latest disconnect` removes the WorkTrust entries (Hermes's hook with them), the hook (and Codex's `notify` line and
|
|
470
|
-
Antigravity's `worktrust` hook when WorkTrust set them), the
|
|
488
|
+
Antigravity's `worktrust` hook when WorkTrust set them), the credentials and installed bridge scripts.
|
|
489
|
+
Protected mode retains an encrypted empty slot and its OS wrapping key so reconnecting stays protected.
|
|
471
490
|
A small note of the previous account (masked) remains so that a later coupling by another account
|
|
472
491
|
does not offer its earlier work. Other retained files and your local evidence archive are not an
|
|
473
492
|
automatic server or archive erasure.
|
|
@@ -510,3 +529,10 @@ claim eligibility remains the server publication gate's responsibility.
|
|
|
510
529
|
Revoking a computer key stops new submissions, not the validity of every historical publication.
|
|
511
530
|
Passport withdrawal is a separate audited operation. Neither operation automatically erases the
|
|
512
531
|
person's prior data. Release signing keys, computer keys and passport signing keys are separate.
|
|
532
|
+
|
|
533
|
+
In 0.10.25, hooks and helper processes from the official launcher stay inside the checked
|
|
534
|
+
release. The old loose `~/.worktrust/count-behaviour.mjs` and individual-script download
|
|
535
|
+
fallbacks are no longer executed. Persistent Python hooks use the host Python to check the
|
|
536
|
+
copied Node runtime before starting it, even after the temporary uvx/pipx cache is removed.
|
|
537
|
+
Keep that host Python installed. Updating preserves credentials, pending uploads and archives;
|
|
538
|
+
it does not approve held history or publish a passport automatically.
|
package/SECURITY.md
CHANGED
|
@@ -9,11 +9,11 @@ private transcripts or account data in a public issue.
|
|
|
9
9
|
|
|
10
10
|
- Setup changes client configuration and local coupling files; preservation can change retention
|
|
11
11
|
settings and create or append archives. See the README for the paths and individual options.
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
The complete official release is required. Individual script download fallbacks are removed;
|
|
13
|
+
interactive commands may check for a newer release.
|
|
14
14
|
- Submissions go to the configured WorkTrust MCP endpoint. Interactive commands can also contact
|
|
15
|
-
the npm registry for a version notice.
|
|
16
|
-
modules, but installation and
|
|
15
|
+
the npm registry for a version notice. Release notices never execute a different version. The npm package bundles its runtime
|
|
16
|
+
modules, but package-manager installation and explicit upgrades still use the network. `preserve` itself is local.
|
|
17
17
|
A custom `--origin`, URL or registry override changes whom you trust.
|
|
18
18
|
- The key it receives is a WorkTrust coupling for this computer: it can submit work metadata to your
|
|
19
19
|
record and cannot read your record back. Revoke it in WorkTrust at any time.
|
|
@@ -28,12 +28,22 @@ private transcripts or account data in a public issue.
|
|
|
28
28
|
|
|
29
29
|
## Where the key is, and how long it lives
|
|
30
30
|
|
|
31
|
-
-
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
- Existing installations use a private local file until explicit `worktrust protect-key` migration
|
|
32
|
+
(0.10.26 candidate). Base64 in that legacy file is not encryption.
|
|
33
|
+
- Protected mode uses AES-256-GCM for all coupling secrets and OS storage for a separate random
|
|
34
|
+
wrapping key: macOS Keychain, Windows Credential Manager with local-machine persistence, or
|
|
35
|
+
Linux Secret Service. Only a random identifier, provider, nonce, ciphertext and authentication
|
|
36
|
+
tag remain in `key.json`. Private file checks and atomic replacement still apply. Locked,
|
|
37
|
+
missing or unavailable OS storage fails closed, without a new key or plaintext fallback.
|
|
38
|
+
- This is exportable software credential protection, not hardware attestation. Other software
|
|
39
|
+
authorized as the OS user can request decryption; an attacker controlling the launcher or OS
|
|
40
|
+
can bypass local checks. Local activity remains untrusted for independent public claims.
|
|
41
|
+
- The command does not reset a vault, change its ACLs, erase backups, revoke stolen credentials,
|
|
42
|
+
or move the independent offline archive continuity key. New setup is opt-in; it is not an
|
|
43
|
+
automatic migration of existing users. Hooks never write vault items or trigger unlock UI.
|
|
34
44
|
- In the default mode, requests carry an Ed25519 proof. WorkTrust refuses a bound token without a
|
|
35
45
|
fresh signature (two minutes, a nonce spent once). A bearer token alone is insufficient; theft of
|
|
36
|
-
the
|
|
46
|
+
the legacy plaintext credentials, or the protected file together with access to its OS wrapping key, defeats that protection. Profile/device hashes are not hardware
|
|
37
47
|
attestation. Revoke the computer in WorkTrust if its credential file may have been copied.
|
|
38
48
|
- `--direct` instead places an unbound bearer token in AI client settings and does not provide the
|
|
39
49
|
same proof requirement. Do not apply the default mode's guarantees to that mode.
|
|
@@ -131,3 +141,23 @@ selection and consent. It is not an automatic SDK upload or an MCP submission. D
|
|
|
131
141
|
recording does not erase a separately imported copy; delete that copy through the private app.
|
|
132
142
|
See the service [privacy policy](https://worktrust.io/privacy) and
|
|
133
143
|
[support](https://worktrust.io/support) for account data requests.
|
|
144
|
+
|
|
145
|
+
## Execution boundary in 0.10.25
|
|
146
|
+
|
|
147
|
+
The official launcher starts helpers from its checked release, never a loose counter, hook or
|
|
148
|
+
reader in `~/.worktrust`. Its helper processes re-enter the launcher and its manifest check.
|
|
149
|
+
A missing or changed release is refused with an instruction to reinstall; it is not repaired
|
|
150
|
+
by downloading individual scripts. Earlier loose files may remain for recovery but are not
|
|
151
|
+
used as executable fallbacks.
|
|
152
|
+
|
|
153
|
+
Python's persistent installation now starts with the package manager's host Python in isolated
|
|
154
|
+
mode. A standard-library bootstrap checks the copied Node binary and engine before Node
|
|
155
|
+
executes, against hashes authenticated during installation. It does not trust a rewritten local
|
|
156
|
+
`runtime.json` or `installation.json` to authorize changes. The initial Python package still
|
|
157
|
+
verifies its publisher signature before installation. The host Python must remain available.
|
|
158
|
+
|
|
159
|
+
Bootstrap files, host interpreters, client configuration and processes running as the owner
|
|
160
|
+
remain trust boundaries. Replacing the bootstrap or racing file changes after a check cannot
|
|
161
|
+
be prevented by self-verification on an owner-controlled computer. Generated Claude/OpenCode
|
|
162
|
+
client plugins and user transcript/SDK inputs are not remote attestation. Server claim and
|
|
163
|
+
publication gates remain necessary; a matching client hash never proves truthful activity.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** OS-backed wrapping key, AES-256-GCM credentials. The OS account can still request decryption.
|
|
2
|
+
* No attestation: signed input remains subject to the server's claim-specific trust gates.
|
|
3
|
+
*/
|
|
4
|
+
import { createCipheriv, createDecipheriv, createPrivateKey, createPublicKey, randomBytes } from 'node:crypto';
|
|
5
|
+
import { rmSync } from 'node:fs';
|
|
6
|
+
import { readPrivateFile, writePrivateFile, createPrivateFile } from './package-integrity.mjs';
|
|
7
|
+
import { nativeKeyStore } from './credential-vault.mjs';
|
|
8
|
+
const FORMAT = 'worktrust-os-key/1';
|
|
9
|
+
function validEntry(entry) {
|
|
10
|
+
if (entry !== null && (!entry || typeof entry !== 'object' || Array.isArray(entry) || typeof entry.token !== 'string' || !entry.token)) throw Error('KEY_FILE_INVALID');
|
|
11
|
+
return entry;
|
|
12
|
+
}
|
|
13
|
+
function decode(bytes) {
|
|
14
|
+
if (bytes === null) return null;
|
|
15
|
+
try {
|
|
16
|
+
if (bytes.startsWith('{')) {
|
|
17
|
+
const e = JSON.parse(bytes);
|
|
18
|
+
if (e.format !== FORMAT || !/^[a-f0-9]{64}$/.test(e.id) || !/^[a-z-]{1,40}$/.test(e.provider)
|
|
19
|
+
|| !/^[a-f0-9]{24}$/.test(e.iv) || !/^[a-f0-9]{32}$/.test(e.tag) || typeof e.ciphertext !== 'string'
|
|
20
|
+
|| !/^[A-Za-z0-9+/]+={0,2}$/.test(e.ciphertext)
|
|
21
|
+
|| Object.keys(e).sort().join(',') !== 'ciphertext,format,id,iv,provider,tag') throw Error();
|
|
22
|
+
return e;
|
|
23
|
+
}
|
|
24
|
+
return validEntry(JSON.parse(Buffer.from(bytes, 'base64').toString('utf8')));
|
|
25
|
+
} catch { throw Error('KEY_FILE_INVALID'); }
|
|
26
|
+
}
|
|
27
|
+
function wrappingKey(vault, envelope) {
|
|
28
|
+
if (envelope.provider !== vault.name) throw Error('KEYSTORE_UNAVAILABLE');
|
|
29
|
+
const value = vault.get(envelope.id);
|
|
30
|
+
if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw Error('KEYSTORE_UNAVAILABLE');
|
|
31
|
+
return Buffer.from(value, 'hex');
|
|
32
|
+
}
|
|
33
|
+
const aad = e => Buffer.from(`${FORMAT}\n${e.provider}\n${e.id}`);
|
|
34
|
+
function open(vault, e) {
|
|
35
|
+
if (!e || e.format !== FORMAT) return e;
|
|
36
|
+
const key = wrappingKey(vault, e);
|
|
37
|
+
try {
|
|
38
|
+
const cipher = createDecipheriv('aes-256-gcm', key, Buffer.from(e.iv, 'hex'));
|
|
39
|
+
cipher.setAAD(aad(e)); cipher.setAuthTag(Buffer.from(e.tag, 'hex'));
|
|
40
|
+
return validEntry(JSON.parse(Buffer.concat([cipher.update(Buffer.from(e.ciphertext, 'base64')), cipher.final()]).toString('utf8')));
|
|
41
|
+
} catch { throw Error('KEY_FILE_INVALID'); }
|
|
42
|
+
finally { key.fill(0); }
|
|
43
|
+
}
|
|
44
|
+
function seal(vault, reference, entry) {
|
|
45
|
+
const key = wrappingKey(vault, reference);
|
|
46
|
+
try {
|
|
47
|
+
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
48
|
+
cipher.setAAD(aad(reference));
|
|
49
|
+
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(validEntry(entry)), 'utf8'), cipher.final()]);
|
|
50
|
+
return JSON.stringify({ format: FORMAT, provider: reference.provider, id: reference.id, iv: iv.toString('hex'), tag: cipher.getAuthTag().toString('hex'), ciphertext: ciphertext.toString('base64') });
|
|
51
|
+
} finally { key.fill(0); }
|
|
52
|
+
}
|
|
53
|
+
export function createCredentialStore(file, vault = nativeKeyStore()) {
|
|
54
|
+
const read = () => decode(readPrivateFile(file));
|
|
55
|
+
function locked(action) {
|
|
56
|
+
const lock = `${file}.lock`;
|
|
57
|
+
try { createPrivateFile(lock, JSON.stringify({ pid: process.pid })); }
|
|
58
|
+
catch (error) { throw Error(error.code === 'EEXIST' ? 'KEY_STORE_BUSY' : 'KEY_FILE_UNSAFE'); }
|
|
59
|
+
try { return action(); } finally { rmSync(lock); }
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
load() { return open(vault, read()); },
|
|
63
|
+
protected() { return read()?.format === FORMAT; },
|
|
64
|
+
save(entry) {
|
|
65
|
+
return locked(() => {
|
|
66
|
+
const old = read();
|
|
67
|
+
// Authenticate the previous envelope before replacing it; corruption is never reset quietly.
|
|
68
|
+
if (old?.format === FORMAT) { open(vault, old); writePrivateFile(file, seal(vault, old, entry)); }
|
|
69
|
+
else writePrivateFile(file, Buffer.from(JSON.stringify(validEntry(entry))).toString('base64'));
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
protect() {
|
|
73
|
+
return locked(() => {
|
|
74
|
+
const old = read();
|
|
75
|
+
if (old?.format === FORMAT) { open(vault, old); return; }
|
|
76
|
+
const reference = { format: FORMAT, provider: vault.name, id: randomBytes(32).toString('hex') };
|
|
77
|
+
const secret = randomBytes(32).toString('hex'); let committed = false;
|
|
78
|
+
try {
|
|
79
|
+
vault.put(reference.id, secret);
|
|
80
|
+
if (vault.get(reference.id) !== secret) throw Error('KEYSTORE_UNAVAILABLE');
|
|
81
|
+
const envelope = seal(vault, reference, old);
|
|
82
|
+
if (JSON.stringify(open(vault, JSON.parse(envelope))) !== JSON.stringify(old)) throw Error('KEYSTORE_UNAVAILABLE');
|
|
83
|
+
writePrivateFile(file, envelope); committed = true;
|
|
84
|
+
} finally {
|
|
85
|
+
// If preparation fails the old credentials survive. No backup containing plaintext is made.
|
|
86
|
+
if (!committed) { try { vault.remove(reference.id); } catch { /* orphan random wrapping key, no credentials */ } }
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
},
|
|
90
|
+
erase() {
|
|
91
|
+
return locked(() => {
|
|
92
|
+
const old = read();
|
|
93
|
+
// An encrypted empty slot keeps the storage preference through disconnect/reconnect.
|
|
94
|
+
if (old?.format === FORMAT) { open(vault, old); writePrivateFile(file, seal(vault, old, null)); }
|
|
95
|
+
else rmSync(file, { force: true });
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Archive signing shares the coupling store; an unavailable vault is not an absent device. */
|
|
102
|
+
export function readDeviceSigningKey(file) {
|
|
103
|
+
const entry = createCredentialStore(file).load();
|
|
104
|
+
if (!entry?.device) return null;
|
|
105
|
+
try {
|
|
106
|
+
const privateKey = createPrivateKey(entry.device);
|
|
107
|
+
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "device" };
|
|
108
|
+
} catch { return null; }
|
|
109
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Fixed helper programs are covered by the release manifest. No request is evaluated as code. */
|
|
2
|
+
export const macKeychainScript = String.raw`
|
|
3
|
+
ObjC.import('Foundation'); ObjC.import('Security');
|
|
4
|
+
function run() {
|
|
5
|
+
try {
|
|
6
|
+
var data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
|
|
7
|
+
var request = JSON.parse(ObjC.unwrap($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding)));
|
|
8
|
+
if (!/^[a-f0-9]{64}$/.test(request.id) || request.service !== 'io.worktrust.cli.credentials.v1') throw Error();
|
|
9
|
+
// No reset, default-keychain change, ACL broadening or partition-list modification.
|
|
10
|
+
$.SecKeychainSetUserInteractionAllowed(request.op === 'put');
|
|
11
|
+
var query = $.NSMutableDictionary.alloc.init;
|
|
12
|
+
query.setObjectForKey(ObjC.castRefToObject($.kSecClassGenericPassword), ObjC.castRefToObject($.kSecClass));
|
|
13
|
+
query.setObjectForKey($(request.service), ObjC.castRefToObject($.kSecAttrService));
|
|
14
|
+
query.setObjectForKey($(request.id), ObjC.castRefToObject($.kSecAttrAccount));
|
|
15
|
+
var status, result = Ref();
|
|
16
|
+
if (request.op === 'get') {
|
|
17
|
+
query.setObjectForKey(ObjC.castRefToObject($.kCFBooleanTrue), ObjC.castRefToObject($.kSecReturnData));
|
|
18
|
+
query.setObjectForKey(ObjC.castRefToObject($.kSecMatchLimitOne), ObjC.castRefToObject($.kSecMatchLimit));
|
|
19
|
+
status = $.SecItemCopyMatching(query, result);
|
|
20
|
+
if (status !== 0) throw Error();
|
|
21
|
+
return JSON.stringify({ok: true, value: ObjC.unwrap($.NSString.alloc.initWithDataEncoding(ObjC.castRefToObject(result[0]), $.NSUTF8StringEncoding))});
|
|
22
|
+
}
|
|
23
|
+
if (request.op === 'put') {
|
|
24
|
+
if (!/^[a-f0-9]{64}$/.test(request.value)) throw Error();
|
|
25
|
+
query.setObjectForKey($(request.value).dataUsingEncoding($.NSUTF8StringEncoding), ObjC.castRefToObject($.kSecValueData));
|
|
26
|
+
query.setObjectForKey($('WorkTrust CLI credential encryption'), ObjC.castRefToObject($.kSecAttrLabel));
|
|
27
|
+
query.setObjectForKey(ObjC.castRefToObject($.kCFBooleanFalse), ObjC.castRefToObject($.kSecAttrSynchronizable));
|
|
28
|
+
status = $.SecItemAdd(query, null);
|
|
29
|
+
} else if (request.op === 'remove') { status = $.SecItemDelete(query); }
|
|
30
|
+
else throw Error();
|
|
31
|
+
if (status !== 0 && !(request.op === 'remove' && status === -25300)) throw Error();
|
|
32
|
+
return '{"ok":true}';
|
|
33
|
+
} catch (_) { return '{"ok":false}'; }
|
|
34
|
+
}
|
|
35
|
+
`;
|
|
36
|
+
export const windowsCredentialScript = String.raw`
|
|
37
|
+
$ErrorActionPreference = 'Stop'
|
|
38
|
+
try {
|
|
39
|
+
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
40
|
+
if ($request.id -cnotmatch '^[a-f0-9]{64}$' -or $request.service -cne 'io.worktrust.cli.credentials.v1') { throw 'invalid' }
|
|
41
|
+
Add-Type -TypeDefinition @'
|
|
42
|
+
using System;
|
|
43
|
+
using System.Runtime.InteropServices;
|
|
44
|
+
public static class WorkTrustVault {
|
|
45
|
+
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct Credential {
|
|
46
|
+
public uint Flags; public uint Type; public string TargetName; public string Comment;
|
|
47
|
+
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
|
48
|
+
public uint CredentialBlobSize; public IntPtr CredentialBlob; public uint Persist;
|
|
49
|
+
public uint AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;
|
|
50
|
+
}
|
|
51
|
+
[DllImport("advapi32.dll", EntryPoint="CredWriteW", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool Write(ref Credential value, uint flags);
|
|
52
|
+
[DllImport("advapi32.dll", EntryPoint="CredReadW", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool Read(string target, uint type, uint flags, out IntPtr value);
|
|
53
|
+
[DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool Delete(string target, uint type, uint flags);
|
|
54
|
+
[DllImport("advapi32.dll", EntryPoint="CredFree")] public static extern void Free(IntPtr value);
|
|
55
|
+
}
|
|
56
|
+
'@
|
|
57
|
+
$target = $request.service + '/' + $request.id
|
|
58
|
+
if ($request.op -ceq 'get') {
|
|
59
|
+
$pointer = [IntPtr]::Zero
|
|
60
|
+
if (![WorkTrustVault]::Read($target, 1, 0, [ref]$pointer)) { throw 'unavailable' }
|
|
61
|
+
try {
|
|
62
|
+
$credential = [Runtime.InteropServices.Marshal]::PtrToStructure($pointer, [type][WorkTrustVault+Credential])
|
|
63
|
+
if ($credential.CredentialBlobSize -ne 128) { throw 'invalid' }
|
|
64
|
+
$value = [Runtime.InteropServices.Marshal]::PtrToStringUni($credential.CredentialBlob, 64)
|
|
65
|
+
@{ok=$true; value=$value} | ConvertTo-Json -Compress
|
|
66
|
+
} finally { [WorkTrustVault]::Free($pointer) }
|
|
67
|
+
} elseif ($request.op -ceq 'put') {
|
|
68
|
+
if ($request.value -cnotmatch '^[a-f0-9]{64}$') { throw 'invalid' }
|
|
69
|
+
$credential = New-Object WorkTrustVault+Credential
|
|
70
|
+
$credential.Type=1; $credential.TargetName=$target; $credential.UserName='WorkTrust CLI'
|
|
71
|
+
$credential.Persist=2; $credential.CredentialBlobSize=128
|
|
72
|
+
$credential.CredentialBlob=[Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($request.value)
|
|
73
|
+
try { if (![WorkTrustVault]::Write([ref]$credential, 0)) { throw 'unavailable' } }
|
|
74
|
+
finally { [Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($credential.CredentialBlob) }
|
|
75
|
+
'{"ok":true}'
|
|
76
|
+
} elseif ($request.op -ceq 'remove') {
|
|
77
|
+
$removed = [WorkTrustVault]::Delete($target, 1, 0)
|
|
78
|
+
if (!$removed -and [Runtime.InteropServices.Marshal]::GetLastWin32Error() -ne 1168) { throw 'unavailable' }
|
|
79
|
+
'{"ok":true}'
|
|
80
|
+
} else { throw 'invalid' }
|
|
81
|
+
} catch { '{"ok":false}'; exit 1 }
|
|
82
|
+
`;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Native OS facilities only. Secrets travel over stdin/stdout, never arguments or log output.
|
|
2
|
+
* Only explicit protect-key writes a vault item. Runtime reads never request an unlock prompt.
|
|
3
|
+
*/
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { userInfo } from 'node:os';
|
|
8
|
+
import { macKeychainScript, windowsCredentialScript } from './credential-vault-scripts.mjs';
|
|
9
|
+
const SERVICE = 'io.worktrust.cli.credentials.v1';
|
|
10
|
+
function invoke(executable, args, input) {
|
|
11
|
+
// Do not inherit credential-bearing WorkTrust environment variables into the OS helper.
|
|
12
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(WORKTRUST_|NODE_|PYTHON|DYLD_|LD_)/.test(key)));
|
|
13
|
+
if (process.platform === "darwin") env.HOME = userInfo().homedir; // Keychain belongs to the OS user, not a caller-supplied HOME.
|
|
14
|
+
// Windows PowerShell compiles the small Credential Manager binding on every call; a cold start on a slow or busy
|
|
15
|
+
// machine passed eight seconds on native CI (2026-10-20), so it gets thirty there. Elsewhere eight remain.
|
|
16
|
+
const r = spawnSync(executable, args, { input, env, encoding: 'utf8', timeout: process.platform === 'win32' ? 30000 : 8000, maxBuffer: 32768, windowsHide: true });
|
|
17
|
+
if (r.error || r.status !== 0) throw Error('KEYSTORE_UNAVAILABLE');
|
|
18
|
+
return r.stdout.trim();
|
|
19
|
+
}
|
|
20
|
+
export function nativeKeyStore() {
|
|
21
|
+
const platform = process.platform;
|
|
22
|
+
const name = platform === 'darwin' ? 'macos-keychain' : platform === 'win32' ? 'windows-credential-manager' : platform === 'linux' ? 'linux-secret-service' : 'unsupported';
|
|
23
|
+
function call(op, id, value) {
|
|
24
|
+
if (!/^[a-f0-9]{64}$/.test(id) || (value !== undefined && !/^[a-f0-9]{64}$/.test(value))) throw Error('KEYSTORE_INVALID_REQUEST');
|
|
25
|
+
if (platform === 'darwin' || platform === 'win32') {
|
|
26
|
+
const executable = platform === 'darwin' ? '/usr/bin/osascript' : join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
27
|
+
const args = platform === 'darwin' ? ['-l', 'JavaScript', '-e', macKeychainScript] : ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', windowsCredentialScript];
|
|
28
|
+
const out = invoke(executable, args, JSON.stringify({ op, id, value, service: SERVICE }));
|
|
29
|
+
try { const reply = JSON.parse(out); if (reply.ok === true) return reply.value ?? null; } catch { /* never log OS error payloads */ }
|
|
30
|
+
throw Error('KEYSTORE_UNAVAILABLE');
|
|
31
|
+
}
|
|
32
|
+
if (platform === 'linux') {
|
|
33
|
+
const executable = '/usr/bin/secret-tool';
|
|
34
|
+
if (!existsSync(executable)) throw Error('KEYSTORE_UNAVAILABLE');
|
|
35
|
+
const attributes = ['service', SERVICE, 'account', id];
|
|
36
|
+
if (op === 'get') {
|
|
37
|
+
// `lookup` can unlock and prompt. `search` without --unlock never does.
|
|
38
|
+
const out = invoke(executable, ['search', '--all', ...attributes], '');
|
|
39
|
+
const secrets = [...out.matchAll(/^secret = ([a-f0-9]{64})$/gm)];
|
|
40
|
+
if (secrets.length !== 1) throw Error('KEYSTORE_UNAVAILABLE');
|
|
41
|
+
return secrets[0][1];
|
|
42
|
+
}
|
|
43
|
+
if (op === 'put') return invoke(executable, ['store', '--label=WorkTrust CLI credential encryption', ...attributes], value);
|
|
44
|
+
if (op === 'remove') return invoke(executable, ['clear', ...attributes], '');
|
|
45
|
+
}
|
|
46
|
+
throw Error('KEYSTORE_UNAVAILABLE');
|
|
47
|
+
}
|
|
48
|
+
return { name, get: id => call('get', id), put: (id, value) => call('put', id, value), remove: id => call('remove', id) };
|
|
49
|
+
}
|
package/engine-release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"
|
|
1
|
+
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"c5e6e4d44a85768f21c25945b8630f31306ec2665193886870c1010ef6bf3c26","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"6ecfbf44f001dd433512b26736031ebc855b154e2bb0a401e2512b43623cd9cd","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"413948644a74dc0bf1b49548be193bf596bcf82ac7eae668f624345a18e189e7","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"78260b4615226ac901211094a908e7535e2d8b8ff18856d907a817f3cb5a1e08"},"format":"worktrust-package/1","kind":"engine","version":"0.10.26"},"signature":"5pk8vqS79gPJPO03dpO7dV4HLSbFeeD-kk2WUy_-3RUTYznr4o33rmkH5CGlO9nR6eWlITxWg3Mz6nFBI7leBA"}
|
package/log-session.mjs
CHANGED
|
@@ -60,12 +60,14 @@
|
|
|
60
60
|
* honoured here too, matched against the transcript's project directory, before a file is read.
|
|
61
61
|
*/
|
|
62
62
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
63
|
-
import {
|
|
63
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
|
|
64
64
|
import { homedir } from "node:os";
|
|
65
65
|
import { dirname, join, resolve, sep } from "node:path";
|
|
66
66
|
import { fileURLToPath } from "node:url";
|
|
67
67
|
import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
|
|
68
68
|
|
|
69
|
+
import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
|
|
70
|
+
|
|
69
71
|
async function main() {
|
|
70
72
|
const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
|
|
71
73
|
const flag = (name) => args.includes(`--${name}`), value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; }, DRY = flag("dry-run");
|
|
@@ -83,32 +85,13 @@ const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("",
|
|
|
83
85
|
* may stage, only the owner may count — and a hook that could send counts by itself would put an
|
|
84
86
|
* automatic writer on the one surface that describes how a person thinks.
|
|
85
87
|
*/
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
+
const RELEASE_DIR = dirname(fileURLToPath(import.meta.url));
|
|
89
|
+
const COUNTER = join(RELEASE_DIR, "count-behaviour.mjs");
|
|
90
|
+
/** Legacy marker, used only when the person explicitly purges the old installation. */
|
|
88
91
|
const PINNED = join(homedir(), ".worktrust", "pinned");
|
|
89
92
|
/** A hook command is ours when it runs this file, or the `worktrust hook` wrapper that hands it the key from the key file. */
|
|
90
|
-
const ours = (command) => /log-session|worktrust
|
|
93
|
+
const ours = (command) => /log-session|worktrust(?:-launch)?\.(?:mjs|py)" (?:hook|--internal-module)|worktrust(?:-launch)?\.(?:mjs|py) hook/.test(String(command ?? ""));
|
|
91
94
|
const COUNTER_EVERY_MS = 24 * 3600_000;
|
|
92
|
-
/**
|
|
93
|
-
* Counter compatibility is pinned by the verified release.
|
|
94
|
-
*/
|
|
95
|
-
const versionOf = (text) => /export const ANALYZER_VERSION = "counter@(\d+)\.(\d+)\.(\d+)"/.exec(text ?? "")?.slice(1, 4).map(Number) ?? null;
|
|
96
|
-
const newer = (a, b) => { if (!a || !b) return false; for (let i = 0; i < 3; i += 1) { if (a[i] === b[i]) continue; return a[i] > b[i]; } return false; };
|
|
97
|
-
async function refreshCounter(origin, announce) {
|
|
98
|
-
if (!origin || !existsSync(COUNTER) || existsSync(PINNED)) return false;
|
|
99
|
-
try {
|
|
100
|
-
const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
|
|
101
|
-
if (!response.ok) return false;
|
|
102
|
-
const remote = await response.text();
|
|
103
|
-
const have = versionOf(readFileSync(COUNTER, "utf8")), theirs = versionOf(remote);
|
|
104
|
-
if (!newer(theirs, have)) return false;
|
|
105
|
-
writeFileSync(COUNTER, remote);
|
|
106
|
-
await installReaders(origin, true);
|
|
107
|
-
announce?.(`counter: updated to counter@${theirs.join(".")} (was counter@${have?.join(".") ?? "?"}) — the next reading counts under the new rubric`);
|
|
108
|
-
return true;
|
|
109
|
-
} catch { return false; }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
95
|
/**
|
|
113
96
|
* The live door refuses stretches older than two days; older work uses the history door.
|
|
114
97
|
*
|
|
@@ -254,20 +237,6 @@ const EXPORT_PATHS = []; for (let i = 0; i < args.length; i += 1) if (args[i] ==
|
|
|
254
237
|
const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot"]; // the registry's keys, the name each line carries
|
|
255
238
|
const LIVE_SOURCE = new RegExp(`^(codex|antigravity|${DATABASE_CLIENTS.join("|")}):`); // a sweep entry's id → the client it names (every database client, 0.6.16)
|
|
256
239
|
const READER_FILES = ["history-outbox.mjs", "transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
|
|
257
|
-
/** The readers go where the hook and the counter run: copied from beside this file, else (or for a newer counter) from the deployment. */
|
|
258
|
-
async function installReaders(origin, fromNetwork = false) {
|
|
259
|
-
let installed = true;
|
|
260
|
-
for (const name of READER_FILES) { // Hermes, Goose, OpenCode and OpenClaw are read by session-databases.mjs
|
|
261
|
-
const here = join(dirname(fileURLToPath(import.meta.url)), name), home = join(homedir(), ".worktrust", name);
|
|
262
|
-
try {
|
|
263
|
-
if (!fromNetwork && existsSync(here)) { mkdirSync(dirname(home), { recursive: true }); if (here !== home) copyFileSync(here, home); continue; }
|
|
264
|
-
const response = origin ? await fetch(`${origin}/counter/${name}`) : null;
|
|
265
|
-
if (response?.ok) writeFileSync(home, await response.text()); else installed = false;
|
|
266
|
-
} catch { installed = false; }
|
|
267
|
-
}
|
|
268
|
-
return installed;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
240
|
/** The roots this machine's transcripts live under; a test names its own. */
|
|
272
241
|
const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
|
|
273
242
|
const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
|
|
@@ -1070,7 +1039,7 @@ if (flag("uninstall")) {
|
|
|
1070
1039
|
}
|
|
1071
1040
|
const removed = before !== JSON.stringify(HOOK_EVENTS.map((event) => settings.hooks?.[event] ?? []));
|
|
1072
1041
|
if (removed) writeFileSync(file, JSON.stringify(settings, null, 2));
|
|
1073
|
-
if (flag("purge")) for (const path of [
|
|
1042
|
+
if (flag("purge")) for (const path of [join(homedir(), ".worktrust", "count-behaviour.mjs"), PINNED, join(homedir(), ".worktrust", "log-session.mjs"), STATE, ...READER_FILES.map((name) => join(homedir(), ".worktrust", name)), join(homedir(), ".worktrust", "antigravity.json")]) { try { rmSync(path); } catch { /* already gone */ } }
|
|
1074
1043
|
console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
|
|
1075
1044
|
console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
|
|
1076
1045
|
return await exitFlushed(0);
|
|
@@ -1085,32 +1054,17 @@ if (flag("install")) {
|
|
|
1085
1054
|
if (value("history-floor") === "now") floors.__historyFloor = now;
|
|
1086
1055
|
writeState(floors);
|
|
1087
1056
|
}
|
|
1088
|
-
//
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
// from a person who stopped working. So install copies itself to ~/.worktrust and wires that.
|
|
1095
|
-
const home = join(homedir(), ".worktrust", "log-session.mjs");
|
|
1096
|
-
const self = process.argv[1];
|
|
1097
|
-
// The copy that runs is refreshed from the file you ran — and SAYS so, because "already installed —
|
|
1098
|
-
// nothing changed" after a newer download read as "your hook is old" to the person who had just updated it.
|
|
1099
|
-
let hookRefreshed = false;
|
|
1100
|
-
if (self !== home) {
|
|
1101
|
-
const next = readFileSync(self, "utf8");
|
|
1102
|
-
const current = existsSync(home) ? readFileSync(home, "utf8") : null;
|
|
1103
|
-
mkdirSync(dirname(home), { recursive: true });
|
|
1104
|
-
if (current !== next) { writeFileSync(home, next); hookRefreshed = current !== null; }
|
|
1057
|
+
// Only complete, verified releases may be installed. Old loose scripts are never copied or fetched.
|
|
1058
|
+
const home = join(RELEASE_DIR, "log-session.mjs");
|
|
1059
|
+
let via = value("via");
|
|
1060
|
+
if (!via) {
|
|
1061
|
+
const { installSignedPackage } = await import("./package-integrity.mjs");
|
|
1062
|
+
via = installSignedPackage(RELEASE_DIR, join(homedir(), ".worktrust"));
|
|
1105
1063
|
}
|
|
1106
|
-
// A counter handed over by the package (`--counter <path>`) is copied and pinned: nothing below fetches one.
|
|
1107
|
-
const given = args.indexOf("--counter") >= 0 ? args[args.indexOf("--counter") + 1] : null;
|
|
1108
|
-
if (given) { mkdirSync(dirname(COUNTER), { recursive: true }); writeFileSync(COUNTER, readFileSync(given, "utf8")); writeFileSync(PINNED, "the counter comes with the worktrust package; it is not refreshed from the network\n"); console.log(`counter: ${COUNTER} — from the package, pinned`); }
|
|
1109
1064
|
const file = join(homedir(), ".claude", "settings.json");
|
|
1110
1065
|
const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
|
1111
|
-
|
|
1112
|
-
const
|
|
1113
|
-
const command = `"${process.env.WORKTRUST_NODE || process.execPath}" "${via ?? home}"${via ? " hook" : ""}`;
|
|
1066
|
+
const direct = flag("direct");
|
|
1067
|
+
const command = `"${process.env.WORKTRUST_NODE || process.execPath}"${process.env.WORKTRUST_NODE_ARGS === '["-I"]' ? " -I" : ""} "${via}"${direct ? " --internal-module log-session.mjs" : " hook"}`;
|
|
1114
1068
|
settings.hooks ??= {};
|
|
1115
1069
|
for (const event of HOOK_EVENTS) settings.hooks[event] ??= [];
|
|
1116
1070
|
// A WIRING THAT POINTS SOMEWHERE ELSE IS REPAIRED, NOT LEFT. An earlier install wired whatever
|
|
@@ -1135,24 +1089,7 @@ if (flag("install")) {
|
|
|
1135
1089
|
// how a person ends up certain that a thing works which does not.
|
|
1136
1090
|
const added = HOOK_EVENTS.filter((event) => !wired.has(event));
|
|
1137
1091
|
const already = added.length === 0;
|
|
1138
|
-
|
|
1139
|
-
// says plainly that it could not — a half nobody knows is missing is the worse outcome.
|
|
1140
|
-
const counterOrigin = coupling()?.url ? new URL(coupling().url).origin : null;
|
|
1141
|
-
if (!(await installReaders(counterOrigin))) console.log("readers: transcript-readers.mjs or session-databases.mjs not found beside this file nor at the deployment; the clients they read are not read until they are");
|
|
1142
|
-
if (existsSync(COUNTER)) await refreshCounter(counterOrigin, (line) => console.log(line));
|
|
1143
|
-
if (!existsSync(COUNTER)) {
|
|
1144
|
-
const origin = counterOrigin;
|
|
1145
|
-
if (!origin) console.log("counter: not installed — no coupling found to name the deployment; fetch /counter/count-behaviour.mjs yourself");
|
|
1146
|
-
else {
|
|
1147
|
-
try {
|
|
1148
|
-
const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
|
|
1149
|
-
if (!response.ok) throw new Error(String(response.status));
|
|
1150
|
-
writeFileSync(COUNTER, await response.text());
|
|
1151
|
-
console.log(`counter: ${COUNTER} — it runs once a day from this hook and STAGES its reading; nothing counts until you click Import in the app`);
|
|
1152
|
-
} catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
if (already && !repaired) { console.log(hookRefreshed ? `hook updated: ${home} now runs the version you downloaded; the wiring was already right (${command})` : `already installed — nothing changed (${command})`); return await exitFlushed(0); }
|
|
1092
|
+
if (already && !repaired) { console.log(`already installed — nothing changed (${command})`); return await exitFlushed(0); }
|
|
1156
1093
|
for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
|
|
1157
1094
|
mkdirSync(dirname(file), { recursive: true });
|
|
1158
1095
|
writeFileSync(file, JSON.stringify(settings, null, 2));
|
|
@@ -1234,7 +1171,7 @@ if (flag("history") && flag("from-archive")) {
|
|
|
1234
1171
|
// archive must still verify whole, and only stretches no longer in any AI app here travel.
|
|
1235
1172
|
let ownKey = null;
|
|
1236
1173
|
try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
|
|
1237
|
-
const verified = spawnSync(
|
|
1174
|
+
const verified = spawnSync(moduleExecutable(RELEASE_DIR), [...moduleArgs(RELEASE_DIR, "preserve.mjs", ["--verify", dir])], { encoding: "utf8" });
|
|
1238
1175
|
if (verified.status !== 0) { say(`The archive in ${dir} does not verify, so nothing was sent: ${(verified.stdout || verified.stderr || "").trim().split("\n").pop()}`); return await exitFlushed(1); }
|
|
1239
1176
|
const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
|
|
1240
1177
|
if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
|
|
@@ -1360,12 +1297,10 @@ if (!DRY && (sent > 0 || filed > 0)) writeState(state);
|
|
|
1360
1297
|
// `--send`: staging is idempotent on the reading's own digest, so a day that changed nothing
|
|
1361
1298
|
// leaves nothing behind.
|
|
1362
1299
|
if (!DRY && existsSync(COUNTER)) {
|
|
1363
|
-
// Before the day's count: the deployment's counter, if it is newer than the one on this machine.
|
|
1364
|
-
await refreshCounter(door?.url ? new URL(door.url).origin : null, (line) => console.log(line));
|
|
1365
1300
|
const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
|
|
1366
1301
|
if (Date.now() - last > COUNTER_EVERY_MS) {
|
|
1367
1302
|
try {
|
|
1368
|
-
const child = spawn(
|
|
1303
|
+
const child = spawn(moduleExecutable(RELEASE_DIR), moduleArgs(RELEASE_DIR, "count-behaviour.mjs", ["--stage"]), { detached: true, stdio: ["ignore", "ignore", "inherit"] });
|
|
1369
1304
|
child.unref();
|
|
1370
1305
|
state.__counter = { at: new Date().toISOString() };
|
|
1371
1306
|
writeState(state);
|