@parnniti/snow 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nitipan Su-inn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # snow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small ServiceNow CLI that logs in through your browser, so it works with SSO (SAML/OIDC) and MFA.
4
+ You don't need a password, an admin-created OAuth app, or a client secret. It has no dependencies and needs Node ≥ 20.18.
5
+
6
+ ```bash
7
+ npm install -g @parnniti/snow # installs the `snow` command
8
+ snow context add prod acme # → https://acme.service-now.com
9
+ snow login
10
+ snow inc list --mine
11
+ ```
12
+
13
+ ## How login works
14
+
15
+ `snow login` uses OAuth 2.0 authorization code + PKCE with the public OAuth client that ServiceNow ships
16
+ on instances for the [ServiceNow SDK](https://servicenow.github.io/sdk/). It is the same client and redirect
17
+ that `now-sdk auth --type oauth` uses: `client_id 543e5655f77746a28228c6009a599dfb`, redirect `/sdk-oauth.do`.
18
+
19
+ 1. Your browser opens the instance's consent page. Sign in the way the instance normally asks: SSO, MFA or a local login.
20
+ 2. The `/sdk-oauth.do` page shows a one-time code. Paste it into the terminal. You can paste the bare code,
21
+ the `CODE&state=…` string the page shows, or the full URL.
22
+ 3. The tokens are stored and the access token refreshes automatically. When the refresh token
23
+ expires, run `snow login` again.
24
+
25
+ For scripts or agents that can't type into a prompt: run `snow login --print-url`, open the URL, then run
26
+ `snow login --code '<pasted>'` within 10 minutes.
27
+
28
+ **If login fails with an OAuth error,** the instance may have disabled or restricted the SDK client. Ask an
29
+ admin to register a public OAuth client (Application Registry → "Create an OAuth API endpoint for external
30
+ clients", PKCE, no secret). Then point `snow` at it:
31
+
32
+ ```bash
33
+ export SNOW_OAUTH_CLIENT_ID=<client_id>
34
+ export SNOW_OAUTH_REDIRECT_URI=<redirect registered on the client> # default /sdk-oauth.do
35
+ ```
36
+
37
+ To check whether an instance accepts the SDK client, run the command below. A 302 means the client is
38
+ registered; a 401 means it is not.
39
+
40
+ ```bash
41
+ curl -s -o /dev/null -w '%{http_code}\n' \
42
+ 'https://acme.service-now.com/oauth_auth.do?response_type=code&client_id=543e5655f77746a28228c6009a599dfb&redirect_uri=%2Fsdk-oauth.do'
43
+ ```
44
+
45
+ ### Where tokens live
46
+
47
+ - **macOS:** the login keychain, service `snow-cli`, with the context name as the account. The secret is passed
48
+ to `security` on stdin, never on the command line.
49
+ - **Elsewhere, or with `SNOW_TOKEN_STORE=file`:** `~/.config/snow/tokens/<context>.json`, file mode 0600.
50
+
51
+ `snow logout` revokes the token on the instance (best effort) and deletes it locally.
52
+
53
+ ## Contexts
54
+
55
+ ```bash
56
+ snow context add dev acmedev # the first context added becomes current
57
+ snow context add prod acme
58
+ snow context # list; * = current, user = logged-in account
59
+ snow context use prod
60
+ snow -c dev inc list # per-command override (or SNOW_CONTEXT=dev)
61
+ ```
62
+
63
+ The instance can be given as `acme`, `acme.service-now.com`, or a full URL for custom domains.
64
+ The config file is `~/.config/snow/config.json`; set `SNOW_CONFIG_DIR` to use another directory.
65
+
66
+ ## Records
67
+
68
+ | command | table | subcommands |
69
+ |---|---|---|
70
+ | `incident` / `inc` | `incident` | list, get, create, update, comment |
71
+ | `change` / `chg` | `change_request` | list, get, create, update, comment |
72
+ | `ritm` | `sc_req_item` | list, get, update, comment |
73
+ | `sctask` / `task` | `sc_task` | list, get, update, comment |
74
+
75
+ ```bash
76
+ snow inc list # active records, newest update first, 20 rows
77
+ snow inc list --mine # assigned to me
78
+ snow inc list --opened-by-me --all # include inactive records
79
+ snow inc list --group "Service Desk" -q 'priority<=2' -l 50
80
+ snow inc get INC0010001
81
+ snow inc create -t "VPN down for site B" --description "..." --group "Network" --urgency 2 --impact 2
82
+ snow inc update INC0010001 -s state=2 --assignee "Jane Doe"
83
+ snow inc comment INC0010001 "Mitigated; monitoring" # customer-visible comment
84
+ snow inc comment INC0010001 "Root cause: ..." --work-note # internal work note
85
+ snow chg create -t "Patch DB cluster" --type normal --start "2026-12-01 22:00:00" --end "2026-12-01 23:00:00"
86
+ ```
87
+
88
+ - **Reads** return display values. Add `--raw` to get stored values (sys_ids, choice numbers) instead.
89
+ - **Writes** send `sysparm_input_display_value=true`, so reference fields take names:
90
+ `--group "Service Desk"`, `-s assigned_to="Jane Doe"`. Choice fields take their stored value, e.g. `-s state=2`.
91
+ - **Lookup** takes a record number in any numbering format, or a 32-character sys_id.
92
+ - Add `-o json` to any command for machine-readable output.
93
+
94
+ ## Generic access
95
+
96
+ ```bash
97
+ snow table list sys_user_group -q 'nameLIKEnetwork' -f name,manager
98
+ snow table get sys_user <sys_id> --all-fields
99
+ snow table update u_custom_table <sys_id> -d @patch.json
100
+ snow api GET /api/now/table/sys_user_group -q sysparm_fields=sys_id,name -q sysparm_limit=5
101
+ snow api POST /api/now/table/incident -d '{"short_description":"test"}'
102
+ curl -H "$(snow token --header)" 'https://acme.service-now.com/api/now/table/incident?sysparm_limit=1'
103
+ ```
104
+
105
+ `snow api` and `snow table` refuse to send the token to any host other than the context's instance.
106
+
107
+ ## Agent skills
108
+
109
+ `snow` ships an agent skill, so coding agents know how to use it: the agent login flow, picking the
110
+ context, queries, rules for writes, and what the errors mean.
111
+
112
+ ```bash
113
+ snow skills # bundled skills and where they are installed
114
+ snow skills install # → ~/.agents/skills/snow (Codex, Cursor, Gemini, Copilot, ...)
115
+ snow skills install --agent claude # also link ~/.claude/skills/snow (Claude Code)
116
+ snow skills install --local # this project only: ./.agents/skills, ./.claude/skills
117
+ snow skills get snow # print it without installing
118
+ snow skills uninstall
119
+ ```
120
+
121
+ Re-run `snow skills install` after upgrading `snow` to refresh the installed copy. A directory with the same name
122
+ that `snow` did not install is left untouched unless you pass `--force`.
123
+
124
+ The skill also lives in the repo at `skills/snow/`, so `npx skills add parnniti/snow` works too.
125
+
126
+ ## Notes
127
+
128
+ - Results follow your ServiceNow roles and ACLs. `(0 visible of N matching; rows hidden by ACLs)` means
129
+ the records exist but your account can't read them.
130
+ - `SNOW_DEBUG=1` prints stack traces.
131
+ - Run `npm test` to execute the unit tests (Node's built-in test runner).
132
+
133
+ ## License
134
+
135
+ MIT
package/bin/snow.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { handleError, main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).catch(handleError);
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@parnniti/snow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "ServiceNow CLI with browser/SSO login (OAuth 2.0 authorization code + PKCE). Incidents, changes, requests, any table, raw REST.",
5
+ "keywords": [
6
+ "servicenow",
7
+ "cli",
8
+ "sso",
9
+ "oauth",
10
+ "pkce",
11
+ "incident",
12
+ "itsm"
13
+ ],
14
+ "homepage": "https://github.com/parnniti/snow#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/parnniti/snow.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/parnniti/snow/issues"
21
+ },
22
+ "author": "Nitipan Su-inn (https://github.com/parnniti)",
23
+ "type": "module",
24
+ "bin": {
25
+ "snow": "bin/snow.js"
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "src",
30
+ "skills"
31
+ ],
32
+ "scripts": {
33
+ "test": "node --test"
34
+ },
35
+ "engines": {
36
+ "node": ">=20.18"
37
+ },
38
+ "license": "MIT",
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: snow
3
+ description: Use for ServiceNow work through the `snow` CLI - incidents, changes, requests (RITM), catalog tasks (SCTASK), any table or REST call - plus SSO login, instance contexts, and "rows hidden by ACLs" or 403 permission errors.
4
+ metadata:
5
+ short-description: ServiceNow CLI with browser/SSO login
6
+ compatibility: claude-code, codex-cli, any .agents/skills-compatible agent
7
+ ---
8
+
9
+ # ServiceNow via `snow`
10
+
11
+ `snow` talks to ServiceNow's REST Table API with an OAuth token obtained through the browser
12
+ (works with SSO and MFA). Run `snow <command> -h` for exact flags. If `snow` is missing:
13
+ `npm install -g @parnniti/snow`.
14
+
15
+ ## Pick the instance first
16
+
17
+ - `snow context` lists configured instances (`*` = current, `user` = logged-in account).
18
+ - Pass `-c <context>` on every command unless the user named the current one. A wrong context is the
19
+ most common cause of empty lists and 403s: the same account usually has roles on production but
20
+ not on dev or test instances.
21
+ - No contexts yet: `snow context add <name> <instance>` (instance = `acme`, `acme.service-now.com`, or URL).
22
+
23
+ ## Log in (agent-driven)
24
+
25
+ You cannot type into the interactive prompt, so use the two-step flow:
26
+
27
+ 1. `url=$(snow -c <ctx> login --print-url 2>/dev/null) && open "$url"` (use `xdg-open` on Linux, or
28
+ show the URL to the user).
29
+ 2. Ask the user to sign in and paste the code that the `/sdk-oauth.do` page shows. The page shows
30
+ `CODE&state=STATE`; the whole string is fine.
31
+ 3. Within 10 minutes: `snow -c <ctx> login --code '<pasted>'`.
32
+ 4. Confirm with `snow -c <ctx> whoami`. Tokens refresh automatically afterwards.
33
+
34
+ Never print, log, or store the output of `snow token`; it is a live bearer token.
35
+
36
+ ## Read
37
+
38
+ ```bash
39
+ snow -c prod inc list # active, newest update first, 20 rows
40
+ snow -c prod inc list --mine # assigned to me
41
+ snow -c prod inc list --opened-by-me --all # include closed
42
+ snow -c prod task list -q 'assignment_group=javascript:getMyGroups()' # "assigned to my groups"
43
+ snow -c prod chg list --group "Network" -l 50
44
+ snow -c prod ritm get <NUMBER> # any numbering scheme, or a 32-char sys_id
45
+ snow -c prod table list <table> -q '<encoded query>' -f field1,field2
46
+ snow -c prod api GET /api/now/<path> -q sysparm_limit=5
47
+ ```
48
+
49
+ - Add `-o json` whenever you will parse the result.
50
+ - Reads return display values; `--raw` returns stored values (sys_ids, choice numbers).
51
+ - Filters use ServiceNow encoded queries. See [references/encoded-queries.md](references/encoded-queries.md).
52
+
53
+ Command map: `incident`/`inc` → incident, `change`/`chg` → change_request, `ritm` → sc_req_item,
54
+ `sctask`/`task` → sc_task. All have list, get, update, comment; incident and change also have create.
55
+
56
+ ## Write
57
+
58
+ Creating, updating, and commenting change shared records that other people see and that may notify
59
+ requesters. Before any write:
60
+
61
+ 1. Confirm the context (`-c`) and the exact record with the user.
62
+ 2. Show the fields you will send and get an explicit go-ahead.
63
+
64
+ ```bash
65
+ snow -c prod inc create -t "Short description" --description "..." --group "Service Desk" --urgency 2 --impact 2
66
+ snow -c prod inc update <NUMBER> -s state=2 --assignee "Jane Doe"
67
+ snow -c prod task comment <NUMBER> "Customer-visible comment"
68
+ snow -c prod task comment <NUMBER> "Internal note" --work-note
69
+ snow -c prod table update <table> <sys_id> -d '{"field":"value"}'
70
+ ```
71
+
72
+ - Reference fields take display names (`--group "Service Desk"`, `-s assigned_to="Jane Doe"`).
73
+ - Choice fields take stored values. Look them up instead of guessing:
74
+ `snow -c prod table list sys_choice -q 'name=incident^element=state^inactive=false' -f value,label --raw`
75
+
76
+ ## Errors
77
+
78
+ | Message | Meaning | Action |
79
+ |---|---|---|
80
+ | `not logged in to "<ctx>"` / `refresh token rejected` | No or expired session | Run the login flow above |
81
+ | `(0 visible of N matching; rows hidden by ACLs)` | Records exist, account lacks read roles | Check `-c`; otherwise the user needs a role, not a CLI fix |
82
+ | `HTTP 403: Insufficient rights to query records: Field(s) present in the query do not have permission` | Account cannot read a field used in the filter/sort (often on an instance where it has no roles) | Check `-c`; drop the field from `-q`/`--order` |
83
+ | `HTTP 400: Invalid table` | Wrong table name | Check the name with `snow table list sys_db_object -q 'nameLIKE<x>' -f name,label` |
84
+ | `token request failed` during login | Instance blocks the SDK OAuth client | Admin registers a public PKCE client; set `SNOW_OAUTH_CLIENT_ID` |
@@ -0,0 +1,27 @@
1
+ # ServiceNow encoded queries (for `snow ... -q`)
2
+
3
+ Conditions are joined with `^` (AND). Field names are column names, not labels. Use `--raw` with
4
+ `table list` to see stored values when building a filter.
5
+
6
+ | Want | Encoded query |
7
+ |---|---|
8
+ | equals / not equals | `state=2` / `state!=7` |
9
+ | contains / starts with | `short_descriptionLIKEvpn` / `numberSTARTSWITHINC` |
10
+ | one of | `priorityIN1,2` |
11
+ | empty / not empty | `assigned_toISEMPTY` / `assigned_toISNOTEMPTY` |
12
+ | comparison | `priority<=2`, `sys_updated_on>=2026-01-01 00:00:00` |
13
+ | OR (same group) | `priority=1^ORpriority=2` |
14
+ | new OR group | `active=true^NQnumber=INC0010001` |
15
+ | dot-walk a reference | `assignment_group.name=Service Desk`, `caller_id.department.name=IT` |
16
+ | me | `assigned_to=javascript:gs.getUserID()` |
17
+ | my groups | `assignment_group=javascript:getMyGroups()` |
18
+ | today / last 7 days | `sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()` / `sys_created_on>=javascript:gs.daysAgoStart(7)` |
19
+ | sort | `ORDERBYnumber`, `ORDERBYDESCsys_updated_on` (or use `--order -sys_updated_on`) |
20
+
21
+ Notes:
22
+
23
+ - Record commands (`inc`, `chg`, `ritm`, `task`) already add `active=true` (unless `--all`) and sort by
24
+ newest update (unless `--order`); `-q` is appended to that.
25
+ - Quote the whole query in single quotes so the shell leaves `^`, `<`, `>` and spaces alone.
26
+ - An easy way to get a correct query: build the filter in the ServiceNow list view, right-click the
27
+ breadcrumb, choose "Copy query", and pass it to `-q`.
package/src/args.js ADDED
@@ -0,0 +1,49 @@
1
+ import fs from 'node:fs';
2
+
3
+ export const GLOBAL_OPTIONS = {
4
+ context: { type: 'string', short: 'c' },
5
+ output: { type: 'string', short: 'o' },
6
+ help: { type: 'boolean', short: 'h' },
7
+ };
8
+
9
+ export function outputMode(opts, fallback) {
10
+ const mode = opts.output || fallback;
11
+ if (!['table', 'json'].includes(mode)) throw new Error(`--output must be table or json, got "${mode}"`);
12
+ return mode;
13
+ }
14
+
15
+ /** -s key=value (repeatable) → object. Splits on the first "=" only. */
16
+ export function parseSets(sets = []) {
17
+ const out = {};
18
+ for (const s of sets) {
19
+ const i = s.indexOf('=');
20
+ if (i <= 0) throw new Error(`--set expects key=value, got "${s}"`);
21
+ out[s.slice(0, i)] = s.slice(i + 1);
22
+ }
23
+ return out;
24
+ }
25
+
26
+ /** -d '<json>' | -d @file.json | -d - (stdin) → parsed object. */
27
+ export function readData(arg) {
28
+ if (arg === undefined) return undefined;
29
+ const text = arg === '-' ? fs.readFileSync(0, 'utf8') : arg.startsWith('@') ? fs.readFileSync(arg.slice(1), 'utf8') : arg;
30
+ try {
31
+ return JSON.parse(text);
32
+ } catch (e) {
33
+ throw new Error(`--data is not valid JSON: ${e.message}`);
34
+ }
35
+ }
36
+
37
+ export function splitFields(f) {
38
+ return f ? f.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
39
+ }
40
+
41
+ /** "-field" → ORDERBYDESCfield, "field" → ORDERBYfield */
42
+ export function orderClause(order) {
43
+ if (!order) return undefined;
44
+ return order.startsWith('-') ? `ORDERBYDESC${order.slice(1)}` : `ORDERBY${order}`;
45
+ }
46
+
47
+ export function joinQuery(...parts) {
48
+ return parts.filter(Boolean).join('^') || undefined;
49
+ }
package/src/auth.js ADDED
@@ -0,0 +1,171 @@
1
+ // OAuth 2.0 authorization code + PKCE.
2
+ // Default client: the public OAuth client that ServiceNow ships on instances for the ServiceNow SDK
3
+ // (same client and redirect as `now-sdk auth --type oauth`, see @servicenow/sdk-cli
4
+ // src/auth/OAuth/CodeGrant.ts). It has no secret; /sdk-oauth.do shows the code to paste back.
5
+ // The browser login uses whatever the instance uses (local login, SAML/OIDC SSO, MFA).
6
+ // Instances that disable that client can register their own public client: SNOW_OAUTH_CLIENT_ID.
7
+ import crypto from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { spawn } from 'node:child_process';
11
+ import readline from 'node:readline/promises';
12
+ import { BIN, configDir, writePrivateFile } from './config.js';
13
+ import { loadTokens, saveTokens } from './tokenstore.js';
14
+
15
+ export const CLIENT_ID = process.env.SNOW_OAUTH_CLIENT_ID || '543e5655f77746a28228c6009a599dfb';
16
+ const REDIRECT_URI = process.env.SNOW_OAUTH_REDIRECT_URI || '/sdk-oauth.do';
17
+ const EXPIRY_SKEW_MS = 60_000;
18
+ const PENDING_TTL_MS = 10 * 60_000;
19
+
20
+ export class LoginRequired extends Error {
21
+ constructor(ctx, reason) {
22
+ super(`not logged in to "${ctx.name}" (${ctx.instance})${reason ? `: ${reason}` : ''}; run: ${BIN} login -c ${ctx.name}`);
23
+ this.name = 'LoginRequired';
24
+ }
25
+ }
26
+
27
+ const b64url = (buf) => buf.toString('base64url');
28
+
29
+ export function pkcePair() {
30
+ const verifier = b64url(crypto.randomBytes(32));
31
+ const challenge = b64url(crypto.createHash('sha256').update(verifier).digest());
32
+ return { verifier, challenge };
33
+ }
34
+
35
+ function pendingPath(ctx) {
36
+ return path.join(configDir(), 'pending', `${ctx.name}.json`);
37
+ }
38
+
39
+ /** Step 1: build the authorize URL and remember state + verifier for step 2. */
40
+ export function startLogin(ctx) {
41
+ const { verifier, challenge } = pkcePair();
42
+ const state = b64url(crypto.randomBytes(16));
43
+ writePrivateFile(pendingPath(ctx), JSON.stringify({ instance: ctx.instance, state, verifier, created: Date.now() }));
44
+ const u = new URL(`${ctx.instance}/oauth_auth.do`);
45
+ u.search = new URLSearchParams({
46
+ response_type: 'code',
47
+ client_id: CLIENT_ID,
48
+ redirect_uri: REDIRECT_URI,
49
+ state,
50
+ code_challenge: challenge,
51
+ code_challenge_method: 'S256',
52
+ scope: '',
53
+ }).toString();
54
+ return u.toString();
55
+ }
56
+
57
+ /**
58
+ * Accepts what /sdk-oauth.do shows: a bare code, "CODE&state=STATE", or the full redirect URL / query string.
59
+ * Returns { code, state } (state may be undefined).
60
+ */
61
+ export function parsePastedCode(input) {
62
+ let s = input.trim();
63
+ if (s.includes('?')) s = s.slice(s.indexOf('?') + 1);
64
+ if (!s.includes('=')) return { code: s };
65
+ const params = new URLSearchParams(s.includes('code=') ? s : `code=${s}`);
66
+ return { code: params.get('code') ?? '', state: params.get('state') ?? undefined };
67
+ }
68
+
69
+ /** Step 2: exchange the pasted code for tokens and persist them. */
70
+ export async function finishLogin(ctx, pasted) {
71
+ const file = pendingPath(ctx);
72
+ if (!fs.existsSync(file)) throw new Error(`no pending login for "${ctx.name}"; run: ${BIN} login -c ${ctx.name}`);
73
+ const pending = JSON.parse(fs.readFileSync(file, 'utf8'));
74
+ if (pending.instance !== ctx.instance) throw new Error('pending login was started for a different instance; start again');
75
+ if (Date.now() - pending.created > PENDING_TTL_MS) {
76
+ fs.rmSync(file, { force: true });
77
+ throw new Error('pending login expired (10 min); start again');
78
+ }
79
+ const { code, state } = parsePastedCode(pasted);
80
+ if (!code) throw new Error('empty code');
81
+ if (state !== undefined && state !== pending.state) throw new Error('state mismatch: code belongs to a different login attempt; start again');
82
+ const tok = await tokenRequest(ctx, {
83
+ grant_type: 'authorization_code',
84
+ code,
85
+ redirect_uri: REDIRECT_URI,
86
+ code_verifier: pending.verifier,
87
+ });
88
+ fs.rmSync(file, { force: true });
89
+ const record = toRecord(ctx, tok);
90
+ saveTokens(ctx.name, record);
91
+ return record;
92
+ }
93
+
94
+ export function openBrowser(url) {
95
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
96
+ try {
97
+ spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();
98
+ return true;
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ export async function promptCode() {
105
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
106
+ try {
107
+ return (await rl.question('Paste the code shown in the browser: ')).trim();
108
+ } finally {
109
+ rl.close();
110
+ }
111
+ }
112
+
113
+ async function tokenRequest(ctx, params) {
114
+ const res = await fetch(`${ctx.instance}/oauth_token.do`, {
115
+ method: 'POST',
116
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
117
+ body: new URLSearchParams({ client_id: CLIENT_ID, ...params }),
118
+ });
119
+ const text = await res.text();
120
+ let body;
121
+ try {
122
+ body = JSON.parse(text);
123
+ } catch {
124
+ body = null;
125
+ }
126
+ if (!res.ok || !body?.access_token) {
127
+ const reason = body?.error_description || body?.error || text.slice(0, 200) || res.statusText;
128
+ const err = new Error(`token request failed (HTTP ${res.status}): ${reason}`);
129
+ err.status = res.status;
130
+ throw err;
131
+ }
132
+ return body;
133
+ }
134
+
135
+ function toRecord(ctx, tok, previous) {
136
+ const now = Date.now();
137
+ return {
138
+ instance: ctx.instance,
139
+ access_token: tok.access_token,
140
+ refresh_token: tok.refresh_token || previous?.refresh_token,
141
+ expires_at: now + (Number(tok.expires_in) || 1800) * 1000,
142
+ logged_in_at: previous?.logged_in_at ?? now,
143
+ user: previous?.user,
144
+ };
145
+ }
146
+
147
+ /** Returns the stored record with a valid access token, refreshing when needed. */
148
+ export async function getSession(ctx, { forceRefresh = false } = {}) {
149
+ const rec = loadTokens(ctx.name);
150
+ if (!rec) throw new LoginRequired(ctx);
151
+ if (rec.instance !== ctx.instance) throw new LoginRequired(ctx, `stored token is for ${rec.instance}`);
152
+ if (!forceRefresh && rec.expires_at - EXPIRY_SKEW_MS > Date.now()) return rec;
153
+ if (!rec.refresh_token) throw new LoginRequired(ctx, 'access token expired and no refresh token');
154
+ let tok;
155
+ try {
156
+ tok = await tokenRequest(ctx, { grant_type: 'refresh_token', refresh_token: rec.refresh_token });
157
+ } catch (e) {
158
+ if (e.status === 400 || e.status === 401) throw new LoginRequired(ctx, 'refresh token rejected or expired');
159
+ throw e;
160
+ }
161
+ const next = toRecord(ctx, tok, rec);
162
+ saveTokens(ctx.name, next);
163
+ return next;
164
+ }
165
+
166
+ export function rememberUser(ctx, user) {
167
+ const rec = loadTokens(ctx.name);
168
+ if (!rec) return;
169
+ rec.user = user;
170
+ saveTokens(ctx.name, rec);
171
+ }