worktrust 0.10.25 → 0.10.27
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 +44 -20
- package/SECURITY.md +14 -4
- 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/history-outbox.mjs +12 -6
- package/log-session.mjs +58 -21
- package/package-release.json +1 -1
- package/package.json +5 -2
- package/preserve.mjs +10 -9
- package/worktrust.mjs +55 -40
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,23 @@
|
|
|
1
1
|
# worktrust
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.10.27: history kept on the server
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A re-measure (`worktrust history`) sends its batches as one run; WorkTrust keeps each batch it
|
|
6
|
+
receives and rebuilds the days itself once the run is whole, so no `--resume` is needed. A line
|
|
7
|
+
under no product name is replaced only where the new lines overlap it.
|
|
8
|
+
|
|
9
|
+
## 0.10.26: OS credential storage
|
|
10
|
+
|
|
11
|
+
Explicit `worktrust protect-key` migration: an OS-vault wrapping key protects the locally
|
|
12
|
+
encrypted coupling credentials. It does not attest that local activity is truthful. See
|
|
13
|
+
[credential protection](#credential-protection) before enabling it.
|
|
14
|
+
|
|
15
|
+
After an approved update, WorkTrust receives the running version without
|
|
6
16
|
an activity upload. Pending metadata batches can be resumed with `worktrust history --resume`,
|
|
7
17
|
even after an AI app removed the original session files. Review-held revisions need review;
|
|
8
18
|
reconnecting does not approve them. Keep archives for work that was never queued.
|
|
9
19
|
|
|
10
|
-
The
|
|
20
|
+
The server limits new personal registrations to five active device
|
|
11
21
|
identities. AI apps sharing one key share one slot; cloned keys share account upload capacity.
|
|
12
22
|
Retiring a device preserves earlier data. Existing accounts above the limit are preserved but
|
|
13
23
|
cannot add another identity. Version labels and device signatures are not independent evidence
|
|
@@ -24,8 +34,8 @@ npx worktrust@latest
|
|
|
24
34
|
**The official npm package** is `worktrust`, published by the npm account **worktrustio** with
|
|
25
35
|
provenance from this repository (github.com/fhomey/worktrust-cli). Check it on npmjs.com before you run
|
|
26
36
|
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
|
-
|
|
37
|
+
individual support scripts are no longer downloaded and executed during setup. The live 0.10.25
|
|
38
|
+
release includes signed startup checks; 0.10.21 does not include this guard.
|
|
29
39
|
|
|
30
40
|
**Python tool runners:** this repository also builds `worktrust` for `uvx` and `pipx` from the
|
|
31
41
|
same measurement modules. Native wheels (0.10.13+) include a pinned official Node runtime,
|
|
@@ -381,20 +391,33 @@ a day it sealed before), but such a day reaches WorkTrust as reconstructed. It i
|
|
|
381
391
|
pairing: `connect` always mints a fresh pair, because a private key that lived on disk before the pairing would weaken
|
|
382
392
|
the proof of possession the pairing binds, for nothing your record would gain.
|
|
383
393
|
|
|
384
|
-
##
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
394
|
+
## Credential protection
|
|
395
|
+
|
|
396
|
+
Existing installations keep private file storage until the person opts in. From 0.10.26,
|
|
397
|
+
run `worktrust update`, quit the AI apps, then run `worktrust protect-key` and restart
|
|
398
|
+
those apps. A new computer can run `worktrust protect-key` before connecting. `worktrust status`
|
|
399
|
+
shows the storage mode. This command is local and does not publish or change a Passport.
|
|
400
|
+
|
|
401
|
+
Protected mode encrypts the token, pending renewal token, device private key and coupling metadata
|
|
402
|
+
with AES-256-GCM in `~/.worktrust/key.json`. Its random encryption key lives in macOS Keychain,
|
|
403
|
+
Windows Credential Manager, or Linux Secret Service (`/usr/bin/secret-tool` from libsecret-tools,
|
|
404
|
+
with a running, unlocked desktop secret service). No keychain reset is performed. First-time
|
|
405
|
+
protection may require OS approval; background reads never request an unlock prompt. An unavailable
|
|
406
|
+
vault stops uploads without advancing their checkpoints. There is no plaintext fallback.
|
|
407
|
+
|
|
408
|
+
Migration verifies the vault write before atomically replacing the old file. No plaintext backup
|
|
409
|
+
is created. Existing backups and already running processes can still hold the old secrets; this
|
|
410
|
+
is not secure erasure of an SSD or revocation of previously copied credentials. The local archive's
|
|
411
|
+
separate continuity key (`archive-key.json`) is not migrated by this command. `preserve` remains
|
|
412
|
+
offline and refuses to silently change signing identity when protected credentials are unavailable.
|
|
413
|
+
|
|
414
|
+
- **AI apps use the bridge.** The bridge and hooks read the protected credentials as the OS user;
|
|
415
|
+
their settings contain a launcher command, not the credentials. Update every installed bridge
|
|
416
|
+
first: older releases cannot read the encrypted format. Protected mode refuses `--direct`.
|
|
417
|
+
- **A device signature proves possession.** The server stores the public key and checks fresh
|
|
418
|
+
signed requests and single-use nonces. Neither file encryption nor an OS vault proves genuine
|
|
419
|
+
local activity. Software authorized as the same OS user may still obtain or use these secrets.
|
|
420
|
+
This is not a hardware-bound, non-exportable key. Revoke the connection if it may be compromised.
|
|
398
421
|
- **The key renews itself every week.** A new secret is made here, only its hash is sent, signed,
|
|
399
422
|
and last week's key stops working.
|
|
400
423
|
- `npx worktrust --direct` writes a plain key into the apps' settings instead, for an app
|
|
@@ -467,7 +490,8 @@ never as proof.
|
|
|
467
490
|
## Undo
|
|
468
491
|
|
|
469
492
|
`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
|
|
493
|
+
Antigravity's `worktrust` hook when WorkTrust set them), the credentials and installed bridge scripts.
|
|
494
|
+
Protected mode retains an encrypted empty slot and its OS wrapping key so reconnecting stays protected.
|
|
471
495
|
A small note of the previous account (masked) remains so that a later coupling by another account
|
|
472
496
|
does not offer its earlier work. Other retained files and your local evidence archive are not an
|
|
473
497
|
automatic server or archive erasure.
|
package/SECURITY.md
CHANGED
|
@@ -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 and later). 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.
|
|
@@ -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":"
|
|
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":"013885af8239da9fbd0f7fb339383f6dbcb462f439d8900c9290757f63fb597a","log-session.mjs":"87066a26e9d2d3947540b24e34139f63b25a1e4f8e13f389fa5e2d398893c368","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":"4fc0b26c65394591ef13a354c53792926c43a4c829357c6dac12570181ac0e47"},"format":"worktrust-package/1","kind":"engine","version":"0.10.27"},"signature":"5m483yf79RTRQEzPghieWXgMJv77iUwp7wmRJMf8Vxu6zvOw5nPCS1V4TPRvAjCwjwedSJ9yI1q7IpG0gZbcCA"}
|
package/history-outbox.mjs
CHANGED
|
@@ -38,7 +38,7 @@ export function queuedHistory(target,body,source) {
|
|
|
38
38
|
const scope=scopeOf(target),id=digest(scope+'\0'+source+'\0'+body);
|
|
39
39
|
const request=join(root,id+'.request.json'),ack=join(root,id+'.ack.json'),state=join(root,id+'.state.json');
|
|
40
40
|
const acknowledged=read(ack);
|
|
41
|
-
if(acknowledged?.id===id)return {status:'acknowledged',confirm(){},defer(){}};
|
|
41
|
+
if(acknowledged?.id===id)return {status:'acknowledged',confirm(){},close(){},defer(){}};
|
|
42
42
|
const current=read(state);
|
|
43
43
|
reservation(root,()=>{
|
|
44
44
|
if(!existsSync(request)) {
|
|
@@ -50,6 +50,8 @@ export function queuedHistory(target,body,source) {
|
|
|
50
50
|
});
|
|
51
51
|
const status=current?.status==='review'?'review':Number(current?.retryAt)>Date.now()?'waiting':'pending';
|
|
52
52
|
return {status,retryAt:current?.retryAt??null,
|
|
53
|
+
// close (0.10.27): WorkTrust refused the batch for good (its run closed): kept here it would wait forever, so it is let go.
|
|
54
|
+
close(){write(ack,{id,closedAt:new Date().toISOString()});if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}},
|
|
53
55
|
confirm(){write(ack,{id,confirmedAt:new Date().toISOString()});if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}},
|
|
54
56
|
defer(reason,seconds=0){if(existsSync(ack))return;write(state,{id,status:reason==='review'?'review':'retry',retryAt:Date.now()+Math.max(0,Math.min(MAX_RETRY_SECONDS,seconds))*1000});},
|
|
55
57
|
};
|
|
@@ -59,14 +61,16 @@ export function historyRefusal(text,response) {
|
|
|
59
61
|
try {rpc=JSON.parse(text.trim().startsWith('{')?text:text.split(/\r?\n/).find(s=>s.startsWith('data:'))?.slice(5));}catch{/* Unknown reply stays retryable, never acknowledged. */}
|
|
60
62
|
const review=rpc?.id===1 && (rpc?.error?.data?.outcome==='review' || String(rpc?.error?.message??'').startsWith('history replacement held for review:'));
|
|
61
63
|
const raw=Number(response.headers.get('retry-after'));
|
|
62
|
-
|
|
64
|
+
// A staged run WorkTrust closed or refused (0.10.27: another computer's key, seven days without its last batch) is final.
|
|
65
|
+
const closed=rpc?.id===1 && String(rpc?.error?.message??'').startsWith('history run refused:');
|
|
66
|
+
return {reason:review?'review':closed?'closed':response.status===429?'capacity':'unconfirmed',seconds:Number.isFinite(raw)&&raw>0?Math.min(MAX_RETRY_SECONDS,raw):0};
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
/** Explicit recovery, even after the AI client removed its source files. A changed account/key
|
|
66
70
|
* cannot replay another coupling's pending data. Review is retried only on an explicit request. */
|
|
67
|
-
export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false}) {
|
|
71
|
+
export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false, limit=Infinity}) {
|
|
68
72
|
const root=join(homedir(),'.worktrust','history-outbox'),scope=scopeOf(target);
|
|
69
|
-
const totals={received:0,review:0,waiting:0,batches:0};let paused=null;
|
|
73
|
+
const totals={received:0,review:0,waiting:0,batches:0,refused:0};let paused=null,sent=0;
|
|
70
74
|
if(!existsSync(root))return totals;
|
|
71
75
|
directory(root);
|
|
72
76
|
const files=readdirSync(root);if(files.length>12000)throw Error('HISTORY_QUEUE_FULL');
|
|
@@ -78,14 +82,16 @@ export async function resumeHistory(target, {send, confirmed, note, retryReview=
|
|
|
78
82
|
if(rpc.jsonrpc!=='2.0'||rpc.id!==1||rpc.method!=='tools/call'||rpc.params.name!=='import_history'||!Array.isArray(entries)||!entries.length||entries.length>200)throw Error('HISTORY_QUEUE_CHANGED');
|
|
79
83
|
const queued=queuedHistory(target,item.body,item.source);totals.batches++;
|
|
80
84
|
if(queued.status==='acknowledged')continue;
|
|
85
|
+
// `limit` (0.10.27): the hook sends a few a run by itself; the rest wait, untouched, for the next run.
|
|
86
|
+
if(sent>=limit){totals.waiting+=entries.length;continue;}
|
|
81
87
|
if(queued.status==='review'&&!retryReview){totals.review+=entries.length;continue;}
|
|
82
88
|
if(dry){totals.waiting+=entries.length;continue;}
|
|
83
89
|
if(queued.status==='waiting'&&!paused)paused={reason:'unconfirmed',seconds:Math.max(1,Math.ceil((queued.retryAt-Date.now())/1000))};
|
|
84
90
|
if(paused){if(queued.status==='review'){totals.review+=entries.length;continue;}queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;continue;}
|
|
85
91
|
try {
|
|
86
|
-
const response=await send(item.body,item.source),text=await response.text();
|
|
92
|
+
sent++;const response=await send(item.body,item.source),text=await response.text();
|
|
87
93
|
try{if(!response.ok)throw Error();confirmed(text,entries.length);}
|
|
88
|
-
catch{const refusal=historyRefusal(text,response);if(refusal.reason!=='review')paused={reason:refusal.reason,seconds:refusal.seconds>0?refusal.seconds:5};queued.defer(refusal.reason,paused?.seconds??refusal.seconds);totals[refusal.reason==='review'?'review':'waiting']+=entries.length;continue;}
|
|
94
|
+
catch{const refusal=historyRefusal(text,response);if(refusal.reason==='closed'){queued.close();totals.refused+=entries.length;continue;}if(refusal.reason!=='review')paused={reason:refusal.reason,seconds:refusal.seconds>0?refusal.seconds:5};queued.defer(refusal.reason,paused?.seconds??refusal.seconds);totals[refusal.reason==='review'?'review':'waiting']+=entries.length;continue;}
|
|
89
95
|
queued.confirm();totals.received+=entries.length;note(text);
|
|
90
96
|
}catch{paused={reason:'unconfirmed',seconds:5};queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;}
|
|
91
97
|
}
|
package/log-session.mjs
CHANGED
|
@@ -654,7 +654,7 @@ function batchesOf(group, byDay) {
|
|
|
654
654
|
return out;
|
|
655
655
|
}
|
|
656
656
|
/** THE RECEIPTS' COUNTS (2026-10-10): what an export send replaced, how many AI-app lines lie on its days, how many were withdrawn; summed over the batches, read for the counts alone. */
|
|
657
|
-
const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0 }; // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
|
|
657
|
+
const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, staged: 0, kept: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
|
|
658
658
|
const noteReceipt = (answer) => {
|
|
659
659
|
try {
|
|
660
660
|
const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
|
|
@@ -675,6 +675,10 @@ function confirmedReceipt(answer, expectedCount = null) {
|
|
|
675
675
|
const receipt = JSON.parse(content[0].text);
|
|
676
676
|
if (expectedCount === null) {
|
|
677
677
|
if (!(receipt.receipt === "received" && ["accepted", "flagged", "pending"].includes(receipt.status)) && !(receipt.receipt === "unchanged" && receipt.reason === "duplicate")) throw Error();
|
|
678
|
+
} else if (receipt.staged === true) {
|
|
679
|
+
// KEPT ON THE SERVER (0.10.27): a batch of a run WorkTrust holds and rebuilds itself; every line counted as kept or refused.
|
|
680
|
+
if (receipt.receipt !== "received" || receipt.received !== expectedCount || !Number.isInteger(receipt.kept) || receipt.kept < 0
|
|
681
|
+
|| !Number.isInteger(receipt.refused) || receipt.refused < 0 || receipt.kept + receipt.refused > expectedCount) throw Error();
|
|
678
682
|
} else if (receipt.receipt !== "received" || receipt.received !== expectedCount || receipt.refused !== 0
|
|
679
683
|
|| !Number.isInteger(receipt.new) || receipt.new < 0 || !Number.isInteger(receipt.alreadyHeld) || receipt.alreadyHeld < 0
|
|
680
684
|
|| receipt.new + receipt.alreadyHeld !== expectedCount) throw Error();
|
|
@@ -699,29 +703,43 @@ function retainMeasurement(payload, source) {
|
|
|
699
703
|
}
|
|
700
704
|
} finally { closeSync(fd); unlinkSync(temporary); }
|
|
701
705
|
}
|
|
702
|
-
const HISTORY_DELIVERY = { review: 0, waiting: 0 };
|
|
706
|
+
const HISTORY_DELIVERY = { review: 0, waiting: 0, refused: 0 };
|
|
707
|
+
/**
|
|
708
|
+
* ONE RUN PER COUPLING (0.10.27; owner, 2026-10-21: re-measured history is kept on the server). The batches of a re-measure
|
|
709
|
+
* to one key are one run: an id, each batch's number and the run's count ride in every batch, and WorkTrust keeps each batch
|
|
710
|
+
* it receives and rebuilds the run's days itself, every AI app of the run together, once all of them have arrived. The id is
|
|
711
|
+
* a digest of the UTC day and the run's batches, never of a key: the same plan sent again the same day is the same run, so a
|
|
712
|
+
* batch already received is neither uploaded nor kept twice. Never an export, a copied folder or the hook's late days.
|
|
713
|
+
*/
|
|
714
|
+
const historyRunId = (bodies) => {
|
|
715
|
+
const h = createHash("sha256").update(`worktrust-history-run|${new Date().toISOString().slice(0, 10)}|${bodies.join("\n")}`).digest("hex");
|
|
716
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${(8 | (parseInt(h[16], 16) & 3)).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
717
|
+
};
|
|
703
718
|
async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
|
|
704
719
|
let accepted = 0;
|
|
705
720
|
const { queuedHistory, historyRefusal } = await import("./history-outbox.mjs");
|
|
706
721
|
// Keep each source and its approved coupling separate.
|
|
707
722
|
const groups = [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS, ...EXPORT_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])];
|
|
708
|
-
|
|
723
|
+
// Imported entries carry no live commit/session join.
|
|
724
|
+
const encodeBatch = (batch, run = null) => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map(({commits, ...rest}) => { void commits; return rest; }), ...(run ? { run } : {}) } } });
|
|
725
|
+
const plan = groups.flatMap(([source, group]) => { const target = source === "codex" ? codexDoor ?? door : door; return group.length > 0 && target ? batchesOf(group, byDay).map((batch) => ({ source, target, batch, run: null })) : []; });
|
|
726
|
+
if (rebuild && !byDay) for (const token of new Set(plan.map((item) => item.target.token))) {
|
|
727
|
+
const run = plan.filter((item) => item.target.token === token), id = historyRunId(run.map((item) => encodeBatch(item.batch)));
|
|
728
|
+
run.forEach((item, index) => { item.run = { id, index, count: run.length }; });
|
|
729
|
+
}
|
|
730
|
+
for (const item of plan) item.body = encodeBatch(item.batch, item.run);
|
|
709
731
|
// Persist the approved plan before sending, so later batches survive removed source files too.
|
|
710
|
-
try { for (const
|
|
732
|
+
try { for (const item of plan) queuedHistory(item.target, item.body, item.source); }
|
|
711
733
|
catch { console.error("History queue is full, busy or unavailable. Resume the saved batches before retrying this import; nothing was marked complete."); HISTORY_DELIVERY.waiting += entries.length; return 0; }
|
|
712
|
-
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
for (const batch of batchesOf(group, byDay)) {
|
|
717
|
-
number += 1;
|
|
718
|
-
// Imported entries carry no live commit/session join.
|
|
719
|
-
const body = encodeBatch(batch);
|
|
734
|
+
const numbers = new Map(), stopped = new Set();
|
|
735
|
+
for (const { source, target, batch, body } of plan) {
|
|
736
|
+
if (stopped.has(source)) continue;
|
|
737
|
+
const number = (numbers.get(source) ?? 0) + 1; numbers.set(source, number);
|
|
720
738
|
for (const entry of batch) retainMeasurement(entry, source);
|
|
721
739
|
// `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
|
|
722
740
|
let queued;
|
|
723
741
|
try { queued = queuedHistory(target, body, source); }
|
|
724
|
-
catch { console.error("Pending history could not be stored safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); HISTORY_DELIVERY.waiting += batch.length;
|
|
742
|
+
catch { console.error("Pending history could not be stored safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue; }
|
|
725
743
|
if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; continue; }
|
|
726
744
|
if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
|
|
727
745
|
if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
|
|
@@ -730,18 +748,36 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
|
|
|
730
748
|
const text = await response.text();
|
|
731
749
|
try { if (!response.ok) throw Error(); confirmedReceipt(text, batch.length); }
|
|
732
750
|
catch {
|
|
733
|
-
const refusal = historyRefusal(text, response);
|
|
751
|
+
const refusal = historyRefusal(text, response);
|
|
752
|
+
// A run WorkTrust closed (seven days without its last batch, another computer's key) is final: kept here it would wait forever.
|
|
753
|
+
if (refusal.reason === "closed") { queued.close(); HISTORY_DELIVERY.refused += batch.length; continue; }
|
|
754
|
+
queued.defer(refusal.reason, refusal.seconds);
|
|
734
755
|
if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
|
|
735
|
-
HISTORY_DELIVERY.waiting += batch.length;
|
|
756
|
+
HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue;
|
|
736
757
|
}
|
|
737
758
|
queued.confirm(); accepted += batch.length; noteReceipt(text);
|
|
738
759
|
if (announce) console.log(`batch ${number}: received ${batch.length}`);
|
|
739
|
-
} catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length;
|
|
740
|
-
}
|
|
760
|
+
} catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); }
|
|
741
761
|
}
|
|
742
762
|
return accepted;
|
|
743
763
|
}
|
|
744
764
|
|
|
765
|
+
/** The outbox's batches for one coupling, sent as `--resume` and the hook send them: signed, named, bounded in time. */
|
|
766
|
+
const sendQueued = (target, ms = 65_000) => (body, source) => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(ms) });
|
|
767
|
+
/**
|
|
768
|
+
* PENDING HISTORY GOES BY ITSELF (0.10.27; owner, 2026-10-21). A batch the server did not receive (no network, a closed lid,
|
|
769
|
+
* the upload limit) stays in ~/.worktrust/history-outbox and is sent again by the next hook run, a few at a time, without a
|
|
770
|
+
* question: the person said yes when the run was planned, and once WorkTrust has the batch nothing waits here. A batch held
|
|
771
|
+
* for review is never resent this way (`--retry-review` is the person's own).
|
|
772
|
+
*/
|
|
773
|
+
async function resendPending(limit) {
|
|
774
|
+
try {
|
|
775
|
+
const { resumeHistory } = await import("./history-outbox.mjs");
|
|
776
|
+
for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean))
|
|
777
|
+
await resumeHistory(target, { limit, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target, 20_000) });
|
|
778
|
+
} catch (error) { if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: ${error.message}`); }
|
|
779
|
+
}
|
|
780
|
+
|
|
745
781
|
/** Whether the door's import_history takes `from_archive` (0.8.0): asked with tools/list, never assumed. */
|
|
746
782
|
async function doorKnowsArchive(target) {
|
|
747
783
|
if (!target) return false;
|
|
@@ -1148,12 +1184,10 @@ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled
|
|
|
1148
1184
|
*/
|
|
1149
1185
|
if (flag("history") && flag("resume")) {
|
|
1150
1186
|
const { resumeHistory } = await import("./history-outbox.mjs");
|
|
1151
|
-
const totals = { received: 0, review: 0, waiting: 0, batches: 0 };
|
|
1187
|
+
const totals = { received: 0, review: 0, waiting: 0, batches: 0, refused: 0 };
|
|
1152
1188
|
try {
|
|
1153
1189
|
for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean)) {
|
|
1154
|
-
const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt,
|
|
1155
|
-
send: (body, source) => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(65_000) }),
|
|
1156
|
-
});
|
|
1190
|
+
const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
|
|
1157
1191
|
for (const key of Object.keys(totals)) totals[key] += result[key];
|
|
1158
1192
|
}
|
|
1159
1193
|
console.log(JSON.stringify({ resumed: totals.received, ...totals, ...RECEIPTS }));
|
|
@@ -1291,6 +1325,9 @@ if (!DRY && late.length > 0) {
|
|
|
1291
1325
|
if (filed < late.length) for (const [id, mark] of heldBack) { if (mark) state[id] = mark; else delete state[id]; }
|
|
1292
1326
|
}
|
|
1293
1327
|
if (!DRY && (sent > 0 || filed > 0)) writeState(state);
|
|
1328
|
+
// What an earlier history run left on this computer because the server never received it: a few batches a run, by itself; not in a
|
|
1329
|
+
// run that just sent late days itself (a batch it just tried waits for the next run, as it always did).
|
|
1330
|
+
if (!DRY && late.length === 0) await resendPending(4);
|
|
1294
1331
|
|
|
1295
1332
|
// The counter, at most once a day, detached: reading every transcript takes longer than a hook
|
|
1296
1333
|
// may hold a session's exit, and its result waits for a click either way. `--stage` and never
|
package/package-release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"
|
|
1
|
+
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"cc8a27fbabea83b0fb1beabf5ecb88b22bd3b119f277962dbf5a2d8ceb0bdbcd","SECURITY.md":"b0cf3c839c918f3a403ae33e857c947fe62cbbad96bee6cac748bb42924839fc","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","engine-release.json":"ba2a3976481100d2dd8e35c95e7ecbc8aa61c58d50a3bd1b1262971e0b42b459","history-outbox.mjs":"013885af8239da9fbd0f7fb339383f6dbcb462f439d8900c9290757f63fb597a","log-session.mjs":"87066a26e9d2d3947540b24e34139f63b25a1e4f8e13f389fa5e2d398893c368","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"38a2d376319d548668011efd51db7a43255923b33a742f6963262f3361832f00","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":"4fc0b26c65394591ef13a354c53792926c43a4c829357c6dac12570181ac0e47"},"format":"worktrust-package/1","kind":"npm","version":"0.10.27"},"signature":"P02S_9sBSMsXrW4AmS7ioWEj0ujkHw5HVxQUBAe-lT13zLTfxhp3xVcbjl1G98VextHoGPILd2cUNzDkm3E4CQ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "worktrust",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.27",
|
|
4
4
|
"description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,10 @@
|
|
|
34
34
|
"worktrust-launch.mjs",
|
|
35
35
|
"engine-release.json",
|
|
36
36
|
"package-release.json",
|
|
37
|
-
"history-outbox.mjs"
|
|
37
|
+
"history-outbox.mjs",
|
|
38
|
+
"credential-store.mjs",
|
|
39
|
+
"credential-vault.mjs",
|
|
40
|
+
"credential-vault-scripts.mjs"
|
|
38
41
|
],
|
|
39
42
|
"engines": {
|
|
40
43
|
"node": ">=18"
|
package/preserve.mjs
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* (`prev`, `hash`), appended and never rewritten; each day has proofs/<day>.json, its root, signed with the device key
|
|
24
24
|
* (~/.worktrust/key.json) when there is one. Today waits for the next run. Nothing leaves this computer.
|
|
25
25
|
*/
|
|
26
|
+
import { readDeviceSigningKey } from "./credential-store.mjs";
|
|
26
27
|
import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs";
|
|
27
28
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
28
29
|
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from "node:crypto";
|
|
@@ -190,13 +191,12 @@ function archiveSalt() {
|
|
|
190
191
|
try { const made = randomBytes(32).toString("hex"); createPrivateFile(file, `${made}\n`); return made; } catch { try { return readPrivateFile(file)?.trim() ?? null; } catch { return null; } }
|
|
191
192
|
}
|
|
192
193
|
/** The device key, when this computer is coupled: its private half signs, its public half goes into the proof. */
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "device" };
|
|
198
|
-
} catch { return null; }
|
|
194
|
+
let cachedDeviceKey;
|
|
195
|
+
function deviceKey(required = false) {
|
|
196
|
+
try { if (cachedDeviceKey === undefined) cachedDeviceKey = readDeviceSigningKey(home(".worktrust", "key.json")); return cachedDeviceKey; }
|
|
197
|
+
catch (error) { if (required) throw error; return null; }
|
|
199
198
|
}
|
|
199
|
+
|
|
200
200
|
/**
|
|
201
201
|
* THE LOCAL ARCHIVE KEY (owner, 2026-10-10): a computer that is not coupled still signs its archive, with an Ed25519 key made
|
|
202
202
|
* here (~/.worktrust/archive-key.json, mode 600, folder 700), so a day's root can be told from an edit and the chain stays one
|
|
@@ -308,6 +308,9 @@ function archive(dir) {
|
|
|
308
308
|
fresh.push(line);
|
|
309
309
|
}
|
|
310
310
|
fresh.sort((a, b) => a.started_at.localeCompare(b.started_at) || a.client.localeCompare(b.client) || a.stretch_ref.localeCompare(b.stretch_ref));
|
|
311
|
+
let key;
|
|
312
|
+
try { key = deviceKey(true) ?? archiveKey(true); }
|
|
313
|
+
catch { say(" Signing key unavailable. Unlock your OS vault and retry. No archive data was changed."); process.exitCode = 1; return; }
|
|
311
314
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
312
315
|
let prev = existing.lines.at(-1)?.hash ?? null, seq = existing.lines.length;
|
|
313
316
|
const all = [...existing.lines];
|
|
@@ -322,9 +325,7 @@ function archive(dir) {
|
|
|
322
325
|
// A day that gained lines gets its root again over all of its lines; the lines themselves are never rewritten.
|
|
323
326
|
// THIS KEY SIGNS ONLY ITS OWN LINES (0.6.18, audit S7): a day is signed when every earlier line of it was already under
|
|
324
327
|
// this key's signature (or there were none); a day that came into the folder from elsewhere keeps an unsigned root.
|
|
325
|
-
//
|
|
326
|
-
// there is none. A day or a manifest either of this computer's keys sealed is this computer's to seal again.
|
|
327
|
-
const key = deviceKey() ?? archiveKey(true);
|
|
328
|
+
// Either of this computer's keys may reseal its own days; the signer was resolved before mutation.
|
|
328
329
|
const mineX = new Set(ownKeys().map((own) => own.publicX));
|
|
329
330
|
const ours = (document) => !document || (key && typeof document.signature === "string" && mineX.has(document.public_key));
|
|
330
331
|
mkdirSync(join(dir, "proofs"), { recursive: true });
|
package/worktrust.mjs
CHANGED
|
@@ -39,15 +39,12 @@
|
|
|
39
39
|
* with its secret, can exchange for the key. Nothing is typed, and a link forwarded to someone else
|
|
40
40
|
* approves nothing they can collect. Without a browser (`--device`, or over SSH) the terminal shows
|
|
41
41
|
* a code that you type yourself at app.worktrust.io/connect/computer.
|
|
42
|
-
* WHERE THE KEY LIVES.
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* WorkTrust, the private half stays in the key file. Every call the bridge, the hook and
|
|
49
|
-
* the counter make carries a fresh signature (`WorkTrust-Proof`), and WorkTrust refuses a call
|
|
50
|
-
* through this key without one: a copied key alone is worth nothing.
|
|
42
|
+
* WHERE THE KEY LIVES. A private local file until the person runs protect-key; then an encrypted
|
|
43
|
+
* envelope in that file, with its wrapping key in the OS vault. AI apps run the bridge and never
|
|
44
|
+
* receive these credentials in their settings. Protected mode refuses --direct.
|
|
45
|
+
* SIGNATURES PROVE POSSESSION. connect makes an Ed25519 pair and registers the public half.
|
|
46
|
+
* Requests carry fresh signatures and single-use nonces. Software authorized as the same OS user
|
|
47
|
+
* may still use the private key; neither file encryption nor signatures prove truthful activity.
|
|
51
48
|
*
|
|
52
49
|
* THE KEY RENEWS ITSELF EVERY WEEK. The bridge or the hook makes a new secret on this computer, sends
|
|
53
50
|
* only its hash, signed with the current key, and stores the new one; a copy of last week's key stops
|
|
@@ -78,12 +75,12 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
|
|
|
78
75
|
const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
|
|
79
76
|
const has = (name) => args.includes(`--${name}`);
|
|
80
77
|
/** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
|
|
81
|
-
const CLI_VERSION = "0.10.
|
|
78
|
+
const CLI_VERSION = "0.10.27";
|
|
82
79
|
const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
|
|
83
80
|
const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
|
|
84
81
|
const HOME_DIR = join(homedir(), ".worktrust");
|
|
85
82
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
86
|
-
const SCRIPTS = ["history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs"];
|
|
83
|
+
const SCRIPTS = ["credential-store.mjs", "credential-vault.mjs", "credential-vault-scripts.mjs", "history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs"];
|
|
87
84
|
/** The modules the scripts import by name from beside them; a download keeps that name. */
|
|
88
85
|
const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs"]);
|
|
89
86
|
const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
|
|
@@ -274,7 +271,7 @@ const KEY_FILE = join(HOME_DIR, "key.json");
|
|
|
274
271
|
const STABLE_FILE = join(HOME_DIR, "worktrust.mjs");
|
|
275
272
|
let STABLE = join(HERE, "worktrust-launch.mjs"), runtimePrepared = false, NODE_ARGS = [];
|
|
276
273
|
const RENEW_EVERY_MS = 7 * 24 * 3600_000;
|
|
277
|
-
const KEY_PLACE = "~/.worktrust/key.json (
|
|
274
|
+
const KEY_PLACE = "~/.worktrust/key.json (storage protection is shown by worktrust status)";
|
|
278
275
|
const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 }); try { chmodSync(HOME_DIR, 0o700); } catch { /* Windows */ } };
|
|
279
276
|
|
|
280
277
|
/** A tool-runner cache is disposable. Install the whole verified runtime/engine before changing wiring. */
|
|
@@ -303,29 +300,22 @@ function saveStableEntry() {
|
|
|
303
300
|
finally { try { rmSync(temporary); } catch { /* already renamed */ } }
|
|
304
301
|
}
|
|
305
302
|
|
|
306
|
-
/**
|
|
307
|
-
*
|
|
308
|
-
* private key and when it was last renewed. NO KEYCHAIN (owner, 2026-10-03): a keychain tool can ask
|
|
309
|
-
* the person to "reset" a keychain it cannot find, which deletes every password on the machine, and
|
|
310
|
-
* many will not let a tool near their keychain at all. This file is never written into an AI app's
|
|
311
|
-
* settings: the apps run the bridge, which reads it.
|
|
303
|
+
/** Existing file credentials remain readable until the person explicitly protects them.
|
|
304
|
+
* The OS wrapping key is never written into an AI app or the encrypted credential file.
|
|
312
305
|
*/
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
},
|
|
327
|
-
erase() { try { rmSync(KEY_FILE); } catch { /* gone */ } },
|
|
328
|
-
};
|
|
306
|
+
const { createCredentialStore } = await import("./credential-store.mjs").catch(() => ({}));
|
|
307
|
+
const keyStore = createCredentialStore?.(KEY_FILE);
|
|
308
|
+
async function protectKey() {
|
|
309
|
+
say(" Protect the WorkTrust token and signing key with this OS account's credential vault.");
|
|
310
|
+
say(" Quit AI apps first; restart them after this finishes. Older bridges cannot read protected credentials.");
|
|
311
|
+
say(" This protects stored secrets. It does not prove that local activity is genuine.");
|
|
312
|
+
if (has("dry-run")) { say(" Dry run: no vault or credential was changed."); return; }
|
|
313
|
+
if (keyStore.load() && stableVersion() !== CLI_VERSION) fail("Run worktrust update from this release first, then quit your AI apps and run worktrust protect-key.");
|
|
314
|
+
if (!(await ask("Protect the local credentials?"))) return;
|
|
315
|
+
try { keyStore.protect(); }
|
|
316
|
+
catch { fail("OS credential storage was unavailable or the credential file could not be safely replaced. Existing credentials were preserved. Unlock your OS vault, check worktrust status, and retry. No keychain reset is needed."); }
|
|
317
|
+
say(" Credentials are protected by the OS vault. Restart your AI apps. No account data or Passport was changed.");
|
|
318
|
+
}
|
|
329
319
|
|
|
330
320
|
/**
|
|
331
321
|
* WHICH ACCOUNT THIS COMPUTER LAST FED, after `disconnect` (owner, 2026-10-04). The key file goes; this
|
|
@@ -487,6 +477,9 @@ async function bridge() {
|
|
|
487
477
|
let message;
|
|
488
478
|
try { message = JSON.parse(line); } catch { continue; }
|
|
489
479
|
if (message.method === "initialize" && message.params?.clientInfo?.name) agent = `${message.params.clientInfo.name}/${message.params.clientInfo.version ?? "0"} (worktrust-bridge) worktrust-cli/${CLI_VERSION}`;
|
|
480
|
+
// A long-lived bridge must not keep using a cached key after local disconnect or vault lock.
|
|
481
|
+
try { key = await freshKey(); }
|
|
482
|
+
catch { key = null; if (message.id !== undefined) answer(message.id, "WorkTrust credential storage is unavailable. Unlock your OS vault and retry; no request was sent."); continue; }
|
|
490
483
|
if (!key) { if (message.id !== undefined) answer(message.id, "WorkTrust is not connected on this computer: run `npx worktrust connect`."); continue; }
|
|
491
484
|
try {
|
|
492
485
|
const response = await fetch(key.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${key.token}`, "user-agent": agent, ...(session ? { "mcp-session-id": session } : {}), ...proof(key.device, key.url, line) }, body: line });
|
|
@@ -602,6 +595,7 @@ async function update() {
|
|
|
602
595
|
}
|
|
603
596
|
|
|
604
597
|
async function connect() {
|
|
598
|
+
if (has("direct") && keyStore.protected()) fail("Protected credentials use the local bridge; --direct would expose them in app settings.");
|
|
605
599
|
const host = (flag("name") ?? hostname()).replace(/\.local$/i, "").slice(0, 64);
|
|
606
600
|
say();
|
|
607
601
|
say(` WorkTrust · connect ${host} (${OS_NAME})`);
|
|
@@ -718,8 +712,12 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
718
712
|
: n(did.new) === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
|
|
719
713
|
: `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
|
|
720
714
|
if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
|
|
721
|
-
|
|
722
|
-
if (
|
|
715
|
+
// KEPT ON THE SERVER (0.10.27; owner, 2026-10-21): what did not arrive stays here and goes again by itself; nothing to resume by hand.
|
|
716
|
+
if (Number(did?.delivery?.waiting) > 0) say(" Some batches did not reach WorkTrust yet. They stay on this computer and are sent again by themselves the next time npx worktrust or your AI app's hook runs.");
|
|
717
|
+
if (Number(did?.delivery?.refused) > 0) say(` WorkTrust closed an earlier run of ${did.delivery.refused} lines (it missed a batch for seven days): run npx worktrust@latest history again to send them as a new run.`);
|
|
718
|
+
// A STAGED RUN (0.10.27): WorkTrust holds every batch and rebuilds the days itself once the run is whole; the receipts say what it kept.
|
|
719
|
+
if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(` ✓ Re-measured. WorkTrust holds all ${n(did.staged)} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
|
|
720
|
+
else if (rebuild && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
|
|
723
721
|
else if (!rebuild) say(sent.code === 0 ? " ✓ Sent as history. Activity is recorded with its origin; independent verification and passport publication are separate. A day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
|
|
724
722
|
if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
|
|
725
723
|
}
|
|
@@ -766,6 +764,7 @@ const historyComplete = () => { try { const state = JSON.parse(readFileSync(HIST
|
|
|
766
764
|
async function again() {
|
|
767
765
|
const before = stableVersion();
|
|
768
766
|
if (before && before !== CLI_VERSION) { await update(); return; }
|
|
767
|
+
{ const key = await freshKey(); if (key) await resendHistory(key); }
|
|
769
768
|
if (!historyComplete()) {
|
|
770
769
|
const key = await freshKey();
|
|
771
770
|
if (key) { say(); say(` Your earlier sessions are not yet measured by worktrust ${CLI_VERSION} in WorkTrust, or did not all arrive. This finishes them.`); await offerHistory(await scripts(), key.token, key.device ?? null, key.url, true); }
|
|
@@ -778,6 +777,19 @@ async function again() {
|
|
|
778
777
|
say(" This computer is coupled. `npx worktrust connect` couples it again; `npx worktrust disconnect` takes it out.");
|
|
779
778
|
}
|
|
780
779
|
|
|
780
|
+
/**
|
|
781
|
+
* PENDING HISTORY GOES BY ITSELF (0.10.27; owner, 2026-10-21): batches an earlier history run planned and the server never
|
|
782
|
+
* received (no network, a closed lid, the upload limit) are sent again here, without a question: the person said yes when the
|
|
783
|
+
* run was planned. Held-for-review batches stay held. Quiet when nothing was pending.
|
|
784
|
+
*/
|
|
785
|
+
async function resendHistory(key) {
|
|
786
|
+
const paths = await scripts(), sent = await run(paths["log-session.mjs"], ["--history", "--resume"], key.token, true, { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) });
|
|
787
|
+
let did = null;
|
|
788
|
+
try { did = JSON.parse(sent.out.trim().split("\n").reverse().find((line) => line.startsWith('{"resumed"')) ?? "null"); } catch { /* nothing pending, or an older hook */ }
|
|
789
|
+
if (Number(did?.resumed) > 0) { say(); say(` ✓ ${did.resumed} lines of earlier history that had not reached WorkTrust were sent; WorkTrust keeps them and rebuilds the days itself.`); }
|
|
790
|
+
if (Number(did?.waiting) > 0) say(" Some earlier history is still on this computer; it is sent again by itself the next time npx worktrust or your AI app's hook runs.");
|
|
791
|
+
}
|
|
792
|
+
|
|
781
793
|
async function history() {
|
|
782
794
|
const key = await freshKey();
|
|
783
795
|
if (!key) fail("this computer is not coupled through the key file. Run npx worktrust first.");
|
|
@@ -1032,7 +1044,7 @@ async function disconnect() {
|
|
|
1032
1044
|
const plan = await run(paths["setup-mcp.mjs"], ["--remove"], PLACEHOLDER, true);
|
|
1033
1045
|
say(" 1. The WorkTrust door comes out of every AI app here:");
|
|
1034
1046
|
for (const line of planLines(plan.out)) say(line);
|
|
1035
|
-
say(" 2. The session hook comes out of ~/.claude/settings.json (and Codex's notify line and Antigravity's worktrust hook, when WorkTrust set them),
|
|
1047
|
+
say(" 2. The session hook comes out of ~/.claude/settings.json (and Codex's notify line and Antigravity's worktrust hook, when WorkTrust set them), credentials are removed (an encrypted empty slot keeps the OS-vault preference)");
|
|
1036
1048
|
say(" but for one note of which account this computer fed (masked), so a later coupling by another account starts clean.");
|
|
1037
1049
|
say(" 3. The key itself stays valid until you revoke it: WorkTrust → Sources → Devices → this computer → Revoke.");
|
|
1038
1050
|
say();
|
|
@@ -1104,6 +1116,7 @@ async function status() {
|
|
|
1104
1116
|
const door = Object.entries(servers).find(([name, server]) => /worktrust/i.test(`${name} ${server?.url ?? ""} ${(server?.args ?? []).join(" ")}`));
|
|
1105
1117
|
say(door ? ` Claude Code: coupled (${door[1].url ?? "through the local bridge"})` : " Claude Code: not coupled. Run `npx worktrust connect`.");
|
|
1106
1118
|
const key = keyStore.load();
|
|
1119
|
+
say(` Credential storage: ${keyStore.protected() ? "OS vault + encrypted local file" : "private local file; use worktrust protect-key after updating"}`);
|
|
1107
1120
|
say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
|
|
1108
1121
|
if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
|
|
1109
1122
|
let hook = false;
|
|
@@ -1188,6 +1201,7 @@ function help() {
|
|
|
1188
1201
|
say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
|
|
1189
1202
|
say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
|
|
1190
1203
|
say(" worktrust status what is coupled here");
|
|
1204
|
+
say(" worktrust protect-key after update: move credential protection into the OS vault (asks first)");
|
|
1191
1205
|
say(" worktrust orchestration report --file recording.jsonl inspect local agent metadata; sends nothing");
|
|
1192
1206
|
say(" worktrust mod the WorkTrust mod for Claude Code: what it counts, and whether it is on");
|
|
1193
1207
|
say(" install turn it on: counts permission answers, effort levels, context peaks and subagents (asks first)");
|
|
@@ -1206,10 +1220,10 @@ function help() {
|
|
|
1206
1220
|
// before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
|
|
1207
1221
|
// itself and stay as they are; `status` only reads.
|
|
1208
1222
|
async function main() {
|
|
1209
|
-
if (!moduleArgs || !moduleExecutable) fail("Use the complete WorkTrust package from npm/PyPI or the signed preservation kit; individual scripts cannot run.");
|
|
1223
|
+
if (!moduleArgs || !moduleExecutable || !createCredentialStore) fail("Use the complete WorkTrust package from npm/PyPI or the signed preservation kit; individual scripts cannot run.");
|
|
1210
1224
|
if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
|
|
1211
1225
|
const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
|
|
1212
|
-
const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod"]);
|
|
1226
|
+
const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod", "protect-key"]);
|
|
1213
1227
|
const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
|
|
1214
1228
|
if (agentShell && PERSON_ONLY.has(command)) {
|
|
1215
1229
|
say();
|
|
@@ -1243,7 +1257,7 @@ if (await relayToNewest()) return;
|
|
|
1243
1257
|
|
|
1244
1258
|
if (!["version", "help", "preserve"].includes(command)) {
|
|
1245
1259
|
try { keyStore.load(); }
|
|
1246
|
-
catch { fail("The local WorkTrust key file is unsafe or damaged. Upload stopped.
|
|
1260
|
+
catch { fail("The local WorkTrust key file is unsafe or damaged, or the OS vault is locked or unavailable. Upload stopped. Unlock your OS vault and retry. Do not delete the key file or reset the keychain."); }
|
|
1247
1261
|
}
|
|
1248
1262
|
if (command === "version") say(CLI_VERSION);
|
|
1249
1263
|
else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
|
|
@@ -1251,6 +1265,7 @@ else if (command === "mcp") await bridge();
|
|
|
1251
1265
|
else if (command === "hook") await hook();
|
|
1252
1266
|
else if (command === "connect") await connect();
|
|
1253
1267
|
else if (command === "update") await update();
|
|
1268
|
+
else if (command === "protect-key") await protectKey();
|
|
1254
1269
|
else if (command === "history") await history();
|
|
1255
1270
|
// NOT FROM THE TERMINAL (owner, 2026-10-04): an ACCOUNT is connected under Sources in the app, where the
|
|
1256
1271
|
// page also says what is already connected: Claude and ChatGPT on the web and their earlier
|