@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 +21 -0
- package/README.md +134 -2
- package/bin/snow.js +4 -0
- package/package.json +40 -4
- package/skills/snow/SKILL.md +84 -0
- package/skills/snow/references/encoded-queries.md +27 -0
- package/src/args.js +49 -0
- package/src/auth.js +171 -0
- package/src/cli.js +368 -0
- package/src/config.js +58 -0
- package/src/http.js +61 -0
- package/src/output.js +46 -0
- package/src/records.js +157 -0
- package/src/skills.js +169 -0
- package/src/table.js +63 -0
- package/src/tokenstore.js +60 -0
- package/src/user.js +19 -0
package/src/records.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Task-table commands: incident, change, ritm, sctask. Thin layer over the Table API helpers.
|
|
2
|
+
import { joinQuery, orderClause, outputMode, parseSets, readData, splitFields } from './args.js';
|
|
3
|
+
import { create, get, list, update } from './table.js';
|
|
4
|
+
import { printJSON, printRecord, printTable, printTotalNote } from './output.js';
|
|
5
|
+
import { currentUser } from './user.js';
|
|
6
|
+
import { BIN, loadConfig, resolveContext } from './config.js';
|
|
7
|
+
|
|
8
|
+
const KINDS = {
|
|
9
|
+
incident: {
|
|
10
|
+
table: 'incident',
|
|
11
|
+
aliases: ['inc'],
|
|
12
|
+
listFields: ['number', 'short_description', 'state', 'priority', 'assignment_group', 'assigned_to', 'sys_updated_on'],
|
|
13
|
+
first: ['number', 'short_description', 'state', 'priority', 'impact', 'urgency', 'caller_id', 'category', 'assignment_group', 'assigned_to', 'opened_at', 'sys_updated_on', 'description'],
|
|
14
|
+
create: {
|
|
15
|
+
flags: { caller: 'caller_id', urgency: 'urgency', impact: 'impact', category: 'category' },
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
change: {
|
|
19
|
+
table: 'change_request',
|
|
20
|
+
aliases: ['chg'],
|
|
21
|
+
listFields: ['number', 'short_description', 'type', 'state', 'risk', 'start_date', 'end_date', 'assignment_group'],
|
|
22
|
+
first: ['number', 'short_description', 'type', 'state', 'risk', 'impact', 'start_date', 'end_date', 'requested_by', 'assignment_group', 'assigned_to', 'sys_updated_on', 'description', 'justification', 'implementation_plan', 'backout_plan', 'test_plan'],
|
|
23
|
+
create: {
|
|
24
|
+
flags: { type: 'type', start: 'start_date', end: 'end_date', risk: 'risk', impact: 'impact' },
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
ritm: {
|
|
28
|
+
table: 'sc_req_item',
|
|
29
|
+
aliases: [],
|
|
30
|
+
listFields: ['number', 'short_description', 'cat_item', 'stage', 'state', 'requested_for', 'assignment_group', 'assigned_to'],
|
|
31
|
+
first: ['number', 'short_description', 'cat_item', 'stage', 'state', 'request', 'requested_for', 'opened_by', 'assignment_group', 'assigned_to', 'opened_at', 'sys_updated_on', 'description'],
|
|
32
|
+
},
|
|
33
|
+
sctask: {
|
|
34
|
+
table: 'sc_task',
|
|
35
|
+
aliases: ['task'],
|
|
36
|
+
listFields: ['number', 'short_description', 'state', 'request_item', 'assignment_group', 'assigned_to', 'sys_updated_on'],
|
|
37
|
+
first: ['number', 'short_description', 'state', 'request_item', 'request', 'assignment_group', 'assigned_to', 'opened_at', 'sys_updated_on', 'description'],
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const COMMON_WRITE = {
|
|
42
|
+
title: { type: 'string', short: 't' },
|
|
43
|
+
description: { type: 'string' },
|
|
44
|
+
group: { type: 'string' },
|
|
45
|
+
assignee: { type: 'string' },
|
|
46
|
+
set: { type: 'string', short: 's', multiple: true },
|
|
47
|
+
data: { type: 'string', short: 'd' },
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
function usage(name, k) {
|
|
51
|
+
const createFlags = k.create ? Object.keys(k.create.flags).map((f) => `[--${f} V]`).join(' ') : '';
|
|
52
|
+
return `Usage:
|
|
53
|
+
${BIN} ${name} list [--mine] [--opened-by-me] [--group NAME] [--all] [-q QUERY] [-f FIELDS] [-l N] [--offset N] [--order [-]FIELD] [--raw]
|
|
54
|
+
${BIN} ${name} get <NUMBER|sys_id> [-f FIELDS] [--all-fields] [--raw]
|
|
55
|
+
${k.create ? ` ${BIN} ${name} create -t TITLE [--description T] [--group NAME] [--assignee NAME] ${createFlags} [-s k=v]... [-d JSON]\n` : ''} ${BIN} ${name} update <NUMBER|sys_id> [-t TITLE] [--description T] [--group NAME] [--assignee NAME] [-s k=v]... [-d JSON]
|
|
56
|
+
${BIN} ${name} comment <NUMBER|sys_id> <TEXT> [--work-note]
|
|
57
|
+
|
|
58
|
+
Table: ${k.table}. Lists show active records, newest update first, unless --all / --order.
|
|
59
|
+
Writes take display values for reference fields (e.g. --group "DevOps", --assignee "Jane Doe").
|
|
60
|
+
Global: -c CONTEXT, -o table|json`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function writeFields(opts, kind, isCreate) {
|
|
64
|
+
const fields = { ...(readData(opts.data) || {}) };
|
|
65
|
+
if (opts.title !== undefined) fields.short_description = opts.title;
|
|
66
|
+
if (opts.description !== undefined) fields.description = opts.description;
|
|
67
|
+
if (opts.group !== undefined) fields.assignment_group = opts.group;
|
|
68
|
+
if (opts.assignee !== undefined) fields.assigned_to = opts.assignee;
|
|
69
|
+
if (isCreate) for (const [flag, field] of Object.entries(kind.create.flags)) if (opts[flag] !== undefined) fields[field] = opts[flag];
|
|
70
|
+
Object.assign(fields, parseSets(opts.set));
|
|
71
|
+
return fields;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function makeCommand(name, kind) {
|
|
75
|
+
const createOpts = kind.create ? Object.fromEntries(Object.keys(kind.create.flags).map((f) => [f, { type: 'string' }])) : {};
|
|
76
|
+
return {
|
|
77
|
+
usage: usage(name, kind),
|
|
78
|
+
options: {
|
|
79
|
+
mine: { type: 'boolean' },
|
|
80
|
+
'opened-by-me': { type: 'boolean' },
|
|
81
|
+
all: { type: 'boolean' },
|
|
82
|
+
query: { type: 'string', short: 'q' },
|
|
83
|
+
fields: { type: 'string', short: 'f' },
|
|
84
|
+
limit: { type: 'string', short: 'l' },
|
|
85
|
+
offset: { type: 'string' },
|
|
86
|
+
order: { type: 'string' },
|
|
87
|
+
raw: { type: 'boolean' },
|
|
88
|
+
'all-fields': { type: 'boolean' },
|
|
89
|
+
'work-note': { type: 'boolean' },
|
|
90
|
+
...COMMON_WRITE,
|
|
91
|
+
...createOpts,
|
|
92
|
+
},
|
|
93
|
+
async run(_, opts, [sub, ...args]) {
|
|
94
|
+
const ctx = resolveContext(loadConfig(), opts.context);
|
|
95
|
+
const displayValue = !opts.raw;
|
|
96
|
+
switch (sub) {
|
|
97
|
+
case 'list': {
|
|
98
|
+
let me;
|
|
99
|
+
if (opts.mine || opts['opened-by-me']) me = await currentUser(ctx);
|
|
100
|
+
const query = joinQuery(
|
|
101
|
+
opts.all ? '' : 'active=true',
|
|
102
|
+
opts.mine ? `assigned_to=${me.sys_id}` : '',
|
|
103
|
+
opts['opened-by-me'] ? `opened_by=${me.sys_id}` : '',
|
|
104
|
+
opts.group ? `assignment_group.name=${opts.group}` : '',
|
|
105
|
+
opts.query,
|
|
106
|
+
orderClause(opts.order || '-sys_updated_on'),
|
|
107
|
+
);
|
|
108
|
+
const fields = splitFields(opts.fields) || kind.listFields;
|
|
109
|
+
const { rows, total } = await list(ctx, kind.table, { query, fields, limit: opts.limit ?? 20, offset: opts.offset, displayValue });
|
|
110
|
+
if (outputMode(opts, 'table') === 'json') return printJSON(rows);
|
|
111
|
+
printTable(rows, fields);
|
|
112
|
+
printTotalNote(rows.length, total);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
case 'get': {
|
|
116
|
+
if (!args[0]) throw new Error(`usage: ${BIN} ${name} get <NUMBER|sys_id>`);
|
|
117
|
+
const rec = await get(ctx, kind.table, args[0], { fields: splitFields(opts.fields), displayValue });
|
|
118
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(rec) : printRecord(rec, { first: kind.first, all: opts['all-fields'] });
|
|
119
|
+
}
|
|
120
|
+
case 'create': {
|
|
121
|
+
if (!kind.create) throw new Error(`${BIN} ${name} create is not supported; ${kind.table} records come from their parent flow`);
|
|
122
|
+
const fields = writeFields(opts, kind, true);
|
|
123
|
+
if (!fields.short_description) throw new Error('create needs -t/--title (short_description)');
|
|
124
|
+
const rec = await create(ctx, kind.table, fields);
|
|
125
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(rec) : printRecord(rec, { first: kind.first });
|
|
126
|
+
}
|
|
127
|
+
case 'update': {
|
|
128
|
+
if (!args[0]) throw new Error(`usage: ${BIN} ${name} update <NUMBER|sys_id> -s k=v`);
|
|
129
|
+
const fields = writeFields(opts, kind, false);
|
|
130
|
+
if (!Object.keys(fields).length) throw new Error('update needs at least one field (-s k=v, -t, --group, ...)');
|
|
131
|
+
const rec = await update(ctx, kind.table, args[0], fields);
|
|
132
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(rec) : printRecord(rec, { first: kind.first });
|
|
133
|
+
}
|
|
134
|
+
case 'comment': {
|
|
135
|
+
const [id, ...words] = args;
|
|
136
|
+
const text = words.join(' ');
|
|
137
|
+
if (!id || !text) throw new Error(`usage: ${BIN} ${name} comment <NUMBER|sys_id> <TEXT> [--work-note]`);
|
|
138
|
+
const rec = await update(ctx, kind.table, id, { [opts['work-note'] ? 'work_notes' : 'comments']: text });
|
|
139
|
+
process.stderr.write(`${opts['work-note'] ? 'work note' : 'comment'} added to ${rec.number}\n`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
default:
|
|
143
|
+
throw new Error(`unknown subcommand "${sub ?? ''}"\n\n${usage(name, kind)}`);
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function recordCommands() {
|
|
150
|
+
const out = {};
|
|
151
|
+
for (const [name, kind] of Object.entries(KINDS)) {
|
|
152
|
+
const cmd = makeCommand(name, kind);
|
|
153
|
+
out[name] = cmd;
|
|
154
|
+
for (const a of kind.aliases) out[a] = cmd;
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
package/src/skills.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Agent skills bundled with the package (skills/<name>/SKILL.md) and their installer.
|
|
2
|
+
// Canonical destination: ~/.agents/skills/<name> (read by Codex, Cursor, Gemini, Copilot and other
|
|
3
|
+
// .agents-compatible harnesses). Claude Code reads ~/.claude/skills, so `--agent claude` adds a symlink
|
|
4
|
+
// there pointing at the canonical copy. Installed copies carry a marker file; directories without it are
|
|
5
|
+
// someone else's and are never overwritten or removed without --force.
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
const BUNDLE_DIR = fileURLToPath(new URL('../skills/', import.meta.url));
|
|
13
|
+
const MARKER = '.snow-skill.json';
|
|
14
|
+
export const AGENTS = ['claude'];
|
|
15
|
+
|
|
16
|
+
function packageVersion() {
|
|
17
|
+
const pkg = JSON.parse(fs.readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
|
|
18
|
+
return pkg.version;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function bundledSkills(bundleDir = BUNDLE_DIR) {
|
|
22
|
+
return fs
|
|
23
|
+
.readdirSync(bundleDir, { withFileTypes: true })
|
|
24
|
+
.filter((e) => e.isDirectory() && fs.existsSync(path.join(bundleDir, e.name, 'SKILL.md')))
|
|
25
|
+
.map((e) => {
|
|
26
|
+
const md = fs.readFileSync(path.join(bundleDir, e.name, 'SKILL.md'), 'utf8');
|
|
27
|
+
return { name: e.name, dir: path.join(bundleDir, e.name), description: md.match(/^description:\s*(.+)$/m)?.[1]?.trim() ?? '' };
|
|
28
|
+
})
|
|
29
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function listFiles(dir, base = dir) {
|
|
33
|
+
return fs
|
|
34
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
35
|
+
.flatMap((e) => {
|
|
36
|
+
const p = path.join(dir, e.name);
|
|
37
|
+
if (e.isDirectory()) return listFiles(p, base);
|
|
38
|
+
return e.name === MARKER ? [] : [path.relative(base, p)];
|
|
39
|
+
})
|
|
40
|
+
.sort();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Content hash of a skill directory (relative paths + bytes), ignoring the marker. */
|
|
44
|
+
export function hashDir(dir) {
|
|
45
|
+
const h = crypto.createHash('sha256');
|
|
46
|
+
for (const rel of listFiles(dir)) h.update(rel).update('\0').update(fs.readFileSync(path.join(dir, rel))).update('\0');
|
|
47
|
+
return h.digest('hex');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Destination roots for a scope: canonical .agents/skills plus per-agent link dirs. */
|
|
51
|
+
export function destinations({ local = false, dir } = {}) {
|
|
52
|
+
const home = os.homedir();
|
|
53
|
+
const root = dir ? path.resolve(dir) : local ? path.resolve('.agents') : path.join(home, '.agents');
|
|
54
|
+
return {
|
|
55
|
+
canonical: path.join(root, 'skills'),
|
|
56
|
+
agents: { claude: local ? path.resolve('.claude', 'skills') : path.join(home, '.claude', 'skills') },
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function lstat(p) {
|
|
61
|
+
try {
|
|
62
|
+
return fs.lstatSync(p);
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** absent | managed | foreign, for a canonical skill directory. */
|
|
69
|
+
function inspect(dst) {
|
|
70
|
+
const st = lstat(dst);
|
|
71
|
+
if (!st) return { state: 'absent' };
|
|
72
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return { state: 'foreign' };
|
|
73
|
+
const markerPath = path.join(dst, MARKER);
|
|
74
|
+
if (!fs.existsSync(markerPath)) return { state: 'foreign' };
|
|
75
|
+
return { state: 'managed', marker: JSON.parse(fs.readFileSync(markerPath, 'utf8')) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Per-skill install state across destinations, for `snow skills list`. */
|
|
79
|
+
export function skillStatus(skill, dests) {
|
|
80
|
+
const dst = path.join(dests.canonical, skill.name);
|
|
81
|
+
const info = inspect(dst);
|
|
82
|
+
let canonical = info.state;
|
|
83
|
+
if (info.state === 'managed') canonical = hashDir(dst) === hashDir(skill.dir) ? 'installed' : 'outdated';
|
|
84
|
+
const agents = {};
|
|
85
|
+
for (const [agent, linkDir] of Object.entries(dests.agents)) {
|
|
86
|
+
const link = path.join(linkDir, skill.name);
|
|
87
|
+
const st = lstat(link);
|
|
88
|
+
agents[agent] = !st ? 'absent' : st.isSymbolicLink() && path.resolve(linkDir, fs.readlinkSync(link)) === dst ? 'linked' : 'foreign';
|
|
89
|
+
}
|
|
90
|
+
return { canonical, agents };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Install skills. Returns [{ skill, path, action }]; action is one of
|
|
95
|
+
* installed | updated | unchanged | linked | link-ok | skipped-foreign (would-* in dry run).
|
|
96
|
+
*/
|
|
97
|
+
export function installSkills(skills, { dests, agents = [], force = false, dryRun = false }) {
|
|
98
|
+
const results = [];
|
|
99
|
+
const WOULD = { installed: 'would-install', updated: 'would-update', linked: 'would-link' };
|
|
100
|
+
const record = (skill, p, action) => results.push({ skill, path: p, action: (dryRun && WOULD[action]) || action });
|
|
101
|
+
const version = packageVersion();
|
|
102
|
+
for (const skill of skills) {
|
|
103
|
+
const dst = path.join(dests.canonical, skill.name);
|
|
104
|
+
const info = inspect(dst);
|
|
105
|
+
const srcHash = hashDir(skill.dir);
|
|
106
|
+
if (info.state === 'foreign' && !force) {
|
|
107
|
+
record(skill.name, dst, 'skipped-foreign');
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (info.state === 'managed' && hashDir(dst) === srcHash) {
|
|
111
|
+
record(skill.name, dst, 'unchanged');
|
|
112
|
+
} else {
|
|
113
|
+
if (!dryRun) {
|
|
114
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
115
|
+
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
116
|
+
fs.cpSync(skill.dir, dst, { recursive: true });
|
|
117
|
+
fs.writeFileSync(
|
|
118
|
+
path.join(dst, MARKER),
|
|
119
|
+
JSON.stringify({ name: skill.name, package: '@parnniti/snow', version, hash: srcHash, installedAt: new Date().toISOString() }, null, 2) + '\n',
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
record(skill.name, dst, info.state === 'absent' ? 'installed' : 'updated');
|
|
123
|
+
}
|
|
124
|
+
for (const agent of agents) {
|
|
125
|
+
const linkDir = dests.agents[agent];
|
|
126
|
+
const link = path.join(linkDir, skill.name);
|
|
127
|
+
const st = lstat(link);
|
|
128
|
+
if (st?.isSymbolicLink() && path.resolve(linkDir, fs.readlinkSync(link)) === dst) {
|
|
129
|
+
record(skill.name, link, 'link-ok');
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (st && !force) {
|
|
133
|
+
record(skill.name, link, 'skipped-foreign');
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (!dryRun) {
|
|
137
|
+
fs.rmSync(link, { recursive: true, force: true });
|
|
138
|
+
fs.mkdirSync(linkDir, { recursive: true });
|
|
139
|
+
fs.symlinkSync(dst, link, 'dir');
|
|
140
|
+
}
|
|
141
|
+
record(skill.name, link, 'linked');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return results;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Remove snow-managed copies and the agent links that point at them. Foreign entries are left alone. */
|
|
148
|
+
export function uninstallSkills(skills, { dests, dryRun = false }) {
|
|
149
|
+
const results = [];
|
|
150
|
+
for (const skill of skills) {
|
|
151
|
+
const dst = path.join(dests.canonical, skill.name);
|
|
152
|
+
for (const linkDir of Object.values(dests.agents)) {
|
|
153
|
+
const link = path.join(linkDir, skill.name);
|
|
154
|
+
const st = lstat(link);
|
|
155
|
+
if (st?.isSymbolicLink() && path.resolve(linkDir, fs.readlinkSync(link)) === dst) {
|
|
156
|
+
if (!dryRun) fs.unlinkSync(link);
|
|
157
|
+
results.push({ skill: skill.name, path: link, action: dryRun ? 'would-unlink' : 'unlinked' });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const info = inspect(dst);
|
|
161
|
+
if (info.state === 'managed') {
|
|
162
|
+
if (!dryRun) fs.rmSync(dst, { recursive: true, force: true });
|
|
163
|
+
results.push({ skill: skill.name, path: dst, action: dryRun ? 'would-remove' : 'removed' });
|
|
164
|
+
} else if (info.state === 'foreign') {
|
|
165
|
+
results.push({ skill: skill.name, path: dst, action: 'skipped-foreign' });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return results;
|
|
169
|
+
}
|
package/src/table.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Table API helpers. Reads default to display values; writes accept display values for reference fields
|
|
2
|
+
// (e.g. assignment_group=DevOps) via sysparm_input_display_value.
|
|
3
|
+
import { request } from './http.js';
|
|
4
|
+
|
|
5
|
+
export const SYS_ID_RE = /^[0-9a-f]{32}$/;
|
|
6
|
+
|
|
7
|
+
const tablePath = (table, sysId) => `/api/now/table/${encodeURIComponent(table)}${sysId ? `/${sysId}` : ''}`;
|
|
8
|
+
|
|
9
|
+
export async function list(ctx, table, { query, fields, limit = 20, offset, displayValue = true } = {}) {
|
|
10
|
+
const res = await request(ctx, 'GET', tablePath(table), {
|
|
11
|
+
query: {
|
|
12
|
+
sysparm_query: query,
|
|
13
|
+
sysparm_fields: fields?.length ? fields.join(',') : undefined,
|
|
14
|
+
sysparm_limit: limit,
|
|
15
|
+
sysparm_offset: offset,
|
|
16
|
+
sysparm_display_value: String(displayValue),
|
|
17
|
+
sysparm_exclude_reference_link: 'true',
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
const total = Number(res.headers.get('x-total-count'));
|
|
21
|
+
return { rows: res.data.result, total: Number.isFinite(total) ? total : undefined };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Get by sys_id, or by `number` (INC0012345, CHG..., RITM..., SCTASK...). */
|
|
25
|
+
export async function get(ctx, table, id, { fields, displayValue = true } = {}) {
|
|
26
|
+
if (SYS_ID_RE.test(id)) {
|
|
27
|
+
const res = await request(ctx, 'GET', tablePath(table, id), {
|
|
28
|
+
query: {
|
|
29
|
+
sysparm_fields: fields?.length ? fields.join(',') : undefined,
|
|
30
|
+
sysparm_display_value: String(displayValue),
|
|
31
|
+
sysparm_exclude_reference_link: 'true',
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
return res.data.result;
|
|
35
|
+
}
|
|
36
|
+
const { rows } = await list(ctx, table, { query: `number=${id.toUpperCase()}`, fields, limit: 2, displayValue });
|
|
37
|
+
if (!rows.length) throw new Error(`${table}: no record with number ${id.toUpperCase()}`);
|
|
38
|
+
if (rows.length > 1) throw new Error(`${table}: number ${id.toUpperCase()} is ambiguous; use the sys_id`);
|
|
39
|
+
return rows[0];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function resolveSysId(ctx, table, id) {
|
|
43
|
+
if (SYS_ID_RE.test(id)) return id;
|
|
44
|
+
const rec = await get(ctx, table, id, { fields: ['sys_id'], displayValue: false });
|
|
45
|
+
return rec.sys_id;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const writeQuery = {
|
|
49
|
+
sysparm_input_display_value: 'true',
|
|
50
|
+
sysparm_display_value: 'true',
|
|
51
|
+
sysparm_exclude_reference_link: 'true',
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export async function create(ctx, table, fields) {
|
|
55
|
+
const res = await request(ctx, 'POST', tablePath(table), { query: writeQuery, body: fields });
|
|
56
|
+
return res.data.result;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function update(ctx, table, id, fields) {
|
|
60
|
+
const sysId = await resolveSysId(ctx, table, id);
|
|
61
|
+
const res = await request(ctx, 'PATCH', tablePath(table, sysId), { query: writeQuery, body: fields });
|
|
62
|
+
return res.data.result;
|
|
63
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Token persistence. macOS: login keychain via `security`; elsewhere (or SNOW_TOKEN_STORE=file): 0600 file.
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { configDir, writePrivateFile } from './config.js';
|
|
6
|
+
|
|
7
|
+
const SERVICE = 'snow-cli';
|
|
8
|
+
|
|
9
|
+
function useKeychain() {
|
|
10
|
+
const mode = process.env.SNOW_TOKEN_STORE;
|
|
11
|
+
if (mode === 'file') return false;
|
|
12
|
+
if (mode === 'keychain') return true;
|
|
13
|
+
return process.platform === 'darwin';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function filePath(ctx) {
|
|
17
|
+
return path.join(configDir(), 'tokens', `${ctx}.json`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function storeName() {
|
|
21
|
+
return useKeychain() ? `macOS keychain (service "${SERVICE}")` : `file ${path.join(configDir(), 'tokens')}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function loadTokens(ctx) {
|
|
25
|
+
if (!useKeychain()) {
|
|
26
|
+
const f = filePath(ctx);
|
|
27
|
+
return fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : null;
|
|
28
|
+
}
|
|
29
|
+
const r = spawnSync('security', ['find-generic-password', '-s', SERVICE, '-a', ctx, '-w'], { encoding: 'utf8' });
|
|
30
|
+
if (r.status === 44) return null; // item not found
|
|
31
|
+
if (r.status !== 0) throw new Error(`keychain read failed: ${r.stderr.trim()}`);
|
|
32
|
+
let out = r.stdout.trim();
|
|
33
|
+
// `security -w` prints hex when it considers the data non-printable.
|
|
34
|
+
if (/^([0-9a-f]{2})+$/i.test(out) && !out.startsWith('{')) out = Buffer.from(out, 'hex').toString('utf8');
|
|
35
|
+
return JSON.parse(out);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function saveTokens(ctx, data) {
|
|
39
|
+
const json = JSON.stringify(data);
|
|
40
|
+
if (!useKeychain()) {
|
|
41
|
+
writePrivateFile(filePath(ctx), json + '\n');
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
// Feed the command through `security -i` stdin so the secret never appears in argv / ps.
|
|
45
|
+
const hex = Buffer.from(json, 'utf8').toString('hex');
|
|
46
|
+
const r = spawnSync('security', ['-i'], {
|
|
47
|
+
input: `add-generic-password -U -s ${SERVICE} -a ${ctx} -l "${SERVICE} ${ctx}" -X ${hex}\n`,
|
|
48
|
+
encoding: 'utf8',
|
|
49
|
+
});
|
|
50
|
+
if (r.status !== 0 || /error/i.test(r.stderr)) throw new Error(`keychain write failed: ${r.stderr.trim()}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function deleteTokens(ctx) {
|
|
54
|
+
if (!useKeychain()) {
|
|
55
|
+
fs.rmSync(filePath(ctx), { force: true });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const r = spawnSync('security', ['delete-generic-password', '-s', SERVICE, '-a', ctx], { encoding: 'utf8' });
|
|
59
|
+
if (r.status !== 0 && r.status !== 44) throw new Error(`keychain delete failed: ${r.stderr.trim()}`);
|
|
60
|
+
}
|
package/src/user.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { getSession, rememberUser } from './auth.js';
|
|
2
|
+
import { request } from './http.js';
|
|
3
|
+
|
|
4
|
+
/** Signed-in user {sys_id, user_name, name}; cached alongside the token after first lookup. */
|
|
5
|
+
export async function currentUser(ctx, { refresh = false } = {}) {
|
|
6
|
+
const session = await getSession(ctx);
|
|
7
|
+
if (!refresh && session.user?.sys_id) return session.user;
|
|
8
|
+
const res = await request(ctx, 'GET', '/api/now/table/sys_user', {
|
|
9
|
+
query: {
|
|
10
|
+
sysparm_query: 'sys_id=javascript:gs.getUserID()',
|
|
11
|
+
sysparm_fields: 'sys_id,user_name,name,email',
|
|
12
|
+
sysparm_limit: 1,
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
const user = res.data.result?.[0];
|
|
16
|
+
if (!user?.sys_id) throw new Error('could not resolve the signed-in user (sys_user lookup returned nothing)');
|
|
17
|
+
rememberUser(ctx, user);
|
|
18
|
+
return user;
|
|
19
|
+
}
|