@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/README.md +567 -2
- package/bin/known +156 -0
- package/lib/auth.js +206 -0
- package/lib/cmds/_audit.js +153 -0
- package/lib/cmds/_code.js +673 -0
- package/lib/cmds/_config.js +91 -0
- package/lib/cmds/_endpoints.js +58 -0
- package/lib/cmds/_feedback.js +44 -0
- package/lib/cmds/_help.js +70 -0
- package/lib/cmds/_login.js +50 -0
- package/lib/cmds/_logout.js +40 -0
- package/lib/cmds/_members.js +403 -0
- package/lib/cmds/_ping.js +49 -0
- package/lib/cmds/_post.js +103 -0
- package/lib/cmds/_rpc.js +86 -0
- package/lib/cmds/_sessions.js +68 -0
- package/lib/cmds/_sites.js +300 -0
- package/lib/cmds/_teams.js +269 -0
- package/lib/cmds/_whoami.js +76 -0
- package/lib/cmds/_wiki.js +1555 -0
- package/lib/cmds/org.js +85 -0
- package/lib/config.js +297 -0
- package/lib/helpers.js +371 -0
- package/lib/output.js +338 -0
- package/lib/project.js +100 -0
- package/package.json +50 -4
package/bin/known
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* known — the Known CLI.
|
|
4
|
+
*
|
|
5
|
+
* A session is one sign-in: an endpoint, an org, an account, and its tokens —
|
|
6
|
+
* inseparable, because a token is issued by one API for one org. So there is no
|
|
7
|
+
* "current environment" to switch and no state at all: you choose the endpoint
|
|
8
|
+
* when you sign in, and naming the org picks the endpoint with it.
|
|
9
|
+
*
|
|
10
|
+
* One machine can hold as many sessions as you like, each potentially a different
|
|
11
|
+
* Known account. The org leads every command scoped to one:
|
|
12
|
+
*
|
|
13
|
+
* known <org> the commands available for that org
|
|
14
|
+
* known <org> <verb> [args] act as that org
|
|
15
|
+
*
|
|
16
|
+
* Qualify the org as `<org>@<env>` when the same one is signed in on more than
|
|
17
|
+
* one environment (`known acme@staging ping`).
|
|
18
|
+
*
|
|
19
|
+
* Machine-level commands are single keywords:
|
|
20
|
+
* known login [--endpoint <name>] | logout | whoami | sessions | config
|
|
21
|
+
* known endpoints | ping | post | wiki | code | teams | members | audit | rpc <method>
|
|
22
|
+
*
|
|
23
|
+
* Those keywords are RESERVED: a first argument matching one is dispatched as a
|
|
24
|
+
* command, never as an org, so an org whose slug collides with one is not
|
|
25
|
+
* addressable here. Anything else is an org.
|
|
26
|
+
*
|
|
27
|
+
* Where a command works both ways, the bare form resolves the org from context:
|
|
28
|
+
* $KNOWN_ORG, else the nearest KNOWN_ORG file above the working directory, else the
|
|
29
|
+
* only session on the machine (lib/project.js, helpers.sessionFor).
|
|
30
|
+
*
|
|
31
|
+
* Global flags: --endpoint <name|url> (login), --json, --yes/-y, and
|
|
32
|
+
* --confirm <name> for what is confirmed by name (deleting a wiki or a team).
|
|
33
|
+
*/
|
|
34
|
+
const minimist = require("minimist")
|
|
35
|
+
const colors = require("@colors/colors")
|
|
36
|
+
const config = require("../lib/config")
|
|
37
|
+
const output = require("../lib/output")
|
|
38
|
+
|
|
39
|
+
// Colour is for people at a terminal: output piped to a file, a script or an
|
|
40
|
+
// agent carries none, and NO_COLOR turns it off anywhere.
|
|
41
|
+
if (!process.stdout.isTTY || process.env.NO_COLOR) colors.disable()
|
|
42
|
+
|
|
43
|
+
// Flags that carry prose take the next argument whatever it starts with:
|
|
44
|
+
// `--old "- an item"` is the text "- an item", not a flag. minimist reads a
|
|
45
|
+
// value that begins with a dash as the next flag, so such pairs are joined
|
|
46
|
+
// (`--old=- an item`) before it sees them.
|
|
47
|
+
const PROSE_FLAGS = ["text", "title", "message", "description", "old", "new"]
|
|
48
|
+
|
|
49
|
+
function joinProse(args) {
|
|
50
|
+
const out = []
|
|
51
|
+
for (let i = 0; i < args.length; i++) {
|
|
52
|
+
const flag = /^--([a-z-]+)$/.exec(args[i])
|
|
53
|
+
if (flag && PROSE_FLAGS.includes(flag[1]) && i + 1 < args.length && args[i + 1].startsWith("-")) {
|
|
54
|
+
out.push(args[i] + "=" + args[++i])
|
|
55
|
+
} else {
|
|
56
|
+
out.push(args[i])
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const argv = minimist(joinProse(process.argv.slice(2)), {
|
|
63
|
+
boolean: ["json", "yes", "help", "recursive", "all", "deep", "latest", "reverse", "replace", "restricted", "open", "regex", "ignore-case", "off"],
|
|
64
|
+
string: [
|
|
65
|
+
"endpoint", "text", "file", "title",
|
|
66
|
+
// wiki flags: conditional writes, notes on a change, historical reads,
|
|
67
|
+
// limits, and record timestamps/paging (--ts backfill, --since/--until
|
|
68
|
+
// range, --cursor continuation, --if-version compare-and-swap); --old and
|
|
69
|
+
// --new are what `wiki edit` replaces; --description what `wiki update` says
|
|
70
|
+
"message", "if-revision", "if-change", "if-version", "change", "before", "at", "depth", "limit", "resolve", "revision", "version",
|
|
71
|
+
"ts", "since", "until", "cursor", "metadata", "old", "new", "description",
|
|
72
|
+
// multi-wiki: --wiki names the wiki a command runs in; --grant and
|
|
73
|
+
// --member (repeatable) build a restricted wiki's grants at creation
|
|
74
|
+
"wiki", "member", "grant",
|
|
75
|
+
// code: --lines reads part of a file, --context widens grep, --starter
|
|
76
|
+
// begins a tree from a starter's files
|
|
77
|
+
"lines", "context", "starter",
|
|
78
|
+
// feedback: what a note is about, and a failed call's reference
|
|
79
|
+
"about", "ref",
|
|
80
|
+
// wikis, teams and members: --confirm <name> deletes a wiki or a team,
|
|
81
|
+
// --level and --as share a wiki and accept one, --name renames a team or
|
|
82
|
+
// a site, --role and --query choose and filter the org's people
|
|
83
|
+
"confirm", "level", "as", "name", "role", "query",
|
|
84
|
+
// audit: narrow the log by what was done, who did it, who it was done
|
|
85
|
+
// to, and what it was done to
|
|
86
|
+
"action", "actor", "person", "kind", "target"
|
|
87
|
+
],
|
|
88
|
+
alias: { y: "yes", h: "help" }
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
output.setJson(argv.json)
|
|
92
|
+
|
|
93
|
+
// Reserved first arguments. Everything not listed here is an org reference.
|
|
94
|
+
// The ones that take an optional org resolve it from context when called bare.
|
|
95
|
+
const root = {
|
|
96
|
+
help: require("../lib/cmds/_help"),
|
|
97
|
+
login: require("../lib/cmds/_login"),
|
|
98
|
+
logout: require("../lib/cmds/_logout"),
|
|
99
|
+
whoami: require("../lib/cmds/_whoami"),
|
|
100
|
+
sessions: require("../lib/cmds/_sessions"),
|
|
101
|
+
endpoints: require("../lib/cmds/_endpoints"),
|
|
102
|
+
config: require("../lib/cmds/_config"),
|
|
103
|
+
ping: require("../lib/cmds/_ping"),
|
|
104
|
+
post: require("../lib/cmds/_post"),
|
|
105
|
+
wiki: require("../lib/cmds/_wiki"),
|
|
106
|
+
code: require("../lib/cmds/_code"),
|
|
107
|
+
teams: require("../lib/cmds/_teams"),
|
|
108
|
+
members: require("../lib/cmds/_members"),
|
|
109
|
+
audit: require("../lib/cmds/_audit"),
|
|
110
|
+
rpc: require("../lib/cmds/_rpc")
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// `known <org> …` — every org-scoped command.
|
|
114
|
+
const org = require("../lib/cmds/org")
|
|
115
|
+
|
|
116
|
+
// Commands with a menu of their own, which they show for --help.
|
|
117
|
+
const MENUS = ["wiki", "code", "sites", "teams", "members", "audit"]
|
|
118
|
+
|
|
119
|
+
async function main() {
|
|
120
|
+
// Older layouts kept machine-wide state in config.json. One that only recorded
|
|
121
|
+
// the selected endpoint is removed silently (a session now carries its own);
|
|
122
|
+
// one still holding tokens is moved aside and reported, since it can't be
|
|
123
|
+
// re-filed by org without knowing each token's org.
|
|
124
|
+
const legacy = config.legacyCleanup()
|
|
125
|
+
if (legacy && legacy.backup && !output.isJson()) {
|
|
126
|
+
output.info(("previous session format moved to " + legacy.backup + " — run `known login`").grey)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const _ = argv._
|
|
130
|
+
|
|
131
|
+
if (_.length === 0 || _[0] === "help") {
|
|
132
|
+
return root.help(argv)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// --help after a command runs nothing: `known acme code create --help`
|
|
136
|
+
// shows the code menu, which lists each verb's flags; a command without
|
|
137
|
+
// a menu of its own shows the org's, or the machine's.
|
|
138
|
+
if (argv.help) {
|
|
139
|
+
const at = root[_[0]] ? 0 : 1
|
|
140
|
+
argv._ = MENUS.includes(_[at]) ? _.slice(0, at + 1) : _.slice(0, at)
|
|
141
|
+
if (!argv._.length) return root.help(argv)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (root[argv._[0]]) {
|
|
145
|
+
// Root commands take no org; the ones that accept one resolve it from
|
|
146
|
+
// context, so pass the remaining positionals through as their arguments.
|
|
147
|
+
return root[argv._[0]](argv, null, argv._.slice(1))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return org(argv)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
main().catch((e) => {
|
|
154
|
+
output.error(e)
|
|
155
|
+
process.exit(1)
|
|
156
|
+
})
|
package/lib/auth.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authentication — OAuth 2.0 Authorization Code + PKCE (RFC 7636).
|
|
3
|
+
*
|
|
4
|
+
* Known's sign-in does not offer the device grant, so known
|
|
5
|
+
* authenticates the way gh/gcloud/vercel CLIs do: open the browser to the
|
|
6
|
+
* authorize endpoint, capture the redirect on a localhost loopback listener,
|
|
7
|
+
* then exchange the code (with the PKCE verifier) for tokens.
|
|
8
|
+
*
|
|
9
|
+
* The Known API publishes auth configuration at `/.well-known/trace`:
|
|
10
|
+
* {
|
|
11
|
+
* "authorization_endpoint": "https://.../oauth/authorize",
|
|
12
|
+
* "token_endpoint": "https://.../oauth/token",
|
|
13
|
+
* "client_id": "…",
|
|
14
|
+
* "scopes": ["openid","profile","email","offline_access","user:org:read"],
|
|
15
|
+
* "redirect_uris": ["http://127.0.0.1:8790/callback", …],
|
|
16
|
+
* "code_challenge_method": "S256"
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* known hard-codes none of this: the API it is pointed at says where to sign
|
|
20
|
+
* in, and the CLI follows.
|
|
21
|
+
*/
|
|
22
|
+
const http = require("http")
|
|
23
|
+
const crypto = require("crypto")
|
|
24
|
+
const open = require("open")
|
|
25
|
+
require("@colors/colors")
|
|
26
|
+
|
|
27
|
+
async function fetchWellKnown(endpoint) {
|
|
28
|
+
const url = endpoint.replace(/\/+$/, "") + "/.well-known/trace"
|
|
29
|
+
const res = await fetch(url)
|
|
30
|
+
if (!res.ok) throw new Error("not a Known API endpoint: " + endpoint)
|
|
31
|
+
return res.json()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function postForm(url, params) {
|
|
35
|
+
const res = await fetch(url, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
38
|
+
body: new URLSearchParams(params).toString()
|
|
39
|
+
})
|
|
40
|
+
return { status: res.status, body: await res.json().catch(() => ({})) }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function base64url(buf) {
|
|
44
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// PKCE verifier + S256 challenge (RFC 7636).
|
|
48
|
+
function pkce() {
|
|
49
|
+
const verifier = base64url(crypto.randomBytes(32))
|
|
50
|
+
const challenge = base64url(crypto.createHash("sha256").update(verifier).digest())
|
|
51
|
+
return { verifier, challenge }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function scopeString(cfg) {
|
|
55
|
+
if (Array.isArray(cfg.scopes)) return cfg.scopes.join(" ")
|
|
56
|
+
return cfg.scope || "openid profile email"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Prefer a 127.0.0.1 loopback redirect (binds reliably), then localhost.
|
|
60
|
+
function pickRedirect(cfg) {
|
|
61
|
+
const uris = cfg.redirect_uris || (cfg.redirect_uri ? [cfg.redirect_uri] : [])
|
|
62
|
+
const pick =
|
|
63
|
+
uris.find((u) => /^https?:\/\/127\.0\.0\.1[:/]/.test(u)) ||
|
|
64
|
+
uris.find((u) => /^https?:\/\/localhost[:/]/.test(u)) ||
|
|
65
|
+
uris[0]
|
|
66
|
+
if (!pick) throw new Error("endpoint advertises no redirect_uri for the CLI")
|
|
67
|
+
return pick
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Text placed in the result page. What it shows can come from the request (an
|
|
71
|
+
// `error` parameter), so nothing is written into the page as markup.
|
|
72
|
+
function escapeHtml(text) {
|
|
73
|
+
return String(text).replace(/[&<>"']/g, (ch) => (
|
|
74
|
+
{ "&": "&", "<": "<", ">": ">", "\"": """, "'": "'" }[ch]
|
|
75
|
+
))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function resultPage(title, message) {
|
|
79
|
+
return (
|
|
80
|
+
"<!doctype html><meta charset=utf-8><title>" + escapeHtml(title) + "</title>" +
|
|
81
|
+
"<body style=\"font-family:system-ui,sans-serif;text-align:center;padding:4rem;color:#222\">" +
|
|
82
|
+
"<h1>" + escapeHtml(title) + "</h1><p>" + escapeHtml(message) + "</p></body>"
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Stand up a one-shot loopback server and resolve with the authorization code.
|
|
87
|
+
function awaitCallback(redirectUri, state, timeoutMs) {
|
|
88
|
+
const u = new URL(redirectUri)
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
let timer
|
|
91
|
+
const server = http.createServer((req, res) => {
|
|
92
|
+
const reqUrl = new URL(req.url, u.origin)
|
|
93
|
+
if (reqUrl.pathname !== u.pathname) {
|
|
94
|
+
res.writeHead(404)
|
|
95
|
+
return res.end()
|
|
96
|
+
}
|
|
97
|
+
const code = reqUrl.searchParams.get("code")
|
|
98
|
+
const retState = reqUrl.searchParams.get("state")
|
|
99
|
+
const err = reqUrl.searchParams.get("error")
|
|
100
|
+
// Each answer closes its connection, so a finished listener holds
|
|
101
|
+
// nothing open and a later sign-in never reaches an old one.
|
|
102
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" })
|
|
103
|
+
|
|
104
|
+
// Only the redirect this sign-in started carries its state. Anything
|
|
105
|
+
// else that reaches this address — another page on the machine, a stale
|
|
106
|
+
// tab — is answered and ignored: it neither ends the sign-in nor is
|
|
107
|
+
// believed, and the listener keeps waiting for the real one.
|
|
108
|
+
if (retState !== state) {
|
|
109
|
+
return res.end(resultPage("known: sign-in failed", "This is not the sign-in the terminal is waiting for."))
|
|
110
|
+
}
|
|
111
|
+
if (err) {
|
|
112
|
+
res.end(resultPage("known: sign-in failed", err))
|
|
113
|
+
return finish(new Error(err))
|
|
114
|
+
}
|
|
115
|
+
if (!code) {
|
|
116
|
+
res.end(resultPage("known: sign-in failed", "no authorization code"))
|
|
117
|
+
return finish(new Error("no authorization code returned"))
|
|
118
|
+
}
|
|
119
|
+
res.end(resultPage("known: signed in", "You may close this window and return to your terminal."))
|
|
120
|
+
finish(null, code)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
function finish(err, code) {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
server.close()
|
|
126
|
+
err ? reject(err) : resolve(code)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
server.on("error", reject)
|
|
130
|
+
server.listen(Number(u.port || 80), u.hostname)
|
|
131
|
+
timer = setTimeout(() => finish(new Error("authentication timed out")), timeoutMs)
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Full interactive sign-in. Opens the browser, captures the loopback redirect,
|
|
137
|
+
* exchanges the code with PKCE, and returns the token bundle
|
|
138
|
+
* ({ access_token, refresh_token?, expires_in?, ... }).
|
|
139
|
+
*/
|
|
140
|
+
async function authenticate(endpoint) {
|
|
141
|
+
const cfg = await fetchWellKnown(endpoint)
|
|
142
|
+
if (!cfg.authorization_endpoint || !cfg.token_endpoint) {
|
|
143
|
+
throw new Error("endpoint does not advertise an OAuth authorization flow")
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const { verifier, challenge } = pkce()
|
|
147
|
+
const state = base64url(crypto.randomBytes(16))
|
|
148
|
+
const redirectUri = pickRedirect(cfg)
|
|
149
|
+
|
|
150
|
+
const authUrl = new URL(cfg.authorization_endpoint)
|
|
151
|
+
authUrl.searchParams.set("response_type", "code")
|
|
152
|
+
authUrl.searchParams.set("client_id", cfg.client_id)
|
|
153
|
+
authUrl.searchParams.set("redirect_uri", redirectUri)
|
|
154
|
+
authUrl.searchParams.set("scope", scopeString(cfg))
|
|
155
|
+
authUrl.searchParams.set("state", state)
|
|
156
|
+
authUrl.searchParams.set("code_challenge", challenge)
|
|
157
|
+
authUrl.searchParams.set("code_challenge_method", cfg.code_challenge_method || "S256")
|
|
158
|
+
|
|
159
|
+
console.log()
|
|
160
|
+
console.log(" Opening your browser to sign in…".brightYellow)
|
|
161
|
+
console.log(" If it doesn't open, visit:".grey)
|
|
162
|
+
console.log(" " + authUrl.toString())
|
|
163
|
+
|
|
164
|
+
// Start listening before opening the browser so we never miss the redirect.
|
|
165
|
+
const codePromise = awaitCallback(redirectUri, state, (cfg.expires_in || 300) * 1000)
|
|
166
|
+
try {
|
|
167
|
+
await open(authUrl.toString())
|
|
168
|
+
} catch (e) {
|
|
169
|
+
// headless / no browser — the user can open the printed URL manually
|
|
170
|
+
}
|
|
171
|
+
const code = await codePromise
|
|
172
|
+
|
|
173
|
+
const tok = await postForm(cfg.token_endpoint, {
|
|
174
|
+
grant_type: "authorization_code",
|
|
175
|
+
code,
|
|
176
|
+
redirect_uri: redirectUri,
|
|
177
|
+
client_id: cfg.client_id,
|
|
178
|
+
code_verifier: verifier
|
|
179
|
+
})
|
|
180
|
+
if (tok.status !== 200 || !tok.body.access_token) {
|
|
181
|
+
throw new Error(tok.body.error_description || tok.body.error || "token exchange failed")
|
|
182
|
+
}
|
|
183
|
+
console.log()
|
|
184
|
+
return tok.body
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Non-interactive refresh. Returns a fresh token bundle, preserving the
|
|
189
|
+
* refresh_token when the server doesn't rotate it. Throws if the refresh token
|
|
190
|
+
* is expired/revoked (caller should fall back to `authenticate`).
|
|
191
|
+
*/
|
|
192
|
+
async function refresh(endpoint, refreshToken) {
|
|
193
|
+
const cfg = await fetchWellKnown(endpoint)
|
|
194
|
+
const tok = await postForm(cfg.token_endpoint, {
|
|
195
|
+
grant_type: "refresh_token",
|
|
196
|
+
refresh_token: refreshToken,
|
|
197
|
+
client_id: cfg.client_id
|
|
198
|
+
})
|
|
199
|
+
if (tok.status !== 200 || !tok.body.access_token) {
|
|
200
|
+
throw new Error(tok.body.error_description || tok.body.error || "token refresh failed")
|
|
201
|
+
}
|
|
202
|
+
if (!tok.body.refresh_token) tok.body.refresh_token = refreshToken
|
|
203
|
+
return tok.body
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { authenticate, refresh, fetchWellKnown, awaitCallback }
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
require("@colors/colors")
|
|
2
|
+
const output = require("../output")
|
|
3
|
+
const { getClient, sessionFor, run, unwrap, actorNames, person, friendly } = require("../helpers")
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `known <org> audit` — the org's audit log.
|
|
7
|
+
*
|
|
8
|
+
* Every change to the organization itself is recorded as it is made, and
|
|
9
|
+
* never changed or removed afterwards: its people and their roles,
|
|
10
|
+
* invitations and requests to join, teams and their rosters, which wikis
|
|
11
|
+
* exist and who holds them, what is shared with other organizations, its
|
|
12
|
+
* sites, domains and settings. Each event says what was done, when, who did
|
|
13
|
+
* it and through what (the web app, this CLI, an agent — named), and what it
|
|
14
|
+
* was done to. What is written in a wiki is that wiki's own history (`wiki
|
|
15
|
+
* changes`), not this.
|
|
16
|
+
*
|
|
17
|
+
* Org owners read it. The newest event comes first.
|
|
18
|
+
*
|
|
19
|
+
* known acme audit
|
|
20
|
+
* known acme audit --action wiki.grant one kind of change
|
|
21
|
+
* known acme audit --action team a whole family
|
|
22
|
+
* known acme audit --person @ada made to her, or by her
|
|
23
|
+
* known acme audit --actor ada@acme.com made by her
|
|
24
|
+
* known acme audit --kind wiki --target vault what happened to one thing
|
|
25
|
+
* known acme audit --limit 100 --before 412 the page after one that ended at 412
|
|
26
|
+
* known acme audit --json
|
|
27
|
+
*/
|
|
28
|
+
const KINDS = ["org", "member", "invitation", "team", "wiki", "share", "site", "domain", "agent"]
|
|
29
|
+
const ACTION = /^[a-z][A-Za-z]*(\.[A-Za-z]+)?$/
|
|
30
|
+
const LIMIT_MAX = 200
|
|
31
|
+
|
|
32
|
+
module.exports = function (argv, ref) {
|
|
33
|
+
if (argv.help) return showMenu(ref)
|
|
34
|
+
return list(argv, ref)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function showMenu(ref) {
|
|
38
|
+
const org = ref ? ref + " " : ""
|
|
39
|
+
console.log()
|
|
40
|
+
console.log((" known " + org + "audit").cyan + " the org's audit log — who changed what, when, and through what (org owners)".grey)
|
|
41
|
+
console.log()
|
|
42
|
+
output.commands([
|
|
43
|
+
[org + "audit", "the latest changes to the org: people, roles, teams, access to wikis, shares, sites, settings"],
|
|
44
|
+
[org + "audit --action <method>", "one kind of change (wiki.grant, team.addMember) or a family (wiki, team, members, share, site)"],
|
|
45
|
+
[org + "audit --person <person>", "changes made to someone, or by them"],
|
|
46
|
+
[org + "audit --actor <person>", "changes someone made"],
|
|
47
|
+
[org + "audit --kind <kind> --target <name>", "what happened to one thing (" + KINDS.join(", ") + ")"],
|
|
48
|
+
[org + "audit --limit <n> --before <id>", "page size (to " + LIMIT_MAX + "), and the page after the one that ended at <id>"]
|
|
49
|
+
])
|
|
50
|
+
console.log()
|
|
51
|
+
process.exit(0)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function list(argv, ref) {
|
|
55
|
+
return run(async () => {
|
|
56
|
+
const params = {}
|
|
57
|
+
if (argv.action !== undefined) {
|
|
58
|
+
if (!ACTION.test(String(argv.action))) throw friendly("--action takes a method (wiki.grant) or a family (wiki)")
|
|
59
|
+
params.action = String(argv.action)
|
|
60
|
+
}
|
|
61
|
+
if (argv.kind !== undefined) {
|
|
62
|
+
if (!KINDS.includes(String(argv.kind))) throw friendly("--kind is one of " + KINDS.join(", "))
|
|
63
|
+
params.kind = String(argv.kind)
|
|
64
|
+
}
|
|
65
|
+
if (argv.target !== undefined) params.target = String(argv.target)
|
|
66
|
+
if (argv.limit !== undefined) params.limit = whole(argv.limit, "--limit", LIMIT_MAX)
|
|
67
|
+
if (argv.before !== undefined) params.before = whole(argv.before, "--before")
|
|
68
|
+
|
|
69
|
+
const session = sessionFor(argv, ref)
|
|
70
|
+
const client = getClient(argv, { session })
|
|
71
|
+
if (argv.actor !== undefined) params.actor = (await person(client, argv.actor)).id
|
|
72
|
+
if (argv.person !== undefined) params.person = (await person(client, argv.person)).id
|
|
73
|
+
|
|
74
|
+
const page = unwrap(await client.audit.list(params))
|
|
75
|
+
if (output.isJson()) return output.data(page)
|
|
76
|
+
if (!page.items.length) return output.empty(Object.keys(params).length ? "no events match" : "nothing recorded yet")
|
|
77
|
+
|
|
78
|
+
const names = await actorNames(client, page.items.flatMap((event) => [
|
|
79
|
+
{ id: event.actor && event.actor.id },
|
|
80
|
+
{ id: event.person },
|
|
81
|
+
{ id: event.detail && event.detail.grantee && event.detail.grantee.kind === "user" ? event.detail.grantee.id : null }
|
|
82
|
+
]))
|
|
83
|
+
const who = (id) => (id ? names({ id }) : "someone")
|
|
84
|
+
output.table(page.items.map((event) => ({
|
|
85
|
+
id: String(event.id).grey,
|
|
86
|
+
when: output.timeAgo(new Date(event.at)),
|
|
87
|
+
who: who(event.actor && event.actor.id) + through(event.actor),
|
|
88
|
+
what: sentence(event, who)
|
|
89
|
+
})))
|
|
90
|
+
if (page.next) output.info(("more — add --before " + page.next).grey)
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function whole(value, flag, max) {
|
|
95
|
+
const number = Number(value)
|
|
96
|
+
if (!Number.isInteger(number) || number < 1 || (max && number > max)) throw friendly(flag + " takes a whole number" + (max ? " from 1 to " + max : ""))
|
|
97
|
+
return number
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Through what the change was made, when it was not the web app: this CLI,
|
|
101
|
+
// or an agent by the name it gave.
|
|
102
|
+
function through(actor) {
|
|
103
|
+
if (!actor) return ""
|
|
104
|
+
if (actor.agent && actor.agent.name) return (" via " + actor.agent.name).grey
|
|
105
|
+
if (actor.agent && actor.agent.site) return " via a site".grey
|
|
106
|
+
if (actor.client === "assistant") return " via Known's assistant".grey
|
|
107
|
+
if (actor.client === "mcp") return " via an agent".grey
|
|
108
|
+
if (actor.client === "cli") return " via the CLI".grey
|
|
109
|
+
return ""
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// What an event did, as a line: the method that did it leads, so the line
|
|
113
|
+
// can be asked for again with --action.
|
|
114
|
+
function sentence(event, who) {
|
|
115
|
+
const detail = event.detail || {}
|
|
116
|
+
const target = event.target && (event.target.name || event.target.id)
|
|
117
|
+
const said = SAID[event.action]
|
|
118
|
+
const rest = said ? said({ event, detail, target, who }) : [target, event.person ? who(event.person) : null].filter(Boolean).join(" · ")
|
|
119
|
+
return event.action.cyan + (rest ? " " + rest : "")
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const grantee = (detail, who) => (detail.grantee ? (detail.grantee.kind === "user" ? who(detail.grantee.id) : "team " + (detail.grantee.name || detail.grantee.id)) : "")
|
|
123
|
+
const changed = (detail) => Object.entries(detail).map(([field, change]) => field + " " + change.from + " → " + change.to).join(", ")
|
|
124
|
+
|
|
125
|
+
const SAID = {
|
|
126
|
+
"wiki.create": ({ detail, target }) => target + " (" + (detail.visibility === "restricted" ? "restricted" : "open to the org") + ")",
|
|
127
|
+
"wiki.update": ({ detail, target }) => target + ": " + changed(detail),
|
|
128
|
+
"wiki.grant": ({ detail, target, who }) => target + ": " + grantee(detail, who) + " " + (detail.from ? detail.from + " → " : "") + detail.level + (detail.self ? " (themselves)" : ""),
|
|
129
|
+
"wiki.revoke": ({ detail, target, who }) => target + ": " + grantee(detail, who) + " lost " + detail.level,
|
|
130
|
+
"wiki.rename": ({ detail, target }) => detail.from + " → " + target,
|
|
131
|
+
"team.update": ({ detail, target }) => target + ": " + changed(detail),
|
|
132
|
+
"team.remove": ({ detail, target }) => target + (detail.wikis && detail.wikis.length ? " (held " + detail.wikis.join(", ") + ")" : ""),
|
|
133
|
+
"team.addMember": ({ event, detail, target, who }) => target + ": " + who(event.person) + (detail.maintainer ? " as maintainer" : ""),
|
|
134
|
+
"team.removeMember": ({ event, target, who }) => target + ": " + who(event.person),
|
|
135
|
+
"team.setMaintainer": ({ event, detail, target, who }) => target + ": " + who(event.person) + (detail.maintainer ? " maintainer" : " member"),
|
|
136
|
+
"members.setRole": ({ event, detail, who }) => who(event.person) + " → " + detail.role,
|
|
137
|
+
"members.invite": ({ detail, target }) => target + " as " + detail.role,
|
|
138
|
+
"members.approveRequest": ({ event, detail, who }) => who(event.person) + " as " + detail.role,
|
|
139
|
+
"membership.ended": ({ event, detail, who }) => who(event.person) + ": " + [(detail.wikis || []).length + " wiki grants", (detail.teams || []).length + " team seats"].join(", ") + " removed",
|
|
140
|
+
"share.invite": ({ detail, target }) => target + (detail.guest ? " with " + (detail.guestOrg || detail.guest) : " from " + (detail.homeOrg || detail.home)) + " at " + detail.ceiling,
|
|
141
|
+
"share.accept": ({ detail, target }) => target + (detail.guest ? " by " + (detail.guestOrg || detail.guest) : " from " + (detail.homeOrg || detail.home)),
|
|
142
|
+
"share.revoke": ({ detail, target }) => target + (detail.guest ? " from " + (detail.guestOrg || detail.guest) : " by " + (detail.homeOrg || detail.home)),
|
|
143
|
+
"share.decline": ({ detail, target }) => target + (detail.guest ? " by " + (detail.guestOrg || detail.guest) : " from " + (detail.homeOrg || detail.home)),
|
|
144
|
+
"share.leave": ({ detail, target }) => target + (detail.guest ? " by " + (detail.guestOrg || detail.guest) : " from " + (detail.homeOrg || detail.home)),
|
|
145
|
+
"site.create": ({ detail, target }) => target + " in " + detail.wiki,
|
|
146
|
+
"site.attach": ({ detail, target }) => target + ": " + detail.wiki,
|
|
147
|
+
"site.detach": ({ detail, target }) => target + ": " + detail.wiki,
|
|
148
|
+
"site.update": ({ detail, target }) => target + ": " + changed(detail),
|
|
149
|
+
"org.rename": ({ detail }) => "→ " + detail.name,
|
|
150
|
+
"org.setLogo": ({ detail }) => "logo " + detail.logo,
|
|
151
|
+
"org.updateSettings": ({ detail }) => Object.keys(detail.settings || {}).join(", "),
|
|
152
|
+
"domains.setEnrollment": ({ detail, target }) => target + ": " + detail.enrollment
|
|
153
|
+
}
|