@foleo/cli 0.1.45 → 0.1.53

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/index.js CHANGED
@@ -1,4 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { loadDefaultWorkspace, saveDefaultWorkspace, } from "./workspace-default.js";
3
+ import { moveCommand, MOVE_HELP } from "./move.js";
4
+ import { loadWorkspaceBinding, saveWorkspaceBinding, } from "./workspace-binding.js";
5
+ import { pathWorkspaceCommand, PATH_WORKSPACE_HELP } from "./path-workspace.js";
6
+ import { CliEditContext, cliStateRoot } from "./edit-context.js";
7
+ import { sharedCommand, SHARED_HELP } from "./shared.js";
8
+ import { membersCommand, MEMBERS_HELP } from "./members.js";
2
9
  import { workspaceCommand, WORKSPACE_HELP } from "./workspaces.js";
3
10
  import { spawn } from "node:child_process";
4
11
  import { createHash, randomUUID } from "node:crypto";
@@ -199,9 +206,56 @@ export async function runCli(argv, deps = {
199
206
  let activeDeps = deps;
200
207
  try {
201
208
  const global = parseGlobalFlags(argv);
202
- const commandDeps = global.environment
209
+ const selectedDeps = global.environment
203
210
  ? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
204
211
  : deps;
212
+ const commandDeps = { ...selectedDeps };
213
+ const explicitWorkspace = global.workspace;
214
+ const defaultWorkspace = global.argv[0] === "login"
215
+ ? null
216
+ : await defaultWorkspaceFor(commandDeps);
217
+ const selectedWorkspace = explicitWorkspace ?? defaultWorkspace ?? undefined;
218
+ if (selectedWorkspace && !isTreeId(selectedWorkspace))
219
+ commandDeps.credentialWorkspace = selectedWorkspace;
220
+ else if (defaultWorkspace)
221
+ commandDeps.credentialWorkspace = defaultWorkspace;
222
+ const isLogin = global.argv[0] === "login";
223
+ const bindings = new Map();
224
+ commandDeps.fetch = async (input, init) => {
225
+ const url = input instanceof Request ? input.url : String(input);
226
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
227
+ const bearer = headers.get("authorization")?.match(/^Bearer (.+)$/u)?.[1];
228
+ if (bearer &&
229
+ url.startsWith(apiBase(commandDeps) + "/") &&
230
+ !isLogin &&
231
+ global.argv[0] !== "use" &&
232
+ selectedWorkspace &&
233
+ !isTreeId(selectedWorkspace)) {
234
+ let bound = bindings.get(bearer) ?? (await boundWorkspace(commandDeps, bearer));
235
+ if (!bound) {
236
+ const meResponse = await selectedDeps.fetch(`${apiBase(commandDeps)}/me`, { headers: { authorization: `Bearer ${bearer}` } });
237
+ if (!meResponse.ok)
238
+ throw apiResponseError(meResponse.status, await meResponse.json());
239
+ bound = workspaceFromMe(await meResponse.json());
240
+ }
241
+ if (!bound)
242
+ throw new LocalError("workspace_unknown", "Cannot determine this login's workspace.", { next: `Run foleo login --workspace ${selectedWorkspace}.` });
243
+ bindings.set(bearer, bound);
244
+ if (bound !== selectedWorkspace)
245
+ throw workspaceMismatch(bound, selectedWorkspace);
246
+ headers.set("Foleo-Workspace", selectedWorkspace);
247
+ }
248
+ return selectedWorkspace &&
249
+ !isLogin &&
250
+ global.argv[0] !== "use" &&
251
+ bearer &&
252
+ !isTreeId(selectedWorkspace)
253
+ ? selectedDeps.fetch(input, {
254
+ ...init,
255
+ headers: Object.fromEntries(headers),
256
+ })
257
+ : selectedDeps.fetch(input, init);
258
+ };
205
259
  activeDeps = commandDeps;
206
260
  jsonOutputs.set(commandDeps, wantsJson);
207
261
  const [command, ...rest] = global.argv;
@@ -215,7 +269,13 @@ export async function runCli(argv, deps = {
215
269
  command === "-h" ||
216
270
  (command === "settings" &&
217
271
  (rest.includes("--help") || rest.includes("-h")))) {
218
- commandDeps.stdout(help() + "\n" + WORKSPACE_HELP);
272
+ commandDeps.stdout(PATH_WORKSPACE_HELP +
273
+ "\n" +
274
+ help() +
275
+ "\n" +
276
+ WORKSPACE_HELP +
277
+ "\n" +
278
+ MEMBERS_HELP);
219
279
  return 0;
220
280
  }
221
281
  if (command === "--version" || command === "-v" || command === "version") {
@@ -272,6 +332,117 @@ export async function runCli(argv, deps = {
272
332
  },
273
333
  });
274
334
  }
335
+ if (["save", "read", "share", "ls"].includes(command) ||
336
+ (command === "list" &&
337
+ (rest.some((arg) => arg.startsWith("/")) ||
338
+ rest.includes("--workspace") ||
339
+ selectedWorkspace !== undefined))) {
340
+ if (rest.includes("--help") || rest.includes("-h")) {
341
+ commandDeps.stdout(PATH_WORKSPACE_HELP);
342
+ return 0;
343
+ }
344
+ const credential = await resolveCredentialWithSource(commandDeps);
345
+ if (!credential)
346
+ throw new LocalError("credential_missing", "No Foleo credential found.", { next: "Sign in or set FOLEO_TOKEN." });
347
+ const sessionAt = rest.indexOf("--session"), session = sessionAt >= 0 ? (rest[sessionAt + 1] ?? "default") : "default";
348
+ return await pathWorkspaceCommand(command === "list" ? "ls" : command, rest, {
349
+ stdout: commandDeps.stdout,
350
+ readStdin: async () => {
351
+ if (commandDeps.readStdin)
352
+ return commandDeps.readStdin();
353
+ const chunks = [];
354
+ let size = 0;
355
+ for await (const chunk of process.stdin) {
356
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
357
+ size += bytes.length;
358
+ if (size > 65536)
359
+ throw new UsageError("Use foleo workspace put for large or binary input.", "transport_requires_advanced");
360
+ chunks.push(bytes);
361
+ }
362
+ try {
363
+ return new TextDecoder("utf-8", {
364
+ fatal: true,
365
+ ignoreBOM: true,
366
+ }).decode(Buffer.concat(chunks));
367
+ }
368
+ catch {
369
+ throw new UsageError("Use foleo workspace put for binary input.", "transport_requires_advanced");
370
+ }
371
+ },
372
+ state: new CliEditContext(cliStateRoot(commandDeps.env), apiBase(commandDeps) +
373
+ ":" +
374
+ createHash("sha256").update(credential.token).digest("hex") +
375
+ ":" +
376
+ session),
377
+ request: async (path, init) => {
378
+ const response = await commandDeps.fetch(apiBase(commandDeps) + path, {
379
+ ...init,
380
+ headers: {
381
+ ...Object.fromEntries(new Headers(init?.headers)),
382
+ authorization: `Bearer ${credential.token}`,
383
+ },
384
+ });
385
+ return response;
386
+ },
387
+ });
388
+ }
389
+ if (command === "mv") {
390
+ if (rest.includes("--help") || rest.includes("-h")) {
391
+ commandDeps.stdout(MOVE_HELP);
392
+ return 0;
393
+ }
394
+ if (selectedWorkspace) {
395
+ const credential = await resolveCredentialWithSource(commandDeps);
396
+ if (credential) {
397
+ const bound = (await boundWorkspace(commandDeps, credential.token)) ??
398
+ workspaceFromMe(await requestJson(commandDeps, "/me", {
399
+ method: "GET",
400
+ body: undefined,
401
+ }));
402
+ if (!bound)
403
+ throw new LocalError("workspace_unknown", "Cannot verify this login’s source workspace.");
404
+ if (bound !== selectedWorkspace)
405
+ throw workspaceMismatch(bound, selectedWorkspace);
406
+ }
407
+ }
408
+ return await moveCommand(rest, {
409
+ stdout: commandDeps.stdout,
410
+ stderr: commandDeps.stderr,
411
+ ...(commandDeps.confirm ? { confirm: commandDeps.confirm } : {}),
412
+ ...(commandDeps.sleep ? { sleep: commandDeps.sleep } : {}),
413
+ request: (path, method, body) => requestJson(commandDeps, path, { method, body }),
414
+ });
415
+ }
416
+ if (command === "shared")
417
+ return await sharedCommand(rest, {
418
+ stdout: commandDeps.stdout,
419
+ request: (path) => requestJson(commandDeps, path, { method: "GET", body: undefined }),
420
+ });
421
+ if (command === "members" || command === "invites")
422
+ return await membersCommand(command, rest, {
423
+ stdout: commandDeps.stdout,
424
+ ...(commandDeps.confirm ? { confirm: commandDeps.confirm } : {}),
425
+ request: (path, method, body) => requestJson(commandDeps, path, { method, body }),
426
+ workspace: async () => {
427
+ const credential = await resolveCredentialWithSource(commandDeps);
428
+ if (!credential)
429
+ throw new LocalError("credential_missing", "Sign in first.");
430
+ const bound = (await boundWorkspace(commandDeps, credential.token)) ??
431
+ workspaceFromMe(await requestJson(commandDeps, "/me", {
432
+ method: "GET",
433
+ body: undefined,
434
+ }));
435
+ if (!bound)
436
+ throw new LocalError("workspace_unknown", "Run foleo login --workspace <handle>.");
437
+ if (selectedWorkspace && selectedWorkspace !== bound)
438
+ throw workspaceMismatch(bound, selectedWorkspace);
439
+ return bound;
440
+ },
441
+ });
442
+ if (command === "use")
443
+ return await useWorkspace(rest, commandDeps);
444
+ if (command === "workspaces")
445
+ return await workspaceOrganizations(rest, commandDeps);
275
446
  if (command === "publish")
276
447
  return await publish(rest, commandDeps);
277
448
  if (command === "update")
@@ -326,8 +497,13 @@ export async function runCli(argv, deps = {
326
497
  return await settingsCommand(rest, commandDeps);
327
498
  if (command === "limits")
328
499
  return await limitsCommand(rest, commandDeps);
500
+ if (command === "login" &&
501
+ (rest.includes("--help") || rest.includes("-h"))) {
502
+ commandDeps.stdout("Usage: foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]\nThe sign-in URL is always printed to stderr; --no-browser skips opening it. The approving browser must be on this computer (the callback is local).\nThe browser confirms the workspace. This replaces only the chosen workspace login for this API.\n");
503
+ return 0;
504
+ }
329
505
  if (command === "login")
330
- return await login(rest, commandDeps);
506
+ return await login(rest, commandDeps, explicitWorkspace);
331
507
  if (command === "logout")
332
508
  return await logout(rest, commandDeps);
333
509
  if (command === "list")
@@ -675,6 +851,12 @@ async function doctor(args, deps) {
675
851
  checks.push({ key: "credential", status: "pass" });
676
852
  try {
677
853
  const me = await requestJsonWithToken(deps, "/me", credential.token, { method: "GET", body: undefined });
854
+ const handle = workspaceFromMe(me) ?? (await boundWorkspace(deps, credential.token));
855
+ checks.push({
856
+ key: "workspace",
857
+ status: handle ? "pass" : "warn",
858
+ message: handle ?? "Unknown; run foleo login to record the bound workspace.",
859
+ });
678
860
  const bootstrapRequired = me.bootstrapRequired === true;
679
861
  const scopes = stringArray(me.scopes);
680
862
  const entitlements = stringArray(me.entitlements);
@@ -731,6 +913,7 @@ async function doctor(args, deps) {
731
913
  checks.push(await updateCheck(deps, version));
732
914
  const result = {
733
915
  ok: !checks.some((check) => check.status === "fail"),
916
+ workspaceHandle: checks.find((check) => check.key === "workspace" && check.status === "pass")?.message ?? null,
734
917
  cliVersion: version,
735
918
  environment: info.name,
736
919
  apiOrigin: new URL(info.apiBase).origin,
@@ -748,10 +931,12 @@ function stringArray(value) {
748
931
  ? value
749
932
  : [];
750
933
  }
751
- async function login(args, deps) {
934
+ async function login(args, deps, workspace) {
935
+ if (workspace && isTreeId(workspace))
936
+ throw new UsageError("login --workspace requires a handle, not a tree ID.");
752
937
  const parsed = parseFlags(args, { allowLoginScopeFlags: true });
753
938
  if (parsed.positionals.length > 0)
754
- throw new Error("Usage: foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
939
+ throw new Error("Usage: foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
755
940
  const base = apiBase(deps);
756
941
  const workspaceScopes = [
757
942
  ...(parsed.allowWorkspaces || parsed.allowWorkspaceSharing
@@ -762,23 +947,34 @@ async function login(args, deps) {
762
947
  ];
763
948
  const target = new URL(base);
764
949
  if (workspaceScopes.length &&
765
- !(target.origin === "https://api-staging.foleo.app" ||
950
+ !(
951
+ // Spec 114 G0: production is allowed; the server's allowlist decides
952
+ // who is actually offered workspace permissions.
953
+ (target.origin === "https://api.foleo.app" ||
954
+ target.origin === "https://api-staging.foleo.app" ||
766
955
  (target.protocol === "http:" &&
767
- ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname))))
768
- throw new LocalError("workspace_login_unavailable", "Workspace login flags are available only on staging/local. Production workspace access is disabled.", {
769
- next: "Use FOLEO_ENV=staging foleo login --allow-workspaces (add --allow-workspace-sharing for sharing).",
956
+ ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname)))))
957
+ throw new LocalError("workspace_login_unavailable", "Workspace login flags are available only against Foleo's own API.", {
958
+ next: "Sign in against production or --staging with --allow-workspaces (add --allow-workspace-sharing for sharing).",
770
959
  });
771
960
  announceApi(deps, parsed.json);
772
961
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
773
962
  const saveCredential = deps.saveCredential ?? saveKeychainCredential;
774
963
  const deleteCredential = deps.deleteCredential ?? deleteKeychainCredential;
964
+ const storeCredential = (token) => credentialHandle
965
+ ? saveCredential(base, token, credentialHandle)
966
+ : saveCredential(base, token);
967
+ const clearCredential = () => credentialHandle
968
+ ? deleteCredential(base, credentialHandle)
969
+ : deleteCredential(base);
775
970
  const createCallback = deps.createBrowserCallback ?? createLoopbackCallback;
776
971
  const openUrl = deps.openUrl ?? openBrowser;
777
972
  await verifyStore(base);
778
973
  // The Keychain entry this login overwrites holds the only copy of the
779
974
  // previous key's token. Keep it, so a failed login can put it back and a
780
975
  // successful one can revoke that key instead of stranding it (ADR 0044).
781
- const previousToken = await (deps.loadCredential ?? loadKeychainCredential)(base);
976
+ let credentialHandle = workspace;
977
+ let previousToken = null;
782
978
  const nonce = createHash("sha256").update(randomUUID()).digest("hex");
783
979
  const callback = await createCallback(nonce);
784
980
  let appSessionToken = null;
@@ -789,14 +985,23 @@ async function login(args, deps) {
789
985
  nonce,
790
986
  callbackUrl: callback.callbackUrl,
791
987
  clientKind: "cli",
988
+ ...(workspace ? { workspaceHandle: workspace } : {}),
792
989
  ...(workspaceScopes.length ? { workspaceScopes } : {}),
793
990
  });
794
- deps.stderr("Opening Foleo sign-in in your browser...\n");
795
- try {
796
- await openUrl(start.authorizeUrl);
991
+ if (workspace) {
992
+ const authorize = new URL(start.authorizeUrl);
993
+ // The server stores this hint with request_id; query hints are not binding authority.
994
+ start.authorizeUrl = authorize.href;
797
995
  }
798
- catch {
799
- deps.stderr(`Open this URL to continue:\n${start.authorizeUrl}\n`);
996
+ deps.stderr(`Open this link to sign in: ${start.authorizeUrl}\n`);
997
+ if (!parsed.noBrowser) {
998
+ deps.stderr("Opening Foleo sign-in in your browser...\n");
999
+ try {
1000
+ await openUrl(start.authorizeUrl);
1001
+ }
1002
+ catch {
1003
+ // The URL above also works when the browser cannot be opened.
1004
+ }
800
1005
  }
801
1006
  const code = await callback.waitForCode();
802
1007
  const exchanged = await requestPublicJson(deps, "/desktop/handoff/exchange", {
@@ -806,6 +1011,11 @@ async function login(args, deps) {
806
1011
  sessionTtlSeconds: 600,
807
1012
  });
808
1013
  appSessionToken = exchanged.token;
1014
+ credentialHandle =
1015
+ exchanged.org.kind === "shared" ? exchanged.org.handle : workspace;
1016
+ previousToken = await (deps.loadCredential ?? loadKeychainCredential)(base, credentialHandle);
1017
+ if (workspace && exchanged.org.handle !== workspace)
1018
+ throw workspaceMismatch(exchanged.org.handle, workspace);
809
1019
  const key = await requestJsonWithToken(deps, "/keys", appSessionToken, {
810
1020
  method: "POST",
811
1021
  body: {
@@ -813,22 +1023,37 @@ async function login(args, deps) {
813
1023
  // `--allow-delete` is now redundant and accepted silently, so existing
814
1024
  // scripts and docs keep working.
815
1025
  scopes: [
816
- ...CLI_KEY_SCOPES,
817
- ...(parsed.allowPurge ? ["artifacts:purge"] : []),
1026
+ ...CLI_KEY_SCOPES.filter((scope) => exchanged.actor?.role === "viewer"
1027
+ ? scope === "artifacts:read"
1028
+ : ["publisher", "admin"].includes(exchanged.actor?.role ?? "")
1029
+ ? ![
1030
+ "artifacts:delete",
1031
+ "artifacts:purge",
1032
+ "keys:read",
1033
+ ].includes(scope)
1034
+ : true),
1035
+ ...(parsed.allowPurge &&
1036
+ !["viewer", "publisher", "admin"].includes(exchanged.actor?.role ?? "")
1037
+ ? ["artifacts:purge"]
1038
+ : []),
818
1039
  ...workspaceScopes.filter((scope) => exchanged.approvedWorkspaceScopes?.includes(scope)),
819
1040
  ],
820
1041
  deferredActivation: true,
821
1042
  },
822
1043
  });
823
1044
  try {
824
- await saveCredential(base, key.token);
1045
+ await storeCredential(key.token);
825
1046
  await requestJsonWithToken(deps, `/keys/${encodeURIComponent(key.id)}/activate`, appSessionToken, { method: "POST", body: {} });
1047
+ await (deps.saveWorkspaceBinding ??
1048
+ ((api, token, handle) => saveWorkspaceBinding(deps.env, api, token, handle)))(base, key.token, exchanged.org.handle);
1049
+ if (!workspace && credentialHandle)
1050
+ await persistDefaultWorkspace(deps, credentialHandle);
826
1051
  }
827
1052
  catch (error) {
828
1053
  const restored = previousToken !== null &&
829
- (await saveCredential(base, previousToken).then(() => true, () => false));
1054
+ (await storeCredential(previousToken).then(() => true, () => false));
830
1055
  if (!restored) {
831
- await deleteCredential(base).catch(() => undefined);
1056
+ await clearCredential().catch(() => undefined);
832
1057
  // The previous token is now gone from the Keychain for good. Retire its
833
1058
  // key while this process still holds the token, or it stays live with
834
1059
  // no one able to use or revoke it.
@@ -843,6 +1068,7 @@ async function login(args, deps) {
843
1068
  loginResult = {
844
1069
  ok: true,
845
1070
  org: exchanged.org.handle,
1071
+ workspaceHandle: exchanged.org.handle,
846
1072
  keyId: key.id,
847
1073
  scopes: key.scopes,
848
1074
  replacedCredential: previousToken === null
@@ -915,7 +1141,18 @@ async function logout(args, deps) {
915
1141
  throw new Error("Usage: foleo logout [--no-revoke] [--json]");
916
1142
  const base = apiBase(deps);
917
1143
  announceApi(deps, parsed.json);
918
- const token = await (deps.loadCredential ?? loadKeychainCredential)(base);
1144
+ let credentialHandle = deps.credentialWorkspace;
1145
+ const load = deps.loadCredential ?? loadKeychainCredential;
1146
+ let token = credentialHandle
1147
+ ? await load(base, credentialHandle)
1148
+ : await load(base);
1149
+ if (!token && credentialHandle) {
1150
+ const legacy = await (deps.loadCredential ?? loadKeychainCredential)(base);
1151
+ if (legacy && (await boundWorkspace(deps, legacy)) === credentialHandle) {
1152
+ token = legacy;
1153
+ credentialHandle = undefined;
1154
+ }
1155
+ }
919
1156
  const revocation = token === null
920
1157
  ? null
921
1158
  : noRevoke
@@ -923,7 +1160,11 @@ async function logout(args, deps) {
923
1160
  : await revokeOwnCredential(deps, token);
924
1161
  if (token !== null) {
925
1162
  try {
926
- await (deps.deleteCredential ?? deleteKeychainCredential)(base);
1163
+ const remove = deps.deleteCredential ?? deleteKeychainCredential;
1164
+ if (credentialHandle)
1165
+ await remove(base, credentialHandle);
1166
+ else
1167
+ await remove(base);
927
1168
  }
928
1169
  catch (error) {
929
1170
  throw new LocalError("keychain_delete_failed", `Unable to remove the CLI credential from macOS Keychain: ${errorMessage(error)}`, {
@@ -3287,11 +3528,12 @@ async function whoami(args, deps) {
3287
3528
  method: "GET",
3288
3529
  body: undefined,
3289
3530
  });
3531
+ const workspaceHandle = workspaceFromMe(result) ?? (await boundWorkspace(deps, credential.token));
3290
3532
  if (parsed.json) {
3291
- deps.stdout(`${JSON.stringify({ ...(isRecord(result) ? result : { me: result }), credentialSource: credential.source, environment: environmentInfo(deps) }, null, 2)}\n`);
3533
+ deps.stdout(`${JSON.stringify({ workspaceHandle, ...(isRecord(result) ? result : { me: result }), credentialSource: credential.source, environment: environmentInfo(deps) }, null, 2)}\n`);
3292
3534
  return 0;
3293
3535
  }
3294
- deps.stdout(`${whoamiText(result, credential.source)}Environment: ${environmentInfo(deps).name}\nAPI: ${environmentInfo(deps).apiBase}\n`);
3536
+ deps.stdout(`${whoamiText(result, credential.source)}Workspace: ${workspaceHandle ?? "unknown (run foleo login)"}\nEnvironment: ${environmentInfo(deps).name}\nAPI: ${environmentInfo(deps).apiBase}\n`);
3295
3537
  return 0;
3296
3538
  }
3297
3539
  function environmentCommand(args, deps) {
@@ -3824,38 +4066,42 @@ async function resolveCredentialWithSource(deps) {
3824
4066
  if (deps.env.FOLEO_TOKEN)
3825
4067
  return { token: deps.env.FOLEO_TOKEN, source: "env" };
3826
4068
  const base = apiBase(deps);
3827
- const cliToken = await (deps.loadCredential ?? loadKeychainCredential)(base);
4069
+ const load = deps.loadCredential ?? loadKeychainCredential;
4070
+ const cliToken = deps.credentialWorkspace
4071
+ ? ((await load(base, deps.credentialWorkspace)) ?? (await load(base)))
4072
+ : await load(base);
3828
4073
  if (cliToken)
3829
4074
  return { token: cliToken, source: "cli-keychain" };
3830
4075
  return null;
3831
4076
  }
3832
- function keychainAccount(apiBaseUrl) {
3833
- return createHash("sha256").update(apiBaseUrl).digest("hex");
4077
+ export function keychainAccount(apiBaseUrl, handle) {
4078
+ return (createHash("sha256").update(apiBaseUrl).digest("hex") +
4079
+ (handle ? `:workspace:${handle}` : ""));
3834
4080
  }
3835
4081
  async function keyringAsyncEntry() {
3836
4082
  const module = (await Function("specifier", "return import(specifier)")("@napi-rs/keyring"));
3837
4083
  return module.AsyncEntry;
3838
4084
  }
3839
- async function keychainEntry(apiBaseUrl, suffix = "") {
4085
+ async function keychainEntry(apiBaseUrl, handle, suffix = "") {
3840
4086
  const AsyncEntry = await keyringAsyncEntry();
3841
- return new AsyncEntry(KEYCHAIN_SERVICE, `${keychainAccount(apiBaseUrl)}${suffix}`);
4087
+ return new AsyncEntry(KEYCHAIN_SERVICE, `${keychainAccount(apiBaseUrl, handle)}${suffix}`);
3842
4088
  }
3843
- async function loadKeychainCredential(apiBaseUrl) {
4089
+ async function loadKeychainCredential(apiBaseUrl, handle) {
3844
4090
  try {
3845
- return (await (await keychainEntry(apiBaseUrl)).getPassword()) ?? null;
4091
+ return ((await (await keychainEntry(apiBaseUrl, handle)).getPassword()) ?? null);
3846
4092
  }
3847
4093
  catch {
3848
4094
  return null;
3849
4095
  }
3850
4096
  }
3851
- async function saveKeychainCredential(apiBaseUrl, token) {
3852
- await (await keychainEntry(apiBaseUrl)).setPassword(token);
4097
+ async function saveKeychainCredential(apiBaseUrl, token, handle) {
4098
+ await (await keychainEntry(apiBaseUrl, handle)).setPassword(token);
3853
4099
  }
3854
- async function deleteKeychainCredential(apiBaseUrl) {
3855
- await (await keychainEntry(apiBaseUrl)).deleteCredential();
4100
+ async function deleteKeychainCredential(apiBaseUrl, handle) {
4101
+ await (await keychainEntry(apiBaseUrl, handle)).deleteCredential();
3856
4102
  }
3857
4103
  async function verifyKeychainWritable(apiBaseUrl) {
3858
- const entry = await keychainEntry(apiBaseUrl, ":probe");
4104
+ const entry = await keychainEntry(apiBaseUrl, undefined, ":probe");
3859
4105
  const probe = `foleo_probe_${randomUUID()}`;
3860
4106
  try {
3861
4107
  await entry.setPassword(probe);
@@ -4223,6 +4469,7 @@ function parseFlags(args, options = {}) {
4223
4469
  let acceptHostingRisk = false;
4224
4470
  let publishSeparately = false;
4225
4471
  let allowDelete = false;
4472
+ let noBrowser = false;
4226
4473
  let allowPurge = false;
4227
4474
  let allowWorkspaces = false;
4228
4475
  let allowWorkspaceSharing = false;
@@ -4382,6 +4629,12 @@ function parseFlags(args, options = {}) {
4382
4629
  throw new Error("--cursor requires a value");
4383
4630
  continue;
4384
4631
  }
4632
+ if (arg === "--no-browser") {
4633
+ if (!options.allowLoginScopeFlags)
4634
+ throw new UsageError("--no-browser is valid only with login");
4635
+ noBrowser = true;
4636
+ continue;
4637
+ }
4385
4638
  if (arg === "--allow-delete") {
4386
4639
  if (!options.allowLoginScopeFlags)
4387
4640
  throw new Error("--allow-delete is valid only with login");
@@ -4426,6 +4679,7 @@ function parseFlags(args, options = {}) {
4426
4679
  acceptHostingRisk,
4427
4680
  publishSeparately,
4428
4681
  allowDelete,
4682
+ noBrowser,
4429
4683
  allowPurge,
4430
4684
  allowWorkspaces,
4431
4685
  allowWorkspaceSharing,
@@ -4440,13 +4694,204 @@ function parseFlags(args, options = {}) {
4440
4694
  ...(cursor === undefined ? {} : { cursor }),
4441
4695
  };
4442
4696
  }
4697
+ async function defaultWorkspaceFor(deps) {
4698
+ return (deps.loadDefaultWorkspace ?? ((api) => loadDefaultWorkspace(deps.env, api)))(apiBase(deps));
4699
+ }
4700
+ async function persistDefaultWorkspace(deps, handle) {
4701
+ await (deps.saveDefaultWorkspace ??
4702
+ ((api, h) => saveDefaultWorkspace(deps.env, api, h)))(apiBase(deps), handle);
4703
+ }
4704
+ async function useWorkspace(args, deps) {
4705
+ const handles = args.filter((a) => a !== "--json");
4706
+ if (handles.length !== 1 || !/^[a-z0-9-]{1,63}$/u.test(handles[0]))
4707
+ throw new UsageError("Usage: foleo use <handle> [--json]");
4708
+ const handle = handles[0], base = apiBase(deps), load = deps.loadCredential ?? loadKeychainCredential;
4709
+ const named = await load(base, handle), legacy = named ? null : await load(base), token = named ?? legacy;
4710
+ if (!token)
4711
+ throw new LocalError("credential_missing", `Run foleo login --workspace ${handle}.`);
4712
+ // Deliberately bypass the command's current default header. Live identity must
4713
+ // match before persisting the hint, even if local binding metadata is stale.
4714
+ const response = await deps.fetch(base + "/me", {
4715
+ headers: { authorization: `Bearer ${token}`, "Foleo-Workspace": handle },
4716
+ });
4717
+ if (!response.ok)
4718
+ throw apiResponseError(response.status, await response.json());
4719
+ const bound = workspaceFromMe(await response.json());
4720
+ if (bound !== handle)
4721
+ throw workspaceMismatch(bound ?? "unknown", handle);
4722
+ await (deps.saveWorkspaceBinding ??
4723
+ ((api, token, h) => saveWorkspaceBinding(deps.env, api, token, h)))(base, token, handle);
4724
+ await persistDefaultWorkspace(deps, handle);
4725
+ deps.stdout(args.includes("--json")
4726
+ ? JSON.stringify({ defaultWorkspaceHandle: handle }) + "\n"
4727
+ : `Default workspace: ${handle}\n`);
4728
+ return 0;
4729
+ }
4730
+ function isTreeId(value) {
4731
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value);
4732
+ }
4733
+ function workspaceFromMe(value) {
4734
+ const org = nestedRecord(value, "org");
4735
+ return ((org ? stringField(org, "handle") : null) ??
4736
+ (isRecord(value) ? stringField(value, "orgHandle") : null));
4737
+ }
4738
+ async function boundWorkspace(deps, token) {
4739
+ return (deps.loadWorkspaceBinding ??
4740
+ ((api, credential) => loadWorkspaceBinding(deps.env, api, credential)))(apiBase(deps), token);
4741
+ }
4742
+ function workspaceMismatch(bound, requested) {
4743
+ return new LocalError("workspace_mismatch", `This login is for ${bound}. Run foleo login --workspace ${requested}.`, {
4744
+ next: `Run foleo login --workspace ${requested}.`,
4745
+ context: {
4746
+ boundWorkspaceHandle: bound,
4747
+ requestedWorkspaceHandle: requested,
4748
+ },
4749
+ });
4750
+ }
4751
+ const WORKSPACES_HELP = `Usage: foleo workspaces [ls] [--json]
4752
+ foleo workspaces create <name> [--address <handle>] [--mutation-id <id>] [--json]
4753
+ Lists workspace addresses, names, roles, stored logins and the default; * marks the active login.
4754
+ foleo use <handle> [--json]
4755
+ Requires workspace read consent (create also needs write): foleo login --allow-workspaces.
4756
+ Creation keeps this login in its current workspace. To use the new one:
4757
+ foleo login --workspace <handle>
4758
+ `;
4759
+ async function workspaceOrganizations(args, deps) {
4760
+ if (args.includes("--help") || args.includes("-h")) {
4761
+ deps.stdout(WORKSPACES_HELP);
4762
+ return 0;
4763
+ }
4764
+ const flags = new Map();
4765
+ const positional = [];
4766
+ for (let i = 0; i < args.length; i++) {
4767
+ const arg = args[i];
4768
+ if (arg === "--json")
4769
+ continue;
4770
+ if (arg.startsWith("--")) {
4771
+ const value = args[++i];
4772
+ if (!["--address", "--mutation-id"].includes(arg) ||
4773
+ !value ||
4774
+ value.startsWith("--") ||
4775
+ flags.has(arg))
4776
+ throw new UsageError(WORKSPACES_HELP);
4777
+ flags.set(arg, value);
4778
+ }
4779
+ else
4780
+ positional.push(arg);
4781
+ }
4782
+ const create = positional[0] === "create";
4783
+ if (create
4784
+ ? positional.length !== 2
4785
+ : positional.length > 1 ||
4786
+ (positional.length === 1 && positional[0] !== "ls") ||
4787
+ flags.size > 0)
4788
+ throw new UsageError(WORKSPACES_HELP);
4789
+ const name = positional[1]?.trim();
4790
+ const handle = flags.get("--address") ??
4791
+ name
4792
+ ?.normalize("NFKD")
4793
+ .replace(/[\u0300-\u036f]/gu, "")
4794
+ .toLowerCase()
4795
+ .replace(/[^a-z0-9]+/gu, "-")
4796
+ .replace(/^-+|-+$/gu, "");
4797
+ if (create &&
4798
+ (!name || name.length > 120 || !handle || !/^[a-z0-9-]+$/u.test(handle)))
4799
+ throw new UsageError("Use a name (1–120 characters) and --address with a lowercase handle.");
4800
+ try {
4801
+ if (create) {
4802
+ const result = await requestJson(deps, "/me/workspaces", {
4803
+ method: "POST",
4804
+ body: {
4805
+ name,
4806
+ handle,
4807
+ clientMutationId: flags.get("--mutation-id") ?? randomUUID(),
4808
+ },
4809
+ });
4810
+ if (args.includes("--json"))
4811
+ deps.stdout(JSON.stringify(result, null, 2) + "\n");
4812
+ else
4813
+ deps.stdout(`Created ${result.workspace.name}: ${result.workspace.handle}.foleo.site\nThis login stays in ${result.boundWorkspaceHandle}. Run foleo login --workspace ${result.workspace.handle} to work in the new workspace.\n`);
4814
+ }
4815
+ else {
4816
+ const listing = await requestJson(deps, "/me/workspaces", { method: "GET", body: undefined });
4817
+ const workspaces = Array.isArray(listing) ? listing : listing.workspaces;
4818
+ const credential = await resolveCredentialWithSource(deps);
4819
+ let bound = !Array.isArray(listing)
4820
+ ? listing.boundWorkspaceHandle
4821
+ : credential
4822
+ ? await boundWorkspace(deps, credential.token)
4823
+ : null;
4824
+ if (!bound)
4825
+ bound = workspaceFromMe(await requestJson(deps, "/me", { method: "GET", body: undefined }));
4826
+ const defaultHandle = (await defaultWorkspaceFor(deps)) ??
4827
+ workspaces.find((w) => w.kind === "personal")?.handle ??
4828
+ bound;
4829
+ const stored = new Map();
4830
+ const load = deps.loadCredential ?? loadKeychainCredential;
4831
+ const legacy = await load(apiBase(deps));
4832
+ const legacyHandle = legacy ? await boundWorkspace(deps, legacy) : null;
4833
+ for (const w of workspaces)
4834
+ stored.set(w.handle, !!(await load(apiBase(deps), w.handle)) ||
4835
+ (legacy !== null &&
4836
+ (legacyHandle === w.handle ||
4837
+ (!legacyHandle && w.kind === "personal"))));
4838
+ if (args.includes("--json"))
4839
+ deps.stdout(JSON.stringify({
4840
+ defaultWorkspaceHandle: defaultHandle,
4841
+ workspaces: workspaces.map((w) => ({
4842
+ ...w,
4843
+ bound: w.handle === bound,
4844
+ storedLogin: stored.get(w.handle),
4845
+ default: w.handle === defaultHandle,
4846
+ })),
4847
+ boundWorkspaceHandle: bound,
4848
+ }, null, 2) + "\n");
4849
+ else {
4850
+ for (const w of workspaces)
4851
+ deps.stdout(`${w.handle === bound ? "*" : " "} ${w.handle}\t${w.name}\t${w.role}\t${stored.get(w.handle) ? "logged in" : "no stored login"}${w.handle === defaultHandle ? " (default)" : ""}\n`);
4852
+ deps.stdout(bound
4853
+ ? `* This login is bound to ${bound}.\n`
4854
+ : "Bound workspace unknown; run foleo whoami.\n");
4855
+ }
4856
+ }
4857
+ }
4858
+ catch (error) {
4859
+ if (error instanceof FoleoError && error.code === "session_required")
4860
+ throw new LocalError("session_required", "This server does not allow CLI credentials to list or create workspaces yet.", {
4861
+ next: "Use Foleo's web workspace picker. CLI access needs server support.",
4862
+ });
4863
+ throw error;
4864
+ }
4865
+ return 0;
4866
+ }
4443
4867
  function parseGlobalFlags(argv) {
4444
- const selected = argv.filter((arg) => ["--production", "--staging", "--local"].includes(arg));
4868
+ let workspace;
4869
+ const filtered = [];
4870
+ for (let i = 0; i < argv.length; i++) {
4871
+ if (argv[i] !== "--workspace") {
4872
+ filtered.push(argv[i]);
4873
+ continue;
4874
+ }
4875
+ const value = argv[++i];
4876
+ if (workspace ||
4877
+ !value ||
4878
+ (!isTreeId(value) && !/^[a-z0-9-]+$/u.test(value)))
4879
+ throw new UsageError("--workspace requires one lowercase handle or UUID tree ID.");
4880
+ workspace = value;
4881
+ }
4882
+ const command = filtered.find((arg) => !["--production", "--staging", "--local"].includes(arg));
4883
+ if (workspace && isTreeId(workspace)) {
4884
+ if (!["save", "read", "share", "ls", "list"].includes(command ?? ""))
4885
+ throw new UsageError("A UUID --workspace tree ID is supported only on cloud-file commands.");
4886
+ filtered.push("--workspace", workspace);
4887
+ }
4888
+ const selected = filtered.filter((arg) => ["--production", "--staging", "--local"].includes(arg));
4445
4889
  if (new Set(selected).size > 1)
4446
4890
  throw new Error("Choose only one of --production, --staging, or --local");
4447
4891
  const environment = selected[0]?.slice(2);
4448
4892
  return {
4449
- argv: argv.filter((arg) => !["--production", "--staging", "--local"].includes(arg)),
4893
+ ...(workspace ? { workspace } : {}),
4894
+ argv: filtered.filter((arg) => !["--production", "--staging", "--local"].includes(arg)),
4450
4895
  ...(environment ? { environment } : {}),
4451
4896
  };
4452
4897
  }
@@ -4454,10 +4899,20 @@ function help() {
4454
4899
  return [
4455
4900
  "Usage:",
4456
4901
  " foleo --help",
4457
- " foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
4902
+ " foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
4903
+ " Login always prints the sign-in URL to stderr; --no-browser skips opening it.",
4904
+ " The approving browser must be on this computer (the callback is local).",
4458
4905
  " foleo logout [--no-revoke] [--json]",
4459
- " Workspace login flags are staging/local only; browser consent starts unchecked.",
4906
+ " Workspace access is offered only to invited alpha accounts; role-permitted requested browser permissions start checked; untick to decline.",
4460
4907
  " --allow-workspaces requests read + write; --allow-workspace-sharing requests share + read.",
4908
+ SHARED_HELP,
4909
+ " foleo mv <path> --to-workspace <handle> [--to <folder>] [--yes] [--json]",
4910
+ MOVE_HELP,
4911
+ " foleo workspaces [ls] [--json]",
4912
+ " foleo workspaces create <name> [--address <handle>] [--mutation-id <id>] [--json]",
4913
+ " --workspace <handle> chooses its stored login and sends Foleo-Workspace; each credential must match.",
4914
+ " foleo use <handle> sets the default for this API; foleo workspaces shows stored logins.",
4915
+ " Cloud-file commands also accept a UUID tree ID in --workspace.",
4461
4916
  " foleo whoami [--json]",
4462
4917
  " foleo doctor [--json]",
4463
4918
  " foleo skill get|path",