crewly 1.20.132 → 1.20.133

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.
Files changed (60) hide show
  1. package/config/constants.ts +49 -0
  2. package/config/index.ts +2 -0
  3. package/dist/backend/backend/src/controllers/cloud/cloud-device-pairing.controller.d.ts +56 -0
  4. package/dist/backend/backend/src/controllers/cloud/cloud-device-pairing.controller.d.ts.map +1 -0
  5. package/dist/backend/backend/src/controllers/cloud/cloud-device-pairing.controller.js +114 -0
  6. package/dist/backend/backend/src/controllers/cloud/cloud-device-pairing.controller.js.map +1 -0
  7. package/dist/backend/backend/src/controllers/cloud/cloud.controller.d.ts +25 -0
  8. package/dist/backend/backend/src/controllers/cloud/cloud.controller.d.ts.map +1 -1
  9. package/dist/backend/backend/src/controllers/cloud/cloud.controller.js +73 -55
  10. package/dist/backend/backend/src/controllers/cloud/cloud.controller.js.map +1 -1
  11. package/dist/backend/backend/src/controllers/cloud/cloud.routes.d.ts +3 -0
  12. package/dist/backend/backend/src/controllers/cloud/cloud.routes.d.ts.map +1 -1
  13. package/dist/backend/backend/src/controllers/cloud/cloud.routes.js +9 -0
  14. package/dist/backend/backend/src/controllers/cloud/cloud.routes.js.map +1 -1
  15. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.client.d.ts +132 -0
  16. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.client.d.ts.map +1 -0
  17. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.client.js +228 -0
  18. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.client.js.map +1 -0
  19. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.service.d.ts +115 -0
  20. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.service.d.ts.map +1 -0
  21. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.service.js +160 -0
  22. package/dist/backend/backend/src/services/cloud/cloud-device-pairing.service.js.map +1 -0
  23. package/dist/backend/backend/src/services/cloud/mobile-api-relay.service.d.ts.map +1 -1
  24. package/dist/backend/backend/src/services/cloud/mobile-api-relay.service.js +8 -0
  25. package/dist/backend/backend/src/services/cloud/mobile-api-relay.service.js.map +1 -1
  26. package/dist/backend/build-info.json +2 -2
  27. package/dist/backend/config/constants.d.ts +48 -0
  28. package/dist/backend/config/constants.d.ts.map +1 -1
  29. package/dist/backend/config/constants.js +48 -0
  30. package/dist/backend/config/constants.js.map +1 -1
  31. package/dist/backend/config/index.d.ts +2 -2
  32. package/dist/backend/config/index.d.ts.map +1 -1
  33. package/dist/backend/config/index.js +2 -2
  34. package/dist/backend/config/index.js.map +1 -1
  35. package/dist/cli/backend/src/services/cloud/cloud-device-pairing.client.d.ts +132 -0
  36. package/dist/cli/backend/src/services/cloud/cloud-device-pairing.client.d.ts.map +1 -0
  37. package/dist/cli/backend/src/services/cloud/cloud-device-pairing.client.js +228 -0
  38. package/dist/cli/backend/src/services/cloud/cloud-device-pairing.client.js.map +1 -0
  39. package/dist/cli/cli/src/commands/cloud.d.ts +45 -25
  40. package/dist/cli/cli/src/commands/cloud.d.ts.map +1 -1
  41. package/dist/cli/cli/src/commands/cloud.js +153 -47
  42. package/dist/cli/cli/src/commands/cloud.js.map +1 -1
  43. package/dist/cli/cli/src/commands/onboard-checklist.js +3 -3
  44. package/dist/cli/cli/src/commands/onboard-checklist.js.map +1 -1
  45. package/dist/cli/cli/src/index.js +6 -4
  46. package/dist/cli/cli/src/index.js.map +1 -1
  47. package/dist/cli/cli/src/utils/cloud-submit.d.ts.map +1 -1
  48. package/dist/cli/cli/src/utils/cloud-submit.js +14 -5
  49. package/dist/cli/cli/src/utils/cloud-submit.js.map +1 -1
  50. package/dist/cli/config/constants.d.ts +48 -0
  51. package/dist/cli/config/constants.d.ts.map +1 -1
  52. package/dist/cli/config/constants.js +48 -0
  53. package/dist/cli/config/constants.js.map +1 -1
  54. package/dist/cli/config/index.d.ts +2 -2
  55. package/dist/cli/config/index.d.ts.map +1 -1
  56. package/dist/cli/config/index.js +2 -2
  57. package/dist/cli/config/index.js.map +1 -1
  58. package/frontend/dist/assets/{index-5b98bf77.js → index-e6c403b6.js} +265 -265
  59. package/frontend/dist/index.html +1 -1
  60. package/package.json +1 -1
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Cloud device-code pairing client.
3
+ *
4
+ * Talks to crewly-auth's `/api/cloud/device/*` endpoints so this machine can
5
+ * sign in to the owner's Crewly account without anyone at it:
6
+ *
7
+ * 1. {@link startCloudDevicePairing} — get a secret `deviceCode`, a short
8
+ * `userCode` (`ABCD-2345`) and the link the owner opens
9
+ * (`crewlyai.com/cloud/pair?code=ABCD-2345`).
10
+ * 2. {@link waitForCloudDeviceApproval} — poll at the Cloud's interval
11
+ * (backing off on `slow_down` and rate limits) until the owner approves,
12
+ * denies, or the pairing expires. On approval the Cloud hands over the
13
+ * token pair exactly once.
14
+ *
15
+ * Shared by `crewly cloud login` (CLI) and {@link CloudDevicePairingService}
16
+ * (backend, for `/setup` and Settings → Cloud). No state; the device code
17
+ * never leaves the caller's memory.
18
+ *
19
+ * @module services/cloud/cloud-device-pairing.client
20
+ */
21
+ import { CLOUD_DEVICE_PAIRING_CONSTANTS } from '../../../../config/constants.js';
22
+ const C = CLOUD_DEVICE_PAIRING_CONSTANTS;
23
+ /** Milliseconds per second. */
24
+ const MS_PER_S = 1000;
25
+ /** HTTP 429. */
26
+ const HTTP_TOO_MANY_REQUESTS = 429;
27
+ /** Lowest HTTP status treated as a server-side (retryable) failure. */
28
+ const HTTP_SERVER_ERROR_MIN = 500;
29
+ /** A request the Cloud refused (or could not answer). */
30
+ export class DevicePairingError extends Error {
31
+ status;
32
+ retryable;
33
+ /**
34
+ * @param message - Human-readable reason (never contains a secret)
35
+ * @param status - HTTP status, 0 when the Cloud was unreachable
36
+ * @param retryable - True for network errors, 5xx and 429
37
+ */
38
+ constructor(message, status, retryable) {
39
+ super(message);
40
+ this.status = status;
41
+ this.retryable = retryable;
42
+ this.name = 'DevicePairingError';
43
+ }
44
+ }
45
+ /**
46
+ * POST JSON to crewly-auth and unwrap `{ success, data }`.
47
+ *
48
+ * @param fetchImpl - fetch
49
+ * @param url - Absolute URL
50
+ * @param body - JSON body
51
+ * @returns `data`
52
+ * @throws DevicePairingError on transport errors and non-success replies
53
+ */
54
+ async function postJson(fetchImpl, url, body) {
55
+ let response;
56
+ try {
57
+ response = await fetchImpl(url, {
58
+ method: 'POST',
59
+ headers: { 'Content-Type': 'application/json' },
60
+ body: JSON.stringify(body),
61
+ signal: AbortSignal.timeout(C.REQUEST_TIMEOUT_MS),
62
+ });
63
+ }
64
+ catch (err) {
65
+ throw new DevicePairingError(`Crewly Cloud unreachable: ${err instanceof Error ? err.message : String(err)}`, 0, true);
66
+ }
67
+ let parsed = {};
68
+ try {
69
+ parsed = (await response.json());
70
+ }
71
+ catch {
72
+ // handled below
73
+ }
74
+ if (!response.ok || !parsed.success || parsed.data === undefined) {
75
+ const retryable = response.status === HTTP_TOO_MANY_REQUESTS || response.status >= HTTP_SERVER_ERROR_MIN;
76
+ throw new DevicePairingError(parsed.error || `Crewly Cloud returned HTTP ${response.status}`, response.status, retryable);
77
+ }
78
+ return parsed.data;
79
+ }
80
+ /**
81
+ * Join the Cloud base URL and an endpoint path.
82
+ *
83
+ * @param cloudUrl - Cloud API base URL
84
+ * @param path - Endpoint path
85
+ * @returns Absolute URL
86
+ */
87
+ function endpoint(cloudUrl, path) {
88
+ return `${cloudUrl.replace(/\/+$/, '')}${path}`;
89
+ }
90
+ /**
91
+ * Ask the Cloud for a pairing.
92
+ *
93
+ * @param cloudUrl - Cloud API base URL (e.g. https://api.crewlyai.com)
94
+ * @param input - How the device introduces itself on the approve page
95
+ * @param fetchImpl - fetch (tests)
96
+ * @returns Device code, user code, link, lifetime and interval
97
+ * @throws DevicePairingError when the Cloud refuses or is unreachable
98
+ */
99
+ export async function startCloudDevicePairing(cloudUrl, input, fetchImpl = fetch) {
100
+ const data = await postJson(fetchImpl, endpoint(cloudUrl, C.CLOUD_ENDPOINTS.START), input);
101
+ if (!data.deviceCode || !data.userCode || !data.verificationUrl) {
102
+ throw new DevicePairingError('Crewly Cloud returned an incomplete pairing', 0, false);
103
+ }
104
+ return {
105
+ deviceCode: data.deviceCode,
106
+ userCode: data.userCode,
107
+ verificationUrl: data.verificationUrl,
108
+ ...(data.verificationUri ? { verificationUri: data.verificationUri } : {}),
109
+ expiresIn: typeof data.expiresIn === 'number' ? data.expiresIn : C.DEFAULT_EXPIRES_IN_S,
110
+ interval: typeof data.interval === 'number' ? data.interval : C.DEFAULT_INTERVAL_S,
111
+ };
112
+ }
113
+ /**
114
+ * Poll a pairing once.
115
+ *
116
+ * @param cloudUrl - Cloud API base URL
117
+ * @param deviceCode - Secret from {@link startCloudDevicePairing}
118
+ * @param fetchImpl - fetch (tests)
119
+ * @returns The Cloud's answer
120
+ * @throws DevicePairingError when the request fails (see `retryable`)
121
+ */
122
+ export async function pollCloudDevicePairing(cloudUrl, deviceCode, fetchImpl = fetch) {
123
+ const data = await postJson(fetchImpl, endpoint(cloudUrl, C.CLOUD_ENDPOINTS.POLL), { deviceCode });
124
+ switch (data.status) {
125
+ case C.POLL_STATUS.APPROVED:
126
+ if (!data.token || !data.refreshToken) {
127
+ throw new DevicePairingError('Crewly Cloud approved the device but sent no tokens', 0, false);
128
+ }
129
+ return {
130
+ status: 'approved',
131
+ credentials: { token: data.token, refreshToken: data.refreshToken, tier: data.tier || 'free', ...(data.email ? { email: data.email } : {}) },
132
+ };
133
+ case C.POLL_STATUS.PENDING:
134
+ case C.POLL_STATUS.SLOW_DOWN:
135
+ return { status: data.status, ...(typeof data.interval === 'number' ? { interval: data.interval } : {}) };
136
+ case C.POLL_STATUS.DENIED:
137
+ return { status: 'denied' };
138
+ case C.POLL_STATUS.EXPIRED:
139
+ return { status: 'expired' };
140
+ default:
141
+ throw new DevicePairingError(`Unexpected pairing status: ${String(data.status)}`, 0, false);
142
+ }
143
+ }
144
+ /**
145
+ * Wait `ms`, resolving early when `signal` aborts.
146
+ *
147
+ * @param ms - Milliseconds
148
+ * @param signal - Optional abort signal
149
+ * @returns Resolves after the delay or on abort
150
+ */
151
+ export function abortableSleep(ms, signal) {
152
+ return new Promise((resolve) => {
153
+ if (signal?.aborted) {
154
+ resolve();
155
+ return;
156
+ }
157
+ const timer = setTimeout(() => {
158
+ signal?.removeEventListener('abort', onAbort);
159
+ resolve();
160
+ }, ms);
161
+ const onAbort = () => {
162
+ clearTimeout(timer);
163
+ resolve();
164
+ };
165
+ signal?.addEventListener('abort', onAbort, { once: true });
166
+ });
167
+ }
168
+ /**
169
+ * Poll until the owner approves or denies, or the pairing expires.
170
+ *
171
+ * Honours the Cloud's interval, adds {@link CLOUD_DEVICE_PAIRING_CONSTANTS.SLOW_DOWN_INCREMENT_S}
172
+ * on `slow_down` / HTTP 429 (capped), and rides out up to
173
+ * {@link CLOUD_DEVICE_PAIRING_CONSTANTS.MAX_CONSECUTIVE_POLL_ERRORS} network
174
+ * or server errors in a row (a laptop changing Wi-Fi mid-login).
175
+ *
176
+ * @param options - Cloud URL, the started pairing and hooks
177
+ * @returns How it ended; `approved` carries the token pair
178
+ * @throws DevicePairingError on a non-retryable refusal or too many errors in a row
179
+ */
180
+ export async function waitForCloudDeviceApproval(options) {
181
+ const { cloudUrl, start, signal, onPoll } = options;
182
+ const fetchImpl = options.fetchImpl ?? fetch;
183
+ const sleep = options.sleep ?? abortableSleep;
184
+ const now = options.now ?? (() => Date.now());
185
+ const deadline = now() + start.expiresIn * MS_PER_S;
186
+ let intervalS = Math.max(1, start.interval || C.DEFAULT_INTERVAL_S);
187
+ let consecutiveErrors = 0;
188
+ for (;;) {
189
+ await sleep(intervalS * MS_PER_S, signal);
190
+ if (signal?.aborted)
191
+ return { status: 'cancelled' };
192
+ if (now() >= deadline)
193
+ return { status: 'expired' };
194
+ let result;
195
+ try {
196
+ result = await pollCloudDevicePairing(cloudUrl, start.deviceCode, fetchImpl);
197
+ consecutiveErrors = 0;
198
+ }
199
+ catch (err) {
200
+ if (!(err instanceof DevicePairingError) || !err.retryable)
201
+ throw err;
202
+ consecutiveErrors++;
203
+ if (consecutiveErrors > C.MAX_CONSECUTIVE_POLL_ERRORS)
204
+ throw err;
205
+ if (err.status === HTTP_TOO_MANY_REQUESTS) {
206
+ intervalS = Math.min(C.MAX_INTERVAL_S, intervalS + C.SLOW_DOWN_INCREMENT_S);
207
+ }
208
+ continue;
209
+ }
210
+ if (signal?.aborted)
211
+ return { status: 'cancelled' };
212
+ onPoll?.(result.status, intervalS);
213
+ switch (result.status) {
214
+ case 'approved':
215
+ return result;
216
+ case 'expired':
217
+ case 'denied':
218
+ return { status: result.status };
219
+ case 'slow_down':
220
+ intervalS = Math.min(C.MAX_INTERVAL_S, result.interval ?? intervalS + C.SLOW_DOWN_INCREMENT_S);
221
+ break;
222
+ default:
223
+ if (typeof result.interval === 'number')
224
+ intervalS = Math.min(C.MAX_INTERVAL_S, Math.max(1, result.interval));
225
+ }
226
+ }
227
+ }
228
+ //# sourceMappingURL=cloud-device-pairing.client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-device-pairing.client.js","sourceRoot":"","sources":["../../../../../../backend/src/services/cloud/cloud-device-pairing.client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AAEjF,MAAM,CAAC,GAAG,8BAA8B,CAAC;AAEzC,+BAA+B;AAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC;AAEtB,gBAAgB;AAChB,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,uEAAuE;AACvE,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAwClC,yDAAyD;AACzD,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAML;IAAyB;IAL/D;;;;OAIG;IACH,YAAY,OAAe,EAAW,MAAc,EAAW,SAAkB;QAC/E,KAAK,CAAC,OAAO,CAAC,CAAC;QADqB,WAAM,GAAN,MAAM,CAAQ;QAAW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,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QACnC,QAAQ,MAAM,CAAC,MAAM,EAAE,CAAC;YACtB,KAAK,UAAU;gBACb,OAAO,MAAM,CAAC;YAChB,KAAK,SAAS,CAAC;YACf,KAAK,QAAQ;gBACX,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;YACnC,KAAK,WAAW;gBACd,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC,QAAQ,IAAI,SAAS,GAAG,CAAC,CAAC,qBAAqB,CAAC,CAAC;gBAC/F,MAAM;YACR;gBACE,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;oBAAE,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QAClH,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -6,22 +6,52 @@
6
6
  * crewly cloud status — Show current connection status
7
7
  * crewly cloud logout — Disconnect from CrewlyAI Cloud
8
8
  *
9
- * The login flow supports three modes:
10
- * 1. Direct token login via --token flag
11
- * 2. Browser-based OAuth: starts a local HTTP callback server, opens the
12
- * backend Google OAuth URL, receives the token via redirect, persists
13
- * credentials to ~/.crewly/cloud/config.json, then calls POST /api/cloud/connect.
14
- * 3. Mobile/no-browser login via --no-browser flag: prints a URL for the user
15
- * to open on their phone, which displays the token after OAuth for manual copy-paste.
9
+ * Login modes:
10
+ * 1. **Device pairing (default)**: asks Crewly Cloud for a pairing, prints a
11
+ * link + short code (`crewlyai.com/cloud/pair?code=ABCD-2345`) the owner
12
+ * opens on any device — usually their phone — and approves. The CLI polls
13
+ * and receives the token pair by itself: nobody copies a token, and nobody
14
+ * has to be at this machine. Credentials are saved to
15
+ * `$CREWLY_HOME/cloud/config.json` and `POST /api/cloud/connect` is called.
16
+ * 2. `--token <token>`: direct token login.
17
+ * 3. `--web`: the old localhost-callback flow (local callback server + Google
18
+ * OAuth in this machine's browser).
19
+ * 4. `--paste`: the old copy-paste flow (sign in on the portal's token page,
20
+ * paste the token and refresh token here).
16
21
  *
17
22
  * @module cli/commands/cloud
18
23
  */
19
24
  import http from 'http';
25
+ import { startCloudDevicePairing, type DevicePairingOutcome, type WaitForApprovalOptions } from '../../../backend/src/services/cloud/cloud-device-pairing.client.js';
26
+ /**
27
+ * Directory for cloud credentials — `$CREWLY_HOME/cloud` (default
28
+ * `~/.crewly/cloud`). Resolved per call so `CREWLY_HOME` set after import
29
+ * (tests, isolated profiles) is honoured; it must match the backend's
30
+ * `CloudClientService` path so both read the same file.
31
+ *
32
+ * @returns Absolute directory path
33
+ */
34
+ export declare function getCloudConfigDir(): string;
35
+ /**
36
+ * Path to the cloud credentials file.
37
+ *
38
+ * @returns Absolute file path
39
+ */
40
+ export declare function getCloudConfigFile(): string;
20
41
  /** Options for the login subcommand */
21
- interface LoginOptions {
42
+ export interface LoginOptions {
22
43
  token?: string;
23
44
  /** Commander.js sets this to false when --no-browser is passed */
24
45
  browser?: boolean;
46
+ /** `--web`: old flow — localhost callback server + Google OAuth in this machine's browser */
47
+ web?: boolean;
48
+ /** `--paste`: old flow — sign in on the portal's token page and paste the tokens here */
49
+ paste?: boolean;
50
+ }
51
+ /** Injectable pairing client (tests). */
52
+ export interface LoginDeps {
53
+ startPairing: typeof startCloudDevicePairing;
54
+ waitForApproval: (options: WaitForApprovalOptions) => Promise<DevicePairingOutcome>;
25
55
  }
26
56
  /**
27
57
  * Shape of the credentials saved to config.json.
@@ -37,15 +67,7 @@ interface CloudCredentials {
37
67
  connectedAt: string;
38
68
  }
39
69
  /**
40
- * Save cloud credentials to ~/.crewly/cloud/config.json.
41
- *
42
- * Creates the directory hierarchy if it does not exist.
43
- *
44
- * @param token - JWT access token
45
- * @param refreshToken - Optional refresh token
46
- */
47
- /**
48
- * Save cloud credentials to ~/.crewly/cloud/config.json.
70
+ * Save cloud credentials to $CREWLY_HOME/cloud/config.json.
49
71
  *
50
72
  * Creates the directory hierarchy if it does not exist. The format matches
51
73
  * PersistedCloudConfig so the backend's loadPersistedConfig() can read it.
@@ -55,7 +77,7 @@ interface CloudCredentials {
55
77
  */
56
78
  export declare function saveCloudCredentials(token: string, refreshToken?: string): void;
57
79
  /**
58
- * Load cloud credentials from ~/.crewly/cloud/config.json.
80
+ * Load cloud credentials from $CREWLY_HOME/cloud/config.json.
59
81
  *
60
82
  * @returns The saved credentials, or null if the file does not exist or is invalid
61
83
  */
@@ -109,15 +131,13 @@ export declare function promptForToken(prompt: string): Promise<string>;
109
131
  /**
110
132
  * Handle the `crewly cloud login` subcommand.
111
133
  *
112
- * Supports three login modes:
113
- * 1. `--token <token>`: saves the token and calls POST /api/cloud/connect directly.
114
- * 2. `--no-browser`: prints a URL for mobile login, waits for user to paste token.
115
- * 3. Default: starts a local HTTP callback server, opens the browser to the
116
- * backend OAuth URL, waits for the callback, saves credentials.
134
+ * Modes (see the module comment): device pairing by default; `--token`,
135
+ * `--web` and `--paste` keep the older flows.
117
136
  *
118
- * @param options - Login command options (optional --token, --no-browser)
137
+ * @param options - Login command options
138
+ * @param deps - Pairing client (tests)
119
139
  */
120
- export declare function loginCommand(options: LoginOptions): Promise<void>;
140
+ export declare function loginCommand(options: LoginOptions, deps?: LoginDeps): Promise<void>;
121
141
  /**
122
142
  * Handle the `crewly cloud status` subcommand.
123
143
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../../../../../cli/src/commands/cloud.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,IAAI,MAAM,MAAM,CAAC;AAiDxB,uCAAuC;AACvC,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;GAKG;AACH,UAAU,gBAAgB;IACxB,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C,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;IACpB,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAChE,CAsDA;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAY9D;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,YAAY,EAAE,IAAI,GAAE,SAA8B,GAAG,OAAO,CAAC,IAAI,CAAC,CAuB7G;AA2OD;;;;;GAKG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAqCnD;AAMD;;;;GAIG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAkBnD"}
@@ -6,13 +6,18 @@
6
6
  * crewly cloud status — Show current connection status
7
7
  * crewly cloud logout — Disconnect from CrewlyAI Cloud
8
8
  *
9
- * The login flow supports three modes:
10
- * 1. Direct token login via --token flag
11
- * 2. Browser-based OAuth: starts a local HTTP callback server, opens the
12
- * backend Google OAuth URL, receives the token via redirect, persists
13
- * credentials to ~/.crewly/cloud/config.json, then calls POST /api/cloud/connect.
14
- * 3. Mobile/no-browser login via --no-browser flag: prints a URL for the user
15
- * to open on their phone, which displays the token after OAuth for manual copy-paste.
9
+ * Login modes:
10
+ * 1. **Device pairing (default)**: asks Crewly Cloud for a pairing, prints a
11
+ * link + short code (`crewlyai.com/cloud/pair?code=ABCD-2345`) the owner
12
+ * opens on any device — usually their phone — and approves. The CLI polls
13
+ * and receives the token pair by itself: nobody copies a token, and nobody
14
+ * has to be at this machine. Credentials are saved to
15
+ * `$CREWLY_HOME/cloud/config.json` and `POST /api/cloud/connect` is called.
16
+ * 2. `--token <token>`: direct token login.
17
+ * 3. `--web`: the old localhost-callback flow (local callback server + Google
18
+ * OAuth in this machine's browser).
19
+ * 4. `--paste`: the old copy-paste flow (sign in on the portal's token page,
20
+ * paste the token and refresh token here).
16
21
  *
17
22
  * @module cli/commands/cloud
18
23
  */
@@ -23,8 +28,11 @@ import readline from 'readline';
23
28
  import { exec } from 'child_process';
24
29
  import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
25
30
  import { join } from 'path';
26
- import { homedir, platform } from 'os';
31
+ import { hostname, platform } from 'os';
27
32
  import { DEFAULT_WEB_PORT } from '../constants.js';
33
+ import { CLOUD_DEVICE_PAIRING_CONSTANTS } from '../../../config/constants.js';
34
+ import { getCrewlyHomePath } from '../../../backend/src/services/core/crewly-home.utils.js';
35
+ import { startCloudDevicePairing, waitForCloudDeviceApproval, } from '../../../backend/src/services/cloud/cloud-device-pairing.client.js';
28
36
  // ---------------------------------------------------------------------------
29
37
  // Constants
30
38
  // ---------------------------------------------------------------------------
@@ -46,23 +54,39 @@ const CLOUD_CONSOLE_URL = process.env['CLOUD_CONSOLE_URL'] || 'https://crewlyai.
46
54
  const CLI_TOKEN_PAGE_PATH = '/cloud/cli-token';
47
55
  /** Timeout for backend API requests (ms) */
48
56
  const API_TIMEOUT_MS = 15_000;
49
- /** Directory for cloud credentials */
50
- const CLOUD_CONFIG_DIR = join(homedir(), '.crewly', 'cloud');
51
- /** Path to cloud config file */
52
- const CLOUD_CONFIG_FILE = join(CLOUD_CONFIG_DIR, 'config.json');
53
- // ---------------------------------------------------------------------------
54
- // Helpers
55
- // ---------------------------------------------------------------------------
57
+ /** Sub-directory of the Crewly home that holds cloud credentials */
58
+ const CLOUD_CONFIG_SUBDIR = 'cloud';
59
+ /** Cloud credentials file name */
60
+ const CLOUD_CONFIG_FILENAME = 'config.json';
56
61
  /**
57
- * Save cloud credentials to ~/.crewly/cloud/config.json.
62
+ * Directory for cloud credentials — `$CREWLY_HOME/cloud` (default
63
+ * `~/.crewly/cloud`). Resolved per call so `CREWLY_HOME` set after import
64
+ * (tests, isolated profiles) is honoured; it must match the backend's
65
+ * `CloudClientService` path so both read the same file.
58
66
  *
59
- * Creates the directory hierarchy if it does not exist.
67
+ * @returns Absolute directory path
68
+ */
69
+ export function getCloudConfigDir() {
70
+ return join(getCrewlyHomePath(), CLOUD_CONFIG_SUBDIR);
71
+ }
72
+ /**
73
+ * Path to the cloud credentials file.
60
74
  *
61
- * @param token - JWT access token
62
- * @param refreshToken - Optional refresh token
75
+ * @returns Absolute file path
63
76
  */
77
+ export function getCloudConfigFile() {
78
+ return join(getCloudConfigDir(), CLOUD_CONFIG_FILENAME);
79
+ }
80
+ /** The real pairing client. */
81
+ const DEFAULT_LOGIN_DEPS = {
82
+ startPairing: startCloudDevicePairing,
83
+ waitForApproval: waitForCloudDeviceApproval,
84
+ };
85
+ // ---------------------------------------------------------------------------
86
+ // Helpers
87
+ // ---------------------------------------------------------------------------
64
88
  /**
65
- * Save cloud credentials to ~/.crewly/cloud/config.json.
89
+ * Save cloud credentials to $CREWLY_HOME/cloud/config.json.
66
90
  *
67
91
  * Creates the directory hierarchy if it does not exist. The format matches
68
92
  * PersistedCloudConfig so the backend's loadPersistedConfig() can read it.
@@ -71,14 +95,16 @@ const CLOUD_CONFIG_FILE = join(CLOUD_CONFIG_DIR, 'config.json');
71
95
  * @param refreshToken - Optional refresh token for auto-renewal
72
96
  */
73
97
  export function saveCloudCredentials(token, refreshToken) {
74
- if (!existsSync(CLOUD_CONFIG_DIR)) {
75
- mkdirSync(CLOUD_CONFIG_DIR, { recursive: true });
98
+ const configDir = getCloudConfigDir();
99
+ const configFile = getCloudConfigFile();
100
+ if (!existsSync(configDir)) {
101
+ mkdirSync(configDir, { recursive: true });
76
102
  }
77
103
  // Merge with existing config to preserve fields the backend may have written
78
104
  let existing = {};
79
105
  try {
80
- if (existsSync(CLOUD_CONFIG_FILE)) {
81
- existing = JSON.parse(readFileSync(CLOUD_CONFIG_FILE, 'utf-8'));
106
+ if (existsSync(configFile)) {
107
+ existing = JSON.parse(readFileSync(configFile, 'utf-8'));
82
108
  }
83
109
  }
84
110
  catch {
@@ -93,19 +119,20 @@ export function saveCloudCredentials(token, refreshToken) {
93
119
  // Preserve existing refreshToken if new one not provided
94
120
  ...(!refreshToken && existing.refreshToken && { refreshToken: existing.refreshToken }),
95
121
  };
96
- writeFileSync(CLOUD_CONFIG_FILE, JSON.stringify(credentials, null, 2), 'utf-8');
122
+ writeFileSync(configFile, JSON.stringify(credentials, null, 2), 'utf-8');
97
123
  }
98
124
  /**
99
- * Load cloud credentials from ~/.crewly/cloud/config.json.
125
+ * Load cloud credentials from $CREWLY_HOME/cloud/config.json.
100
126
  *
101
127
  * @returns The saved credentials, or null if the file does not exist or is invalid
102
128
  */
103
129
  export function loadCloudCredentials() {
104
- if (!existsSync(CLOUD_CONFIG_FILE)) {
130
+ const configFile = getCloudConfigFile();
131
+ if (!existsSync(configFile)) {
105
132
  return null;
106
133
  }
107
134
  try {
108
- const raw = readFileSync(CLOUD_CONFIG_FILE, 'utf-8');
135
+ const raw = readFileSync(configFile, 'utf-8');
109
136
  return JSON.parse(raw);
110
137
  }
111
138
  catch {
@@ -270,35 +297,114 @@ export function promptForToken(prompt) {
270
297
  /**
271
298
  * Handle the `crewly cloud login` subcommand.
272
299
  *
273
- * Supports three login modes:
274
- * 1. `--token <token>`: saves the token and calls POST /api/cloud/connect directly.
275
- * 2. `--no-browser`: prints a URL for mobile login, waits for user to paste token.
276
- * 3. Default: starts a local HTTP callback server, opens the browser to the
277
- * backend OAuth URL, waits for the callback, saves credentials.
300
+ * Modes (see the module comment): device pairing by default; `--token`,
301
+ * `--web` and `--paste` keep the older flows.
278
302
  *
279
- * @param options - Login command options (optional --token, --no-browser)
303
+ * @param options - Login command options
304
+ * @param deps - Pairing client (tests)
280
305
  */
281
- export async function loginCommand(options) {
306
+ export async function loginCommand(options, deps = DEFAULT_LOGIN_DEPS) {
282
307
  if (options.token) {
283
308
  // Direct token login
284
309
  console.log(chalk.blue('Logging in with provided token...'));
285
310
  await connectWithToken(options.token);
286
311
  return;
287
312
  }
288
- // Auto-detect: use mobile flow if --no-browser was passed OR environment
289
- // cannot open a browser (SSH, Docker, CI, headless Linux).
290
- const useBrowser = options.browser !== false && canOpenBrowser();
291
- if (!useBrowser) {
292
- if (options.browser !== false) {
293
- // Auto-detected headless — inform the user
294
- console.log(chalk.yellow(' Headless environment detected — using manual token flow.'));
295
- }
313
+ if (options.paste) {
296
314
  await mobileLoginFlow();
297
315
  return;
298
316
  }
299
- // Browser-based OAuth flow — redirects to crewlyai.com (Cloud), NOT local backend.
300
- // The Cloud server handles Google OAuth and redirects back to our local callback
301
- // with token + refreshToken as query parameters.
317
+ if (options.web) {
318
+ if (options.browser === false || !canOpenBrowser()) {
319
+ console.log(chalk.red(' ✗ --web needs a browser on this machine. Run `crewly cloud login` to approve from your phone instead.'));
320
+ process.exit(1);
321
+ }
322
+ await browserLoginFlow();
323
+ return;
324
+ }
325
+ await deviceLoginFlow(options, deps);
326
+ }
327
+ /**
328
+ * Print a pairing's link and code where the owner can use them from any device.
329
+ *
330
+ * @param started - The pairing
331
+ */
332
+ function printPairingInstructions(started) {
333
+ console.log(chalk.white(' On your phone or any browser, open:'));
334
+ console.log('');
335
+ console.log(chalk.cyan(` ${started.verificationUrl}`));
336
+ console.log('');
337
+ console.log(chalk.white(` and check the code matches: ${chalk.bold(started.userCode)}`));
338
+ if (started.verificationUri) {
339
+ console.log(chalk.gray(` (or go to ${started.verificationUri} and type the code)`));
340
+ }
341
+ console.log('');
342
+ console.log(chalk.gray(` The link expires in ${Math.round(started.expiresIn / 60)} minutes.`));
343
+ }
344
+ /**
345
+ * Default login: device-code pairing.
346
+ *
347
+ * Prints a link + code, optionally opens the link locally, and waits while
348
+ * the owner approves from wherever they are. On approval the token pair
349
+ * arrives here by itself and is saved + connected like any other login.
350
+ *
351
+ * @param options - Login options (`--no-browser` stops the local browser from opening)
352
+ * @param deps - Pairing client
353
+ */
354
+ async function deviceLoginFlow(options, deps) {
355
+ console.log('');
356
+ console.log(chalk.blue('CrewlyAI Cloud Login'));
357
+ console.log(chalk.gray('─'.repeat(40)));
358
+ console.log('');
359
+ let started;
360
+ try {
361
+ started = await deps.startPairing(CLOUD_API_URL, {
362
+ deviceName: hostname(),
363
+ purpose: CLOUD_DEVICE_PAIRING_CONSTANTS.PURPOSES.CLI,
364
+ });
365
+ }
366
+ catch (error) {
367
+ const msg = error instanceof Error ? error.message : String(error);
368
+ console.log(chalk.red(` ✗ Could not start login: ${msg}`));
369
+ console.log(chalk.gray(' Other ways in: crewly cloud login --paste | crewly cloud login --token <token>'));
370
+ process.exit(1);
371
+ }
372
+ printPairingInstructions(started);
373
+ if (options.browser !== false && canOpenBrowser()) {
374
+ openBrowser(started.verificationUrl);
375
+ }
376
+ console.log('');
377
+ console.log(chalk.gray(' Waiting for approval… (Ctrl+C to cancel)'));
378
+ let outcome;
379
+ try {
380
+ outcome = await deps.waitForApproval({ cloudUrl: CLOUD_API_URL, start: started });
381
+ }
382
+ catch (error) {
383
+ const msg = error instanceof Error ? error.message : String(error);
384
+ console.log(chalk.red(` ✗ Login failed: ${msg}`));
385
+ process.exit(1);
386
+ }
387
+ if (outcome.status !== 'approved') {
388
+ const reason = outcome.status === 'denied'
389
+ ? 'The request was denied on crewlyai.com.'
390
+ : outcome.status === 'expired'
391
+ ? 'The link expired before it was approved.'
392
+ : 'Login cancelled.';
393
+ console.log(chalk.red(` ✗ ${reason}`));
394
+ console.log(chalk.gray(' Run `crewly cloud login` again for a new link.'));
395
+ process.exit(1);
396
+ }
397
+ const { credentials } = outcome;
398
+ console.log(chalk.green(` ✓ Approved${credentials.email ? ` by ${credentials.email}` : ''}`));
399
+ await connectWithToken(credentials.token, credentials.refreshToken);
400
+ }
401
+ /**
402
+ * `--web`: the localhost-callback flow.
403
+ *
404
+ * Starts a local HTTP callback server, opens Google OAuth on Crewly Cloud in
405
+ * this machine's browser and waits for the redirect back with the tokens.
406
+ */
407
+ async function browserLoginFlow() {
302
408
  console.log('');
303
409
  console.log(chalk.blue('CrewlyAI Cloud Login'));
304
410
  console.log(chalk.gray('─'.repeat(40)));
@@ -413,7 +519,7 @@ async function connectWithToken(token, refreshToken) {
413
519
  catch (error) {
414
520
  if (axios.isAxiosError(error) && error.code === 'ECONNREFUSED') {
415
521
  // Backend not running — this is OK, credentials are saved
416
- console.log(chalk.green(' ✓ Credentials saved to ~/.crewly/cloud/config.json'));
522
+ console.log(chalk.green(` ✓ Credentials saved to ${getCloudConfigFile()}`));
417
523
  console.log(chalk.gray(' Backend not running — Cloud will connect automatically on next crewly start'));
418
524
  }
419
525
  else {