recess-cli 3.5.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 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
- return response;
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({ sessionDuration: options.sessionDuration }),
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,15 +5,17 @@ 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";
12
12
  import { readAssignmentSelection, runGoalCurriculumCommand, } from "./commands/goal-curriculum.js";
13
13
  import { runChannelsCommand } from "./commands/channels.js";
14
14
  import { runChatLogsCommand } from "./commands/chat-logs.js";
15
+ import { runDbCommand } from "./commands/db.js";
15
16
  import { runRoomsCommand } from "./commands/rooms.js";
16
17
  import { runFamiliesCommand } from "./commands/families.js";
18
+ import { runStudentsTextsCommand, runUsersPhoneCommand, } from "./commands/phone-and-texts.js";
17
19
  import { runMasteryCommand } from "./commands/mastery.js";
18
20
  import { runOnboardingCommand } from "./commands/onboarding.js";
19
21
  import { runScheduleCommand, runMemoryFilesCommand, } from "./commands/safe-staff-operations.js";
@@ -28,6 +30,7 @@ import { cliRequestHeaders, noteServerCliVersions, requireCliRequestReason, } fr
28
30
  import { runSelfUpdate, UPGRADE_COMMAND, updateNoticeText, updateStatus, } from "./update-notice.js";
29
31
  import { requireConfirmation } from "./safety.js";
30
32
  import { installSkill, isEphemeralInstall, readBundledSkillVersion, readCliVersion, } from "./setup.js";
33
+ import { ensureFreshSession, revokeSession } from "./session-refresh.js";
31
34
  import { compareVersions, updateSkillFromServer } from "./skill-update.js";
32
35
  import { readSkillCache, writeSkillCache } from "./skills-cache.js";
33
36
  import { sanitizeWorkspaceUploadName } from "./upload-names.js";
@@ -140,7 +143,12 @@ function resolveCommandDiscovery(config) {
140
143
  if (typeof claim.exp !== "number" || !Number.isFinite(claim.exp)) {
141
144
  return unavailable;
142
145
  }
143
- if (claim.exp * 1000 <= Date.now()) {
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()) {
144
152
  return signedOut;
145
153
  }
146
154
  const scope = typeof claim.cliScope === "string" &&
@@ -1932,6 +1940,15 @@ export async function executeRecessCommand(argv, options = {}) {
1932
1940
  }
1933
1941
  }
1934
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
+ }
1935
1952
  const requestReason = noun === "auth"
1936
1953
  ? undefined
1937
1954
  : noun === "update"
@@ -2043,8 +2060,15 @@ export async function executeRecessCommand(argv, options = {}) {
2043
2060
  if (verb === "status")
2044
2061
  return sessionStatus(config);
2045
2062
  if (verb === "logout") {
2046
- await clearStoredSession(config.profileName);
2047
- return { loggedOut: true };
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 };
2048
2072
  }
2049
2073
  throw new CliError("invalid_arguments", "Use auth login, request, poll, status, or logout.");
2050
2074
  }
@@ -2674,6 +2698,9 @@ export async function executeRecessCommand(argv, options = {}) {
2674
2698
  body,
2675
2699
  })));
2676
2700
  }
2701
+ if (noun === "users" && verb === "phone") {
2702
+ return runUsersPhoneCommand({ parsed, api, writeCommand });
2703
+ }
2677
2704
  if (noun === "users" && verb === "get") {
2678
2705
  const userId = positional(parsed, 2, "user ID");
2679
2706
  return unwrap(await api.client.GET("/admin/users/{userId}", {
@@ -5092,9 +5119,15 @@ export async function executeRecessCommand(argv, options = {}) {
5092
5119
  if (noun === "chat-logs") {
5093
5120
  return runChatLogsCommand({ parsed, api, writeCommand });
5094
5121
  }
5122
+ if (noun === "db") {
5123
+ return runDbCommand({ parsed, api, writeCommand });
5124
+ }
5095
5125
  if (noun === "rooms") {
5096
5126
  return runRoomsCommand({ parsed, api, writeCommand });
5097
5127
  }
5128
+ if (noun === "students" && verb === "texts") {
5129
+ return runStudentsTextsCommand({ parsed, api, writeCommand });
5130
+ }
5098
5131
  if (noun === "students") {
5099
5132
  if (verb === "list") {
5100
5133
  const requestedScope = flagString(parsed, "scope");
@@ -13,6 +13,8 @@ const BOOLEAN_FLAGS = new Set([
13
13
  "archived",
14
14
  "cancel-subscriptions",
15
15
  "clear",
16
+ "clear-focus",
17
+ "clear-send-hour",
16
18
  "confirm",
17
19
  "confirm-destructive-changes",
18
20
  "disable-applet-follow-ups",
@@ -0,0 +1,78 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { unwrap } from "../api.js";
4
+ import { flagNumber, flagString } from "../args.js";
5
+ import { CliError } from "../errors.js";
6
+ import { positional } from "./shared.js";
7
+ const MAX_ROW_LIMIT = 5000;
8
+ async function readSql(parsed) {
9
+ const inline = parsed.positionals[2];
10
+ const file = flagString(parsed, "file");
11
+ if ((inline === undefined) === (file === undefined)) {
12
+ throw new CliError("invalid_arguments", "Pass the SQL either as one quoted argument or with --file <path>, not both.");
13
+ }
14
+ if (inline !== undefined)
15
+ return { sql: inline };
16
+ const absolutePath = path.resolve(file);
17
+ const sql = await fs.readFile(absolutePath, "utf8").catch(() => {
18
+ throw new CliError("invalid_arguments", `Cannot read ${absolutePath}.`);
19
+ });
20
+ return { sql, file: absolutePath };
21
+ }
22
+ /**
23
+ * `recess db query` — one read-only SQL query against the product database,
24
+ * for ADMINs holding `cli:db-query`; `recess db access` — list/grant/revoke
25
+ * that access, for `cli:db-query:grant` holders. The server owns every check
26
+ * (live role + access role, restricted Postgres login); a query is a read, so
27
+ * it needs no confirmation.
28
+ */
29
+ export async function runDbCommand({ parsed, api, writeCommand, }) {
30
+ const verb = parsed.positionals[1];
31
+ if (verb === "query") {
32
+ const { sql, file } = await readSql(parsed);
33
+ const rowLimit = flagNumber(parsed, "limit") ?? 100;
34
+ if (!Number.isInteger(rowLimit) ||
35
+ rowLimit < 1 ||
36
+ rowLimit > MAX_ROW_LIMIT) {
37
+ throw new CliError("invalid_arguments", `--limit must be an integer from 1 to ${MAX_ROW_LIMIT}.`);
38
+ }
39
+ const result = unwrap(await api.client.POST("/admin/db-query/query/", {
40
+ body: { sql, rowLimit },
41
+ }));
42
+ return file ? { file, ...result } : result;
43
+ }
44
+ if (verb === "access") {
45
+ const action = positional(parsed, 2, "access action (list|grant|revoke)");
46
+ if (action === "list") {
47
+ return unwrap(await api.client.GET("/admin/db-query/grants/"));
48
+ }
49
+ if (action !== "grant" && action !== "revoke") {
50
+ throw new CliError("invalid_arguments", "Use db access list|grant|revoke.");
51
+ }
52
+ const userId = flagString(parsed, "user", { required: true });
53
+ // Read-only preflight: the approval must name the exact person gaining or
54
+ // losing global database read access.
55
+ const { user } = unwrap(await api.client.GET("/admin/users/{userId}", {
56
+ params: { path: { userId } },
57
+ }));
58
+ if (action === "grant" && user.role !== "ADMIN") {
59
+ throw new CliError("invalid_arguments", `User ${userId} has role ${user.role}; database query access is ADMIN-only.`);
60
+ }
61
+ const body = { userId, action };
62
+ return writeCommand(parsed, {
63
+ action: action === "grant"
64
+ ? "grant global read-only database query access (recess db query) to this admin"
65
+ : "revoke this user's database query access",
66
+ target: { userId },
67
+ request: body,
68
+ details: {
69
+ email: user.email,
70
+ firstName: user.firstName,
71
+ lastName: user.lastName,
72
+ role: user.role,
73
+ },
74
+ }, async () => unwrap(await api.client.POST("/admin/db-query/grants/", { body })));
75
+ }
76
+ throw new CliError("invalid_arguments", "Use db query|access.");
77
+ }
78
+ //# sourceMappingURL=db.js.map
@@ -0,0 +1,167 @@
1
+ import { unwrap } from "../api.js";
2
+ import { flagString, hasFlag } from "../args.js";
3
+ import { CliError } from "../errors.js";
4
+ import { assertChoice, flagBooleanValue, flagInteger, positional, } from "./shared.js";
5
+ const TEXT_FREQUENCIES = ["all", "daily", "important"];
6
+ function fullName(user) {
7
+ return [user.firstName, user.lastName].filter(Boolean).join(" ");
8
+ }
9
+ /**
10
+ * `users phone get|set|clear` — a user's SMS/login phone number. The server
11
+ * normalizes whatever is typed to E.164 (bare numbers read as US) and rejects
12
+ * invalid or already-taken numbers, so the preview shows the raw input.
13
+ */
14
+ export async function runUsersPhoneCommand({ parsed, api, writeCommand, }) {
15
+ const action = positional(parsed, 2, "users phone action");
16
+ if (!["get", "set", "clear"].includes(action)) {
17
+ throw new CliError("invalid_arguments", "Use users phone get|set|clear.");
18
+ }
19
+ const userId = positional(parsed, 3, "user ID");
20
+ const phoneNumber = action === "set" ? flagString(parsed, "phone", { required: true }) : null;
21
+ const { user } = unwrap(await api.client.GET("/admin/users/{userId}", {
22
+ params: { path: { userId } },
23
+ }));
24
+ const current = {
25
+ userId: user.id,
26
+ name: fullName(user),
27
+ role: user.role,
28
+ phoneNumber: user.phoneNumber ?? null,
29
+ };
30
+ if (action === "get")
31
+ return current;
32
+ return writeCommand(parsed, {
33
+ action: phoneNumber === null
34
+ ? "remove the user's phone number (they stop receiving SMS and can't sign in by phone)"
35
+ : "set the user's phone number (stored as E.164 and marked unverified until their next phone sign-in)",
36
+ target: { userId: user.id },
37
+ request: { phoneNumber },
38
+ details: { current },
39
+ }, async () => {
40
+ const result = unwrap(await api.client.PATCH("/admin/users/{userId}", {
41
+ params: { path: { userId: user.id } },
42
+ body: { phoneNumber },
43
+ }));
44
+ return { ...current, phoneNumber: result.phoneNumber ?? null };
45
+ });
46
+ }
47
+ /**
48
+ * `students texts get|set|set-guardian` — the parent SMS activity-summary
49
+ * controls. Student-level: summary on/off and the end-of-day send hour (in the
50
+ * student's timezone). Per guardian: texts on/off, frequency, and the custom
51
+ * focus instructions that steer that guardian's summaries.
52
+ */
53
+ export async function runStudentsTextsCommand({ parsed, api, writeCommand, }) {
54
+ const action = positional(parsed, 2, "students texts action");
55
+ if (!["get", "set", "set-guardian"].includes(action)) {
56
+ throw new CliError("invalid_arguments", "Use students texts get|set|set-guardian.");
57
+ }
58
+ const studentId = positional(parsed, 3, "student ID");
59
+ // Validate every flag before the first request.
60
+ const studentBody = action === "set" ? studentTextsBody(parsed) : undefined;
61
+ const guardianId = action === "set-guardian" ? positional(parsed, 4, "guardian ID") : "";
62
+ const guardianBody = action === "set-guardian" ? guardianTextsBody(parsed) : undefined;
63
+ const readSettings = async () => {
64
+ const [profile, focuses] = await Promise.all([
65
+ api.client.GET("/tutor/students/{studentId}/profile", {
66
+ params: { path: { studentId } },
67
+ }),
68
+ api.client.GET("/admin/browser/students/{userId}/guardian-focuses/", {
69
+ params: { path: { userId: studentId } },
70
+ }),
71
+ ]);
72
+ const student = unwrap(profile);
73
+ return {
74
+ studentId,
75
+ timezone: student.timezone,
76
+ summaryEnabled: student.dailySummaryEnabled,
77
+ sendHour: student.dailySummarySendHour,
78
+ recipients: unwrap(focuses).guardians.map((guardian) => ({
79
+ guardianId: guardian.guardianId,
80
+ name: fullName(guardian),
81
+ email: guardian.email,
82
+ phoneNumber: guardian.phoneNumber,
83
+ isFamilyMember: guardian.isFamilyMember,
84
+ hasSubscription: guardian.hasSubscription,
85
+ textsEnabled: guardian.textsEnabled,
86
+ textFrequency: guardian.textFrequency,
87
+ focus: guardian.dailySummaryFocus,
88
+ })),
89
+ };
90
+ };
91
+ const current = await readSettings();
92
+ if (action === "get")
93
+ return current;
94
+ if (studentBody) {
95
+ return writeCommand(parsed, {
96
+ action: "update the student's parent SMS summary settings (applies to every recipient)",
97
+ target: { studentId },
98
+ request: studentBody,
99
+ details: {
100
+ current: {
101
+ summaryEnabled: current.summaryEnabled,
102
+ sendHour: current.sendHour,
103
+ timezone: current.timezone,
104
+ },
105
+ },
106
+ }, async () => {
107
+ unwrap(await api.client.PATCH("/tutor/students/{studentId}/profile", {
108
+ params: { path: { studentId } },
109
+ body: studentBody,
110
+ }));
111
+ return readSettings();
112
+ });
113
+ }
114
+ const recipient = current.recipients.find((r) => r.guardianId === guardianId) ?? null;
115
+ return writeCommand(parsed, {
116
+ action: recipient
117
+ ? "update this recipient's SMS settings for the student"
118
+ : "subscribe a new recipient to the student's SMS summaries (only ADMINs may be subscribed across families)",
119
+ target: { studentId, guardianId },
120
+ request: guardianBody,
121
+ details: { current: recipient },
122
+ }, async () => unwrap(await api.client.PATCH("/admin/browser/students/{userId}/guardian-focuses/{guardianId}/", {
123
+ params: { path: { userId: studentId, guardianId } },
124
+ body: guardianBody,
125
+ })));
126
+ }
127
+ function studentTextsBody(parsed) {
128
+ const summaryEnabled = flagBooleanValue(parsed, "summary-enabled");
129
+ const clearSendHour = hasFlag(parsed, "clear-send-hour");
130
+ const sendHour = flagInteger(parsed, "send-hour", { min: 0, max: 23 });
131
+ if (clearSendHour && sendHour !== undefined) {
132
+ throw new CliError("invalid_arguments", "Pass --send-hour or --clear-send-hour, not both.");
133
+ }
134
+ const body = {
135
+ ...(summaryEnabled !== undefined && {
136
+ dailySummaryEnabled: summaryEnabled,
137
+ }),
138
+ ...(sendHour !== undefined && { dailySummarySendHour: sendHour }),
139
+ ...(clearSendHour && { dailySummarySendHour: null }),
140
+ };
141
+ if (Object.keys(body).length === 0) {
142
+ throw new CliError("invalid_arguments", "Pass at least one of --summary-enabled, --send-hour, --clear-send-hour.");
143
+ }
144
+ return body;
145
+ }
146
+ function guardianTextsBody(parsed) {
147
+ const textsEnabled = flagBooleanValue(parsed, "texts-enabled");
148
+ const frequency = flagString(parsed, "frequency");
149
+ const focus = flagString(parsed, "focus");
150
+ const clearFocus = hasFlag(parsed, "clear-focus");
151
+ if (focus !== undefined && clearFocus) {
152
+ throw new CliError("invalid_arguments", "Pass --focus or --clear-focus, not both.");
153
+ }
154
+ const body = {
155
+ ...(textsEnabled !== undefined && { textsEnabled }),
156
+ ...(frequency !== undefined && {
157
+ textFrequency: assertChoice(frequency, TEXT_FREQUENCIES, "--frequency").toUpperCase(),
158
+ }),
159
+ ...(focus !== undefined && { dailySummaryFocus: focus }),
160
+ ...(clearFocus && { dailySummaryFocus: null }),
161
+ };
162
+ if (Object.keys(body).length === 0) {
163
+ throw new CliError("invalid_arguments", "Pass at least one of --texts-enabled, --frequency, --focus, --clear-focus.");
164
+ }
165
+ return body;
166
+ }
167
+ //# sourceMappingURL=phone-and-texts.js.map
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
- const normalized = assertProfileName(name);
93
- const stored = await readStoredConfig();
94
- await writeStoredConfig({
95
- ...stored,
96
- profiles: {
97
- ...stored.profiles,
98
- [normalized]: {
99
- ...stored.profiles?.[normalized],
100
- ...profile,
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
- const normalized = assertProfileName(name);
107
- const stored = await readStoredConfig();
108
- if (!stored.profiles?.[normalized]) {
109
- throw new CliError("unknown_profile", `Unknown Recess CLI profile ${normalized}. Run \`recess --json profile list\`.`);
110
- }
111
- await writeStoredConfig({ ...stored, activeProfile: normalized });
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
- const normalized = assertProfileName(name);
115
- const stored = await readStoredConfig();
116
- if (!stored.profiles?.[normalized]) {
117
- throw new CliError("unknown_profile", `Unknown Recess CLI profile ${normalized}.`);
118
- }
119
- const profiles = { ...stored.profiles };
120
- delete profiles[normalized];
121
- if (stored.activeProfile === normalized)
122
- delete stored.activeProfile;
123
- await writeStoredConfig({ ...stored, profiles });
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
- const configPath = defaultConfigPath();
137
- const current = await readStoredConfig(configPath);
138
- const next = profileName
139
- ? {
140
- ...current,
141
- profiles: {
142
- ...current.profiles,
143
- [assertProfileName(profileName)]: {
144
- ...current.profiles?.[profileName],
145
- ...update,
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
- : { ...current, ...update };
150
- await writeStoredConfig(next, configPath);
151
- return next;
211
+ }
212
+ : { ...current, ...update };
213
+ await writeStoredConfig(next, configPath);
214
+ return next;
215
+ });
152
216
  }
153
217
  export async function clearStoredSession(profileName) {
154
- const configPath = defaultConfigPath();
155
- const current = await readStoredConfig(configPath);
156
- const target = profileName ? current.profiles?.[profileName] : current;
157
- if (!target)
158
- return;
159
- delete target.sessionCookie;
160
- delete target.sessionExpiresAt;
161
- delete target.user;
162
- await writeStoredConfig(current, configPath);
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
- const configPath = defaultConfigPath();
166
- const current = await readStoredConfig(configPath);
167
- const target = profileName ? current.profiles?.[profileName] : current;
168
- if (!target)
169
- return;
170
- delete target.pendingDeviceCode;
171
- delete target.pendingUserCode;
172
- delete target.pendingApprovalUrl;
173
- delete target.pendingExpiresAt;
174
- await writeStoredConfig(current, configPath);
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
package/dist/help.js CHANGED
@@ -47,6 +47,9 @@ Usage:
47
47
  recess [--json] users enrollment set <user-id>
48
48
  --entity online-learning-program|recess-academy-school|partner-school|unset
49
49
  [--partner-school <school-id-or-slug>] [--confirm]
50
+ recess [--json] users phone get <user-id>
51
+ recess [--json] users phone set <user-id> --phone <number> [--confirm]
52
+ recess [--json] users phone clear <user-id> [--confirm]
50
53
  recess [--json] users lock <user-id> [--confirm]
51
54
  recess [--json] users unlock <user-id> [--confirm]
52
55
  recess [--json] users disable <user-id> [--whole-family] [--allow-billing] [--confirm]
@@ -62,6 +65,12 @@ Usage:
62
65
  recess [--json] guides invite --user <user-id> [--confirm]
63
66
  recess [--json] guardians invite --family <family-id> --email <email>
64
67
  --first-name TEXT [--last-name TEXT] [--no-invite] [--confirm]
68
+ recess [--json] students texts get <kid-id>
69
+ recess [--json] students texts set <kid-id> [--summary-enabled true|false]
70
+ [--send-hour <0-23> | --clear-send-hour] [--confirm]
71
+ recess [--json] students texts set-guardian <kid-id> <guardian-id>
72
+ [--texts-enabled true|false] [--frequency all|daily|important]
73
+ [--focus <text> | --clear-focus] [--confirm]
65
74
  recess [--json] students upload-map-scores --student <kid-id>
66
75
  --file </path/to/map-report.pdf> [--confirm]
67
76
  recess [--json] chat-logs list --student <user-id> [--limit 100] [--cursor <cursor>]
@@ -352,6 +361,10 @@ Usage:
352
361
  [--sort-order asc|desc]
353
362
  recess [--json] store-items set-status <village-store-item-id>
354
363
  --status ACTIVE|INACTIVE|COMING_SOON [--confirm]
364
+ recess [--json] db query [sql] [--file <path.sql>] [--limit 100]
365
+ recess [--json] db access list
366
+ recess [--json] db access grant --user <user-id> [--confirm]
367
+ recess [--json] db access revoke --user <user-id> [--confirm]
355
368
  recess [--json] content-library search <query> [--limit 8]
356
369
  recess [--json] content-library status <gem-id-or-url>
357
370
  recess [--json] content-library set-stage [<gem-id-or-url>...] [--file <path>]
@@ -584,6 +597,19 @@ what the account was; ADMIN and MODERATOR are not restorable from the CLI.
584
597
  Note that after a disable "users get" and "users search" no longer resolve the
585
598
  account — the confirmed write's own response is the record of what changed.
586
599
 
600
+ "users phone set" accepts any common format; the server stores E.164 (a number
601
+ without +country is read as US), rejects invalid or already-taken numbers, and
602
+ marks the new number unverified until the user's next phone sign-in.
603
+
604
+ Parent SMS summary notes: "students texts get" shows the kid-level switch and
605
+ end-of-day send hour (0-23 in the kid's timezone; unset = 18) plus every
606
+ recipient's phone, texts on/off, frequency, and focus. "set" changes the
607
+ kid-level switch/hour for all recipients. "set-guardian" changes one adult's
608
+ settings: --frequency all = per-todo texts + daily summary, daily = the daily
609
+ summary only, important = only non-routine summaries; --focus is that adult's
610
+ custom instructions for what the summary should emphasize. A recipient with no
611
+ phone number receives nothing, so check "users phone get" too.
612
+
587
613
  Onboarding notes: "status" and "intake-session" are reads — "intake-session"
588
614
  looks up the current IN_PROGRESS session without creating one (prints a "none
589
615
  yet" result when absent). "intake-session-create" is the explicit write that
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recess-cli",
3
- "version": "3.5.0",
3
+ "version": "3.7.0",
4
4
  "description": "Safe Recess administration and family AI tools from the command line.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -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
- - `auth logout` clears the stored session.
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
 
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "3.2.0",
2
+ "version": "3.3.0",
3
3
  "minCliVersion": "3.2.0"
4
4
  }