recess-cli 3.6.0 → 3.7.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/dist/api.js +22 -2
- package/dist/auth.js +18 -3
- package/dist/cli.js +26 -4
- package/dist/config.js +130 -60
- package/dist/session-refresh.js +122 -0
- package/package.json +1 -1
- package/skill/recess-cli/SKILL.md +4 -2
- package/skill/recess-cli/agents/version.json +1 -1
package/dist/api.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import createClient from "openapi-fetch";
|
|
3
3
|
import { apiError, CliError } from "./errors.js";
|
|
4
|
+
import { refreshSession } from "./session-refresh.js";
|
|
4
5
|
import { cliRequestHeaders, markCliRequest, noteServerCliVersions, RECESS_CLIENT_CLI, } from "./http.js";
|
|
5
6
|
const idempotencyContext = new AsyncLocalStorage();
|
|
6
7
|
export function withIdempotencyContext(context, execute) {
|
|
@@ -34,15 +35,34 @@ export class RecessAdminApi {
|
|
|
34
35
|
});
|
|
35
36
|
const requestReason = this.reason;
|
|
36
37
|
const requestClientTag = this.clientTag;
|
|
38
|
+
const liveConfig = this.config;
|
|
39
|
+
const doFetch = fetchOverride ?? globalThis.fetch;
|
|
40
|
+
// Replayable copies for the one 401 retry below (the sent body is spent).
|
|
41
|
+
const replays = new WeakMap();
|
|
37
42
|
this.client.use({
|
|
38
43
|
onRequest({ request }) {
|
|
44
|
+
// The refresh updates the config in place; always send the current cookie.
|
|
45
|
+
if (liveConfig.sessionCookie) {
|
|
46
|
+
request.headers.set("cookie", liveConfig.sessionCookie);
|
|
47
|
+
}
|
|
39
48
|
markCliRequest(request.headers, requestReason, requestClientTag);
|
|
40
49
|
applyIdempotencyHeaders(request.headers);
|
|
50
|
+
if (liveConfig.refreshToken)
|
|
51
|
+
replays.set(request, request.clone());
|
|
41
52
|
return request;
|
|
42
53
|
},
|
|
43
|
-
onResponse({ response }) {
|
|
54
|
+
async onResponse({ request, response }) {
|
|
44
55
|
noteServerCliVersions(response.headers);
|
|
45
|
-
|
|
56
|
+
const replay = replays.get(request);
|
|
57
|
+
if (response.status !== 401 || !replay)
|
|
58
|
+
return response;
|
|
59
|
+
// An access cookie that expired mid-command: refresh once and resend
|
|
60
|
+
// the identical request (same operation key, so writes stay safe).
|
|
61
|
+
await refreshSession(liveConfig);
|
|
62
|
+
replay.headers.set("cookie", liveConfig.sessionCookie);
|
|
63
|
+
const retried = await doFetch(replay);
|
|
64
|
+
noteServerCliVersions(retried.headers);
|
|
65
|
+
return retried;
|
|
46
66
|
},
|
|
47
67
|
});
|
|
48
68
|
}
|
package/dist/auth.js
CHANGED
|
@@ -4,6 +4,14 @@ import { randomBytes } from "node:crypto";
|
|
|
4
4
|
import { clearPendingDeviceAuth, updateStoredConfig } from "./config.js";
|
|
5
5
|
import { apiError, CliError } from "./errors.js";
|
|
6
6
|
import { cliRequestHeaders } from "./http.js";
|
|
7
|
+
/** Stored secrets stay in the 0600 config; never return them to stdout. */
|
|
8
|
+
function publicSession(session) {
|
|
9
|
+
return {
|
|
10
|
+
success: true,
|
|
11
|
+
expiresAt: session.expiresAt,
|
|
12
|
+
user: session.user,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
7
15
|
function openBrowser(url) {
|
|
8
16
|
// Windows goes through rundll32, not `cmd /c start`: cmd treats `&` (and the
|
|
9
17
|
// `%`-encoded redirect_uri) as metacharacters and chops the URL at the first
|
|
@@ -81,7 +89,10 @@ export async function login(config, options) {
|
|
|
81
89
|
authorization: `Bearer ${assertion}`,
|
|
82
90
|
"content-type": "application/json",
|
|
83
91
|
}),
|
|
84
|
-
body: JSON.stringify({
|
|
92
|
+
body: JSON.stringify({
|
|
93
|
+
sessionDuration: options.sessionDuration,
|
|
94
|
+
refreshable: true,
|
|
95
|
+
}),
|
|
85
96
|
});
|
|
86
97
|
const body = (await response.json());
|
|
87
98
|
if (!response.ok)
|
|
@@ -97,9 +108,11 @@ export async function login(config, options) {
|
|
|
97
108
|
oauthClientId: options.oauthClientId,
|
|
98
109
|
sessionCookie: pair,
|
|
99
110
|
sessionExpiresAt: exchange.expiresAt,
|
|
111
|
+
refreshToken: exchange.refreshToken,
|
|
112
|
+
accessExpiresAt: exchange.accessExpiresAt,
|
|
100
113
|
user: exchange.user,
|
|
101
114
|
}, config.profileName);
|
|
102
|
-
return exchange;
|
|
115
|
+
return publicSession(exchange);
|
|
103
116
|
}
|
|
104
117
|
// Start the headless (device-authorization) sign-in. Non-blocking: it stores the secret
|
|
105
118
|
// device code locally and returns the approval URL for the agent to surface to a human, who
|
|
@@ -154,7 +167,7 @@ export async function pollDeviceAuth(config, options) {
|
|
|
154
167
|
const response = await fetch(new URL("/auth/admin-cli/device/token/", config.apiOrigin), {
|
|
155
168
|
method: "POST",
|
|
156
169
|
headers: cliRequestHeaders({ "content-type": "application/json" }),
|
|
157
|
-
body: JSON.stringify({ deviceCode }),
|
|
170
|
+
body: JSON.stringify({ deviceCode, refreshable: true }),
|
|
158
171
|
});
|
|
159
172
|
const body = (await response.json());
|
|
160
173
|
if (!response.ok) {
|
|
@@ -177,6 +190,8 @@ export async function pollDeviceAuth(config, options) {
|
|
|
177
190
|
webOrigin: config.webOrigin,
|
|
178
191
|
sessionCookie: pair,
|
|
179
192
|
sessionExpiresAt: exchange.expiresAt,
|
|
193
|
+
refreshToken: token.refreshToken,
|
|
194
|
+
accessExpiresAt: token.accessExpiresAt,
|
|
180
195
|
user: exchange.user,
|
|
181
196
|
}, config.profileName);
|
|
182
197
|
await clearPendingDeviceAuth(config.profileName);
|
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import { RecessAdminApi, unwrap, withIdempotencyContext } from "./api.js";
|
|
6
6
|
import { flagNumber, flagString, hasFlag, parseArgs, } from "./args.js";
|
|
7
7
|
import { login, pollDeviceAuth, requestDeviceAuth } from "./auth.js";
|
|
8
|
-
import { clearStoredSession, deleteProfile, listProfiles, resolveConfig, saveProfile, useProfile, } from "./config.js";
|
|
8
|
+
import { clearStoredSession, withConfigLock, deleteProfile, listProfiles, resolveConfig, saveProfile, useProfile, } from "./config.js";
|
|
9
9
|
import { agentContext, buildCommandSchema, findCommandSchema, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
|
|
10
10
|
import { runApplicationsCommand } from "./commands/applications.js";
|
|
11
11
|
import { runAppsCommand } from "./commands/apps.js";
|
|
@@ -30,6 +30,7 @@ import { cliRequestHeaders, noteServerCliVersions, requireCliRequestReason, } fr
|
|
|
30
30
|
import { runSelfUpdate, UPGRADE_COMMAND, updateNoticeText, updateStatus, } from "./update-notice.js";
|
|
31
31
|
import { requireConfirmation } from "./safety.js";
|
|
32
32
|
import { installSkill, isEphemeralInstall, readBundledSkillVersion, readCliVersion, } from "./setup.js";
|
|
33
|
+
import { ensureFreshSession, revokeSession } from "./session-refresh.js";
|
|
33
34
|
import { compareVersions, updateSkillFromServer } from "./skill-update.js";
|
|
34
35
|
import { readSkillCache, writeSkillCache } from "./skills-cache.js";
|
|
35
36
|
import { sanitizeWorkspaceUploadName } from "./upload-names.js";
|
|
@@ -142,7 +143,12 @@ function resolveCommandDiscovery(config) {
|
|
|
142
143
|
if (typeof claim.exp !== "number" || !Number.isFinite(claim.exp)) {
|
|
143
144
|
return unavailable;
|
|
144
145
|
}
|
|
145
|
-
|
|
146
|
+
// A refreshable session's access cookie lapses every 15 minutes; its
|
|
147
|
+
// claims still describe the sign-in until the session itself ends.
|
|
148
|
+
const sessionEnd = config.refreshToken && config.sessionExpiresAt
|
|
149
|
+
? Date.parse(config.sessionExpiresAt)
|
|
150
|
+
: claim.exp * 1000;
|
|
151
|
+
if (sessionEnd <= Date.now()) {
|
|
146
152
|
return signedOut;
|
|
147
153
|
}
|
|
148
154
|
const scope = typeof claim.cliScope === "string" &&
|
|
@@ -1934,6 +1940,15 @@ export async function executeRecessCommand(argv, options = {}) {
|
|
|
1934
1940
|
}
|
|
1935
1941
|
}
|
|
1936
1942
|
const config = options.config ?? (await resolveConfig(flagString(parsed, "profile")));
|
|
1943
|
+
// Renew a refreshable session's 15-minute access cookie before any command
|
|
1944
|
+
// that uses it. Sign-in/out commands manage the session themselves. Not
|
|
1945
|
+
// fatal here: an offline local command must still run, and an API call
|
|
1946
|
+
// that needs auth refreshes on its 401 and reports the real error.
|
|
1947
|
+
if (!isRemote &&
|
|
1948
|
+
!(noun === "auth" && verb !== "status") &&
|
|
1949
|
+
noun !== "setup") {
|
|
1950
|
+
await ensureFreshSession(config).catch(() => undefined);
|
|
1951
|
+
}
|
|
1937
1952
|
const requestReason = noun === "auth"
|
|
1938
1953
|
? undefined
|
|
1939
1954
|
: noun === "update"
|
|
@@ -2045,8 +2060,15 @@ export async function executeRecessCommand(argv, options = {}) {
|
|
|
2045
2060
|
if (verb === "status")
|
|
2046
2061
|
return sessionStatus(config);
|
|
2047
2062
|
if (verb === "logout") {
|
|
2048
|
-
|
|
2049
|
-
|
|
2063
|
+
// Resolve, revoke, and clear ONE session under the config lock, so a
|
|
2064
|
+
// sign-in racing this logout is neither discarded nor left unrevoked.
|
|
2065
|
+
const revoked = await withConfigLock(config.configPath, async () => {
|
|
2066
|
+
const current = await resolveConfig(config.profileName);
|
|
2067
|
+
const wasRevoked = await revokeSession(current);
|
|
2068
|
+
await clearStoredSession(config.profileName);
|
|
2069
|
+
return wasRevoked;
|
|
2070
|
+
});
|
|
2071
|
+
return { loggedOut: true, revokedServerSession: revoked };
|
|
2050
2072
|
}
|
|
2051
2073
|
throw new CliError("invalid_arguments", "Use auth login, request, poll, status, or logout.");
|
|
2052
2074
|
}
|
package/dist/config.js
CHANGED
|
@@ -1,8 +1,52 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import fs from "node:fs/promises";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { CliError } from "./errors.js";
|
|
5
6
|
export const DEFAULT_OAUTH_CLIENT_ID = "c7e34138-18f9-45b1-a2fb-26a4e3a6d739";
|
|
7
|
+
const LOCK_STALE_MS = 30 * 1000;
|
|
8
|
+
const LOCK_WAIT_MS = 15 * 1000;
|
|
9
|
+
const heldLocks = new AsyncLocalStorage();
|
|
10
|
+
/**
|
|
11
|
+
* Serialises every read-modify-write of the config file across recess
|
|
12
|
+
* processes (sign-in, refresh, logout, pending device auth, profiles), so no
|
|
13
|
+
* writer can restore a stale or spent refresh token over a newer one.
|
|
14
|
+
* Reentrant within one async call chain; creates the config directory first.
|
|
15
|
+
*/
|
|
16
|
+
export async function withConfigLock(configPath, run) {
|
|
17
|
+
const held = heldLocks.getStore();
|
|
18
|
+
if (held?.has(configPath))
|
|
19
|
+
return run();
|
|
20
|
+
await fs.mkdir(path.dirname(configPath), { recursive: true, mode: 0o700 });
|
|
21
|
+
const lockPath = `${configPath}.lock`;
|
|
22
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
23
|
+
for (;;) {
|
|
24
|
+
try {
|
|
25
|
+
const handle = await fs.open(lockPath, "wx", 0o600);
|
|
26
|
+
await handle.close();
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code !== "EEXIST")
|
|
31
|
+
throw error;
|
|
32
|
+
const stat = await fs.stat(lockPath).catch(() => null);
|
|
33
|
+
if (stat && Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
|
|
34
|
+
await fs.rm(lockPath, { force: true });
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (Date.now() > deadline) {
|
|
38
|
+
throw new CliError("config_busy", "Another recess process is updating the local session; retry in a moment.");
|
|
39
|
+
}
|
|
40
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
return await heldLocks.run(new Set([...(held ?? []), configPath]), run);
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await fs.rm(lockPath, { force: true });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
6
50
|
export function defaultConfigPath() {
|
|
7
51
|
return (process.env.RECESS_CLI_CONFIG ??
|
|
8
52
|
path.join(os.homedir(), ".recess-cli", "config.json"));
|
|
@@ -48,6 +92,18 @@ export async function resolveConfig(profileName) {
|
|
|
48
92
|
sessionExpiresAt: selectedProfileName
|
|
49
93
|
? profile?.sessionExpiresAt
|
|
50
94
|
: stored.sessionExpiresAt,
|
|
95
|
+
// An env cookie is a fixed credential: never pair it with a stored
|
|
96
|
+
// refresh token from a different sign-in.
|
|
97
|
+
refreshToken: envCookie
|
|
98
|
+
? undefined
|
|
99
|
+
: selectedProfileName
|
|
100
|
+
? profile?.refreshToken
|
|
101
|
+
: stored.refreshToken,
|
|
102
|
+
accessExpiresAt: envCookie
|
|
103
|
+
? undefined
|
|
104
|
+
: selectedProfileName
|
|
105
|
+
? profile?.accessExpiresAt
|
|
106
|
+
: stored.accessExpiresAt,
|
|
51
107
|
user: selectedProfileName ? profile?.user : stored.user,
|
|
52
108
|
authSource: envCookie ? "env" : sessionCookie ? "config" : "missing",
|
|
53
109
|
pendingDeviceCode: selectedProfileName
|
|
@@ -89,38 +145,44 @@ export async function listProfiles() {
|
|
|
89
145
|
};
|
|
90
146
|
}
|
|
91
147
|
export async function saveProfile(name, profile) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
148
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
149
|
+
const normalized = assertProfileName(name);
|
|
150
|
+
const stored = await readStoredConfig();
|
|
151
|
+
await writeStoredConfig({
|
|
152
|
+
...stored,
|
|
153
|
+
profiles: {
|
|
154
|
+
...stored.profiles,
|
|
155
|
+
[normalized]: {
|
|
156
|
+
...stored.profiles?.[normalized],
|
|
157
|
+
...profile,
|
|
158
|
+
},
|
|
101
159
|
},
|
|
102
|
-
}
|
|
160
|
+
});
|
|
103
161
|
});
|
|
104
162
|
}
|
|
105
163
|
export async function useProfile(name) {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
164
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
165
|
+
const normalized = assertProfileName(name);
|
|
166
|
+
const stored = await readStoredConfig();
|
|
167
|
+
if (!stored.profiles?.[normalized]) {
|
|
168
|
+
throw new CliError("unknown_profile", `Unknown Recess CLI profile ${normalized}. Run \`recess --json profile list\`.`);
|
|
169
|
+
}
|
|
170
|
+
await writeStoredConfig({ ...stored, activeProfile: normalized });
|
|
171
|
+
});
|
|
112
172
|
}
|
|
113
173
|
export async function deleteProfile(name) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
174
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
175
|
+
const normalized = assertProfileName(name);
|
|
176
|
+
const stored = await readStoredConfig();
|
|
177
|
+
if (!stored.profiles?.[normalized]) {
|
|
178
|
+
throw new CliError("unknown_profile", `Unknown Recess CLI profile ${normalized}.`);
|
|
179
|
+
}
|
|
180
|
+
const profiles = { ...stored.profiles };
|
|
181
|
+
delete profiles[normalized];
|
|
182
|
+
if (stored.activeProfile === normalized)
|
|
183
|
+
delete stored.activeProfile;
|
|
184
|
+
await writeStoredConfig({ ...stored, profiles });
|
|
185
|
+
});
|
|
124
186
|
}
|
|
125
187
|
export async function writeStoredConfig(config, configPath = defaultConfigPath()) {
|
|
126
188
|
const directory = path.dirname(configPath);
|
|
@@ -133,44 +195,52 @@ export async function writeStoredConfig(config, configPath = defaultConfigPath()
|
|
|
133
195
|
await fs.chmod(configPath, 0o600);
|
|
134
196
|
}
|
|
135
197
|
export async function updateStoredConfig(update, profileName) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
198
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
199
|
+
const configPath = defaultConfigPath();
|
|
200
|
+
const current = await readStoredConfig(configPath);
|
|
201
|
+
const next = profileName
|
|
202
|
+
? {
|
|
203
|
+
...current,
|
|
204
|
+
profiles: {
|
|
205
|
+
...current.profiles,
|
|
206
|
+
[assertProfileName(profileName)]: {
|
|
207
|
+
...current.profiles?.[profileName],
|
|
208
|
+
...update,
|
|
209
|
+
},
|
|
146
210
|
},
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
211
|
+
}
|
|
212
|
+
: { ...current, ...update };
|
|
213
|
+
await writeStoredConfig(next, configPath);
|
|
214
|
+
return next;
|
|
215
|
+
});
|
|
152
216
|
}
|
|
153
217
|
export async function clearStoredSession(profileName) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
218
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
219
|
+
const configPath = defaultConfigPath();
|
|
220
|
+
const current = await readStoredConfig(configPath);
|
|
221
|
+
const target = profileName ? current.profiles?.[profileName] : current;
|
|
222
|
+
if (!target)
|
|
223
|
+
return;
|
|
224
|
+
delete target.sessionCookie;
|
|
225
|
+
delete target.sessionExpiresAt;
|
|
226
|
+
delete target.refreshToken;
|
|
227
|
+
delete target.accessExpiresAt;
|
|
228
|
+
delete target.user;
|
|
229
|
+
await writeStoredConfig(current, configPath);
|
|
230
|
+
});
|
|
163
231
|
}
|
|
164
232
|
export async function clearPendingDeviceAuth(profileName) {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
233
|
+
return withConfigLock(defaultConfigPath(), async () => {
|
|
234
|
+
const configPath = defaultConfigPath();
|
|
235
|
+
const current = await readStoredConfig(configPath);
|
|
236
|
+
const target = profileName ? current.profiles?.[profileName] : current;
|
|
237
|
+
if (!target)
|
|
238
|
+
return;
|
|
239
|
+
delete target.pendingDeviceCode;
|
|
240
|
+
delete target.pendingUserCode;
|
|
241
|
+
delete target.pendingApprovalUrl;
|
|
242
|
+
delete target.pendingExpiresAt;
|
|
243
|
+
await writeStoredConfig(current, configPath);
|
|
244
|
+
});
|
|
175
245
|
}
|
|
176
246
|
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { clearStoredSession, resolveConfig, updateStoredConfig, withConfigLock, } from "./config.js";
|
|
2
|
+
import { apiError, CliError } from "./errors.js";
|
|
3
|
+
import { cliRequestHeaders } from "./http.js";
|
|
4
|
+
/**
|
|
5
|
+
* Refreshable Recess CLI sessions, client side.
|
|
6
|
+
*
|
|
7
|
+
* A sign-in stores a 15-minute access cookie plus a rotating refresh token.
|
|
8
|
+
* `ensureFreshSession` renews the cookie before a command when it is close to
|
|
9
|
+
* expiry; the API client also retries one 401 after a refresh
|
|
10
|
+
* (`api.ts`). Each refresh rotates the token, so concurrent CLI processes
|
|
11
|
+
* sharing one config serialise on a lock file and adopt whatever the winner
|
|
12
|
+
* wrote — a stale token presented later would read as theft and end the
|
|
13
|
+
* session server-side.
|
|
14
|
+
*
|
|
15
|
+
* `RECESS_CLI_COOKIE` sessions and legacy (pre-refresh) sign-ins carry no
|
|
16
|
+
* refresh token and are left alone.
|
|
17
|
+
*/
|
|
18
|
+
const REFRESH_MARGIN_MS = 2 * 60 * 1000;
|
|
19
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
function accessIsFresh(config) {
|
|
21
|
+
const expiry = config.accessExpiresAt
|
|
22
|
+
? Date.parse(config.accessExpiresAt)
|
|
23
|
+
: 0;
|
|
24
|
+
return expiry - Date.now() > REFRESH_MARGIN_MS;
|
|
25
|
+
}
|
|
26
|
+
function adopt(target, source) {
|
|
27
|
+
target.sessionCookie = source.sessionCookie;
|
|
28
|
+
target.sessionExpiresAt = source.sessionExpiresAt;
|
|
29
|
+
target.refreshToken = source.refreshToken;
|
|
30
|
+
target.accessExpiresAt = source.accessExpiresAt;
|
|
31
|
+
target.user = source.user;
|
|
32
|
+
}
|
|
33
|
+
/** Refresh unconditionally (after a 401) and update `config` in place. */
|
|
34
|
+
export async function refreshSession(config) {
|
|
35
|
+
if (config.authSource !== "config" || !config.refreshToken) {
|
|
36
|
+
throw new CliError("auth_required", "The Recess CLI session expired. Run `recess auth login`.");
|
|
37
|
+
}
|
|
38
|
+
const presented = config.refreshToken;
|
|
39
|
+
await withConfigLock(config.configPath, async () => {
|
|
40
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
41
|
+
// Another process may have rotated while we waited for the lock.
|
|
42
|
+
const latest = await resolveConfig(config.profileName);
|
|
43
|
+
if (latest.refreshToken && latest.refreshToken !== presented) {
|
|
44
|
+
adopt(config, latest);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const response = await fetch(new URL("/auth/admin-cli/refresh/", config.apiOrigin), {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: cliRequestHeaders({ "content-type": "application/json" }),
|
|
50
|
+
body: JSON.stringify({ refreshToken: presented }),
|
|
51
|
+
});
|
|
52
|
+
const body = (await response.json().catch(() => null));
|
|
53
|
+
if (response.status === 409) {
|
|
54
|
+
await sleep(500);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
// Only touch the stored session if it is still the one we refreshed; a
|
|
58
|
+
// sign-in may have replaced it (it waits on the lock, but a process
|
|
59
|
+
// that ignores the lock must not be clobbered either).
|
|
60
|
+
const stored = await resolveConfig(config.profileName);
|
|
61
|
+
if (stored.refreshToken !== presented) {
|
|
62
|
+
adopt(config, stored);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (response.status === 401) {
|
|
66
|
+
await clearStoredSession(config.profileName);
|
|
67
|
+
config.sessionCookie = undefined;
|
|
68
|
+
config.refreshToken = undefined;
|
|
69
|
+
throw new CliError("auth_required", "The Recess CLI session has ended (expired, revoked, or access changed). Run `recess auth login`.");
|
|
70
|
+
}
|
|
71
|
+
if (!response.ok)
|
|
72
|
+
throw apiError(response.status, body);
|
|
73
|
+
const cookie = response.headers.get("set-cookie")?.split(";", 1)[0];
|
|
74
|
+
if (!cookie?.includes("=")) {
|
|
75
|
+
throw new CliError("auth_failed", "The Recess API refreshed the session but returned no cookie.");
|
|
76
|
+
}
|
|
77
|
+
const refreshed = body;
|
|
78
|
+
await updateStoredConfig({
|
|
79
|
+
sessionCookie: cookie,
|
|
80
|
+
sessionExpiresAt: refreshed.expiresAt,
|
|
81
|
+
refreshToken: refreshed.refreshToken,
|
|
82
|
+
accessExpiresAt: refreshed.accessExpiresAt,
|
|
83
|
+
user: refreshed.user,
|
|
84
|
+
}, config.profileName);
|
|
85
|
+
config.sessionCookie = cookie;
|
|
86
|
+
config.sessionExpiresAt = refreshed.expiresAt;
|
|
87
|
+
config.refreshToken = refreshed.refreshToken;
|
|
88
|
+
config.accessExpiresAt = refreshed.accessExpiresAt;
|
|
89
|
+
config.user = refreshed.user;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
throw new CliError("auth_refresh_busy", "The session refresh kept racing another client; retry the command.");
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** Before a command: renew the access cookie if it is (nearly) expired. */
|
|
96
|
+
export async function ensureFreshSession(config) {
|
|
97
|
+
if (config.authSource !== "config" || !config.refreshToken)
|
|
98
|
+
return;
|
|
99
|
+
if (accessIsFresh(config))
|
|
100
|
+
return;
|
|
101
|
+
await refreshSession(config);
|
|
102
|
+
}
|
|
103
|
+
/** `auth logout`: revoke server-side (best effort), then forget locally. */
|
|
104
|
+
export async function revokeSession(config) {
|
|
105
|
+
if (config.authSource !== "config" || !config.refreshToken)
|
|
106
|
+
return false;
|
|
107
|
+
try {
|
|
108
|
+
const response = await fetch(new URL("/auth/admin-cli/logout/", config.apiOrigin), {
|
|
109
|
+
method: "POST",
|
|
110
|
+
headers: cliRequestHeaders({ "content-type": "application/json" }),
|
|
111
|
+
body: JSON.stringify({ refreshToken: config.refreshToken }),
|
|
112
|
+
signal: AbortSignal.timeout(5000),
|
|
113
|
+
});
|
|
114
|
+
if (!response.ok)
|
|
115
|
+
return false;
|
|
116
|
+
return (await response.json()).revoked === true;
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=session-refresh.js.map
|
package/package.json
CHANGED
|
@@ -44,10 +44,12 @@ For machine-readable discovery filtered to the current session's locally decoded
|
|
|
44
44
|
- Sessions default to 12 hours. Admins can use `auth login --duration 30d` locally or
|
|
45
45
|
`auth request --duration 30d` remotely; only an admin can approve a 30-day request. `auth status` and `doctor` recheck the live user role and permissions;
|
|
46
46
|
discovery stays local and may reflect the minted scope until the next login.
|
|
47
|
-
-
|
|
47
|
+
- Current CLIs hold a short-lived access token plus a refresh token and renew automatically; a
|
|
48
|
+
revoked sign-in, a disabled account, or changed access ends the session at the next request
|
|
49
|
+
(`auth_required` — sign in again). `auth logout` revokes the sign-in server-side and clears it.
|
|
48
50
|
- The default API is production. If `RECESS_CLI_API_ORIGIN` is set, state the non-default origin before acting.
|
|
49
51
|
|
|
50
|
-
Never print or paste session cookies, device codes, or config-file contents.
|
|
52
|
+
Never print or paste session cookies, refresh tokens, device codes, or config-file contents.
|
|
51
53
|
|
|
52
54
|
## Agent contract
|
|
53
55
|
|