@future-unknown/known 0.0.0-stage → 0.2.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/lib/helpers.js ADDED
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Shared command utilities: resolving which session a command runs as, building
3
+ * an authenticated client for it, prompting for confirmation, and small helpers.
4
+ *
5
+ * The endpoint is never resolved on its own. It arrives with the session, because
6
+ * a token is issued by one API for one org and the two can't be separated — so
7
+ * naming the org (`known acme …`) is what picks the API as well.
8
+ */
9
+ const readline = require("readline")
10
+ const config = require("./config")
11
+ const project = require("./project")
12
+ const auth = require("./auth")
13
+ const output = require("./output")
14
+ const { createClient } = require("@future-unknown/known-sdk")
15
+
16
+ function friendly(message, fields) {
17
+ const e = new Error(message)
18
+ e.friendly = true
19
+ if (fields) e.fields = fields
20
+ return e
21
+ }
22
+
23
+ // Candidate sessions as `{ label: account }`, for the ambiguity/not-found detail.
24
+ function candidates(sessions) {
25
+ const out = {}
26
+ for (const s of sessions) out[s.label] = accountLabel(s.account) || s.role || "signed in"
27
+ return out
28
+ }
29
+
30
+ /**
31
+ * The session a command runs as, and where its org came from.
32
+ *
33
+ * Resolution order:
34
+ * 1. the org named on the command line (`known acme ping`)
35
+ * 2. `$KNOWN_ORG` in the environment
36
+ * 3. the nearest `KNOWN_ORG` file at or above the working directory
37
+ * 4. the only session on the machine
38
+ *
39
+ * A bare org matches on any environment; when more than one matches, the
40
+ * command stops and asks to be qualified (`acme@prod`) rather than guessing,
41
+ * since guessing would mean acting on the wrong tenant. For the same reason a
42
+ * binding (2, 3) whose session isn't on this machine is an error — it never
43
+ * falls through to whatever session happens to be here.
44
+ *
45
+ * The returned session carries `source`: null when the org was typed, else what
46
+ * picked it (`$KNOWN_ORG`, the KNOWN_ORG file's path, or "only session").
47
+ */
48
+ function sessionFor(argv, ref) {
49
+ if (ref) return { ...named(ref, null), source: null }
50
+
51
+ const bound = project.binding()
52
+ if (bound) return { ...named(bound.ref, bound), source: bound.from }
53
+
54
+ const held = config.allSessions()
55
+ if (held.length === 1) return { ...held[0], source: "only session" }
56
+ if (!held.length) throw friendly("not signed in — run `known login`")
57
+ throw friendly(
58
+ "several sessions — name one (`known " + held[0].key + " …`) or bind this project: " +
59
+ "`echo " + held[0].key + " > " + project.FILE + "`",
60
+ candidates(held)
61
+ )
62
+ }
63
+
64
+ // The one session matching an org reference. `bound` is the project binding
65
+ // the reference came from, if any, so errors can say where it was written.
66
+ function named(ref, bound) {
67
+ const matches = config.matchSessions(ref)
68
+ if (matches.length === 1) return matches[0]
69
+
70
+ const held = config.allSessions()
71
+ if (!matches.length) {
72
+ const lead = bound ? "this project uses " + ref + " (" + bound.from + ")" : "no session for " + ref
73
+ throw friendly(
74
+ held.length || bound
75
+ ? lead + " — run `known login` and pick it"
76
+ : "not signed in — run `known login`",
77
+ held.length ? candidates(held) : null
78
+ )
79
+ }
80
+
81
+ throw friendly(
82
+ "'" + ref + "' matches " + matches.length + " sessions — " +
83
+ (bound
84
+ ? "qualify it in " + bound.from + ", e.g. `" + matches[0].label + "`"
85
+ : "qualify it, e.g. `known " + matches[0].label + " …`"),
86
+ candidates(matches)
87
+ )
88
+ }
89
+
90
+ // A bare client with no reauthentication, for the one call made before a session
91
+ // exists on disk (login's whoami probe).
92
+ function clientFor(endpoint, token) {
93
+ return createClient(token, { endpoint })
94
+ }
95
+
96
+ /**
97
+ * Build a client bound to a stored session, talking to that session's endpoint.
98
+ *
99
+ * On 401 the client may only attempt a *silent refresh*. It must never fall back
100
+ * to interactive sign-in: a token is bound to the org picked in the browser, and
101
+ * nothing can steer that choice, so a silent re-auth could hand back a token for
102
+ * a different org — or a different account — than the command asked for. An
103
+ * expired session is reported instead, naming what to sign into.
104
+ */
105
+ function getClient(argv, opts = {}) {
106
+ const session = opts.session || sessionFor(argv, opts.org)
107
+ const endpoint = session.endpoint
108
+
109
+ return createClient(session.access_token, {
110
+ endpoint,
111
+ reauthenticate: async () => {
112
+ if (!session.refresh_token) throw expired(session)
113
+ let next
114
+ try {
115
+ next = await auth.refresh(endpoint, session.refresh_token)
116
+ } catch (e) {
117
+ throw expired(session)
118
+ }
119
+ config.updateSession(endpoint, session.key, next)
120
+ return next.access_token
121
+ },
122
+ onToken: (t) => config.updateSession(endpoint, session.key, { access_token: t })
123
+ })
124
+ }
125
+
126
+ function expired(session) {
127
+ return friendly(
128
+ "session for " + session.label + " expired — run `known login --endpoint " +
129
+ (config.aliasOf(session.endpoint) || session.endpoint) + "` and pick " + session.key
130
+ )
131
+ }
132
+
133
+ // How to name the account a session belongs to, for display.
134
+ function accountLabel(account) {
135
+ if (!account) return null
136
+ return account.email || account.name || account.id || null
137
+ }
138
+
139
+ // Yes/no prompt for destructive actions. Auto-confirms when --yes/-y is passed
140
+ // or when not attached to a TTY (scripted use). `io` names the streams, for
141
+ // tests; a command never passes it.
142
+ function confirm(message, argv, io) {
143
+ const input = (io && io.input) || process.stdin
144
+ if (argv && (argv.yes || argv.y)) return Promise.resolve(true)
145
+ if (!input.isTTY) return Promise.resolve(true)
146
+ const rl = readline.createInterface({ input, output: (io && io.output) || process.stdout })
147
+ return new Promise((resolve) => {
148
+ rl.question("\n " + message + " (y/N) ", (ans) => {
149
+ rl.close()
150
+ resolve(/^y(es)?$/i.test(ans.trim()))
151
+ })
152
+ })
153
+ }
154
+
155
+ // Confirmation that is never assumed, for what cannot be taken back with a
156
+ // second command (removing a person, leaving, renaming a wiki): a person at
157
+ // a terminal is asked; a script, or an agent, must pass --yes.
158
+ function confirmStated(message, argv, io) {
159
+ const input = (io && io.input) || process.stdin
160
+ if (!(argv && (argv.yes || argv.y)) && !input.isTTY) return Promise.reject(friendly("this needs confirming — pass --yes"))
161
+ return confirm(message, argv, io)
162
+ }
163
+
164
+ // Confirmation by name, for what --yes is too light for (deleting a wiki or a
165
+ // team): a person at a terminal is asked to type the name; a script passes
166
+ // `--confirm <name>`. Nothing is assumed: with neither, the command stops.
167
+ // Answers `{ value, asked }` — what was given, and whether it was typed at
168
+ // the prompt; the caller compares it with the name.
169
+ function confirmByName(message, argv, io) {
170
+ if (argv && argv.confirm !== undefined && argv.confirm !== true) {
171
+ return Promise.resolve({ value: String(argv.confirm), asked: false })
172
+ }
173
+ const input = (io && io.input) || process.stdin
174
+ if (!input.isTTY) return Promise.reject(friendly("this is confirmed by name — pass --confirm <name>"))
175
+ const rl = readline.createInterface({ input, output: (io && io.output) || process.stdout })
176
+ return new Promise((resolve) => {
177
+ rl.question("\n " + message + " ", (ans) => {
178
+ rl.close()
179
+ resolve({ value: ans.trim(), asked: true })
180
+ })
181
+ })
182
+ }
183
+
184
+ // The names a mistyped one most likely meant: those it begins, or that begin
185
+ // it, then those within a couple of letters of it. For "unknown command"
186
+ // messages and unknown RPC methods; empty when nothing is near.
187
+ const NEAR_EDITS = 2
188
+ const NEAR_SHOWN = 3
189
+ const NEAR_SHORT = 4
190
+ function nearest(word, names) {
191
+ const typed = String(word).toLowerCase()
192
+ // a name it begins, or that begins it, is the answer on its own
193
+ const leading = names.filter((name) => name.toLowerCase().startsWith(typed) || typed.startsWith(name.toLowerCase()))
194
+ if (leading.length) return leading.sort().slice(0, NEAR_SHOWN)
195
+ return names
196
+ .map((name) => ({ name, distance: edits(typed, name.toLowerCase()) }))
197
+ // a short name is near only when a single letter off
198
+ .filter((entry) => entry.distance <= (entry.name.length <= NEAR_SHORT ? 1 : NEAR_EDITS))
199
+ .sort((x, y) => x.distance - y.distance || x.name.localeCompare(y.name))
200
+ .slice(0, NEAR_SHOWN)
201
+ .map((entry) => entry.name)
202
+ }
203
+
204
+ function edits(a, b) {
205
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
206
+ for (let i = 1; i <= a.length; i++) {
207
+ const next = [i]
208
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
209
+ row = next
210
+ }
211
+ return row[b.length]
212
+ }
213
+
214
+ // "unknown wiki command: renam — did you mean rename?"
215
+ function unknownCommand(kind, verb, names) {
216
+ const near = nearest(verb, names)
217
+ return "unknown " + (kind ? kind + " " : "") + "command: " + verb + (near.length ? " — did you mean " + near.join(", ") + "?" : "")
218
+ }
219
+
220
+ // Collapse a methodry Result into the value a command renders.
221
+ //
222
+ // Under the result model a call resolves to `{ response, refused }` instead of
223
+ // throwing for expected outcomes. The CLI's natural boundary is `run()` →
224
+ // `output.error` → exit 1, so a refusal — the server's deliberate "no" — is
225
+ // re-thrown here, carrying its field detail for `output.error` to render.
226
+ // Operational failures (a MethodryError) already throw on their own.
227
+ function unwrap(result) {
228
+ if (result && result.refused) {
229
+ const e = new Error(result.refused.message || "request refused")
230
+ e.friendly = true
231
+ e.refused = true
232
+ e.fields = result.refused.fields || null
233
+ throw e
234
+ }
235
+ return result ? result.response : result
236
+ }
237
+
238
+ // Exit once stdout and stderr have handed everything to the OS. Writes to
239
+ // a pipe are asynchronous, so exiting at once cut piped output off at the
240
+ // pipe's buffer (64 KB) — a large `--json` read arrived truncated.
241
+ function exitAfterFlush(code) {
242
+ let pending = 2
243
+ const done = () => { if (--pending === 0) process.exit(code) }
244
+ process.stdout.write("", done)
245
+ process.stderr.write("", done)
246
+ }
247
+
248
+ // Wrap a command body so SDK/auth errors render consistently and exit non-zero.
249
+ async function run(fn) {
250
+ try {
251
+ await fn()
252
+ exitAfterFlush(0)
253
+ } catch (e) {
254
+ output.error(e)
255
+ exitAfterFlush(1)
256
+ }
257
+ }
258
+
259
+ // People behind the ids a table shows, named through the API's
260
+ // actors.resolve (names only; null for anyone the reader has not seen).
261
+ // Best-effort: without an answer the ids print as themselves. An author
262
+ // who acted from another org carries its name.
263
+ async function actorNames(client, actors) {
264
+ const ids = [...new Set(actors.flatMap((a) => [a && a.id, a && a.onBehalfOf]).filter(Boolean))].slice(0, 100)
265
+ const orgs = [...new Set(actors.map((a) => a && a.org).filter(Boolean))].slice(0, 20)
266
+ let answer = { actors: {}, orgs: {} }
267
+ if (ids.length) {
268
+ try {
269
+ answer = unwrap(await client.actors.resolve(orgs.length ? { ids, orgs } : { ids }))
270
+ } catch (e) {}
271
+ }
272
+ const name = (id) => (answer.actors && answer.actors[id] && answer.actors[id].name) || id
273
+ return (actor) => {
274
+ if (!actor) return ""
275
+ const org = actor.org && answer.orgs && answer.orgs[actor.org] ? " (" + answer.orgs[actor.org].name + ")" : ""
276
+ return (actor.onBehalfOf ? name(actor.id) + " for " + name(actor.onBehalfOf) : name(actor.id)) + org
277
+ }
278
+ }
279
+ // ---- people ----------------------------------------------------------------
280
+
281
+ // A person on the command line is a user id (user_…), an @handle, or an email
282
+ // address. The last two are looked up among the organization's people
283
+ // (members.list, narrowed by `query`) and must match exactly one
284
+ // of them exactly; anything else is refused with who came close, never
285
+ // guessed. Owners alone read email addresses, so a member finds people by
286
+ // handle or id.
287
+ const USER_ID = /^user_[A-Za-z0-9]+$/
288
+ const PERSON_CANDIDATES = 100
289
+ // Who a lookup searched, said in its refusal, unless the caller says otherwise.
290
+ const PERSON_WHERE = "in this organization"
291
+ const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+$/
292
+
293
+ // What was typed, read as one of the three: { id } | { handle } | { email }.
294
+ function personRef(value) {
295
+ const text = value === undefined || value === null || value === true ? "" : String(value).trim()
296
+ if (!text) throw friendly("name the person — a user id (user_…), an @handle, or an email address")
297
+ if (USER_ID.test(text)) return { id: text }
298
+ if (text.startsWith("@") && text.length > 1) return { handle: text.slice(1).toLowerCase() }
299
+ if (EMAIL_SHAPE.test(text)) return { email: text.toLowerCase() }
300
+ throw friendly("name the person by user id (user_…), @handle, or email address — got “" + text + "”")
301
+ }
302
+
303
+ // How a person reads in a line: "Ada Lovelace @ada ada@acme.com".
304
+ function personLine(person) {
305
+ return [person.name, person.handle ? "@" + person.handle : null, person.email].filter(Boolean).join(" ") || person.user_id
306
+ }
307
+
308
+ // The one of `people` ({ user_id, name, handle, email? }) a reference names
309
+ // exactly; `where` says who was searched ("in acme", "waiting to join").
310
+ function exactPerson(people, ref, where) {
311
+ if (ref.id) return people.find((person) => person.user_id === ref.id) || { user_id: ref.id, name: null, handle: null }
312
+ const said = ref.handle !== undefined ? "@" + ref.handle : ref.email
313
+ const exact = people.filter((person) => (ref.handle !== undefined
314
+ ? String(person.handle || "").toLowerCase() === ref.handle
315
+ : String(person.email || "").toLowerCase() === ref.email))
316
+ if (exact.length === 1) return exact[0]
317
+ const near = exact.length ? exact : people
318
+ const blind = ref.email !== undefined && people.length && !people.some((person) => person.email)
319
+ const lead = blind
320
+ ? "only an organization's owners find a person by email address — name them by @handle or user id"
321
+ : exact.length
322
+ ? said + " matches " + exact.length + " people " + where + " — name one by user id"
323
+ : "nobody " + where + " is exactly " + said
324
+ throw friendly(lead + (near.length ? "; the closest:" : ""), near.length
325
+ ? Object.fromEntries(near.map((person) => [person.user_id, personLine(person)]))
326
+ : null)
327
+ }
328
+
329
+ // The member of the session's organization a command names: their id, and
330
+ // their name when the lookup learned it. A user id is taken as given.
331
+ async function person(client, value, where = PERSON_WHERE) {
332
+ const ref = personRef(value)
333
+ if (ref.id) return { id: ref.id, name: null }
334
+ const page = unwrap(await client.members.list({ query: ref.handle !== undefined ? ref.handle : ref.email, limit: PERSON_CANDIDATES }))
335
+ const found = exactPerson(page.items || [], ref, where)
336
+ return { id: found.user_id, name: found.name || (found.handle ? "@" + found.handle : null) }
337
+ }
338
+
339
+ // Why someone holds a wiki or a site, in words: the reasons the API's access
340
+ // answers carry (`via`). `teamName` names a team by its id.
341
+ function accessReasons(via, teamName) {
342
+ return (via || []).map((reason) => {
343
+ if (reason.kind === "owner") return "org owner"
344
+ if (reason.kind === "user") return "direct grant" + (reason.level ? " (" + reason.level + ")" : "")
345
+ if (reason.kind === "team" && reason.id === "everyone") return "everyone" + (reason.level ? " (" + reason.level + ")" : "")
346
+ if (reason.kind === "team") return "team " + (teamName ? teamName(reason.id) : reason.id) + (reason.level ? " (" + reason.level + ")" : "")
347
+ return reason.kind
348
+ })
349
+ }
350
+
351
+ module.exports = {
352
+ actorNames,
353
+ accessReasons,
354
+ person,
355
+ personRef,
356
+ personLine,
357
+ exactPerson,
358
+ confirmByName,
359
+ confirmStated,
360
+ nearest,
361
+ unknownCommand,
362
+ friendly,
363
+ getClient,
364
+
365
+ clientFor,
366
+ sessionFor,
367
+ accountLabel,
368
+ confirm,
369
+ run,
370
+ unwrap
371
+ }