@jinshuju/cli 0.1.3 → 0.3.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 +80 -1
- package/dist/args.d.ts +47 -0
- package/dist/args.js +185 -0
- package/dist/auth.js +43 -11
- package/dist/cli-bin.js +1 -1
- package/dist/cli.d.ts +2 -20
- package/dist/cli.js +71 -659
- package/dist/commands/account.d.ts +2 -0
- package/dist/commands/account.js +20 -0
- package/dist/commands/comment.d.ts +2 -0
- package/dist/commands/comment.js +66 -0
- package/dist/commands/entry.d.ts +31 -0
- package/dist/commands/entry.js +723 -0
- package/dist/commands/field.d.ts +3 -0
- package/dist/commands/field.js +261 -0
- package/dist/commands/folder.d.ts +2 -0
- package/dist/commands/folder.js +31 -0
- package/dist/commands/form.d.ts +2 -0
- package/dist/commands/form.js +412 -0
- package/dist/commands/index.d.ts +16 -0
- package/dist/commands/index.js +68 -0
- package/dist/commands/local.d.ts +10 -0
- package/dist/commands/local.js +76 -0
- package/dist/commands/opensearch.d.ts +2 -0
- package/dist/commands/opensearch.js +73 -0
- package/dist/commands/shared.d.ts +57 -0
- package/dist/commands/shared.js +122 -0
- package/dist/commands/table.d.ts +2 -0
- package/dist/commands/table.js +101 -0
- package/dist/{commands.d.ts → commands/types.d.ts} +24 -30
- package/dist/commands/types.js +1 -0
- package/dist/commands/upload.d.ts +7 -0
- package/dist/commands/upload.js +40 -0
- package/dist/commands/view.d.ts +2 -0
- package/dist/commands/view.js +81 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +45 -5
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +99 -0
- package/dist/help.d.ts +1 -1
- package/dist/help.js +11 -1
- package/dist/http.d.ts +37 -4
- package/dist/http.js +119 -14
- package/dist/local.d.ts +24 -0
- package/dist/local.js +208 -0
- package/dist/options.d.ts +8 -4
- package/dist/options.js +63 -18
- package/dist/payload.d.ts +14 -8
- package/dist/payload.js +22 -54
- package/dist/render.d.ts +21 -0
- package/dist/render.js +315 -0
- package/dist/result.d.ts +31 -0
- package/dist/result.js +32 -0
- package/dist/values.d.ts +4 -0
- package/dist/values.js +8 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +16 -0
- package/package.json +23 -18
- package/dist/commands.js +0 -1690
package/README.md
CHANGED
|
@@ -93,6 +93,28 @@ The settings block is always sent first. It is the half that can be rejected —
|
|
|
93
93
|
"this is not an exam form" — and sending it first is what guarantees a rejection
|
|
94
94
|
leaves every other change unsent.
|
|
95
95
|
|
|
96
|
+
### When the form takes entries
|
|
97
|
+
|
|
98
|
+
`setting` travels as is, on create and on edit. Its close rules decide when the
|
|
99
|
+
form is open; they coexist, and `form get` reads them back in the shape they
|
|
100
|
+
were written. On edit a rule replaces what was there (`time_periods` is the
|
|
101
|
+
whole list) and `{"enabled": false}` removes it.
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
# between two instants; either end may be left out
|
|
105
|
+
jinshuju form edit Kp7mQ2 --json '{"setting":{"by_time_range_close_rule":{"start_time":"2026-10-01T09:00:00+08:00","end_time":"2026-10-07T18:00:00+08:00"}}}'
|
|
106
|
+
# 11:00-12:40 and 17:00-18:30, every day
|
|
107
|
+
jinshuju form edit Kp7mQ2 --json '{"setting":{"daily_repeat_close_rule":{"time_periods":[
|
|
108
|
+
{"start_time":{"hour":11,"minute":0},"end_time":{"hour":12,"minute":40}},
|
|
109
|
+
{"start_time":{"hour":17,"minute":0},"end_time":{"hour":18,"minute":30}}]}}}'
|
|
110
|
+
jinshuju form edit Kp7mQ2 --json '{"setting":{"daily_repeat_close_rule":{"enabled":false}}}'
|
|
111
|
+
jinshuju form edit Kp7mQ2 --json '{"setting":{"by_entries_close_rule":{"limit":100}}}' # closes after 100 entries
|
|
112
|
+
jinshuju form edit Kp7mQ2 --json '{"setting":{"manually_close_rule":{"closed":true}}}' # stops it now
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`show_form_before_open` and `show_close_count_down` only hold with a time-range
|
|
116
|
+
or daily rule; without one the save resets them to false.
|
|
117
|
+
|
|
96
118
|
## Reading data
|
|
97
119
|
|
|
98
120
|
`entry`, `view`, `field` and `comment` are all top-level resources; the
|
|
@@ -267,10 +289,25 @@ finished.
|
|
|
267
289
|
|
|
268
290
|
That is what `--wait` is for. It waits for the job to settle, reports how many
|
|
269
291
|
rows were written, skipped and rejected, and **exits non-zero on failure**.
|
|
292
|
+
It gives up after thirty minutes, naming the job so it can still be looked up.
|
|
270
293
|
Without it a failed import is invisible — the command succeeds and not a single
|
|
271
294
|
row is written. After the fact, `entry import-status` answers the same question
|
|
272
295
|
from a job id.
|
|
273
296
|
|
|
297
|
+
## Line-delimited JSON
|
|
298
|
+
|
|
299
|
+
`--output jsonl` answers one JSON object per line: a listing becomes its rows,
|
|
300
|
+
anything else is one line. With `--all` the rows are written as each page
|
|
301
|
+
arrives and nothing is held back, so a listing of any size streams through
|
|
302
|
+
`jq -c`, a shell loop or a log shipper without first fitting in memory.
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
jinshuju entry list --form Kp7mQ2 --all --output jsonl | jq -c 'select(.field_3 > 80)'
|
|
306
|
+
jinshuju entry list --form Kp7mQ2 --all --output jsonl | while read -r row; do …; done
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Errors are JSON on stderr under `jsonl` exactly as under `json`.
|
|
310
|
+
|
|
274
311
|
## Progress
|
|
275
312
|
|
|
276
313
|
Long-running commands (`--all` paging, uploads, `--wait`) report progress.
|
|
@@ -278,6 +315,45 @@ Progress is written **to stderr, and only when stderr is a terminal**, so
|
|
|
278
315
|
`--output json | jq` receives exactly the same bytes it would without it: a pipe,
|
|
279
316
|
or an agent on the other end, never sees a stray character.
|
|
280
317
|
|
|
318
|
+
## Exit codes
|
|
319
|
+
|
|
320
|
+
The exit code says what kind of failure it was, so a script can branch without
|
|
321
|
+
parsing anything:
|
|
322
|
+
|
|
323
|
+
| code | meaning |
|
|
324
|
+
| ---- | ------------------------------------------------------------------------ |
|
|
325
|
+
| 0 | done |
|
|
326
|
+
| 1 | something unexpected; please report it |
|
|
327
|
+
| 2 | usage: a flag, argument, input file or unknown command |
|
|
328
|
+
| 3 | authentication: no credential, or one the server refused (401, 403) |
|
|
329
|
+
| 4 | not found (404) |
|
|
330
|
+
| 5 | refused by the API: validation, conflict, quota (other 4xx) |
|
|
331
|
+
| 6 | the server failed (5xx) |
|
|
332
|
+
| 7 | transport: the connection failed or timed out |
|
|
333
|
+
| 8 | rate limited: wait and retry; the message and `retry_after` say how long |
|
|
334
|
+
|
|
335
|
+
With `--output json`, stderr carries the same as JSON, plus the status and body
|
|
336
|
+
the server answered with:
|
|
337
|
+
|
|
338
|
+
```json
|
|
339
|
+
{
|
|
340
|
+
"error": {
|
|
341
|
+
"kind": "not_found",
|
|
342
|
+
"message": "form cannot be found",
|
|
343
|
+
"status": 404,
|
|
344
|
+
"body": { "error_description": "form cannot be found" }
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
## Timeouts and retries
|
|
350
|
+
|
|
351
|
+
Every request has a deadline of one minute; `JINSHUJU_TIMEOUT_MS` changes it. A
|
|
352
|
+
request the server answers with 429 or 503 is tried again after backing off,
|
|
353
|
+
honouring `Retry-After` when it is sent. A read is also retried after a gateway
|
|
354
|
+
failure or a dropped connection. A write is not: a POST that timed out may well
|
|
355
|
+
have landed, and sending it again would create the entry twice.
|
|
356
|
+
|
|
281
357
|
## Before removing a field
|
|
282
358
|
|
|
283
359
|
```bash
|
|
@@ -306,8 +382,11 @@ digits**, for example `Kp7mQ2`, `Vn4xR8`, `aB3dE9`. Examples here and in
|
|
|
306
382
|
|
|
307
383
|
## Development
|
|
308
384
|
|
|
385
|
+
How the code is organised, and why, is in [ARCHITECTURE.md](ARCHITECTURE.md).
|
|
386
|
+
|
|
309
387
|
```bash
|
|
310
388
|
npm install
|
|
311
389
|
npm test
|
|
312
|
-
npm run typecheck
|
|
390
|
+
npm run check # typecheck + oxlint + oxfmt --check, what CI runs
|
|
391
|
+
npm run fmt # format in place with oxfmt
|
|
313
392
|
```
|
package/dist/args.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Command } from './commands/index.js';
|
|
2
|
+
import { type OptionSpec } from './options.js';
|
|
3
|
+
/**
|
|
4
|
+
* The command line, taken apart. Nothing here knows what a command does: it
|
|
5
|
+
* knows which words name one, which flags take a value, and how a value is
|
|
6
|
+
* read into the type its option declares.
|
|
7
|
+
*/
|
|
8
|
+
type RawArgs = {
|
|
9
|
+
words: string[];
|
|
10
|
+
flags: Record<string, unknown>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The words that name the command: enough to find it, and no more.
|
|
14
|
+
*
|
|
15
|
+
* A flag may come first — `jinshuju --config local.json form list` is what a
|
|
16
|
+
* shell alias expands to, and what anyone arriving from `git -C` or
|
|
17
|
+
* `kubectl --context` writes — so a flag this CLI knows without a command is
|
|
18
|
+
* stepped over, along with its value. Stopping at it instead reported "Unknown
|
|
19
|
+
* command: jinshuju form list" while offering that very command as a
|
|
20
|
+
* suggestion.
|
|
21
|
+
*
|
|
22
|
+
* An unknown flag still ends the scan. Only a command declares those, so by the
|
|
23
|
+
* time one appears the command has been named already.
|
|
24
|
+
*/
|
|
25
|
+
export declare function leadingWords(argv: readonly string[]): string[];
|
|
26
|
+
/**
|
|
27
|
+
* Splits the command line, knowing which flags take a value.
|
|
28
|
+
*
|
|
29
|
+
* Guessing from the shape of the next token gets two things wrong that a
|
|
30
|
+
* caller has every right to write: `--json -`, where the value is the very
|
|
31
|
+
* character that looks like a flag, and `--yes 12`, where a boolean must not
|
|
32
|
+
* swallow the argument behind it. Both are decided by the option's own type,
|
|
33
|
+
* so the specs are passed in rather than inferred.
|
|
34
|
+
*/
|
|
35
|
+
export declare function splitArgs(argv: readonly string[], specs?: readonly OptionSpec[]): RawArgs;
|
|
36
|
+
/**
|
|
37
|
+
* Checks the flags against what this command declares. A flag belonging to
|
|
38
|
+
* another command is an error rather than something quietly ignored: that is
|
|
39
|
+
* how a caller learns it asked for something that was never going to happen.
|
|
40
|
+
*/
|
|
41
|
+
export declare function bindOptions(specs: readonly OptionSpec[], flags: Record<string, unknown>, label: string, stdin: () => string): Record<string, unknown>;
|
|
42
|
+
export declare function bindArgs(command: Command, words: readonly string[]): {
|
|
43
|
+
args: Record<string, string>;
|
|
44
|
+
rest: string[];
|
|
45
|
+
};
|
|
46
|
+
export declare function readStdin(): string;
|
|
47
|
+
export {};
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { GLOBAL_OPTIONS, LOCAL_OPTIONS, UsageError, optionKey, readJsonInput } from './options.js';
|
|
3
|
+
/**
|
|
4
|
+
* The words that name the command: enough to find it, and no more.
|
|
5
|
+
*
|
|
6
|
+
* A flag may come first — `jinshuju --config local.json form list` is what a
|
|
7
|
+
* shell alias expands to, and what anyone arriving from `git -C` or
|
|
8
|
+
* `kubectl --context` writes — so a flag this CLI knows without a command is
|
|
9
|
+
* stepped over, along with its value. Stopping at it instead reported "Unknown
|
|
10
|
+
* command: jinshuju form list" while offering that very command as a
|
|
11
|
+
* suggestion.
|
|
12
|
+
*
|
|
13
|
+
* An unknown flag still ends the scan. Only a command declares those, so by the
|
|
14
|
+
* time one appears the command has been named already.
|
|
15
|
+
*/
|
|
16
|
+
export function leadingWords(argv) {
|
|
17
|
+
const known = new Map();
|
|
18
|
+
for (const spec of [...GLOBAL_OPTIONS, ...LOCAL_OPTIONS]) {
|
|
19
|
+
known.set(spec.name, spec);
|
|
20
|
+
if (spec.short)
|
|
21
|
+
known.set(spec.short, spec);
|
|
22
|
+
}
|
|
23
|
+
const words = [];
|
|
24
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
25
|
+
const token = argv[index];
|
|
26
|
+
if (!token.startsWith('-') || token === '-') {
|
|
27
|
+
words.push(token);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const equals = token.indexOf('=');
|
|
31
|
+
const spec = known.get(equals === -1 ? token : token.slice(0, equals));
|
|
32
|
+
if (!spec)
|
|
33
|
+
break;
|
|
34
|
+
if (equals === -1 && spec.type !== 'boolean')
|
|
35
|
+
index += 1;
|
|
36
|
+
}
|
|
37
|
+
return words;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Splits the command line, knowing which flags take a value.
|
|
41
|
+
*
|
|
42
|
+
* Guessing from the shape of the next token gets two things wrong that a
|
|
43
|
+
* caller has every right to write: `--json -`, where the value is the very
|
|
44
|
+
* character that looks like a flag, and `--yes 12`, where a boolean must not
|
|
45
|
+
* swallow the argument behind it. Both are decided by the option's own type,
|
|
46
|
+
* so the specs are passed in rather than inferred.
|
|
47
|
+
*/
|
|
48
|
+
export function splitArgs(argv, specs = []) {
|
|
49
|
+
const takesValue = new Map();
|
|
50
|
+
for (const spec of specs) {
|
|
51
|
+
takesValue.set(spec.name, spec.type !== 'boolean');
|
|
52
|
+
if (spec.short)
|
|
53
|
+
takesValue.set(spec.short, spec.type !== 'boolean');
|
|
54
|
+
}
|
|
55
|
+
const words = [];
|
|
56
|
+
const flags = {};
|
|
57
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
58
|
+
const token = argv[index];
|
|
59
|
+
if (token === '--') {
|
|
60
|
+
words.push(...argv.slice(index + 1));
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (!token.startsWith('-') || token === '-') {
|
|
64
|
+
words.push(token);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const equals = token.indexOf('=');
|
|
68
|
+
const flag = equals === -1 ? token : token.slice(0, equals);
|
|
69
|
+
const inline = equals === -1 ? undefined : token.slice(equals + 1);
|
|
70
|
+
const next = argv[index + 1];
|
|
71
|
+
// An unknown flag is assumed to take a value, so it reaches bindOptions
|
|
72
|
+
// with whatever followed it and is refused by name rather than by shape.
|
|
73
|
+
const wanted = takesValue.get(flag) ?? true;
|
|
74
|
+
const consumable = wanted && next !== undefined && (next === '-' || !next.startsWith('-'));
|
|
75
|
+
const value = inline ?? (consumable ? ((index += 1), next) : true);
|
|
76
|
+
const existing = flags[flag];
|
|
77
|
+
flags[flag] = existing === undefined ? value : [].concat(existing, value);
|
|
78
|
+
}
|
|
79
|
+
return { words, flags };
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Checks the flags against what this command declares. A flag belonging to
|
|
83
|
+
* another command is an error rather than something quietly ignored: that is
|
|
84
|
+
* how a caller learns it asked for something that was never going to happen.
|
|
85
|
+
*/
|
|
86
|
+
export function bindOptions(specs, flags, label, stdin) {
|
|
87
|
+
const byFlag = new Map();
|
|
88
|
+
for (const spec of specs) {
|
|
89
|
+
byFlag.set(spec.name, spec);
|
|
90
|
+
if (spec.short)
|
|
91
|
+
byFlag.set(spec.short, spec);
|
|
92
|
+
}
|
|
93
|
+
const bound = {};
|
|
94
|
+
for (const [flag, value] of Object.entries(flags)) {
|
|
95
|
+
const spec = byFlag.get(flag);
|
|
96
|
+
if (!spec)
|
|
97
|
+
throw new UsageError(`${label} does not take ${flag}. Run it with --help to see what it does take.`);
|
|
98
|
+
bound[optionKey(spec)] = coerce(spec, value, stdin);
|
|
99
|
+
}
|
|
100
|
+
return bound;
|
|
101
|
+
}
|
|
102
|
+
function coerce(spec, value, stdin) {
|
|
103
|
+
if (spec.repeatable)
|
|
104
|
+
return [].concat(value).map((item) => coerceOne(spec, item, stdin));
|
|
105
|
+
if (Array.isArray(value))
|
|
106
|
+
throw new UsageError(`${spec.name} takes a single value, but was given more than once`);
|
|
107
|
+
return coerceOne(spec, value, stdin);
|
|
108
|
+
}
|
|
109
|
+
function coerceOne(spec, value, stdin) {
|
|
110
|
+
if (spec.type === 'boolean') {
|
|
111
|
+
if (value === true || value === 'true')
|
|
112
|
+
return true;
|
|
113
|
+
if (value === 'false')
|
|
114
|
+
return false;
|
|
115
|
+
throw new UsageError(`${spec.name} is a flag and takes no value`);
|
|
116
|
+
}
|
|
117
|
+
if (value === true)
|
|
118
|
+
throw new UsageError(`${spec.name} needs a value`);
|
|
119
|
+
const text = String(value);
|
|
120
|
+
if (spec.choices && !spec.choices.includes(text)) {
|
|
121
|
+
throw new UsageError(`${spec.name} must be one of ${spec.choices.join(', ')}, got ${JSON.stringify(text)}`);
|
|
122
|
+
}
|
|
123
|
+
if (spec.type === 'integer') {
|
|
124
|
+
if (!/^\d+$/.test(text))
|
|
125
|
+
throw new UsageError(`${spec.name} must be a whole number, got ${JSON.stringify(text)}`);
|
|
126
|
+
return Number.parseInt(text, 10);
|
|
127
|
+
}
|
|
128
|
+
if (spec.type === 'list')
|
|
129
|
+
return text
|
|
130
|
+
.split(',')
|
|
131
|
+
.map((item) => item.trim())
|
|
132
|
+
.filter(Boolean);
|
|
133
|
+
if (spec.type === 'json')
|
|
134
|
+
return readJsonInput(text, stdin);
|
|
135
|
+
return text;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* A stray word that looks like a token, on a command whose parent is a flag, is
|
|
139
|
+
* almost always `field list <token>` written as `form get <token>` reads. Saying
|
|
140
|
+
* only that the argument is not taken leaves the caller to find that out.
|
|
141
|
+
*/
|
|
142
|
+
function containerHint(command, extra) {
|
|
143
|
+
const takesContainer = (command.options ?? []).some((option) => option.name === '--form');
|
|
144
|
+
if (!takesContainer || !/^[A-Za-z0-9]{6}$/.test(extra))
|
|
145
|
+
return '';
|
|
146
|
+
return `. Did you mean --form ${extra}? (a table: --table ${extra})`;
|
|
147
|
+
}
|
|
148
|
+
export function bindArgs(command, words) {
|
|
149
|
+
const positionals = words.slice(command.path.length);
|
|
150
|
+
const specs = command.args ?? [];
|
|
151
|
+
const args = {};
|
|
152
|
+
let rest = [];
|
|
153
|
+
specs.forEach((arg, index) => {
|
|
154
|
+
if (arg.variadic) {
|
|
155
|
+
rest = positionals.slice(index);
|
|
156
|
+
if (arg.required && rest.length === 0) {
|
|
157
|
+
throw new UsageError(`jinshuju ${command.path.join(' ')} needs <${arg.name}>: ${arg.description}`);
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const value = positionals[index];
|
|
162
|
+
if (value === undefined) {
|
|
163
|
+
if (arg.required)
|
|
164
|
+
throw new UsageError(`jinshuju ${command.path.join(' ')} needs <${arg.name}>: ${arg.description}`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
args[arg.name] = value;
|
|
168
|
+
});
|
|
169
|
+
if (!specs.some((arg) => arg.variadic)) {
|
|
170
|
+
const extra = positionals.slice(specs.length);
|
|
171
|
+
if (extra.length > 0) {
|
|
172
|
+
throw new UsageError(`jinshuju ${command.path.join(' ')} takes no argument ${JSON.stringify(extra[0])}` +
|
|
173
|
+
containerHint(command, extra[0]));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { args, rest };
|
|
177
|
+
}
|
|
178
|
+
export function readStdin() {
|
|
179
|
+
try {
|
|
180
|
+
return readFileSync(0, 'utf8');
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
throw new UsageError('could not read JSON from stdin');
|
|
184
|
+
}
|
|
185
|
+
}
|
package/dist/auth.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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';
|
|
4
5
|
import { clearOAuthConfig, defaultScopes, loadConfig, saveOAuthConfig } from './config.js';
|
|
5
6
|
function base64Url(bytes) {
|
|
6
7
|
return bytes.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
@@ -22,10 +23,14 @@ export function buildAuthorizationUrl(params) {
|
|
|
22
23
|
return url.toString();
|
|
23
24
|
}
|
|
24
25
|
export async function loginWithOAuth(options = {}, opener = openUrl) {
|
|
25
|
-
const config = loadConfig({
|
|
26
|
+
const config = loadConfig({
|
|
27
|
+
configPath: options.configPath,
|
|
28
|
+
env: options.env,
|
|
29
|
+
cli: { host: options.host, authHost: options.authHost, clientId: options.clientId }
|
|
30
|
+
});
|
|
26
31
|
const clientId = options.clientId ?? config.clientId;
|
|
27
32
|
if (!clientId)
|
|
28
|
-
throw new
|
|
33
|
+
throw new AuthError('Missing OAuth client id. Set JINSHUJU_OAUTH_CLIENT_ID or config client_id.');
|
|
29
34
|
const state = base64Url(randomBytes(24));
|
|
30
35
|
const { verifier, challenge } = createPkcePair();
|
|
31
36
|
const scope = options.scopes ?? defaultScopes;
|
|
@@ -38,6 +43,10 @@ export async function loginWithOAuth(options = {}, opener = openUrl) {
|
|
|
38
43
|
state,
|
|
39
44
|
codeChallenge: challenge
|
|
40
45
|
});
|
|
46
|
+
// The callback can fail while the browser is still being opened — a forged
|
|
47
|
+
// state, a refusal — and a rejection nobody is awaiting yet is reported as
|
|
48
|
+
// unhandled. It is awaited right below; this only says so in the meantime.
|
|
49
|
+
callback.code.catch(() => undefined);
|
|
41
50
|
if (options.openBrowser !== false)
|
|
42
51
|
await opener(authorizeUrl);
|
|
43
52
|
const code = await callback.code;
|
|
@@ -48,12 +57,12 @@ export async function loginWithOAuth(options = {}, opener = openUrl) {
|
|
|
48
57
|
}
|
|
49
58
|
export async function refreshOAuthToken(config) {
|
|
50
59
|
if (!config.auth?.refresh_token)
|
|
51
|
-
throw new
|
|
60
|
+
throw new AuthError('No OAuth refresh token. Run `jinshuju auth login` again.');
|
|
52
61
|
const token = await tokenRequest(config.auth.auth_host, {
|
|
53
62
|
grant_type: 'refresh_token',
|
|
54
63
|
client_id: config.auth.client_id,
|
|
55
64
|
refresh_token: config.auth.refresh_token
|
|
56
|
-
});
|
|
65
|
+
}, config.timeoutMs);
|
|
57
66
|
const auth = toOAuthConfig(config, config.auth.client_id, token, config.auth);
|
|
58
67
|
saveOAuthConfig(config.configPath, auth);
|
|
59
68
|
return auth;
|
|
@@ -65,7 +74,8 @@ export async function revokeOAuthToken(config) {
|
|
|
65
74
|
await fetch(url, {
|
|
66
75
|
method: 'POST',
|
|
67
76
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
68
|
-
body: new URLSearchParams({ client_id: config.auth.client_id, token: config.auth.access_token })
|
|
77
|
+
body: new URLSearchParams({ client_id: config.auth.client_id, token: config.auth.access_token }),
|
|
78
|
+
signal: AbortSignal.timeout(config.timeoutMs ?? TOKEN_TIMEOUT_MS)
|
|
69
79
|
}).catch(() => undefined);
|
|
70
80
|
clearOAuthConfig(config.configPath);
|
|
71
81
|
}
|
|
@@ -83,20 +93,40 @@ async function exchangeAuthorizationCode(authHost, clientId, redirectUri, code,
|
|
|
83
93
|
code_verifier: codeVerifier
|
|
84
94
|
});
|
|
85
95
|
}
|
|
86
|
-
|
|
96
|
+
/**
|
|
97
|
+
* A token endpoint that answers with something other than JSON — a login page,
|
|
98
|
+
* a gateway's error — is reported as the status it sent. Parsing first turned
|
|
99
|
+
* that into "Unexpected token '<'" with the status nowhere to be seen.
|
|
100
|
+
*/
|
|
101
|
+
function parseTokenBody(text, response) {
|
|
102
|
+
if (!text)
|
|
103
|
+
return undefined;
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(text);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
const flat = text.replace(/\s+/g, ' ').trim();
|
|
109
|
+
throw new AuthError(`${response.status} ${response.statusText} from the token endpoint, and the body is not JSON: ` +
|
|
110
|
+
(flat.length <= 120 ? flat : `${flat.slice(0, 120)}…`));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** A token endpoint answers at once or not at all; a minute is generous. */
|
|
114
|
+
const TOKEN_TIMEOUT_MS = 60_000;
|
|
115
|
+
async function tokenRequest(authHost, params, timeoutMs = TOKEN_TIMEOUT_MS) {
|
|
87
116
|
const url = new URL('/oauth/token', authHost);
|
|
88
117
|
const response = await fetch(url, {
|
|
89
118
|
method: 'POST',
|
|
90
119
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
91
|
-
body: new URLSearchParams(params)
|
|
120
|
+
body: new URLSearchParams(params),
|
|
121
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
92
122
|
});
|
|
93
123
|
const text = await response.text();
|
|
94
|
-
const body = text
|
|
124
|
+
const body = parseTokenBody(text, response);
|
|
95
125
|
if (!response.ok) {
|
|
96
|
-
throw new
|
|
126
|
+
throw new AuthError(body?.error_description ?? body?.error ?? `${response.status} ${response.statusText}`.trim());
|
|
97
127
|
}
|
|
98
128
|
if (!body?.access_token)
|
|
99
|
-
throw new
|
|
129
|
+
throw new AuthError('OAuth token response is missing access_token');
|
|
100
130
|
return body;
|
|
101
131
|
}
|
|
102
132
|
function toOAuthConfig(config, clientId, token, previous) {
|
|
@@ -137,7 +167,9 @@ function listenForOAuthCallback(expectedState, port = 0, timeoutMs = 120_000) {
|
|
|
137
167
|
callbackReject(new Error('Missing OAuth code'));
|
|
138
168
|
return;
|
|
139
169
|
}
|
|
140
|
-
res
|
|
170
|
+
res
|
|
171
|
+
.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
172
|
+
.end('Jinshuju CLI login complete. You can close this tab.');
|
|
141
173
|
callbackResolve(code);
|
|
142
174
|
});
|
|
143
175
|
let callbackResolve;
|
package/dist/cli-bin.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { runCli } from './cli.js';
|
|
3
|
-
const result = await runCli(process.argv.slice(2));
|
|
3
|
+
const result = await runCli(process.argv.slice(2), { stdout: (chunk) => void process.stdout.write(chunk) });
|
|
4
4
|
if (result.stdout)
|
|
5
5
|
process.stdout.write(result.stdout);
|
|
6
6
|
if (result.stderr)
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,21 +1,3 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
export type CliResult
|
|
3
|
-
exitCode: number;
|
|
4
|
-
stdout: string;
|
|
5
|
-
stderr: string;
|
|
6
|
-
};
|
|
7
|
-
export type CliRuntime = {
|
|
8
|
-
env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
|
|
9
|
-
client?: HttpClient;
|
|
10
|
-
stdin?: () => string;
|
|
11
|
-
/** How wide a table may be. Defaults to the terminal, or 120 through a pipe. */
|
|
12
|
-
width?: number;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Read from package.json, not restated here. A release bumps that file and
|
|
16
|
-
* nothing else, so a constant reports the previous version from the moment it
|
|
17
|
-
* is published — 0.1.1 shipped saying 0.1.0.
|
|
18
|
-
*/
|
|
19
|
-
export declare const VERSION: string;
|
|
20
|
-
export declare function terminalWidth(stream?: NodeJS.WriteStream): number;
|
|
1
|
+
import { type CliResult, type CliRuntime } from './result.js';
|
|
2
|
+
export type { CliResult, CliRuntime } from './result.js';
|
|
21
3
|
export declare function runCli(args?: string[], runtime?: CliRuntime): Promise<CliResult>;
|