@jinshuju/cli 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,9 +34,25 @@ and an access token (personal or account). Both go in through `auth login`:
34
34
 
35
35
  ```bash
36
36
  jinshuju auth login # browser login
37
+ jinshuju auth login --device # approve a short code on any other device
37
38
  jinshuju auth login --access-token xxx # access token, checked before it is stored
38
39
  ```
39
40
 
41
+ On a machine without a browser — a server over SSH, a container, an agent's
42
+ sandbox — `--device` prints a link and a short code. Open the link on any
43
+ device, a phone will do, check the code matches and approve; the CLI is
44
+ polling and finishes on its own. Nothing has to reach back into the machine.
45
+ Over SSH, or on Linux without a display, `auth login` does this by itself.
46
+ Someone without an account can sign up on that page and come back to approve.
47
+
48
+ An agent whose commands are cut off after a minute or two can split it in
49
+ two:
50
+
51
+ ```bash
52
+ jinshuju auth login --no-wait --output json # prints verification_uri_complete and user_code, then exits
53
+ jinshuju auth login --resume --timeout 60 # waits up to 60s; exit code 9 means still pending
54
+ ```
55
+
40
56
  Either one is written to the config file (`~/.jinshuju/config.json`, mode 600)
41
57
  and replaces whatever credential was stored before. `jinshuju auth logout`
42
58
  forgets it (revoking it first, for a browser session).
package/dist/auth.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type LoadConfigOptions, type LoadedConfig, type OAuthConfig } from './config.js';
1
+ import { type LoadConfigOptions, type LoadedConfig, type OAuthConfig, type PendingDeviceLogin } from './config.js';
2
2
  export type TokenResponse = {
3
3
  access_token: string;
4
4
  refresh_token?: string;
@@ -33,6 +33,35 @@ export declare function buildAuthorizationUrl(params: {
33
33
  codeChallenge: string;
34
34
  }): string;
35
35
  export declare function loginWithOAuth(options?: OAuthLoginOptions, opener?: BrowserOpener): Promise<OAuthLoginResult>;
36
+ export declare const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
37
+ export type DeviceLoginOptions = LoginTarget & {
38
+ /** How to wait between polls; a test passes one that does not. */
39
+ sleep?: (ms: number) => Promise<void>;
40
+ };
41
+ type LoginTarget = LoadConfigOptions & {
42
+ host?: string;
43
+ authHost?: string;
44
+ clientId?: string;
45
+ scopes?: string;
46
+ };
47
+ /**
48
+ * RFC 8628. The CLI only ever calls out: it asks for a code, a person enters
49
+ * it on whatever device has a browser — a phone will do — and the CLI polls
50
+ * until they have approved it. Nothing has to reach back into this machine,
51
+ * which is what a server over SSH or an agent's sandbox cannot offer the
52
+ * loopback login.
53
+ */
54
+ export declare function loginWithDevice(options: DeviceLoginOptions, onCode: (pending: PendingDeviceLogin) => void): Promise<OAuthConfig>;
55
+ /**
56
+ * The first half of a device login, for a caller that cannot wait: an agent
57
+ * whose commands are cut off after a minute or two. The code is stored, the
58
+ * person is sent to approve it, and `resumeDeviceLogin` collects the session.
59
+ */
60
+ export declare function startDeviceLogin(options: LoginTarget): Promise<PendingDeviceLogin>;
61
+ /** Waits up to `waitMs` for the stored device login to be approved; still waiting after that is a PendingError. */
62
+ export declare function resumeDeviceLogin(options: DeviceLoginOptions & {
63
+ waitMs?: number;
64
+ }): Promise<OAuthConfig>;
36
65
  export declare function refreshOAuthToken(config: LoadedConfig): Promise<OAuthConfig>;
37
66
  /**
38
67
  * Revokes a stored OAuth session, then forgets whatever credential is stored.
@@ -40,3 +69,4 @@ export declare function refreshOAuthToken(config: LoadedConfig): Promise<OAuthCo
40
69
  */
41
70
  export declare function logout(config: LoadedConfig): Promise<void>;
42
71
  export declare function shouldRefresh(auth: OAuthConfig, skewMs?: number): boolean;
72
+ export {};
package/dist/auth.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { createServer } from 'node:http';
3
3
  import { execFile } from 'node:child_process';
4
- import { AuthError } from './errors.js';
5
- import { clearCredential, defaultScopes, loadConfig, saveOAuthConfig } from './config.js';
4
+ import { AuthError, PendingError, UsageError } from './errors.js';
5
+ import { clearCredential, defaultScopes, loadConfig, loadPendingDeviceLogin, saveOAuthConfig, saveOAuthLogin, savePendingDeviceLogin } from './config.js';
6
6
  function base64Url(bytes) {
7
7
  return bytes.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
8
8
  }
@@ -51,9 +51,156 @@ export async function loginWithOAuth(options = {}, opener = openUrl) {
51
51
  const code = await callback.code;
52
52
  const token = await exchangeAuthorizationCode(config.authHost, clientId, callback.redirectUri, code, verifier);
53
53
  const auth = toOAuthConfig(config, clientId, token);
54
- saveOAuthConfig(config.configPath, auth);
54
+ saveOAuthLogin(config.configPath, auth);
55
55
  return { authorizeUrl, callbackUrl: callback.redirectUri, token: auth };
56
56
  }
57
+ export const DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
58
+ /**
59
+ * RFC 8628. The CLI only ever calls out: it asks for a code, a person enters
60
+ * it on whatever device has a browser — a phone will do — and the CLI polls
61
+ * until they have approved it. Nothing has to reach back into this machine,
62
+ * which is what a server over SSH or an agent's sandbox cannot offer the
63
+ * loopback login.
64
+ */
65
+ export async function loginWithDevice(options, onCode) {
66
+ const { config, pending } = await requestDeviceCode(options);
67
+ onCode(pending);
68
+ return await finishDeviceLogin(config, pending, Date.parse(pending.expires_at), options.sleep);
69
+ }
70
+ /**
71
+ * The first half of a device login, for a caller that cannot wait: an agent
72
+ * whose commands are cut off after a minute or two. The code is stored, the
73
+ * person is sent to approve it, and `resumeDeviceLogin` collects the session.
74
+ */
75
+ export async function startDeviceLogin(options) {
76
+ const { config, pending } = await requestDeviceCode(options);
77
+ savePendingDeviceLogin(config.configPath, pending);
78
+ return pending;
79
+ }
80
+ /** Waits up to `waitMs` for the stored device login to be approved; still waiting after that is a PendingError. */
81
+ export async function resumeDeviceLogin(options) {
82
+ const config = loadConfig({ configPath: options.configPath, env: options.env });
83
+ const pending = loadPendingDeviceLogin(config.configPath);
84
+ if (!pending)
85
+ throw new UsageError('No device login is waiting. Start one with `jinshuju auth login --no-wait`.');
86
+ const deadline = Math.min(Date.parse(pending.expires_at), Date.now() + (options.waitMs ?? 60_000));
87
+ return await finishDeviceLogin(config, pending, deadline, options.sleep);
88
+ }
89
+ async function requestDeviceCode(options) {
90
+ const config = loadConfig({
91
+ configPath: options.configPath,
92
+ env: options.env,
93
+ cli: { host: options.host, authHost: options.authHost, clientId: options.clientId }
94
+ });
95
+ const clientId = options.clientId ?? config.clientId;
96
+ if (!clientId)
97
+ throw new AuthError('Missing OAuth client id. Set JINSHUJU_OAUTH_CLIENT_ID or config client_id.');
98
+ const response = await fetch(new URL('/oauth/device_authorization', config.authHost), {
99
+ method: 'POST',
100
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
101
+ body: new URLSearchParams({ client_id: clientId, scope: options.scopes ?? defaultScopes }),
102
+ signal: AbortSignal.timeout(config.timeoutMs ?? TOKEN_TIMEOUT_MS)
103
+ });
104
+ const body = parseTokenBody(await response.text(), response);
105
+ if (!response.ok || !body?.device_code || !body.user_code || !body.verification_uri) {
106
+ throw new AuthError(body?.error_description ??
107
+ body?.error ??
108
+ `${response.status} ${response.statusText} from the device authorization endpoint`.trim());
109
+ }
110
+ return {
111
+ config,
112
+ pending: {
113
+ auth_host: config.authHost,
114
+ client_id: clientId,
115
+ device_code: body.device_code,
116
+ user_code: body.user_code,
117
+ verification_uri: body.verification_uri,
118
+ verification_uri_complete: body.verification_uri_complete,
119
+ interval: body.interval ?? 5,
120
+ expires_at: new Date(Date.now() + (body.expires_in ?? 900) * 1000).toISOString()
121
+ }
122
+ };
123
+ }
124
+ /**
125
+ * Polls at the interval the server asked for, five seconds slower each time it
126
+ * says `slow_down`, as RFC 8628 has it. A refusal or an expired code ends the
127
+ * login; running out of `deadline` while the code is still good does not, it
128
+ * only stops this wait.
129
+ */
130
+ async function finishDeviceLogin(config, pending, deadline, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
131
+ let interval = pending.interval;
132
+ const outOfTime = () => {
133
+ if (deadline >= Date.parse(pending.expires_at))
134
+ return new AuthError('The login code expired before it was approved. Start a new login.');
135
+ return new PendingError(`Still waiting for the code ${pending.user_code} to be approved at ` +
136
+ `${pending.verification_uri_complete ?? pending.verification_uri}. Run \`jinshuju auth login --resume\` again.`);
137
+ };
138
+ // The first poll is always made, so `--timeout 0` asks once rather than not at all.
139
+ let first = true;
140
+ for (;;) {
141
+ const remaining = deadline - Date.now();
142
+ const answer = await pollDeviceToken(pending, config.timeoutMs ?? TOKEN_TIMEOUT_MS, first && remaining <= 0 ? Number.POSITIVE_INFINITY : remaining);
143
+ first = false;
144
+ if ('outOfTime' in answer)
145
+ throw outOfTime();
146
+ if ('token' in answer) {
147
+ const auth = toOAuthConfig({ ...config, authHost: pending.auth_host }, pending.client_id, answer.token);
148
+ saveOAuthLogin(config.configPath, auth);
149
+ return auth;
150
+ }
151
+ if (answer.error === 'slow_down')
152
+ interval += 5;
153
+ else if (answer.error === 'access_denied')
154
+ throw new AuthError('The login was refused on the authorization page.');
155
+ else if (answer.error === 'expired_token' || answer.error === 'invalid_grant')
156
+ throw new AuthError('The login code expired before it was approved. Start a new login.');
157
+ else if (answer.error !== 'authorization_pending')
158
+ throw new AuthError(answer.description ?? answer.error);
159
+ if (Date.now() + interval * 1000 >= deadline)
160
+ throw outOfTime();
161
+ await sleep(interval * 1000);
162
+ }
163
+ }
164
+ /**
165
+ * One poll, held to the time the login has left as well as to its own
166
+ * timeout: a request still in flight when the --timeout runs out is abandoned,
167
+ * as `outOfTime`, rather than holding the command past what its caller allowed.
168
+ */
169
+ async function pollDeviceToken(pending, timeoutMs, remainingMs) {
170
+ if (remainingMs <= 0)
171
+ return { outOfTime: true };
172
+ // fetch settles on the headers; the body can still be on its way when time
173
+ // runs out, and an abort there surfaces as a different error. Both halves are
174
+ // under the one signal, and whether it fired is what decides.
175
+ const signal = AbortSignal.timeout(Math.min(timeoutMs, remainingMs));
176
+ let response;
177
+ let text;
178
+ try {
179
+ response = await fetch(new URL('/oauth/token', pending.auth_host), {
180
+ method: 'POST',
181
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
182
+ body: new URLSearchParams({
183
+ grant_type: DEVICE_CODE_GRANT_TYPE,
184
+ client_id: pending.client_id,
185
+ device_code: pending.device_code
186
+ }),
187
+ signal
188
+ });
189
+ text = await response.text();
190
+ }
191
+ catch (error) {
192
+ if (signal.aborted && remainingMs <= timeoutMs)
193
+ return { outOfTime: true };
194
+ throw error;
195
+ }
196
+ const body = parseTokenBody(text, response);
197
+ if (response.ok && body?.access_token)
198
+ return { token: body };
199
+ return {
200
+ error: body?.error ?? `${response.status} ${response.statusText}`.trim(),
201
+ description: body?.error_description
202
+ };
203
+ }
57
204
  export async function refreshOAuthToken(config) {
58
205
  if (!config.auth?.refresh_token)
59
206
  throw new AuthError('No OAuth refresh token. Run `jinshuju auth login` again.');
@@ -212,8 +359,16 @@ function safeEqual(a, b) {
212
359
  const bBuffer = Buffer.from(b);
213
360
  return aBuffer.length === bBuffer.length && timingSafeEqual(aBuffer, bBuffer);
214
361
  }
362
+ /**
363
+ * A browser that cannot be opened — no xdg-open on a server, no display —
364
+ * says so with the URL, rather than leaving the login to wait out its timeout
365
+ * in silence for a page nobody will ever see.
366
+ */
215
367
  async function openUrl(url) {
216
368
  const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
217
369
  const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
218
- await new Promise((resolve) => execFile(command, args, (error) => (error ? resolve() : resolve())));
370
+ const opened = await new Promise((resolve) => execFile(command, args, (error) => resolve(!error)));
371
+ if (!opened)
372
+ process.stderr.write(`Could not open a browser. Open this URL to log in:\n${url}\n` +
373
+ 'Without a browser on this machine, `jinshuju auth login --device` logs in from another device instead.\n');
219
374
  }
@@ -22,11 +22,22 @@ export const LOCAL = [
22
22
  path: ['auth', 'login'],
23
23
  summary: 'Log in through the browser, or with an access token, and store the credential',
24
24
  description: 'Without --access-token: opens the authorization page, waits for the redirect on a loopback ' +
25
- 'port, and writes the session to the config file. With it: checks the token with one call, ' +
26
- 'then stores it; the OAuth options are ignored. Either replaces whatever credential was stored ' +
27
- 'before. JINSHUJU_ACCESS_TOKEN, if set, still outranks what this stores.',
28
- options: local('--access-token', '--auth-host', '--client-id', '--scopes', '--no-open', '--host'),
29
- examples: ['jinshuju auth login', 'jinshuju auth login --no-open', 'jinshuju auth login --access-token <token>']
25
+ 'port, and writes the session to the config file. With --device, or over SSH or on a Linux box ' +
26
+ 'without a display: prints a link and a short code to approve on any other device, and waits ' +
27
+ 'for that instead; nothing has to reach this machine. --no-wait prints the link and code and ' +
28
+ 'exits, for an agent whose commands cannot wait; --resume then waits for the approval, a minute ' +
29
+ 'or --timeout seconds (0 asks once), exiting 9 while it is still pending. With --access-token: checks the token with one ' +
30
+ 'call, then stores it; the OAuth options are ignored. Each replaces whatever credential was ' +
31
+ 'stored before. JINSHUJU_ACCESS_TOKEN, if set, still outranks what this stores.',
32
+ options: local('--access-token', '--auth-host', '--client-id', '--scopes', '--no-open', '--device', '--no-wait', '--resume', '--timeout', '--host'),
33
+ examples: [
34
+ 'jinshuju auth login',
35
+ 'jinshuju auth login --no-open',
36
+ 'jinshuju auth login --device',
37
+ 'jinshuju auth login --no-wait --output json',
38
+ 'jinshuju auth login --resume',
39
+ 'jinshuju auth login --access-token <token>'
40
+ ]
30
41
  },
31
42
  {
32
43
  path: ['auth', 'status'],
package/dist/config.d.ts CHANGED
@@ -14,6 +14,21 @@ export type TokenConfig = {
14
14
  type: 'access_token';
15
15
  access_token: string;
16
16
  };
17
+ /**
18
+ * A device login `auth login --no-wait` started and `auth login --resume`
19
+ * finishes: the code a person is entering on another device, and the device
20
+ * code that turns into a session once they have.
21
+ */
22
+ export type PendingDeviceLogin = {
23
+ auth_host: string;
24
+ client_id: string;
25
+ device_code: string;
26
+ user_code: string;
27
+ verification_uri: string;
28
+ verification_uri_complete?: string;
29
+ interval: number;
30
+ expires_at: string;
31
+ };
17
32
  export type LoadedConfig = {
18
33
  /**
19
34
  * A personal or account access token, sent as a bearer: JINSHUJU_ACCESS_TOKEN,
@@ -55,13 +70,26 @@ export declare const defaultScopes = "public forms read_entries write_entries fo
55
70
  */
56
71
  export type RawConfig = Partial<Record<ConfigKey, string>> & {
57
72
  auth?: OAuthConfig | TokenConfig;
73
+ pending_device?: PendingDeviceLogin;
58
74
  };
59
75
  export declare function loadConfig(options?: LoadConfigOptions): LoadedConfig;
60
76
  export declare function setConfigValue(configPath: string, key: ConfigKey, value: string): void;
61
77
  export declare function unsetConfigValue(configPath: string, key: ConfigKey): void;
78
+ /**
79
+ * Stores a renewed session. A refresh is not a login: a device login started
80
+ * with --no-wait while the old session was still in use keeps waiting.
81
+ */
62
82
  export declare function saveOAuthConfig(configPath: string, auth: OAuthConfig): void;
83
+ /** A login of either kind settles any device login still waiting: what it was waiting for is decided. */
84
+ export declare function saveOAuthLogin(configPath: string, auth: OAuthConfig): void;
63
85
  export declare function saveAccessToken(configPath: string, accessToken: string): void;
64
- /** Forgets the stored credential, whichever kind it is. */
86
+ export declare function savePendingDeviceLogin(configPath: string, pending: PendingDeviceLogin): void;
87
+ export declare function loadPendingDeviceLogin(configPath: string): PendingDeviceLogin | undefined;
88
+ /**
89
+ * Forgets the stored credential, whichever kind it is, and any device login
90
+ * still waiting: after a logout, approving that code in a browser must not
91
+ * log this machine back in.
92
+ */
65
93
  export declare function clearCredential(configPath: string): void;
66
94
  export declare function getConfig(configPath: string): RawConfig;
67
95
  /** Every key the config file holds, in the order help should list them. */
package/dist/config.js CHANGED
@@ -96,22 +96,46 @@ export function unsetConfigValue(configPath, key) {
96
96
  delete config[key];
97
97
  writeConfigFile(configPath, config);
98
98
  }
99
+ /**
100
+ * Stores a renewed session. A refresh is not a login: a device login started
101
+ * with --no-wait while the old session was still in use keeps waiting.
102
+ */
99
103
  export function saveOAuthConfig(configPath, auth) {
100
104
  const config = readConfigFile(configPath);
101
- config.auth = auth;
102
- config.auth_host = auth.auth_host;
103
- config.client_id = auth.client_id;
105
+ writeConfigFile(configPath, withOAuth(config, auth));
106
+ }
107
+ /** A login of either kind settles any device login still waiting: what it was waiting for is decided. */
108
+ export function saveOAuthLogin(configPath, auth) {
109
+ const config = withOAuth(readConfigFile(configPath), auth);
110
+ delete config.pending_device;
104
111
  writeConfigFile(configPath, config);
105
112
  }
113
+ function withOAuth(config, auth) {
114
+ return { ...config, auth, auth_host: auth.auth_host, client_id: auth.client_id };
115
+ }
106
116
  export function saveAccessToken(configPath, accessToken) {
107
117
  const config = readConfigFile(configPath);
108
118
  config.auth = { type: 'access_token', access_token: accessToken };
119
+ delete config.pending_device;
120
+ writeConfigFile(configPath, config);
121
+ }
122
+ export function savePendingDeviceLogin(configPath, pending) {
123
+ const config = readConfigFile(configPath);
124
+ config.pending_device = pending;
109
125
  writeConfigFile(configPath, config);
110
126
  }
111
- /** Forgets the stored credential, whichever kind it is. */
127
+ export function loadPendingDeviceLogin(configPath) {
128
+ return readConfigFile(configPath).pending_device;
129
+ }
130
+ /**
131
+ * Forgets the stored credential, whichever kind it is, and any device login
132
+ * still waiting: after a logout, approving that code in a browser must not
133
+ * log this machine back in.
134
+ */
112
135
  export function clearCredential(configPath) {
113
136
  const config = readConfigFile(configPath);
114
137
  delete config.auth;
138
+ delete config.pending_device;
115
139
  writeConfigFile(configPath, config);
116
140
  }
117
141
  export function getConfig(configPath) {
package/dist/errors.d.ts CHANGED
@@ -24,12 +24,19 @@ export declare class TransportError extends Error {
24
24
  export declare class RefusedError extends Error {
25
25
  name: string;
26
26
  }
27
+ /**
28
+ * Nothing went wrong yet, but the thing waited for has not happened: a device
29
+ * login nobody has approved. Running the same command again is the remedy.
30
+ */
31
+ export declare class PendingError extends Error {
32
+ name: string;
33
+ }
27
34
  /**
28
35
  * What kind of failure it was, which is what a script branches on. The exit
29
36
  * code says it without parsing anything; `--output json` also says it in
30
37
  * words, alongside the status and body the server answered with.
31
38
  */
32
- export type ErrorKind = 'unexpected' | 'usage' | 'auth' | 'not_found' | 'refused' | 'server' | 'transport' | 'rate_limited';
39
+ export type ErrorKind = 'unexpected' | 'usage' | 'auth' | 'not_found' | 'refused' | 'server' | 'transport' | 'rate_limited' | 'pending';
33
40
  export declare const EXIT_CODES: Readonly<Record<ErrorKind, number>>;
34
41
  export type ClassifiedError = {
35
42
  kind: ErrorKind;
package/dist/errors.js CHANGED
@@ -33,6 +33,13 @@ export class TransportError extends Error {
33
33
  export class RefusedError extends Error {
34
34
  name = 'RefusedError';
35
35
  }
36
+ /**
37
+ * Nothing went wrong yet, but the thing waited for has not happened: a device
38
+ * login nobody has approved. Running the same command again is the remedy.
39
+ */
40
+ export class PendingError extends Error {
41
+ name = 'PendingError';
42
+ }
36
43
  export const EXIT_CODES = {
37
44
  unexpected: 1,
38
45
  usage: 2,
@@ -42,7 +49,9 @@ export const EXIT_CODES = {
42
49
  server: 6,
43
50
  transport: 7,
44
51
  // Neither the caller's fault nor permanent: it wants waiting, not a corrected request.
45
- rate_limited: 8
52
+ rate_limited: 8,
53
+ // Not a failure of anything: a device login still waits for someone to approve it.
54
+ pending: 9
46
55
  };
47
56
  function kindOfStatus(status) {
48
57
  if (status === 429)
@@ -78,6 +87,8 @@ export function classify(error) {
78
87
  return { kind: 'refused', exitCode: EXIT_CODES.refused, message };
79
88
  if (error instanceof TransportError)
80
89
  return { kind: 'transport', exitCode: EXIT_CODES.transport, message };
90
+ if (error instanceof PendingError)
91
+ return { kind: 'pending', exitCode: EXIT_CODES.pending, message };
81
92
  if (error instanceof HttpError) {
82
93
  const kind = kindOfStatus(error.status);
83
94
  const retry_after = retryAfterIn(error.body);
package/dist/help.js CHANGED
@@ -38,7 +38,7 @@ export function rootHelp(commands = COMMANDS, style = PLAIN) {
38
38
  `${EXIT_CODES.unexpected} unexpected, ${EXIT_CODES.usage} usage, ${EXIT_CODES.auth} authentication, ` +
39
39
  `${EXIT_CODES.not_found} not found, ${EXIT_CODES.refused} refused by the API, ${EXIT_CODES.server} server failure, ` +
40
40
  `${EXIT_CODES.transport} no connection or timed out, ${EXIT_CODES.rate_limited} rate limited (wait and retry; ` +
41
- '--output json carries retry_after).',
41
+ `--output json carries retry_after), ${EXIT_CODES.pending} a device login still waiting for approval.`,
42
42
  ''
43
43
  ].join('\n');
44
44
  }
package/dist/local.d.ts CHANGED
@@ -15,6 +15,10 @@ type LocalOptions = {
15
15
  clientId?: string;
16
16
  scopes?: string;
17
17
  noOpen: boolean;
18
+ device: boolean;
19
+ noWait: boolean;
20
+ resume: boolean;
21
+ timeout?: string;
18
22
  verify: boolean;
19
23
  };
20
24
  export declare function localOptions(flags: Record<string, unknown>, stdin: () => string): LocalOptions;
package/dist/local.js CHANGED
@@ -1,4 +1,4 @@
1
- import { loginWithOAuth, logout, refreshOAuthToken } from './auth.js';
1
+ import { loginWithDevice, loginWithOAuth, logout, refreshOAuthToken, resumeDeviceLogin, startDeviceLogin } from './auth.js';
2
2
  import { bindOptions } from './args.js';
3
3
  import { assertConfigKey, CONFIG_KEYS, defaultConfigPath, getConfig, loadConfig, saveAccessToken, setConfigValue, unsetConfigValue } from './config.js';
4
4
  import { AuthError } from './errors.js';
@@ -18,6 +18,10 @@ export function localOptions(flags, stdin) {
18
18
  clientId: bound.client_id,
19
19
  scopes: bound.scopes,
20
20
  noOpen: Boolean(bound.no_open),
21
+ device: Boolean(bound.device),
22
+ noWait: Boolean(bound.no_wait),
23
+ resume: Boolean(bound.resume),
24
+ timeout: bound.timeout,
21
25
  verify: Boolean(bound.verify)
22
26
  };
23
27
  }
@@ -58,26 +62,79 @@ function createClient(options, runtime, accessToken) {
58
62
  async function authLogin(options, runtime) {
59
63
  if (options.accessToken !== undefined)
60
64
  return await tokenLogin(options.accessToken, options, runtime);
61
- const result = await loginWithOAuth({
65
+ if (options.noWait && options.resume)
66
+ throw new UsageError('--no-wait starts a device login and --resume finishes it; pick one');
67
+ const target = {
62
68
  configPath: options.configPath,
63
69
  env: runtime.env,
64
70
  host: options.host,
65
71
  authHost: options.authHost,
66
72
  clientId: options.clientId,
67
73
  scopes: options.scopes
68
- }, options.noOpen ? printLoginUrl : undefined);
74
+ };
75
+ if (options.noWait)
76
+ return pendingLogin(await startDeviceLogin(target), options);
77
+ if (options.resume)
78
+ return loggedIn(await resumeDeviceLogin({ ...target, waitMs: waitMs(options.timeout) }), options);
79
+ if (options.device || (!options.noOpen && headless(runtime.env ?? process.env)))
80
+ return loggedIn(await loginWithDevice(target, printDeviceCode), options);
81
+ const result = await loginWithOAuth(target, options.noOpen ? printLoginUrl : undefined);
82
+ return loggedIn(result.token, options);
83
+ }
84
+ function waitMs(seconds) {
85
+ if (seconds === undefined)
86
+ return undefined;
87
+ if (!/^\d+$/.test(seconds))
88
+ throw new UsageError(`--timeout takes a whole number of seconds, got ${JSON.stringify(seconds)}`);
89
+ return Number.parseInt(seconds, 10) * 1000;
90
+ }
91
+ /**
92
+ * No browser could open here, or none that the person at the keyboard would
93
+ * see: a session over SSH, or a Linux box without a display. The loopback
94
+ * login would wait for a redirect that cannot arrive, so a device login is
95
+ * the one that can work. --no-open still asks for the loopback login by name.
96
+ */
97
+ function headless(env) {
98
+ if (env.SSH_CONNECTION || env.SSH_TTY)
99
+ return true;
100
+ return process.platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY;
101
+ }
102
+ function loggedIn(token, options) {
69
103
  const payload = {
70
104
  authenticated: true,
71
105
  mode: 'oauth',
72
- auth_host: result.token.auth_host,
73
- client_id: result.token.client_id,
74
- scope: result.token.scope,
75
- expires_at: result.token.expires_at
106
+ auth_host: token.auth_host,
107
+ client_id: token.client_id,
108
+ scope: token.scope,
109
+ expires_at: token.expires_at
76
110
  };
77
111
  if (options.output !== 'text')
78
112
  return ok(format(payload, options.output, 0));
79
113
  return ok(`Authenticated with OAuth.\nConfig: ${options.configPath}`);
80
114
  }
115
+ /** The link and code go on stdout here: they are the result, and whoever ran this has to pass them on. */
116
+ function pendingLogin(pending, options) {
117
+ const link = pending.verification_uri_complete ?? pending.verification_uri;
118
+ const payload = {
119
+ authenticated: false,
120
+ pending: true,
121
+ user_code: pending.user_code,
122
+ verification_uri: pending.verification_uri,
123
+ verification_uri_complete: pending.verification_uri_complete,
124
+ expires_at: pending.expires_at,
125
+ resume: 'jinshuju auth login --resume'
126
+ };
127
+ if (options.output !== 'text')
128
+ return ok(format(payload, options.output, 0));
129
+ return ok(`To log in, open ${link}\nand check it shows the code ${pending.user_code}, then approve it.\n` +
130
+ `Then run \`jinshuju auth login --resume\` to finish. The code expires at ${pending.expires_at}.`);
131
+ }
132
+ /** While the login waits, so stdout still carries only the result. */
133
+ function printDeviceCode(pending) {
134
+ const link = pending.verification_uri_complete ?? pending.verification_uri;
135
+ process.stderr.write(`To log in, open this link on any device:\n${link}\n` +
136
+ `and check it shows the code ${pending.user_code}, then approve it. Waiting…\n`);
137
+ }
81
138
  /**
82
139
  * A token is checked before it is stored: one pasted wrong would otherwise sit
83
140
  * in the config until the next command failed with it, far from where it was
package/dist/options.js CHANGED
@@ -30,6 +30,23 @@ export const LOCAL_OPTIONS = [
30
30
  { name: '--client-id', type: 'string', placeholder: '<id>', description: 'OAuth public client id' },
31
31
  { name: '--scopes', type: 'string', placeholder: '<scopes>', description: 'Space-separated OAuth scopes' },
32
32
  { name: '--no-open', type: 'boolean', description: 'Print the login URL instead of opening a browser' },
33
+ {
34
+ name: '--device',
35
+ type: 'boolean',
36
+ description: 'Log in by entering a short code on any other device; no browser or open port needed here'
37
+ },
38
+ {
39
+ name: '--no-wait',
40
+ type: 'boolean',
41
+ description: 'Start a device login, print its link and code, and exit; finish it with --resume'
42
+ },
43
+ { name: '--resume', type: 'boolean', description: 'Finish the device login --no-wait started' },
44
+ {
45
+ name: '--timeout',
46
+ type: 'string',
47
+ placeholder: '<seconds>',
48
+ description: 'How long --resume waits for the approval before exiting 9 (default 60)'
49
+ },
33
50
  { name: '--verify', type: 'boolean', description: 'Verify the credentials with a lightweight call' }
34
51
  ];
35
52
  /** The data container a command acts on. Mutually exclusive; both map to form_token. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jinshuju/cli",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Command line interface for Jinshuju Open API v1",
5
5
  "homepage": "https://github.com/jinshuju/cli#readme",
6
6
  "bugs": {