@tokenoftrust/cli 7.3.0 → 7.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/bin/tot.mjs +9 -0
- package/package.json +1 -1
- package/src/agent-credential.mjs +229 -0
- package/src/agent-session.mjs +447 -0
- package/src/commands/agent-session.mjs +163 -0
- package/src/commands/ship.mjs +13 -1
package/README.md
CHANGED
|
@@ -101,6 +101,17 @@ tot login
|
|
|
101
101
|
|
|
102
102
|
A clean short profile name is included in the credential filename; other labels are hashed. Every profile holds independent sessions per MCP authority. `tot whoami` shows the active profile and authority.
|
|
103
103
|
|
|
104
|
+
### Sponsored agents (`tot agent-session`)
|
|
105
|
+
|
|
106
|
+
An automated agent signs in as **itself**, under a sponsor's agent-sponsorship grant — never with a human's `tot login`:
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
tot agent-session <tenant> --grant <grantId> [--out <file>] [--tier qa|production]
|
|
110
|
+
tot agent-session <tenant> --revoke [--out <file>]
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
It exchanges the agent's machine credential plus the grant at tot-mcp (RFC 8693), opens a storefront session on `<tenant>`, and writes a chmod-600 Playwright storageState (default `~/.tot/agent-sessions/<tenant>.json`). What the agent may see is decided server-side from the grant. The machine credential is read only from the keychain (service `tot-agent-credential`, account = the tier's MCP origin) or a hidden terminal prompt — never a flag, an environment variable, or the human login cache. `--tier` defaults to `qa`. `--revoke` ends the server session and deletes that file.
|
|
114
|
+
|
|
104
115
|
## Design notes
|
|
105
116
|
|
|
106
117
|
Dependency-free by design (global `fetch` + `git` + the system `tar`), so `npm i -g @tokenoftrust/cli` stays light. `tot dev` is the only command that pulls in the storefront runner: for a standalone checkout it downloads the moat-free runner once per version — from the public npm package `@tokenoftrust/storefront-runner`, after the entitlement-gated `dev_renderer_artifact` answers `use_npm` (its artifact store is not kept in step with npm) — to `~/.tot/cache/renderer/`, `pnpm install`s it there (via corepack — no separate pnpm install needed), and reuses that cache on every later run. See `src/` for the small modules: `context.mjs` (detection), `mcp.mjs` (transport), `auth.mjs` (the identity seam), `commands/`.
|
package/bin/tot.mjs
CHANGED
|
@@ -53,6 +53,7 @@ const COMMANDS = [
|
|
|
53
53
|
{ invocation: "whoami", blurb: "show who you're signed in as" },
|
|
54
54
|
{ invocation: "link", blurb: "link your identity so your stores resolve" },
|
|
55
55
|
{ invocation: "grants", blurb: "capability/tier/expiry per store you can act on" },
|
|
56
|
+
{ invocation: "agent-session <tenant> --grant <id>", blurb: "a sponsored agent's own storefront session (chmod-600 storageState; --revoke ends it)" },
|
|
56
57
|
{ invocation: "clone [<tenant>]", blurb: "clone a store you can build on" },
|
|
57
58
|
{ invocation: "clone agency-kit [dir]", blurb: "clone the Agency Kit, read-only (needs agency access from Token of Trust)" },
|
|
58
59
|
{ invocation: "validate", blurb: "lint your store before you submit" },
|
|
@@ -396,6 +397,14 @@ function safeSubcommand(cmd, rest) {
|
|
|
396
397
|
|
|
397
398
|
async function main() {
|
|
398
399
|
const [cmd, ...rest] = process.argv.slice(2);
|
|
400
|
+
// A sponsored agent's session runs OUTSIDE the wrapper below: that wrapper reads the human
|
|
401
|
+
// `tot login` cache (activity bridge, actor, trace id, mailbox line), resolves the MCP
|
|
402
|
+
// authority from git, and spawns the update-check worker. This command must touch none of
|
|
403
|
+
// the human's credentials and selects its endpoints by --tier alone.
|
|
404
|
+
if (cmd === "agent-session") {
|
|
405
|
+
const { run } = await import("../src/commands/agent-session.mjs");
|
|
406
|
+
return run(rest);
|
|
407
|
+
}
|
|
399
408
|
const ctx = detectContext();
|
|
400
409
|
const mcpIndex = rest.indexOf("--mcp");
|
|
401
410
|
const mcpUrl = mcpIndex < 0 ? undefined : rest[mcpIndex + 1];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/cli",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.4.0",
|
|
4
4
|
"description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Token of Trust",
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sponsored agent's OWN machine credential, and the private_key_jwt assertion it signs.
|
|
3
|
+
*
|
|
4
|
+
* The credential is a registered tot-mcp machine client: `{ clientId, kid, privateKeyPem }`,
|
|
5
|
+
* stored as one line of compact JSON. It is read from exactly two places:
|
|
6
|
+
*
|
|
7
|
+
* 1. the OS keychain item `tot-agent-credential`, account = the MCP origin it is registered at
|
|
8
|
+
* (macOS `security`, Linux `secret-tool`), or
|
|
9
|
+
* 2. an interactive, no-echo terminal prompt.
|
|
10
|
+
*
|
|
11
|
+
* Never from argv, never from an environment variable, never from a file path, and never
|
|
12
|
+
* from the operator's human `tot login` cache: this module takes no `env` and imports nothing
|
|
13
|
+
* from token-store.mjs, so there is nothing to fall back to. A missing credential is a named
|
|
14
|
+
* error, not a reason to try another source.
|
|
15
|
+
*
|
|
16
|
+
* The keychain read is the one place this command spawns a process: a FIXED absolute binary
|
|
17
|
+
* with a FIXED argument vector (the account is a code-owned MCP origin, never user input),
|
|
18
|
+
* no shell, stdout captured and never echoed. To store the credential without putting it on a
|
|
19
|
+
* command line, let the keychain prompt for it:
|
|
20
|
+
*
|
|
21
|
+
* security add-generic-password -U -s tot-agent-credential -a https://mcp.qa.tokenoftrust.com -w
|
|
22
|
+
* secret-tool store --label "tot agent credential" service tot-agent-credential account https://mcp.qa.tokenoftrust.com
|
|
23
|
+
*/
|
|
24
|
+
import { execFile } from "node:child_process";
|
|
25
|
+
import { createPrivateKey, createSign, randomUUID } from "node:crypto";
|
|
26
|
+
|
|
27
|
+
export const KEYCHAIN_SERVICE = "tot-agent-credential";
|
|
28
|
+
|
|
29
|
+
/** Matches tot-mcp's act.sub grammar (agent-session-policy.ts AGENT_ID). */
|
|
30
|
+
const CLIENT_ID_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
31
|
+
const KID_RE = /^[\x21-\x7e]{1,256}$/;
|
|
32
|
+
/** RFC 7523 assertions are short-lived; tot-mcp refuses one valid for more than 60s. */
|
|
33
|
+
const ASSERTION_LIFETIME_SECONDS = 60;
|
|
34
|
+
|
|
35
|
+
export class AgentCredentialError extends Error {
|
|
36
|
+
/** @param {string} message @param {string} code */
|
|
37
|
+
constructor(message, code) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = "AgentCredentialError";
|
|
40
|
+
this.code = code;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Parse the stored form. Any failure is a fixed message: the raw value is never echoed.
|
|
46
|
+
* @param {string} text
|
|
47
|
+
* @returns {{ clientId: string, kid: string, privateKeyPem: string }}
|
|
48
|
+
*/
|
|
49
|
+
export function parseAgentCredential(text) {
|
|
50
|
+
let value = String(text ?? "").trim();
|
|
51
|
+
// `security -w` prints a value it considers non-printable as hex.
|
|
52
|
+
if (/^(?:[0-9a-f]{2})+$/i.test(value) && !value.startsWith("{")) {
|
|
53
|
+
value = Buffer.from(value, "hex").toString("utf8").trim();
|
|
54
|
+
}
|
|
55
|
+
let parsed;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(value);
|
|
58
|
+
} catch {
|
|
59
|
+
throw new AgentCredentialError("the agent credential is not valid JSON.", "agent_credential_malformed");
|
|
60
|
+
}
|
|
61
|
+
const clientId = parsed?.clientId;
|
|
62
|
+
const kid = parsed?.kid;
|
|
63
|
+
const privateKeyPem = parsed?.privateKeyPem;
|
|
64
|
+
if (typeof clientId !== "string" || !CLIENT_ID_RE.test(clientId) ||
|
|
65
|
+
typeof kid !== "string" || !KID_RE.test(kid) ||
|
|
66
|
+
typeof privateKeyPem !== "string" || !privateKeyPem.includes("PRIVATE KEY")) {
|
|
67
|
+
throw new AgentCredentialError(
|
|
68
|
+
"the agent credential must be {\"clientId\",\"kid\",\"privateKeyPem\"}.", "agent_credential_malformed");
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const key = createPrivateKey(privateKeyPem);
|
|
72
|
+
if (key.asymmetricKeyType !== "rsa") throw new Error("not rsa");
|
|
73
|
+
} catch {
|
|
74
|
+
throw new AgentCredentialError("the agent credential's private key is not an RSA private key.",
|
|
75
|
+
"agent_credential_malformed");
|
|
76
|
+
}
|
|
77
|
+
return { clientId, kid, privateKeyPem };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** macOS `security`: errSecItemNotFound. */
|
|
81
|
+
const SECURITY_ITEM_NOT_FOUND = 44;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @typedef {{ status: "found", value: string }
|
|
85
|
+
* | { status: "absent", detail: string }
|
|
86
|
+
* | { status: "unreadable", reason: string }} KeychainOutcome
|
|
87
|
+
* The ReadOutcome shape (scripts/lib/read-outcome.mjs, which this published package cannot import).
|
|
88
|
+
*/
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Read the keychain item for `mcpOrigin` as a tri-state. `absent` is only a CONFIRMED not-found
|
|
92
|
+
* (no such item, no keychain tool on this machine, an unsupported platform). A locked keychain,
|
|
93
|
+
* a denied access prompt, a timeout or any other failure is `unreadable`, so "could not look" is
|
|
94
|
+
* never reported as "no credential". The child's stderr is inspected, never relayed: a reason is
|
|
95
|
+
* the tool and its exit status only.
|
|
96
|
+
* @param {string} mcpOrigin
|
|
97
|
+
* @param {{ platform?: NodeJS.Platform, execFileImpl?: typeof execFile }} [deps]
|
|
98
|
+
* @returns {Promise<KeychainOutcome>}
|
|
99
|
+
*/
|
|
100
|
+
export function readKeychainCredential(mcpOrigin, { platform = process.platform, execFileImpl = execFile } = {}) {
|
|
101
|
+
/** @type {[string, string[]] | null} */
|
|
102
|
+
const command = platform === "darwin"
|
|
103
|
+
? ["/usr/bin/security", ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", mcpOrigin, "-w"]]
|
|
104
|
+
: platform === "linux"
|
|
105
|
+
? ["secret-tool", ["lookup", "service", KEYCHAIN_SERVICE, "account", mcpOrigin]]
|
|
106
|
+
: null;
|
|
107
|
+
if (!command) return Promise.resolve({ status: "absent", detail: `no keychain support on ${platform}` });
|
|
108
|
+
const [file, args] = command;
|
|
109
|
+
return new Promise((resolve) => {
|
|
110
|
+
execFileImpl(file, args, {
|
|
111
|
+
encoding: "utf8", timeout: 15_000, maxBuffer: 64 * 1024, shell: false, windowsHide: true,
|
|
112
|
+
}, (error, stdout, stderr) => {
|
|
113
|
+
const value = String(stdout ?? "").trim();
|
|
114
|
+
if (!error) {
|
|
115
|
+
return resolve(value ? { status: "found", value } : { status: "absent", detail: "empty keychain item" });
|
|
116
|
+
}
|
|
117
|
+
const e = /** @type {any} */ (error);
|
|
118
|
+
if (e.code === "ENOENT") return resolve({ status: "absent", detail: `${file} is not installed` });
|
|
119
|
+
if (platform === "darwin" && e.code === SECURITY_ITEM_NOT_FOUND) {
|
|
120
|
+
return resolve({ status: "absent", detail: "no keychain item" });
|
|
121
|
+
}
|
|
122
|
+
// secret-tool exits 1 with no output at all when nothing matches.
|
|
123
|
+
if (platform === "linux" && e.code === 1 && !value && !String(stderr ?? "").trim()) {
|
|
124
|
+
return resolve({ status: "absent", detail: "no keychain item" });
|
|
125
|
+
}
|
|
126
|
+
const why = e.killed ? "timed out" : typeof e.code === "number" ? `exited ${e.code}` : "failed to run";
|
|
127
|
+
resolve({ status: "unreadable", reason: `${file} ${why}` });
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Read one line from the terminal with echo off. Refuses a non-TTY stdin: a pipe is
|
|
134
|
+
* neither the keychain nor an interactive prompt.
|
|
135
|
+
* @param {string} question
|
|
136
|
+
* @param {{ input?: NodeJS.ReadStream, output?: NodeJS.WriteStream }} [io]
|
|
137
|
+
* @returns {Promise<string|null>}
|
|
138
|
+
*/
|
|
139
|
+
export function promptHidden(question, { input = process.stdin, output = process.stderr } = {}) {
|
|
140
|
+
if (!input.isTTY || typeof input.setRawMode !== "function") return Promise.resolve(null);
|
|
141
|
+
return new Promise((resolve) => {
|
|
142
|
+
let value = "";
|
|
143
|
+
output.write(question);
|
|
144
|
+
input.setRawMode(true);
|
|
145
|
+
input.resume();
|
|
146
|
+
input.setEncoding("utf8");
|
|
147
|
+
/** @param {string|null} result */
|
|
148
|
+
const finish = (result) => {
|
|
149
|
+
input.removeListener("data", onData);
|
|
150
|
+
input.setRawMode(false);
|
|
151
|
+
input.pause();
|
|
152
|
+
output.write("\n");
|
|
153
|
+
resolve(result);
|
|
154
|
+
};
|
|
155
|
+
/** @param {string} chunk */
|
|
156
|
+
function onData(chunk) {
|
|
157
|
+
for (const ch of chunk) {
|
|
158
|
+
if (ch === "\r" || ch === "\n") return finish(value);
|
|
159
|
+
if (ch === "\u0003" || ch === "\u0004") return finish(null);
|
|
160
|
+
if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
|
|
161
|
+
else value += ch;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
input.on("data", onData);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* An injected reader may answer with the plain value (a string, or null for a confirmed absence)
|
|
170
|
+
* instead of the tri-state; anything else is passed through as a KeychainOutcome.
|
|
171
|
+
* @param {KeychainOutcome | string | null} answer
|
|
172
|
+
* @returns {KeychainOutcome}
|
|
173
|
+
*/
|
|
174
|
+
function toKeychainOutcome(answer) {
|
|
175
|
+
if (typeof answer === "string") {
|
|
176
|
+
return answer.trim() ? { status: "found", value: answer } : { status: "absent", detail: "empty keychain item" };
|
|
177
|
+
}
|
|
178
|
+
if (answer === null) return { status: "absent", detail: "no keychain item" };
|
|
179
|
+
return answer;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The agent's machine credential for `mcpOrigin`: keychain first, then the prompt.
|
|
184
|
+
* @param {string} mcpOrigin
|
|
185
|
+
* A keychain that could not be READ (locked, access denied, timed out) is a refusal, not
|
|
186
|
+
* absence: it never falls through to the prompt, so the operator learns the keychain is the
|
|
187
|
+
* problem instead of being asked to paste a secret the keychain already holds.
|
|
188
|
+
* @param {{ readKeychain?: (origin: string) => Promise<KeychainOutcome | string | null>,
|
|
189
|
+
* prompt?: (question: string) => Promise<string|null>, allowKeychain?: boolean }} [deps]
|
|
190
|
+
*/
|
|
191
|
+
export async function loadAgentCredential(mcpOrigin, {
|
|
192
|
+
readKeychain = readKeychainCredential,
|
|
193
|
+
prompt = promptHidden,
|
|
194
|
+
allowKeychain = true,
|
|
195
|
+
} = {}) {
|
|
196
|
+
if (allowKeychain) {
|
|
197
|
+
const stored = toKeychainOutcome(await readKeychain(mcpOrigin));
|
|
198
|
+
if (stored.status === "found") return parseAgentCredential(stored.value);
|
|
199
|
+
if (stored.status === "unreadable") {
|
|
200
|
+
throw new AgentCredentialError(
|
|
201
|
+
`the keychain item for ${mcpOrigin} (service ${KEYCHAIN_SERVICE}) could not be read: ${stored.reason}. Unlock the keychain or allow access, then retry.`,
|
|
202
|
+
"agent_credential_unreadable");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const typed = await prompt(`agent credential for ${mcpOrigin} (input hidden): `);
|
|
206
|
+
if (typed && typed.trim()) return parseAgentCredential(typed);
|
|
207
|
+
throw new AgentCredentialError(
|
|
208
|
+
`no agent machine credential for ${mcpOrigin}: none in the keychain (service ${KEYCHAIN_SERVICE}) and no terminal to prompt on.`,
|
|
209
|
+
"agent_credential_missing");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Sign the RFC 7523 client assertion tot-mcp's verifyClientAssertion accepts: RS256 with the
|
|
214
|
+
* registered kid, iss = sub = clientId, aud = the token endpoint, a fresh jti, <= 60s life.
|
|
215
|
+
* @param {{ clientId: string, kid: string, privateKeyPem: string }} credential
|
|
216
|
+
* @param {string} audience
|
|
217
|
+
* @param {{ now?: number, jti?: string }} [opts]
|
|
218
|
+
* @returns {string}
|
|
219
|
+
*/
|
|
220
|
+
export function signClientAssertion(credential, audience, { now = Date.now(), jti = randomUUID() } = {}) {
|
|
221
|
+
const iat = Math.floor(now / 1000);
|
|
222
|
+
const enc = (/** @type {object} */ obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
|
|
223
|
+
const signingInput = `${enc({ alg: "RS256", typ: "JWT", kid: credential.kid })}.${enc({
|
|
224
|
+
iss: credential.clientId, sub: credential.clientId, aud: audience,
|
|
225
|
+
iat, exp: iat + ASSERTION_LIFETIME_SECONDS, jti,
|
|
226
|
+
})}`;
|
|
227
|
+
const signature = createSign("RSA-SHA256").update(signingInput).sign(credential.privateKeyPem);
|
|
228
|
+
return `${signingInput}.${signature.toString("base64url")}`;
|
|
229
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sponsored-agent storefront sessions (#8500 sponsored agents, handoff item 5).
|
|
3
|
+
*
|
|
4
|
+
* An agent obtains its OWN storefront session for one tenant, under a sponsor's
|
|
5
|
+
* agent-sponsorship grant, with no human sign-in and no impersonation:
|
|
6
|
+
*
|
|
7
|
+
* 1. its machine credential (agent-credential.mjs) signs a private_key_jwt assertion;
|
|
8
|
+
* 2. tot-mcp's RFC 8693 token exchange (POST <mcp>/oauth/token) trades assertion + grant id
|
|
9
|
+
* for a short-lived storefront-agent-session token;
|
|
10
|
+
* 3. the storefront's POST /<tenant>/api/dev/cli-session {principal:"agent"} introspects that
|
|
11
|
+
* token at the same MCP and, if the grant names this store, sets a `tot_session` cookie;
|
|
12
|
+
* 4. the cookie is written as a Playwright storageState, chmod 600, tmp + rename.
|
|
13
|
+
*
|
|
14
|
+
* Authority stays on the servers: this sends a tenant and a grant id, never a role or a tenant
|
|
15
|
+
* list, and it cannot widen what the grant says. A refusal is final: no retry, and never a
|
|
16
|
+
* fallback to the operator's human `tot login` session (this module does not import
|
|
17
|
+
* token-store.mjs or auth.mjs's resolver).
|
|
18
|
+
*
|
|
19
|
+
* Tokens travel only in request headers and bodies, never in a URL, and are never printed:
|
|
20
|
+
* verbose output is a method, a URL and an HTTP status.
|
|
21
|
+
*/
|
|
22
|
+
import * as nodeFs from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { randomUUID } from "node:crypto";
|
|
25
|
+
import { dirname, join } from "node:path";
|
|
26
|
+
import {
|
|
27
|
+
DEFAULT_STOREFRONT_ORIGIN, describeUnknownStore, parseSessionCookie,
|
|
28
|
+
} from "./viewer-session.mjs";
|
|
29
|
+
import { AgentCredentialError, signClientAssertion } from "./agent-credential.mjs";
|
|
30
|
+
|
|
31
|
+
export const TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
32
|
+
export const AGENT_SPONSORSHIP_GRANT_TOKEN_TYPE = "urn:tot:params:oauth:token-type:agent-sponsorship-grant";
|
|
33
|
+
export const STOREFRONT_AGENT_SESSION_TOKEN_TYPE = "urn:tot:params:oauth:token-type:storefront-agent-session";
|
|
34
|
+
export const AGENT_SESSION_AUDIENCE = "storefront-agent-session";
|
|
35
|
+
const JWT_BEARER_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
36
|
+
/** Matches tot-mcp and the storefront: an agent session never outlives an hour. */
|
|
37
|
+
export const AGENT_SESSION_MAX_TTL_SECONDS = 3600;
|
|
38
|
+
const SESSION_COOKIE = "tot_session";
|
|
39
|
+
export const STORAGE_STATE_KIND = "tot-agent-session";
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The endpoints are fixed per tier. qa is the default; production is an explicit opt-in.
|
|
43
|
+
* There is no flag that points this command at another host.
|
|
44
|
+
*/
|
|
45
|
+
export const AGENT_SESSION_TIERS = Object.freeze({
|
|
46
|
+
qa: Object.freeze({ mcp: "https://mcp.qa.tokenoftrust.com", storefront: DEFAULT_STOREFRONT_ORIGIN }),
|
|
47
|
+
production: Object.freeze({ mcp: "https://mcp.tokenoftrust.com", storefront: DEFAULT_STOREFRONT_ORIGIN }),
|
|
48
|
+
});
|
|
49
|
+
export const DEFAULT_AGENT_TIER = "qa";
|
|
50
|
+
|
|
51
|
+
const TRUSTED_HOST_RE = /(^|\.)tokenoftrust\.(com|store)$/;
|
|
52
|
+
const TENANT_RE = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;
|
|
53
|
+
const MAX_GRANT_ID_LENGTH = 80;
|
|
54
|
+
|
|
55
|
+
/** @typedef {{ ok: false, code: string, message: string, hint: string, status?: number }} Refusal */
|
|
56
|
+
|
|
57
|
+
/** @param {string} code @param {string} message @param {string} hint @param {number} [status] @returns {Refusal} */
|
|
58
|
+
function refusal(code, message, hint, status) {
|
|
59
|
+
return { ok: false, code, message, hint, ...(status !== undefined ? { status } : {}) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* An https origin on a Token of Trust host, with nothing else in it. Returns the origin or null.
|
|
64
|
+
* @param {unknown} value
|
|
65
|
+
* @returns {string|null}
|
|
66
|
+
*/
|
|
67
|
+
export function trustedHttpsOrigin(value) {
|
|
68
|
+
const text = String(value);
|
|
69
|
+
if (!URL.canParse(text)) return null;
|
|
70
|
+
const url = new URL(text);
|
|
71
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) return null;
|
|
72
|
+
if (url.pathname !== "/" && url.pathname !== "") return null;
|
|
73
|
+
if (!TRUSTED_HOST_RE.test(url.hostname)) return null;
|
|
74
|
+
return url.origin;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @param {unknown} tenant @returns {string|null} */
|
|
78
|
+
export function normalizeTenant(tenant) {
|
|
79
|
+
const t = String(tenant ?? "").trim().toLowerCase();
|
|
80
|
+
return TENANT_RE.test(t) && !t.includes("..") ? t : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @param {unknown} grantId @returns {grantId is string} */
|
|
84
|
+
export function isGrantId(grantId) {
|
|
85
|
+
return typeof grantId === "string" && grantId.length > 0 && grantId.length <= MAX_GRANT_ID_LENGTH &&
|
|
86
|
+
/^[\x21-\x7e]+$/.test(grantId);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Validate a tier's endpoints: both https origins on a Token of Trust host.
|
|
91
|
+
* @param {{ mcp: string, storefront: string }|undefined} endpoints
|
|
92
|
+
* @returns {{ ok: true, mcp: string, storefront: string } | Refusal}
|
|
93
|
+
*/
|
|
94
|
+
export function resolveEndpoints(endpoints) {
|
|
95
|
+
const mcp = trustedHttpsOrigin(endpoints?.mcp);
|
|
96
|
+
const storefront = trustedHttpsOrigin(endpoints?.storefront);
|
|
97
|
+
if (!mcp || !storefront) {
|
|
98
|
+
return refusal("endpoint_refused", "refusing a non-https or unknown host for the agent session endpoints.",
|
|
99
|
+
"use --tier qa or --tier production.");
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, mcp, storefront };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Default storageState location: `~/.tot/agent-sessions/<tenant>.json`. @param {string} tenant @param {NodeJS.ProcessEnv} [env] */
|
|
105
|
+
export function defaultStorageStatePath(tenant, env = process.env) {
|
|
106
|
+
return join(env.TOT_HOME || homedir(), ".tot", "agent-sessions", `${tenant}.json`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A response body as a tri-state (the ReadOutcome shape of scripts/lib/read-outcome.mjs, which
|
|
111
|
+
* this published package cannot import): `found` JSON, a confirmed-`absent` (empty) body, or
|
|
112
|
+
* `unreadable` — a stream failure or malformed JSON. A reason is a fixed phrase, never body text:
|
|
113
|
+
* a body can carry a token.
|
|
114
|
+
* @param {{ text: () => Promise<string> }} res
|
|
115
|
+
* @returns {Promise<{ status: "found", value: any } | { status: "absent" } | { status: "unreadable", reason: string }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function readJsonBody(res) {
|
|
118
|
+
let text;
|
|
119
|
+
try {
|
|
120
|
+
text = await res.text();
|
|
121
|
+
} catch {
|
|
122
|
+
// The stream itself failed (reset, aborted): we never saw the body, so it is not "empty".
|
|
123
|
+
return { status: "unreadable", reason: "the response body could not be read" };
|
|
124
|
+
}
|
|
125
|
+
if (!text || !text.trim()) return { status: "absent" };
|
|
126
|
+
try {
|
|
127
|
+
return { status: "found", value: JSON.parse(text) };
|
|
128
|
+
} catch (e) {
|
|
129
|
+
if (!(e instanceof SyntaxError)) throw e;
|
|
130
|
+
return { status: "unreadable", reason: "malformed JSON" };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A server-sent error code, only when it is a plain code: free text from a server is never echoed. */
|
|
135
|
+
const serverCode = (/** @type {unknown} */ value) =>
|
|
136
|
+
typeof value === "string" && /^[a-z0-9_]{1,64}$/.test(value) ? value : null;
|
|
137
|
+
|
|
138
|
+
/** `; its body could not be read (…)` for an unreadable error body, else nothing. */
|
|
139
|
+
const describeUnread = (/** @type {{ status: string, reason?: string }} */ outcome) =>
|
|
140
|
+
outcome.status === "unreadable" ? `; its body could not be read: ${outcome.reason}` : "";
|
|
141
|
+
|
|
142
|
+
/** The body when it was JSON; any other outcome is reported by the caller, never treated as data. */
|
|
143
|
+
const valueOf = (/** @type {Awaited<ReturnType<typeof readJsonBody>>} */ outcome) =>
|
|
144
|
+
outcome.status === "found" ? outcome.value : undefined;
|
|
145
|
+
|
|
146
|
+
/** @param {any} res @returns {string|null} */
|
|
147
|
+
function sessionCookieFrom(res) {
|
|
148
|
+
const headers = res?.headers;
|
|
149
|
+
const list = typeof headers?.getSetCookie === "function" ? headers.getSetCookie() : [];
|
|
150
|
+
for (const line of list) {
|
|
151
|
+
const id = parseSessionCookie(line);
|
|
152
|
+
if (id) return id;
|
|
153
|
+
}
|
|
154
|
+
return parseSessionCookie(typeof headers?.get === "function" ? headers.get("set-cookie") : null);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Trade the agent's credential plus grant id for a storefront-agent-session token.
|
|
159
|
+
* @param {{ mcp: string, credential: { clientId: string, kid: string, privateKeyPem: string },
|
|
160
|
+
* grantId: string, fetchImpl: typeof fetch, now: number, vlog: (s: string) => void }} p
|
|
161
|
+
* @returns {Promise<{ ok: true, accessToken: string, expiresIn: number } | Refusal>}
|
|
162
|
+
*/
|
|
163
|
+
async function exchangeForAgentToken({ mcp, credential, grantId, fetchImpl, now, vlog }) {
|
|
164
|
+
const tokenEndpoint = `${mcp}/oauth/token`;
|
|
165
|
+
const body = new URLSearchParams({
|
|
166
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
167
|
+
client_assertion_type: JWT_BEARER_ASSERTION_TYPE,
|
|
168
|
+
client_assertion: signClientAssertion(credential, tokenEndpoint, { now }),
|
|
169
|
+
subject_token: grantId,
|
|
170
|
+
subject_token_type: AGENT_SPONSORSHIP_GRANT_TOKEN_TYPE,
|
|
171
|
+
audience: AGENT_SESSION_AUDIENCE,
|
|
172
|
+
requested_token_type: STOREFRONT_AGENT_SESSION_TOKEN_TYPE,
|
|
173
|
+
});
|
|
174
|
+
let res;
|
|
175
|
+
try {
|
|
176
|
+
vlog(`POST ${tokenEndpoint}`);
|
|
177
|
+
res = await fetchImpl(tokenEndpoint, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
180
|
+
body: body.toString(),
|
|
181
|
+
redirect: "manual",
|
|
182
|
+
});
|
|
183
|
+
} catch {
|
|
184
|
+
return refusal("exchange_unreachable", `couldn't reach ${mcp} for the token exchange.`, "check your network, then re-run.");
|
|
185
|
+
}
|
|
186
|
+
vlog(`token exchange → HTTP ${res.status}`);
|
|
187
|
+
const outcome = await readJsonBody(res);
|
|
188
|
+
const payload = valueOf(outcome);
|
|
189
|
+
if (!res.ok) {
|
|
190
|
+
const error = serverCode(payload?.error);
|
|
191
|
+
if (error === "invalid_client") {
|
|
192
|
+
return refusal("invalid_client", "tot-mcp refused the agent's machine credential.",
|
|
193
|
+
"check that the keychain credential is this agent's registered client and key.", res.status);
|
|
194
|
+
}
|
|
195
|
+
if (error === "invalid_grant") {
|
|
196
|
+
return refusal("invalid_grant", "the grant can't be exchanged: it is unknown, revoked, expired, or not this agent's.",
|
|
197
|
+
"ask the sponsor for a live agent-sponsorship grant naming this agent.", res.status);
|
|
198
|
+
}
|
|
199
|
+
if (error === "invalid_target") {
|
|
200
|
+
return refusal("invalid_target", "tot-mcp does not issue storefront agent sessions here.",
|
|
201
|
+
"check --tier.", res.status);
|
|
202
|
+
}
|
|
203
|
+
return refusal("exchange_failed", `the token exchange failed (HTTP ${res.status}${describeUnread(outcome)}).`,
|
|
204
|
+
"retry shortly; if it persists, report it with `tot feedback`.", res.status);
|
|
205
|
+
}
|
|
206
|
+
if (outcome.status === "absent") {
|
|
207
|
+
return refusal("exchange_empty", "the token exchange returned an empty response.", "report it with `tot feedback`.");
|
|
208
|
+
}
|
|
209
|
+
if (outcome.status === "unreadable") {
|
|
210
|
+
return refusal("exchange_unreadable", `the token exchange response could not be read (${outcome.reason}).`,
|
|
211
|
+
"retry shortly; if it persists, report it with `tot feedback`.");
|
|
212
|
+
}
|
|
213
|
+
const accessToken = payload?.access_token;
|
|
214
|
+
const expiresIn = payload?.expires_in;
|
|
215
|
+
if (typeof accessToken !== "string" || !accessToken ||
|
|
216
|
+
payload?.issued_token_type !== STOREFRONT_AGENT_SESSION_TOKEN_TYPE ||
|
|
217
|
+
typeof expiresIn !== "number" || !(expiresIn > 0)) {
|
|
218
|
+
return refusal("exchange_malformed", "the token exchange returned an unexpected response.",
|
|
219
|
+
"report it with `tot feedback`.");
|
|
220
|
+
}
|
|
221
|
+
return { ok: true, accessToken, expiresIn };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Obtain a sponsored agent session for `tenant`. Never throws on a refusal.
|
|
226
|
+
*
|
|
227
|
+
* @param {{ tenant: string, grantId: string,
|
|
228
|
+
* endpoints?: { mcp: string, storefront: string },
|
|
229
|
+
* loadCredential: (mcpOrigin: string) => Promise<{ clientId: string, kid: string, privateKeyPem: string }>,
|
|
230
|
+
* fetchImpl?: typeof fetch, now?: () => number, vlog?: (s: string) => void }} params
|
|
231
|
+
* @returns {Promise<{ ok: true, tenant: string, origin: string, cookie: string, expiresAt: number } | Refusal>}
|
|
232
|
+
*/
|
|
233
|
+
export async function obtainAgentSession({
|
|
234
|
+
tenant: rawTenant,
|
|
235
|
+
grantId,
|
|
236
|
+
endpoints = AGENT_SESSION_TIERS[DEFAULT_AGENT_TIER],
|
|
237
|
+
loadCredential,
|
|
238
|
+
fetchImpl = fetch,
|
|
239
|
+
now = () => Date.now(),
|
|
240
|
+
vlog = () => {},
|
|
241
|
+
}) {
|
|
242
|
+
const tenant = normalizeTenant(rawTenant);
|
|
243
|
+
if (!tenant) return refusal("invalid_tenant", "that is not a store name.", "pass the store's domain, e.g. `acme.com`.");
|
|
244
|
+
if (!isGrantId(grantId)) {
|
|
245
|
+
return refusal("invalid_grant_id", "--grant needs the agent-sponsorship grant id.", "ask the sponsor for it.");
|
|
246
|
+
}
|
|
247
|
+
const resolved = resolveEndpoints(endpoints);
|
|
248
|
+
if (!resolved.ok) return resolved;
|
|
249
|
+
const { mcp, storefront } = resolved;
|
|
250
|
+
|
|
251
|
+
let credential;
|
|
252
|
+
try {
|
|
253
|
+
credential = await loadCredential(mcp);
|
|
254
|
+
} catch (e) {
|
|
255
|
+
if (e instanceof AgentCredentialError) {
|
|
256
|
+
return refusal(e.code, e.message,
|
|
257
|
+
"store this agent's credential in the keychain (see `tot agent-session --help`), or run it on a terminal.");
|
|
258
|
+
}
|
|
259
|
+
return refusal("agent_credential_unavailable", "couldn't read the agent machine credential.",
|
|
260
|
+
"see `tot agent-session --help`.");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Discover, without any credential, that this store trusts the tier's MCP before
|
|
264
|
+
// presenting an agent token to it.
|
|
265
|
+
const sessionUrl = `${storefront}/${tenant}/api/dev/cli-session`;
|
|
266
|
+
let discovery;
|
|
267
|
+
try {
|
|
268
|
+
vlog(`GET ${sessionUrl}`);
|
|
269
|
+
discovery = await fetchImpl(sessionUrl, { method: "GET", headers: { accept: "application/json" }, redirect: "manual" });
|
|
270
|
+
} catch {
|
|
271
|
+
return refusal("storefront_unreachable", `couldn't reach ${storefront}.`, "check your network, then re-run.");
|
|
272
|
+
}
|
|
273
|
+
vlog(`cli-session discovery → HTTP ${discovery.status}`);
|
|
274
|
+
if (discovery.status === 404) {
|
|
275
|
+
const { message, hint } = describeUnknownStore(tenant, storefront);
|
|
276
|
+
return refusal("unknown_store", message, hint, 404);
|
|
277
|
+
}
|
|
278
|
+
if (discovery.status === 502 || discovery.status === 503) {
|
|
279
|
+
return refusal("identity_check_unavailable", "the store's identity check is unavailable right now.",
|
|
280
|
+
"retry shortly; if it persists, report it with `tot feedback`.", discovery.status);
|
|
281
|
+
}
|
|
282
|
+
if (!discovery.ok) {
|
|
283
|
+
return refusal("discovery_failed", `couldn't discover the store's identity issuer (HTTP ${discovery.status}).`,
|
|
284
|
+
"retry shortly; if it persists, report it with `tot feedback`.", discovery.status);
|
|
285
|
+
}
|
|
286
|
+
const advertised = await readJsonBody(discovery);
|
|
287
|
+
if (advertised.status !== "found") {
|
|
288
|
+
return refusal("discovery_unreadable",
|
|
289
|
+
`the store's issuer discovery ${advertised.status === "absent" ? "was empty" : `could not be read (${advertised.reason})`}.`,
|
|
290
|
+
"retry shortly; if it persists, report it with `tot feedback`.", discovery.status);
|
|
291
|
+
}
|
|
292
|
+
const trusted = advertised.value?.trustedMcps;
|
|
293
|
+
if (!Array.isArray(trusted) || !trusted.includes(mcp)) {
|
|
294
|
+
return refusal("issuer_not_trusted", `this store does not accept agent sessions from ${mcp}.`,
|
|
295
|
+
"check --tier; if it persists, report it with `tot feedback`.", discovery.status);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const exchanged = await exchangeForAgentToken({ mcp, credential, grantId, fetchImpl, now: now(), vlog });
|
|
299
|
+
if (!exchanged.ok) return exchanged;
|
|
300
|
+
|
|
301
|
+
let res;
|
|
302
|
+
try {
|
|
303
|
+
vlog(`POST ${sessionUrl}`);
|
|
304
|
+
res = await fetchImpl(sessionUrl, {
|
|
305
|
+
method: "POST",
|
|
306
|
+
// JSON content-type takes this out of Astro's form-POST origin check; see viewer-session.mjs.
|
|
307
|
+
headers: { authorization: `Bearer ${exchanged.accessToken}`, "content-type": "application/json" },
|
|
308
|
+
body: JSON.stringify({ mcpOrigin: mcp, principal: "agent" }),
|
|
309
|
+
// A 3xx is a refusal: the token only ever reaches the origin it was addressed to.
|
|
310
|
+
redirect: "manual",
|
|
311
|
+
});
|
|
312
|
+
} catch {
|
|
313
|
+
return refusal("storefront_unreachable", `couldn't reach ${storefront} to start the session.`, "check your network, then re-run.");
|
|
314
|
+
}
|
|
315
|
+
vlog(`cli-session → HTTP ${res.status}`);
|
|
316
|
+
const outcome = await readJsonBody(res);
|
|
317
|
+
const body = valueOf(outcome);
|
|
318
|
+
const error = serverCode(body?.error);
|
|
319
|
+
if (res.status === 403) {
|
|
320
|
+
// Final. The server decided this agent may not enter this store; nothing here may ask again.
|
|
321
|
+
return refusal(error || "forbidden", `the store refused this agent${error ? ` (${error})` : ""}.`,
|
|
322
|
+
"the sponsor's grant decides which stores and roles an agent gets; ask the sponsor.", 403);
|
|
323
|
+
}
|
|
324
|
+
if (res.status === 401) {
|
|
325
|
+
return refusal(error || "unresolved_token", "the store did not recognize an active agent token.",
|
|
326
|
+
"the grant may have just been revoked or expired; ask the sponsor.", 401);
|
|
327
|
+
}
|
|
328
|
+
if (!res.ok) {
|
|
329
|
+
return refusal(error || "session_failed",
|
|
330
|
+
`couldn't start an agent session (HTTP ${res.status}${error ? `, ${error}` : ""}${describeUnread(outcome)}).`,
|
|
331
|
+
"retry shortly; if it persists, report it with `tot feedback`.", res.status);
|
|
332
|
+
}
|
|
333
|
+
if (outcome.status === "unreadable") {
|
|
334
|
+
// The session may exist server-side; it expires on its own within the hour.
|
|
335
|
+
return refusal("session_unreadable", `the store's session response could not be read (${outcome.reason}).`,
|
|
336
|
+
"retry; if it persists, report it with `tot feedback`.");
|
|
337
|
+
}
|
|
338
|
+
const cookie = sessionCookieFrom(res);
|
|
339
|
+
if (body?.principal !== "agent" || !cookie) {
|
|
340
|
+
return refusal("session_malformed", "the store did not return an agent session.", "report it with `tot feedback`.");
|
|
341
|
+
}
|
|
342
|
+
const ttl = Math.min(
|
|
343
|
+
AGENT_SESSION_MAX_TTL_SECONDS,
|
|
344
|
+
typeof body.expiresIn === "number" && body.expiresIn > 0 ? Math.floor(body.expiresIn) : AGENT_SESSION_MAX_TTL_SECONDS,
|
|
345
|
+
Math.floor(exchanged.expiresIn),
|
|
346
|
+
);
|
|
347
|
+
return { ok: true, tenant, origin: storefront, cookie, expiresAt: Math.floor(now() / 1000) + ttl };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The Playwright storageState for a session. `tot` carries non-secret metadata only.
|
|
352
|
+
* @param {{ tenant: string, origin: string, cookie: string, expiresAt: number, tier: string }} s
|
|
353
|
+
*/
|
|
354
|
+
export function buildStorageState({ tenant, origin, cookie, expiresAt, tier }) {
|
|
355
|
+
return {
|
|
356
|
+
cookies: [{
|
|
357
|
+
name: SESSION_COOKIE, value: cookie, domain: new URL(origin).hostname, path: "/",
|
|
358
|
+
expires: expiresAt, httpOnly: true, secure: true, sameSite: "Lax",
|
|
359
|
+
}],
|
|
360
|
+
origins: [],
|
|
361
|
+
tot: { kind: STORAGE_STATE_KIND, tenant, tier, expiresAt: new Date(expiresAt * 1000).toISOString() },
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Write `state` to `filePath` atomically, owner-only: a 0600 temp file in the same
|
|
367
|
+
* directory, renamed over the target. A failure at any step leaves no partial file at
|
|
368
|
+
* the target and removes the temp file. A directory this creates is 0700; an existing
|
|
369
|
+
* `--out` directory's mode is left alone.
|
|
370
|
+
* @param {string} filePath
|
|
371
|
+
* @param {object} state
|
|
372
|
+
* @param {{ fsImpl?: typeof nodeFs }} [deps]
|
|
373
|
+
*/
|
|
374
|
+
export function writeStorageStateAtomic(filePath, state, { fsImpl = nodeFs } = {}) {
|
|
375
|
+
fsImpl.mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
|
376
|
+
const tmp = `${filePath}.${randomUUID()}.tmp`;
|
|
377
|
+
try {
|
|
378
|
+
fsImpl.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
379
|
+
fsImpl.chmodSync(tmp, 0o600);
|
|
380
|
+
fsImpl.renameSync(tmp, filePath);
|
|
381
|
+
fsImpl.chmodSync(filePath, 0o600);
|
|
382
|
+
} finally {
|
|
383
|
+
fsImpl.rmSync(tmp, { force: true });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* End the server-side session held in `filePath`, then delete that file and nothing else.
|
|
389
|
+
* The logout goes to the tier's fixed origin, and only a `tot_session` cookie scoped to that
|
|
390
|
+
* host is sent, so a tampered file cannot aim the cookie elsewhere. A failed logout keeps the
|
|
391
|
+
* file so the revoke can be retried.
|
|
392
|
+
* @param {{ filePath: string, endpoints?: { mcp: string, storefront: string },
|
|
393
|
+
* fetchImpl?: typeof fetch, fsImpl?: typeof nodeFs, vlog?: (s: string) => void }} p
|
|
394
|
+
* @returns {Promise<{ ok: true, revoked: boolean } | Refusal>}
|
|
395
|
+
*/
|
|
396
|
+
export async function revokeAgentSession({
|
|
397
|
+
filePath, endpoints = AGENT_SESSION_TIERS[DEFAULT_AGENT_TIER], fetchImpl = fetch, fsImpl = nodeFs, vlog = () => {},
|
|
398
|
+
}) {
|
|
399
|
+
const resolved = resolveEndpoints(endpoints);
|
|
400
|
+
if (!resolved.ok) return resolved;
|
|
401
|
+
let text;
|
|
402
|
+
try {
|
|
403
|
+
text = fsImpl.readFileSync(filePath, "utf8");
|
|
404
|
+
} catch (e) {
|
|
405
|
+
if (/** @type {any} */ (e)?.code === "ENOENT") return { ok: true, revoked: false };
|
|
406
|
+
return refusal("storage_state_unreadable", "couldn't read that storageState file.", "check its path and permissions.");
|
|
407
|
+
}
|
|
408
|
+
let state;
|
|
409
|
+
try {
|
|
410
|
+
state = JSON.parse(text);
|
|
411
|
+
} catch (e) {
|
|
412
|
+
if (!(e instanceof SyntaxError)) throw e;
|
|
413
|
+
return refusal("storage_state_malformed", "that storageState file is not valid JSON; nothing was changed.",
|
|
414
|
+
"pass the --out path the session was written to.");
|
|
415
|
+
}
|
|
416
|
+
if (state?.tot?.kind !== STORAGE_STATE_KIND) {
|
|
417
|
+
return refusal("not_agent_session", "that file is not a `tot agent-session` storageState; nothing was changed.",
|
|
418
|
+
"pass the --out path the session was written to.");
|
|
419
|
+
}
|
|
420
|
+
const host = new URL(resolved.storefront).hostname;
|
|
421
|
+
const cookie = Array.isArray(state.cookies)
|
|
422
|
+
? state.cookies.find((c) => c?.name === SESSION_COOKIE && c?.domain === host && typeof c?.value === "string")
|
|
423
|
+
: null;
|
|
424
|
+
if (cookie && /^[^;,\s]+$/.test(cookie.value)) {
|
|
425
|
+
const url = `${resolved.storefront}/api/auth/logout`;
|
|
426
|
+
let res;
|
|
427
|
+
try {
|
|
428
|
+
vlog(`POST ${url}`);
|
|
429
|
+
res = await fetchImpl(url, {
|
|
430
|
+
method: "POST",
|
|
431
|
+
headers: { cookie: `${SESSION_COOKIE}=${cookie.value}`, "content-type": "application/json" },
|
|
432
|
+
body: "{}",
|
|
433
|
+
redirect: "manual",
|
|
434
|
+
});
|
|
435
|
+
} catch {
|
|
436
|
+
return refusal("logout_unreachable", `couldn't reach ${resolved.storefront} to end the session; the file was kept.`,
|
|
437
|
+
"re-run the revoke; the session also expires on its own within an hour.");
|
|
438
|
+
}
|
|
439
|
+
vlog(`logout → HTTP ${res.status}`);
|
|
440
|
+
if (res.status >= 400) {
|
|
441
|
+
return refusal("logout_failed", `the store did not end the session (HTTP ${res.status}); the file was kept.`,
|
|
442
|
+
"re-run the revoke; the session also expires on its own within an hour.", res.status);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
fsImpl.rmSync(filePath, { force: true });
|
|
446
|
+
return { ok: true, revoked: true };
|
|
447
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tot agent-session <tenant> --grant <id> [--out <path>] [--tier qa|production] [--verbose]`
|
|
3
|
+
* `tot agent-session <tenant> --revoke [--out <path>] [--tier qa|production]`
|
|
4
|
+
*
|
|
5
|
+
* A sponsored agent signs itself in to a store's preview and admin under a sponsor's grant,
|
|
6
|
+
* and gets a chmod-600 Playwright storageState. See ../agent-session.mjs for the flow and
|
|
7
|
+
* ../agent-credential.mjs for where the agent's machine credential comes from.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately NOT here: any flag that takes a token, credential, key, or host. The credential
|
|
10
|
+
* comes from the keychain or a hidden prompt; the endpoints are fixed per tier.
|
|
11
|
+
*/
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { loadAgentCredential, KEYCHAIN_SERVICE } from "../agent-credential.mjs";
|
|
14
|
+
import {
|
|
15
|
+
AGENT_SESSION_TIERS, DEFAULT_AGENT_TIER, buildStorageState, defaultStorageStatePath,
|
|
16
|
+
normalizeTenant, obtainAgentSession, revokeAgentSession, writeStorageStateAtomic,
|
|
17
|
+
} from "../agent-session.mjs";
|
|
18
|
+
|
|
19
|
+
const USAGE = `tot agent-session — a sponsored agent's own storefront session (no human sign-in)
|
|
20
|
+
|
|
21
|
+
tot agent-session <tenant> --grant <grantId> [--out <file>] [--tier qa|production] [--verbose]
|
|
22
|
+
exchange this agent's machine credential + the sponsor's grant for a session on <tenant>,
|
|
23
|
+
written as a chmod-600 Playwright storageState (default ~/.tot/agent-sessions/<tenant>.json)
|
|
24
|
+
tot agent-session <tenant> --revoke [--out <file>] [--tier qa|production]
|
|
25
|
+
end that session on the server, then delete that file
|
|
26
|
+
|
|
27
|
+
The machine credential is read from the keychain (service ${KEYCHAIN_SERVICE}, account = the
|
|
28
|
+
tier's MCP origin), or from a hidden prompt on a terminal — never from a flag or environment
|
|
29
|
+
variable. Store it so the keychain prompts for the value:
|
|
30
|
+
|
|
31
|
+
security add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${AGENT_SESSION_TIERS.qa.mcp} -w
|
|
32
|
+
|
|
33
|
+
Its value is one line of JSON: {"clientId":"…","kid":"…","privateKeyPem":"<PKCS#8 PEM, newlines as \\n>"}.
|
|
34
|
+
--tier defaults to ${DEFAULT_AGENT_TIER}.`;
|
|
35
|
+
|
|
36
|
+
/** Every flag this command accepts. None of them carries a secret. */
|
|
37
|
+
export const AGENT_SESSION_FLAGS = Object.freeze({
|
|
38
|
+
"--grant": "value",
|
|
39
|
+
"--out": "value",
|
|
40
|
+
"--tier": "value",
|
|
41
|
+
"--revoke": "boolean",
|
|
42
|
+
"--verbose": "boolean",
|
|
43
|
+
"--help": "boolean",
|
|
44
|
+
"-h": "boolean",
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {string[]} argv
|
|
49
|
+
* @returns {{ ok: true, tenant: string|null, grant: string|null, out: string|null, tier: string,
|
|
50
|
+
* revoke: boolean, verbose: boolean, help: boolean } | { ok: false, message: string }}
|
|
51
|
+
*/
|
|
52
|
+
export function parseAgentSessionArgs(argv) {
|
|
53
|
+
/** @type {{ tenant: string|null, grant: string|null, out: string|null, tier: string, revoke: boolean, verbose: boolean, help: boolean }} */
|
|
54
|
+
const a = { tenant: null, grant: null, out: null, tier: DEFAULT_AGENT_TIER, revoke: false, verbose: false, help: false };
|
|
55
|
+
for (let i = 0; i < argv.length; i++) {
|
|
56
|
+
const raw = argv[i];
|
|
57
|
+
const eq = raw.startsWith("--") ? raw.indexOf("=") : -1;
|
|
58
|
+
const name = eq > 0 ? raw.slice(0, eq) : raw;
|
|
59
|
+
if (!name.startsWith("-")) {
|
|
60
|
+
if (a.tenant !== null) return { ok: false, message: "unexpected extra argument (only <tenant> is positional)" };
|
|
61
|
+
a.tenant = raw;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const kind = Object.prototype.hasOwnProperty.call(AGENT_SESSION_FLAGS, name)
|
|
65
|
+
? AGENT_SESSION_FLAGS[/** @type {keyof typeof AGENT_SESSION_FLAGS} */ (name)] : null;
|
|
66
|
+
// Never echo an unknown flag's value: it might be a secret someone tried to pass.
|
|
67
|
+
if (!kind) return { ok: false, message: `unknown option: ${name}` };
|
|
68
|
+
if (kind === "boolean") {
|
|
69
|
+
if (eq > 0) return { ok: false, message: `${name} takes no value` };
|
|
70
|
+
if (name === "--revoke") a.revoke = true;
|
|
71
|
+
else if (name === "--verbose") a.verbose = true;
|
|
72
|
+
else a.help = true;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const value = eq > 0 ? raw.slice(eq + 1) : argv[++i];
|
|
76
|
+
if (value === undefined || value === "" || (eq < 0 && value.startsWith("-"))) {
|
|
77
|
+
return { ok: false, message: `${name} needs a value` };
|
|
78
|
+
}
|
|
79
|
+
if (name === "--grant") a.grant = value;
|
|
80
|
+
else if (name === "--out") a.out = value;
|
|
81
|
+
else a.tier = value;
|
|
82
|
+
}
|
|
83
|
+
return { ok: true, ...a };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {string[]} argv
|
|
88
|
+
* @param {{ out?: (s: string) => void, err?: (s: string) => void, env?: NodeJS.ProcessEnv,
|
|
89
|
+
* fetchImpl?: typeof fetch, loadCredential?: (mcpOrigin: string) => Promise<any>,
|
|
90
|
+
* now?: () => number, cwd?: string }} [deps]
|
|
91
|
+
* @returns {Promise<number>}
|
|
92
|
+
*/
|
|
93
|
+
export async function run(argv, deps = {}) {
|
|
94
|
+
const out = deps.out ?? ((s) => process.stdout.write(`${s}\n`));
|
|
95
|
+
const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
|
|
96
|
+
const env = deps.env ?? process.env;
|
|
97
|
+
const fail = (/** @type {{ message: string, hint?: string, code?: string }} */ r, code = 1) => {
|
|
98
|
+
err(`✗ tot agent-session: ${r.message}${r.code ? ` [${r.code}]` : ""}`);
|
|
99
|
+
if (r.hint) err(` → ${r.hint}`);
|
|
100
|
+
return code;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const args = parseAgentSessionArgs(argv);
|
|
104
|
+
if (!args.ok) {
|
|
105
|
+
err(`✗ tot agent-session: ${args.message}\n\n${USAGE}`);
|
|
106
|
+
return 2;
|
|
107
|
+
}
|
|
108
|
+
if (args.help) {
|
|
109
|
+
out(USAGE);
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
const tenant = normalizeTenant(args.tenant);
|
|
113
|
+
if (!tenant) return fail({ message: "name the store: `tot agent-session <tenant> --grant <grantId>`." }, 2);
|
|
114
|
+
if (!Object.prototype.hasOwnProperty.call(AGENT_SESSION_TIERS, args.tier)) {
|
|
115
|
+
return fail({ message: "unknown --tier; use qa or production." }, 2);
|
|
116
|
+
}
|
|
117
|
+
const tier = /** @type {keyof typeof AGENT_SESSION_TIERS} */ (args.tier);
|
|
118
|
+
const endpoints = AGENT_SESSION_TIERS[tier];
|
|
119
|
+
const filePath = args.out ? resolve(deps.cwd ?? process.cwd(), args.out) : defaultStorageStatePath(tenant, env);
|
|
120
|
+
// Method, URL and status only — never a header, body, token or cookie.
|
|
121
|
+
const vlog = args.verbose ? (/** @type {string} */ s) => err(`[verbose] ${s}`) : () => {};
|
|
122
|
+
|
|
123
|
+
if (args.revoke) {
|
|
124
|
+
if (args.grant) return fail({ message: "--revoke takes no --grant." }, 2);
|
|
125
|
+
const r = await revokeAgentSession({ filePath, endpoints, fetchImpl: deps.fetchImpl, vlog });
|
|
126
|
+
if (!r.ok) return fail(r);
|
|
127
|
+
out(JSON.stringify({ tenant, tier, storageState: filePath, revoked: r.revoked }, null, 2));
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (!args.grant) return fail({ message: "--grant <grantId> is required: the sponsor's agent-sponsorship grant." }, 2);
|
|
132
|
+
const session = await obtainAgentSession({
|
|
133
|
+
tenant,
|
|
134
|
+
grantId: args.grant,
|
|
135
|
+
endpoints,
|
|
136
|
+
loadCredential: deps.loadCredential ?? ((origin) => loadAgentCredential(origin)),
|
|
137
|
+
fetchImpl: deps.fetchImpl,
|
|
138
|
+
now: deps.now,
|
|
139
|
+
vlog,
|
|
140
|
+
});
|
|
141
|
+
if (!session.ok) return fail(session);
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
writeStorageStateAtomic(filePath, buildStorageState({ ...session, tier }));
|
|
145
|
+
} catch {
|
|
146
|
+
return fail({
|
|
147
|
+
message: "couldn't write the storageState file; nothing was left at the target.",
|
|
148
|
+
hint: "check --out and its directory's permissions. The server session expires on its own within an hour.",
|
|
149
|
+
code: "storage_state_write_failed",
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
out(JSON.stringify({
|
|
153
|
+
tenant,
|
|
154
|
+
tier,
|
|
155
|
+
principal: "agent",
|
|
156
|
+
storageState: filePath,
|
|
157
|
+
previewUrl: `${session.origin}/${tenant}/`,
|
|
158
|
+
adminUrl: `${session.origin}/${tenant}/admin`,
|
|
159
|
+
expiresAt: new Date(session.expiresAt * 1000).toISOString(),
|
|
160
|
+
revoke: `tot agent-session ${tenant} --revoke --out ${filePath}${tier === DEFAULT_AGENT_TIER ? "" : ` --tier ${tier}`}`,
|
|
161
|
+
}, null, 2));
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
package/src/commands/ship.mjs
CHANGED
|
@@ -268,6 +268,7 @@ export function normalizeShipPlan(data) {
|
|
|
268
268
|
receiptId: typeof o.receiptId === "string" ? o.receiptId : null,
|
|
269
269
|
rollbackTarget: o.rollbackTarget && typeof o.rollbackTarget === "object" ? o.rollbackTarget : null,
|
|
270
270
|
warning: normalizeLiveDrift(o.warning),
|
|
271
|
+
tours: o.tours && typeof o.tours.tourSetDigest === "string" ? o.tours : null,
|
|
271
272
|
paywall:
|
|
272
273
|
o.paywall && typeof o.paywall === "object"
|
|
273
274
|
? {
|
|
@@ -586,6 +587,15 @@ export async function runShip(
|
|
|
586
587
|
})
|
|
587
588
|
: [` whole-site aggregate: not in this release — ${plan.message}`];
|
|
588
589
|
planLines.push(...spaceReleaseLines(spaces));
|
|
590
|
+
if (plan.ok && plan.tours) {
|
|
591
|
+
for (const tour of plan.tours.changes ?? []) planLines.push(` tour ${tour.kind}: ${tour.title}`);
|
|
592
|
+
for (const finding of plan.tours.findings ?? []) planLines.push(` tour target: ${finding.code} on ${finding.page}${finding.band ? ` (${finding.band})` : ""}`);
|
|
593
|
+
if (plan.tours.findings?.length && !acceptQualityReason) {
|
|
594
|
+
for (const line of planLines) console.log(line);
|
|
595
|
+
console.error(fail("Tour targets need acknowledgement.", 'Review the findings, then use --accept-quality-findings "<reason>".'));
|
|
596
|
+
return 1;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
589
599
|
if (acceptQualityReason) {
|
|
590
600
|
planLines.push(" quality findings: accept this exact revision and continue");
|
|
591
601
|
planLines.push(` acceptance reason: ${acceptQualityReason.trim() || "(missing)"}`);
|
|
@@ -613,7 +623,7 @@ export async function runShip(
|
|
|
613
623
|
// This is the same revision-bound acceptance as the Publish dialog, not a raw validator bypass.
|
|
614
624
|
// The server refuses it unless the current durable problem is quality-only and the reason is
|
|
615
625
|
// substantive. Only after that accountable record exists do we re-dispatch the release.
|
|
616
|
-
if (acceptQualityReason !== null) {
|
|
626
|
+
if (acceptQualityReason !== null && !(plan.ok && plan.tours?.findings?.length)) {
|
|
617
627
|
const postAccept = (extra = {}) => fetchImpl(`${base}/api/changes/accept-issue`, {
|
|
618
628
|
method: "POST",
|
|
619
629
|
headers: { "content-type": "application/json", ...authHeaders },
|
|
@@ -695,6 +705,8 @@ export async function runShip(
|
|
|
695
705
|
confirmGoLive: true,
|
|
696
706
|
...(plan.pinnedSha ? { expectedAggregateSha: plan.pinnedSha } : {}),
|
|
697
707
|
...(plan.artifactDigest ? { expectedArtifactDigest: plan.artifactDigest } : {}),
|
|
708
|
+
...(plan.tours ? { tourSetDigest: plan.tours.tourSetDigest,
|
|
709
|
+
...(acceptQualityReason && plan.tours.findings?.length ? { tourFindingsDigest: plan.tours.findingsDigest } : {}) } : {}),
|
|
698
710
|
}),
|
|
699
711
|
});
|
|
700
712
|
} catch (e) {
|