saturndocs 0.2.0 → 0.4.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/dist/auth-NKYU6ZSC.js +16 -0
- package/dist/{chunk-QF2ADHQZ.js → chunk-22WNRYB7.js} +17 -19
- package/dist/{chunk-2RZEC3VH.js → chunk-2GBM6W4I.js} +102 -34
- package/dist/{chunk-4ORVQCHY.js → chunk-3JUP4HIA.js} +34 -9
- package/dist/chunk-4B6PUKF5.js +915 -0
- package/dist/{chunk-GGGL4O7Z.js → chunk-6JJEMNSP.js} +8 -7
- package/dist/{chunk-Z5CBPJ2L.js → chunk-BB32XQJB.js} +9 -5
- package/dist/chunk-BRC7CU3J.js +427 -0
- package/dist/{chunk-ADZOBRZE.js → chunk-EH6E45H4.js} +805 -146
- package/dist/{chunk-DBMFJXKP.js → chunk-GLB47CSE.js} +5 -5
- package/dist/{chunk-EB7RWFQA.js → chunk-HHRZ3Y55.js} +1594 -140
- package/dist/{chunk-2YTD2XNI.js → chunk-HJ7HRIAT.js} +1 -1
- package/dist/{chunk-WBI4EI3D.js → chunk-KEZAO7P5.js} +2 -2
- package/dist/chunk-KWEWL4MJ.js +53 -0
- package/dist/{chunk-W3GKH5DY.js → chunk-N66SXAI5.js} +19 -11
- package/dist/chunk-QF5ELRAU.js +421 -0
- package/dist/{chunk-WUPP3THV.js → chunk-QMA7433F.js} +5 -5
- package/dist/{chunk-YSFP37B7.js → chunk-TRQCW5CZ.js} +20 -6
- package/dist/{chunk-6JGAA5TF.js → chunk-UXCORL5H.js} +4 -4
- package/dist/{chunk-56U46JVN.js → chunk-YGVC4N4V.js} +2 -1
- package/dist/chunk-ZHYL7FYA.js +1537 -0
- package/dist/chunk-ZXJ3Z3PR.js +115 -0
- package/dist/cli.js +6 -6
- package/dist/{coverage-EBWULNQQ.js → coverage-IUQLC2H6.js} +5 -5
- package/dist/{dist-XISZDQTR.js → dist-LZ5BC7HG.js} +38 -3
- package/dist/index.d.ts +69 -37
- package/dist/index.js +111 -47
- package/dist/{init-PI4VTG7V.js → init-EFZZRZZM.js} +4 -3
- package/dist/{lint-SXBP37G3.js → lint-N7ENEJVU.js} +3 -3
- package/dist/login-34OM3PJ2.js +22 -0
- package/dist/{manage-OB6DQK3Q.js → manage-2AOOCZE2.js} +6 -2
- package/dist/{nav-R4OORY2G.js → nav-DKCGLENP.js} +4 -4
- package/dist/openapiCheck-KEHPUZOD.js +103 -0
- package/dist/pages-E73CUM6I.js +16 -0
- package/dist/{read-WWOMA67R.js → read-TQSSS7EJ.js} +60 -12
- package/dist/{read-VECMKHBW.js → read-UGXFNEGJ.js} +11 -9
- package/dist/requests-OLCBRUAW.js +13 -0
- package/dist/{schema-NKOXZHQH.js → schema-3I6XJSCY.js} +3 -3
- package/dist/{sites-XMMGWPY2.js → sites-6HKU6JP7.js} +5 -4
- package/dist/{status-SYIUUSSU.js → status-DFAYOCC4.js} +4 -4
- package/dist/{suggestions-GX5CQK26.js → suggestions-JSTWOWRY.js} +35 -20
- package/dist/unavailable-HVN65Q7D.js +40 -0
- package/dist/validate-6RIKQWMI.js +11 -0
- package/package.json +14 -8
- package/dist/auth-DUYYFNEZ.js +0 -14
- package/dist/brokenLinks-E364XYH3.js +0 -48
- package/dist/build-F5PWGP57.js +0 -39
- package/dist/chunk-4J33CCAC.js +0 -49
- package/dist/chunk-D3CLXV7D.js +0 -131
- package/dist/chunk-FGKHDJOC.js +0 -697
- package/dist/chunk-GLI3OUYL.js +0 -637
- package/dist/chunk-K5YY6NSF.js +0 -71
- package/dist/chunk-KOJJUISB.js +0 -39
- package/dist/chunk-O72DR5FK.js +0 -152
- package/dist/chunk-SVDVBZPA.js +0 -588
- package/dist/chunk-VNYDYHXM.js +0 -22
- package/dist/chunk-VXEUNRVA.js +0 -26
- package/dist/chunk-WHNL6UYJ.js +0 -57
- package/dist/deploy-QUVLOGII.js +0 -13
- package/dist/dev-VDSDCBO2.js +0 -43
- package/dist/openapiCheck-X2QQGETY.js +0 -66
- package/dist/pages-MKFZAVGI.js +0 -15
- package/dist/requests-A7WC3B4M.js +0 -13
- package/dist/validate-D4I3DY2W.js +0 -32
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
asCliError,
|
|
3
3
|
clientFor
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-4B6PUKF5.js";
|
|
5
5
|
import {
|
|
6
6
|
applyCommandHelp
|
|
7
7
|
} from "./chunk-M2BZEDAS.js";
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
commandMetadata,
|
|
11
11
|
createResultWriter,
|
|
12
12
|
failureResult,
|
|
13
|
-
invalidInput,
|
|
13
|
+
invalidInput2 as invalidInput,
|
|
14
14
|
readSiteStatus,
|
|
15
15
|
resolveGlobalOptions,
|
|
16
16
|
resolveTarget,
|
|
@@ -20,18 +20,18 @@ import {
|
|
|
20
20
|
statusRecovery,
|
|
21
21
|
statusSections,
|
|
22
22
|
successResult
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-EH6E45H4.js";
|
|
24
24
|
|
|
25
25
|
// src/commands/status.ts
|
|
26
26
|
var STATUS_METADATA = Object.freeze([
|
|
27
27
|
commandMetadata("status", {
|
|
28
|
-
description: "A bounded briefing on one site, composed from the reads that already exist: the site itself, one page of conversations, one page of the pending suggestion tab, and one page of activity. There is no status route on the server and nothing here pages on your behalf. Each section reports available, empty, or
|
|
28
|
+
description: "A bounded briefing on one site, composed from the reads that already exist: the site itself, one page of conversations, one page of the pending suggestion tab, and one page of activity. There is no status route on the server and nothing here pages on your behalf. Each section reports available, empty, unavailable, or not_granted on its own, so a route that answered 503 leaves the other sections' data and identities untouched instead of blanking them. Every number comes from a field the server sent \u2014 the request failed and waiting tallies and the suggestion counts \u2014 and never from the length of a page. A credential the server refuses fails the command rather than being reported as a quiet site.",
|
|
29
29
|
target: { arguments: [] },
|
|
30
30
|
effect: "Nothing. Four independent reads of one site.",
|
|
31
31
|
output: {
|
|
32
32
|
fields: ["site", "requests", "suggestions", "activity", "counts", "attention"],
|
|
33
33
|
ids: ["thread_id", "job_id", "attempt"],
|
|
34
|
-
limitations: ["section_unavailable", "page_bounded"]
|
|
34
|
+
limitations: ["section_unavailable", "page_bounded", "field_omitted", "actor_relabeled", "row_visibility", "value_redacted"]
|
|
35
35
|
},
|
|
36
36
|
errors: ["invalid_input", "unauthorized", "forbidden", "not_found", "rate_limited", "service_unavailable", "transport_failure", "interrupted"],
|
|
37
37
|
examples: [
|
|
@@ -41,6 +41,7 @@ var STATUS_METADATA = Object.freeze([
|
|
|
41
41
|
})
|
|
42
42
|
]);
|
|
43
43
|
function sectionLine(part) {
|
|
44
|
+
if (part.state === "not_granted") return `${part.section}: not_granted \u2014 ${part.reason}`;
|
|
44
45
|
if (part.state === "unavailable") {
|
|
45
46
|
return `${part.section}: unavailable \u2014 ${part.error?.message ?? "the read failed and said nothing."} ${part.recovery?.command ?? ""}`.trimEnd();
|
|
46
47
|
}
|
|
@@ -78,12 +79,12 @@ function registerStatus(program, _cliDir, environment = {}) {
|
|
|
78
79
|
const target = await resolveTarget(client, { site });
|
|
79
80
|
context.siteId = target.site_id;
|
|
80
81
|
const status = await readSiteStatus(client, target.site_id);
|
|
81
|
-
context.limitations = statusLimitations(status);
|
|
82
|
+
context.limitations = statusLimitations(status, client.grantAuthenticated === true);
|
|
82
83
|
context.ids = statusIds(status);
|
|
83
84
|
context.recovery = statusRecovery(status);
|
|
84
85
|
const blocker = statusBlocker(status);
|
|
85
86
|
if (blocker !== null) {
|
|
86
|
-
throw new CliError(blocker.code, blocker.message, { server: blocker.server, data: status });
|
|
87
|
+
throw new CliError(blocker.code, globals.json ? blocker.message : statusText(status), { server: blocker.server, data: status });
|
|
87
88
|
}
|
|
88
89
|
process.exitCode = writer.write(successResult(context, status), { text: statusText(status) });
|
|
89
90
|
} catch (error) {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
requestedSite
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-N66SXAI5.js";
|
|
4
4
|
import {
|
|
5
5
|
asCliError,
|
|
6
6
|
clientFor
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-4B6PUKF5.js";
|
|
8
8
|
import {
|
|
9
9
|
applyCommandHelp
|
|
10
10
|
} from "./chunk-M2BZEDAS.js";
|
|
@@ -13,12 +13,14 @@ import {
|
|
|
13
13
|
commandMetadata,
|
|
14
14
|
createResultWriter,
|
|
15
15
|
failureResult,
|
|
16
|
+
grantFields,
|
|
17
|
+
grantLimitation,
|
|
16
18
|
listPages,
|
|
17
19
|
pagesUnavailable,
|
|
18
20
|
resolveGlobalOptions,
|
|
19
21
|
resolveTarget,
|
|
20
22
|
successResult
|
|
21
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-EH6E45H4.js";
|
|
22
24
|
|
|
23
25
|
// src/commands/pages.ts
|
|
24
26
|
import { InvalidArgumentError } from "commander";
|
|
@@ -27,7 +29,7 @@ var PAGES_METADATA = Object.freeze([
|
|
|
27
29
|
description: "Read the pages of the release readers are seeing, with where each one is read, where its source is, and how often it was read in the traffic window. A site with no live release answers unavailable: no_release and carries no page list at all, which this command reports as such rather than as a published site with nothing in it.",
|
|
28
30
|
target: { arguments: [{ name: "site-id", required: false, description: "The site to read. Defaults to the site the credential resolves to." }] },
|
|
29
31
|
effect: "Nothing. One read of the published page listing.",
|
|
30
|
-
output: { fields: ["site_id", "days", "release_id", "traffic", "pages", "unavailable"], ids: ["release_id"], limitations: ["page_bounded", "section_unavailable"] },
|
|
32
|
+
output: { fields: ["site_id", "days", "release_id", "traffic", "pages", "unavailable"], ids: ["release_id"], limitations: ["page_bounded", "section_unavailable", "field_omitted"] },
|
|
31
33
|
errors: ["invalid_input", "unauthorized", "forbidden", "not_found", "rate_limited", "service_unavailable", "transport_failure", "interrupted"],
|
|
32
34
|
examples: [
|
|
33
35
|
{ command: "saturndocs pages list", description: "Every published page of the live release, over the server's default window." },
|
|
@@ -45,12 +47,13 @@ function trafficWindow(value) {
|
|
|
45
47
|
}
|
|
46
48
|
function pagesLimitations(result) {
|
|
47
49
|
if (pagesUnavailable(result)) {
|
|
48
|
-
return [{
|
|
50
|
+
return [...result.days === void 0 ? [grantLimitation("pages", grantFields.pagesUnavailable)] : [], {
|
|
49
51
|
code: "section_unavailable",
|
|
50
52
|
message: "This site has no live release, so there is no published page list to read. That is not a site whose published list is empty.",
|
|
51
53
|
at: "pages"
|
|
52
54
|
}];
|
|
53
55
|
}
|
|
56
|
+
if (result.days === void 0) return [grantLimitation("pages", grantFields.pages)];
|
|
54
57
|
if (result.traffic === "partial") {
|
|
55
58
|
return [{ code: "page_bounded", message: "The edge returned as many address counts as one answer holds, so some reads are missing from the view and agent-read figures.", at: "pages" }];
|
|
56
59
|
}
|
|
@@ -67,6 +70,7 @@ function listText(result) {
|
|
|
67
70
|
if (pagesUnavailable(result)) {
|
|
68
71
|
return `${result.site_id}: no live release, so there is no published page list. Publish a release before reading pages.`;
|
|
69
72
|
}
|
|
73
|
+
if (result.days === void 0) return [`${result.site_id}: release ${result.release_id}, ${result.pages.length} published pages`, ...result.pages.map((page) => `${page.url} ${page.path}`)].join("\n");
|
|
70
74
|
const head = `${result.site_id}: release ${result.release_id}, ${result.pages.length} published pages, traffic ${result.traffic} over ${result.days} days`;
|
|
71
75
|
return [head, ...result.pages.map((page) => `${page.url} views ${page.views} agent reads ${page.agent_reads} ${page.path}`)].join("\n");
|
|
72
76
|
}
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import {
|
|
2
|
+
TOKEN_VARIABLE,
|
|
3
|
+
allRecords,
|
|
4
|
+
asCliError,
|
|
5
|
+
assertSameOrigin,
|
|
6
|
+
emptyRecord,
|
|
7
|
+
environmentToken,
|
|
8
|
+
flowContext,
|
|
9
|
+
grantFromTokens,
|
|
10
|
+
grantStatus,
|
|
11
|
+
hasAnyStore,
|
|
12
|
+
loadRecord,
|
|
13
|
+
lockOptions,
|
|
14
|
+
loginEnvironment,
|
|
15
|
+
normalizeScope,
|
|
16
|
+
pollDevice,
|
|
17
|
+
readStoredRecord,
|
|
18
|
+
revokeToken,
|
|
19
|
+
saveRecord,
|
|
20
|
+
selectStore,
|
|
21
|
+
startDevice,
|
|
22
|
+
storesFor,
|
|
23
|
+
validateNewSite,
|
|
24
|
+
windowsUnsupported,
|
|
25
|
+
withCredentialLock,
|
|
26
|
+
withPollLock
|
|
27
|
+
} from "./chunk-4B6PUKF5.js";
|
|
28
|
+
import {
|
|
29
|
+
applyCommandHelp
|
|
30
|
+
} from "./chunk-M2BZEDAS.js";
|
|
31
|
+
import {
|
|
32
|
+
CliError,
|
|
33
|
+
commandMetadata,
|
|
34
|
+
createResultWriter,
|
|
35
|
+
failureResult,
|
|
36
|
+
invalidInput2 as invalidInput,
|
|
37
|
+
parseOrigin,
|
|
38
|
+
resolveGlobalOptions,
|
|
39
|
+
successResult
|
|
40
|
+
} from "./chunk-EH6E45H4.js";
|
|
41
|
+
|
|
42
|
+
// src/commands/login.ts
|
|
43
|
+
import { execFile } from "child_process";
|
|
44
|
+
import { createHash } from "crypto";
|
|
45
|
+
var LOGIN_ERRORS = ["invalid_input", "forbidden", "conflict", "rate_limited", "service_unavailable", "transport_failure", "unknown_outcome", "wait_timeout", "interrupted"];
|
|
46
|
+
var LOGIN_METADATA = Object.freeze([
|
|
47
|
+
commandMetadata("login", {
|
|
48
|
+
description: "Start the device approval flow: print a link and a code, wait while a person approves this agent for one site in the browser, then save the login. The person chooses the site and the permissions on the approval page; --site or --new-site only proposes one. The login is kept in the macOS Keychain when it answers, otherwise in a file only this user can read (on Linux, always the file; Windows is not supported yet), and every later command uses it when SATURNDOCS_MANAGEMENT_TOKEN is not set.",
|
|
49
|
+
target: { arguments: [] },
|
|
50
|
+
effect: "Creates nothing until the person approves. On approval the server records a grant for the one site, and the CLI saves its tokens on this computer.",
|
|
51
|
+
output: { fields: ["status", "site_id", "scope", "store", "access_expires_at", "primary_host", "repo_connected", "replaced_grant_revoked", "verification_uri_complete", "user_code", "expires_at"], ids: [], limitations: [] },
|
|
52
|
+
errors: [...LOGIN_ERRORS],
|
|
53
|
+
examples: [
|
|
54
|
+
{ command: "saturndocs login", description: "Ask a person to approve this agent; they pick the site." },
|
|
55
|
+
{ command: "saturndocs login --site acme", description: "Propose the existing site acme on the approval page." },
|
|
56
|
+
{ command: "saturndocs login --new-site acme-docs --json", description: "Propose a new site; the person creates it while approving." },
|
|
57
|
+
{ command: "saturndocs login --no-wait --json", description: "Print the link and exit at once, for an agent that must show the link before it waits." },
|
|
58
|
+
{ command: "saturndocs login --resume --json", description: "Wait for the approval that --no-wait started." }
|
|
59
|
+
]
|
|
60
|
+
})
|
|
61
|
+
]);
|
|
62
|
+
var LOGOUT_METADATA = Object.freeze([
|
|
63
|
+
commandMetadata("logout", {
|
|
64
|
+
description: "Revoke the saved login on the server, then delete it from this computer. Without --site it acts on the default saved site. The local copy is deleted even when revocation cannot be confirmed; the result then says so, and a person can revoke the grant from the dashboard. SATURNDOCS_MANAGEMENT_TOKEN is never touched.",
|
|
65
|
+
target: { arguments: [] },
|
|
66
|
+
effect: "Revokes one grant, or every saved grant with --all, and deletes the saved tokens.",
|
|
67
|
+
output: { fields: ["revoked", "failed", "remaining", "unchecked"], ids: [], limitations: [] },
|
|
68
|
+
errors: ["invalid_input", "service_unavailable", "transport_failure", "unknown_outcome", "interrupted"],
|
|
69
|
+
examples: [
|
|
70
|
+
{ command: "saturndocs logout", description: "Revoke and forget the default saved login." },
|
|
71
|
+
{ command: "saturndocs logout --site acme --json", description: "Revoke and forget the login for acme." },
|
|
72
|
+
{ command: "saturndocs logout --all", description: "Revoke and forget every saved login for this API origin." }
|
|
73
|
+
]
|
|
74
|
+
})
|
|
75
|
+
]);
|
|
76
|
+
var SITES_CREATE_METADATA = commandMetadata("sites create", {
|
|
77
|
+
description: "Propose a new site and run the device approval flow for it. The person signs in, can edit the address, creates the site, and can install the GitHub App in the same visit. The login for the new site is then saved, exactly as saturndocs login --new-site would save it.",
|
|
78
|
+
target: { arguments: [{ name: "address", required: true, description: "The proposed site address: lowercase letters, digits, and hyphens, up to 63 characters." }] },
|
|
79
|
+
effect: "Creates nothing until the person approves. Approval creates the site and a grant for it.",
|
|
80
|
+
output: { fields: ["status", "site_id", "scope", "store", "access_expires_at", "primary_host", "repo_connected", "verification_uri_complete", "user_code", "expires_at"], ids: [], limitations: [] },
|
|
81
|
+
errors: [...LOGIN_ERRORS],
|
|
82
|
+
examples: [
|
|
83
|
+
{ command: "saturndocs sites create acme-docs", description: "Ask a person to create acme-docs and approve this agent for it." },
|
|
84
|
+
{ command: "saturndocs sites create acme-docs --no-wait --json", description: "Print the link at once; finish with saturndocs login --resume." }
|
|
85
|
+
]
|
|
86
|
+
});
|
|
87
|
+
function originOf(globals) {
|
|
88
|
+
return parseOrigin(globals.api ?? void 0);
|
|
89
|
+
}
|
|
90
|
+
function pendingResult(pending, store) {
|
|
91
|
+
return {
|
|
92
|
+
status: "pending",
|
|
93
|
+
verification_uri_complete: pending.verification_uri_complete,
|
|
94
|
+
verification_uri: pending.verification_uri,
|
|
95
|
+
user_code: pending.user_code,
|
|
96
|
+
expires_at: pending.expires_at,
|
|
97
|
+
store
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function approvalNotice(pending) {
|
|
101
|
+
return [
|
|
102
|
+
"Ask the person who manages the site to open this link and approve:",
|
|
103
|
+
` ${pending.verification_uri_complete}`,
|
|
104
|
+
`Code: ${pending.user_code} (it must match the code on the page)`,
|
|
105
|
+
`The link expires at ${pending.expires_at}.`,
|
|
106
|
+
""
|
|
107
|
+
].join("\n");
|
|
108
|
+
}
|
|
109
|
+
function openBrowser(url) {
|
|
110
|
+
const [file, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
111
|
+
execFile(file, args, { windowsHide: true }, () => void 0).unref();
|
|
112
|
+
}
|
|
113
|
+
function storesOrRefuse(environment) {
|
|
114
|
+
const choice = storesFor(environment);
|
|
115
|
+
if (!hasAnyStore(choice)) throw windowsUnsupported();
|
|
116
|
+
return choice;
|
|
117
|
+
}
|
|
118
|
+
async function beginLogin(origin, request, environment, deadlineAt) {
|
|
119
|
+
const now = environment.now ?? Date.now;
|
|
120
|
+
const choice = storesOrRefuse(environment);
|
|
121
|
+
const started = await startDevice(flowContext(origin, environment), request, deadlineAt);
|
|
122
|
+
const pending = {
|
|
123
|
+
device_code: started.device_code,
|
|
124
|
+
user_code: started.user_code,
|
|
125
|
+
verification_uri: started.verification_uri,
|
|
126
|
+
verification_uri_complete: started.verification_uri_complete,
|
|
127
|
+
interval: started.interval,
|
|
128
|
+
expires_at: new Date(now() + started.expires_in * 1e3).toISOString(),
|
|
129
|
+
site: request.site,
|
|
130
|
+
new_site: request.newSite,
|
|
131
|
+
scope: request.scope
|
|
132
|
+
};
|
|
133
|
+
const store = await withCredentialLock(choice, async () => {
|
|
134
|
+
const selection = await selectStore(choice, origin.origin);
|
|
135
|
+
if (selection === null) throw windowsUnsupported();
|
|
136
|
+
return saveRecord(selection.store, { ...selection.record ?? emptyRecord(origin.origin), pending });
|
|
137
|
+
}, lockOptions(environment));
|
|
138
|
+
return { pending, store: store.label };
|
|
139
|
+
}
|
|
140
|
+
async function updatePending(origin, environment, deviceCode, change) {
|
|
141
|
+
const choice = storesOrRefuse(environment);
|
|
142
|
+
await withCredentialLock(choice, async () => {
|
|
143
|
+
const loaded = await loadRecord(choice, origin.origin);
|
|
144
|
+
const pending = loaded?.record.pending ?? null;
|
|
145
|
+
if (loaded === null || pending === null || pending.device_code !== deviceCode) return;
|
|
146
|
+
await saveRecord(loaded.store, { ...loaded.record, pending: change(pending) });
|
|
147
|
+
}, lockOptions(environment));
|
|
148
|
+
}
|
|
149
|
+
function pollKey(deviceCode) {
|
|
150
|
+
return createHash("sha256").update(deviceCode).digest("hex").slice(0, 16);
|
|
151
|
+
}
|
|
152
|
+
async function finishLogin(origin, pending, environment, deadlineAt) {
|
|
153
|
+
const now = environment.now ?? Date.now;
|
|
154
|
+
const ctx = flowContext(origin, environment);
|
|
155
|
+
const choice = storesOrRefuse(environment);
|
|
156
|
+
const stillWaiting = async () => {
|
|
157
|
+
const holder2 = await loadRecord(choice, origin.origin);
|
|
158
|
+
if (holder2 === null || holder2.record.pending?.device_code !== pending.device_code) throw new CliError("conflict", "This approval is no longer waiting. Run saturndocs login again for a new link.");
|
|
159
|
+
return holder2;
|
|
160
|
+
};
|
|
161
|
+
const holder = await stillWaiting();
|
|
162
|
+
const result = await withPollLock(choice, holder.store, pollKey(pending.device_code), async () => {
|
|
163
|
+
await stillWaiting();
|
|
164
|
+
const outcome = await pollDevice(ctx, pending, deadlineAt, (seconds) => updatePending(origin, environment, pending.device_code, (current) => ({ ...current, interval: seconds })).catch(() => void 0));
|
|
165
|
+
if (outcome.kind === "timeout") {
|
|
166
|
+
throw new CliError("wait_timeout", "No one approved the request before --timeout. The request is still open until it expires.", {
|
|
167
|
+
recovery: { command: "saturndocs login --resume", replay: null, message: "Run saturndocs login --resume to keep waiting for the same approval." }
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
if (outcome.kind !== "approved") {
|
|
171
|
+
await updatePending(origin, environment, pending.device_code, () => null);
|
|
172
|
+
if (outcome.kind === "denied") throw new CliError("forbidden", "The person denied the request in the browser. Nothing was saved.");
|
|
173
|
+
if (outcome.kind === "expired") throw new CliError("wait_timeout", "The approval link expired before anyone approved it. Run saturndocs login again for a new link.", { mutation: "known" });
|
|
174
|
+
throw new CliError("conflict", "This approval was already used or is no longer valid. Run saturndocs login again for a new link.");
|
|
175
|
+
}
|
|
176
|
+
const grant = grantFromTokens(outcome.tokens, now());
|
|
177
|
+
const revoked = (token) => revokeToken(ctx, token).then(() => true, () => false);
|
|
178
|
+
let displaced = null;
|
|
179
|
+
let writeAttempted = false;
|
|
180
|
+
let saving;
|
|
181
|
+
try {
|
|
182
|
+
saving = await withCredentialLock(choice, async () => {
|
|
183
|
+
const loaded = await loadRecord(choice, origin.origin);
|
|
184
|
+
if (loaded === null || loaded.record.pending?.device_code !== pending.device_code) return { kind: "canceled" };
|
|
185
|
+
const previous = loaded.record.grants[grant.site_id]?.refresh_token ?? null;
|
|
186
|
+
displaced = previous;
|
|
187
|
+
const record = { ...loaded.record, default_site: grant.site_id, grants: { ...loaded.record.grants, [grant.site_id]: grant }, pending: null };
|
|
188
|
+
writeAttempted = true;
|
|
189
|
+
try {
|
|
190
|
+
return { kind: "saved", store: await saveRecord(loaded.store, record) };
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
193
|
+
const code = error instanceof CliError ? error.code : "service_unavailable";
|
|
194
|
+
try {
|
|
195
|
+
const stored = await readStoredRecord(loaded.store, origin.origin);
|
|
196
|
+
const token = stored?.grants[grant.site_id]?.refresh_token ?? null;
|
|
197
|
+
if (token === grant.refresh_token) return { kind: "saved", store: loaded.store };
|
|
198
|
+
return { kind: "not_stored", reason, code, previousKept: previous !== null && token === previous };
|
|
199
|
+
} catch {
|
|
200
|
+
return { kind: "unknown", reason };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}, lockOptions(environment));
|
|
204
|
+
} catch (error) {
|
|
205
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
206
|
+
if (writeAttempted) saving = { kind: "unknown", reason };
|
|
207
|
+
else {
|
|
208
|
+
const cleaned = await revoked(grant.refresh_token);
|
|
209
|
+
throw new CliError(error instanceof CliError ? error.code : "service_unavailable", `The approval succeeded, but the saved logins could not be read to store it: ${reason} ${cleaned ? "The approved grant was revoked; run saturndocs login again." : `The approved grant for ${grant.site_id} could not be revoked; a person can revoke it from the dashboard.`}`, { mutation: cleaned ? "known" : "unknown", cause: error });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (saving.kind === "unknown") {
|
|
213
|
+
throw new CliError("service_unavailable", `The approval succeeded, but saving the login failed (${saving.reason}) and the store could not be read back, so neither the new grant nor the earlier one was revoked. Run saturndocs auth status to see which login is kept, and revoke the other from the dashboard.`, { mutation: "unknown" });
|
|
214
|
+
}
|
|
215
|
+
if (saving.kind === "not_stored") {
|
|
216
|
+
const cleaned = await revoked(grant.refresh_token);
|
|
217
|
+
throw new CliError(saving.code, `The approval succeeded, but the login could not be saved: ${saving.reason} ${cleaned ? "The approved grant was revoked" : `The approved grant for ${grant.site_id} could not be revoked; a person can revoke it from the dashboard`}${saving.previousKept ? ", and the earlier login for this site is unchanged." : "."}`, { mutation: "unknown" });
|
|
218
|
+
}
|
|
219
|
+
const saved = saving.kind === "saved" ? saving.store : null;
|
|
220
|
+
if (saved === null) {
|
|
221
|
+
const cleaned = await revoked(grant.refresh_token);
|
|
222
|
+
throw new CliError("conflict", cleaned ? "The login was canceled while it waited for approval, so the approved grant was revoked and nothing was saved." : `The login was canceled while it waited for approval and nothing was saved, but the approved grant for ${grant.site_id} could not be revoked. A person can revoke it from the dashboard.`, { mutation: cleaned ? "known" : "unknown" });
|
|
223
|
+
}
|
|
224
|
+
const replacedToken = displaced;
|
|
225
|
+
const replaced = replacedToken === null ? null : await revoked(replacedToken);
|
|
226
|
+
return { grant, store: saved, replaced };
|
|
227
|
+
});
|
|
228
|
+
let status = null;
|
|
229
|
+
try {
|
|
230
|
+
status = await grantStatus(ctx, result.grant.access_token, deadlineAt);
|
|
231
|
+
} catch {
|
|
232
|
+
status = null;
|
|
233
|
+
}
|
|
234
|
+
return {
|
|
235
|
+
status: "approved",
|
|
236
|
+
site_id: result.grant.site_id,
|
|
237
|
+
scope: result.grant.scope,
|
|
238
|
+
store: result.store.label,
|
|
239
|
+
access_expires_at: result.grant.access_expires_at,
|
|
240
|
+
primary_host: status?.primary_host ?? null,
|
|
241
|
+
repo_connected: status?.repo_connected ?? null,
|
|
242
|
+
replaced_grant_revoked: result.replaced
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function approvedText(result) {
|
|
246
|
+
const lines = [
|
|
247
|
+
`Logged in to ${result.site_id} with ${result.scope.join(", ")}.`,
|
|
248
|
+
`Saved in the ${result.store}.`
|
|
249
|
+
];
|
|
250
|
+
if (result.primary_host !== null) lines.push(`Site address: https://${result.primary_host}`);
|
|
251
|
+
if (result.repo_connected === false) lines.push("The site has no connected documentation repository yet. The person can connect one from the dashboard.");
|
|
252
|
+
if (result.replaced_grant_revoked === false) lines.push(`The earlier login for ${result.site_id} could not be revoked on the server. A person can revoke it from the dashboard.`);
|
|
253
|
+
return lines.join("\n");
|
|
254
|
+
}
|
|
255
|
+
async function runLogin(globals, request, environment, command) {
|
|
256
|
+
const writer = createResultWriter({ json: globals.json });
|
|
257
|
+
const context = { command, siteId: request.site };
|
|
258
|
+
const login = loginEnvironment(environment);
|
|
259
|
+
const startedAt = (login.now ?? Date.now)();
|
|
260
|
+
try {
|
|
261
|
+
const origin = originOf(globals);
|
|
262
|
+
let pending;
|
|
263
|
+
let store;
|
|
264
|
+
if (request.resume) {
|
|
265
|
+
const loaded = await loadRecord(storesOrRefuse(login), origin.origin);
|
|
266
|
+
const waiting = loaded?.record.pending ?? null;
|
|
267
|
+
if (loaded === null || waiting === null) throw invalidInput("No login is waiting for approval. Run saturndocs login to start one.");
|
|
268
|
+
assertSameOrigin(origin, waiting.verification_uri, "verification link");
|
|
269
|
+
assertSameOrigin(origin, waiting.verification_uri_complete, "verification link");
|
|
270
|
+
pending = waiting;
|
|
271
|
+
store = loaded.store.label;
|
|
272
|
+
} else {
|
|
273
|
+
({ pending, store } = await beginLogin(origin, request, login, globals.timeout === null ? null : startedAt + globals.timeout * 1e3));
|
|
274
|
+
}
|
|
275
|
+
process.stderr.write(approvalNotice(pending));
|
|
276
|
+
if (request.open && globals.input) openBrowser(pending.verification_uri_complete);
|
|
277
|
+
if (!request.wait) {
|
|
278
|
+
process.exitCode = writer.write(successResult(context, pendingResult(pending, store)), {
|
|
279
|
+
text: "Waiting is off. After the person approves, run saturndocs login --resume."
|
|
280
|
+
});
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const deadlineAt = globals.timeout === null ? null : startedAt + globals.timeout * 1e3;
|
|
284
|
+
const result = await finishLogin(origin, pending, login, deadlineAt);
|
|
285
|
+
context.siteId = result.site_id;
|
|
286
|
+
process.exitCode = writer.write(successResult(context, result), { text: approvedText(result) });
|
|
287
|
+
} catch (error) {
|
|
288
|
+
process.exitCode = writer.write(failureResult(asCliError(error), context));
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function loginRequest(globals, options) {
|
|
292
|
+
const resume = options.resume === true;
|
|
293
|
+
const newSite = options.newSite === void 0 ? null : validateNewSite(options.newSite);
|
|
294
|
+
if (globals.site !== null && newSite !== null) throw invalidInput("Pass --site for an existing site or --new-site for a new one, not both.");
|
|
295
|
+
if (resume && (globals.site !== null || newSite !== null || options.scope !== void 0)) {
|
|
296
|
+
throw invalidInput("--resume continues the waiting login as it was started; it takes no --site, --new-site, or --scope.");
|
|
297
|
+
}
|
|
298
|
+
if (resume && options.wait === false) throw invalidInput("--resume waits; it cannot be combined with --no-wait.");
|
|
299
|
+
return { site: globals.site, newSite, scope: normalizeScope(options.scope), wait: options.wait !== false, resume, open: options.open === true };
|
|
300
|
+
}
|
|
301
|
+
function registerLogin(program, _cliDir, environment = {}) {
|
|
302
|
+
const login = program.command("login").option("--new-site <address>", "Propose a new site address; the person creates the site while approving.").option("--scope <permissions>", "Comma-separated permissions to request: read, draft, build, publish.").option("--no-wait", "Print the approval link and exit; finish later with --resume.").option("--resume", "Wait for the approval started by an earlier --no-wait.").option("--open", "Open the approval link in the default browser.").action(async (options, self) => {
|
|
303
|
+
const globals = resolveGlobalOptions(self);
|
|
304
|
+
let request;
|
|
305
|
+
try {
|
|
306
|
+
request = loginRequest(globals, options);
|
|
307
|
+
} catch (error) {
|
|
308
|
+
process.exitCode = createResultWriter({ json: globals.json }).write(failureResult(error, { command: "login", siteId: globals.site }));
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
await runLogin(globals, request, environment, "login");
|
|
312
|
+
});
|
|
313
|
+
applyCommandHelp(login, LOGIN_METADATA[0]);
|
|
314
|
+
}
|
|
315
|
+
function registerSitesCreate(sites, environment = {}) {
|
|
316
|
+
const create = sites.command("create").argument("<address>", "The proposed site address.").option("--scope <permissions>", "Comma-separated permissions to request: read, draft, build, publish.").option("--no-wait", "Print the approval link and exit; finish later with saturndocs login --resume.").option("--open", "Open the approval link in the default browser.").action(async (address, options, self) => {
|
|
317
|
+
const globals = resolveGlobalOptions(self);
|
|
318
|
+
let request;
|
|
319
|
+
try {
|
|
320
|
+
if (globals.site !== null) throw invalidInput("sites create proposes a new site; it takes no --site.");
|
|
321
|
+
request = loginRequest(globals, { ...options, newSite: address, resume: false });
|
|
322
|
+
} catch (error) {
|
|
323
|
+
process.exitCode = createResultWriter({ json: globals.json }).write(failureResult(error, { command: "sites create", siteId: null }));
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
await runLogin(globals, request, environment, "sites create");
|
|
327
|
+
});
|
|
328
|
+
applyCommandHelp(create, SITES_CREATE_METADATA);
|
|
329
|
+
}
|
|
330
|
+
function registerLogout(program, _cliDir, environment = {}) {
|
|
331
|
+
const logout = program.command("logout").option("--all", "Revoke and forget every saved login for this API origin.").action(async (options, self) => {
|
|
332
|
+
const globals = resolveGlobalOptions(self);
|
|
333
|
+
const writer = createResultWriter({ json: globals.json });
|
|
334
|
+
const context = { command: "logout", siteId: globals.site };
|
|
335
|
+
const login = loginEnvironment(environment);
|
|
336
|
+
try {
|
|
337
|
+
if (options.all === true && globals.site !== null) throw invalidInput("Pass --site for one login or --all for every login, not both.");
|
|
338
|
+
const origin = originOf(globals);
|
|
339
|
+
const choice = storesOrRefuse(login);
|
|
340
|
+
const outcome = await withCredentialLock(choice, async () => {
|
|
341
|
+
const { loaded, unreadable } = await allRecords(choice, origin.origin);
|
|
342
|
+
const unchecked = unreadable.map((entry) => ({ store: entry.store.label, reason: entry.reason }));
|
|
343
|
+
const everyStoreAnswered = unreadable.length === 0;
|
|
344
|
+
const known = [...new Set(loaded.flatMap((entry) => Object.keys(entry.record.grants)))];
|
|
345
|
+
const pendingAnywhere = loaded.some((entry) => entry.record.pending !== null);
|
|
346
|
+
if (everyStoreAnswered && known.length === 0 && !pendingAnywhere) throw invalidInput("No login is saved for this API origin.");
|
|
347
|
+
let site = null;
|
|
348
|
+
if (options.all !== true) {
|
|
349
|
+
const primary = loaded[0]?.record ?? null;
|
|
350
|
+
site = globals.site ?? (primary !== null && primary.default_site !== null && primary.default_site in primary.grants ? primary.default_site : null) ?? (known.length === 1 ? known[0] : null);
|
|
351
|
+
if (site === null && everyStoreAnswered) {
|
|
352
|
+
throw invalidInput(known.length === 0 ? "No site has a saved login. Run saturndocs logout --all to cancel a login that is waiting for approval." : "Several sites have saved logins. Pass --site, or --all.");
|
|
353
|
+
}
|
|
354
|
+
if (site !== null && !known.includes(site) && everyStoreAnswered) throw invalidInput(`No login is saved for ${site}.`);
|
|
355
|
+
}
|
|
356
|
+
const revoked = [];
|
|
357
|
+
const failed = [];
|
|
358
|
+
const remaining = [];
|
|
359
|
+
for (const entry of loaded) {
|
|
360
|
+
const record = { ...entry.record, grants: { ...entry.record.grants } };
|
|
361
|
+
const targets = options.all === true ? Object.keys(record.grants) : Object.keys(record.grants).filter((name) => name === site);
|
|
362
|
+
const clearsPending = options.all === true && record.pending !== null;
|
|
363
|
+
if (targets.length === 0 && !clearsPending) {
|
|
364
|
+
remaining.push(...Object.keys(record.grants));
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
for (const name of targets) {
|
|
368
|
+
const grant = record.grants[name];
|
|
369
|
+
try {
|
|
370
|
+
await revokeToken(flowContext(origin, login), grant.refresh_token);
|
|
371
|
+
revoked.push({ site_id: name, store: entry.store.label });
|
|
372
|
+
} catch (error) {
|
|
373
|
+
failed.push({ site_id: name, store: entry.store.label, ...error instanceof CliError ? { code: error.code } : {}, reason: error instanceof Error ? error.message : String(error) });
|
|
374
|
+
}
|
|
375
|
+
delete record.grants[name];
|
|
376
|
+
}
|
|
377
|
+
if (clearsPending) record.pending = null;
|
|
378
|
+
if (record.default_site !== null && !(record.default_site in record.grants)) record.default_site = Object.keys(record.grants)[0] ?? null;
|
|
379
|
+
try {
|
|
380
|
+
await saveRecord(entry.store, record);
|
|
381
|
+
remaining.push(...Object.keys(record.grants));
|
|
382
|
+
} catch (error) {
|
|
383
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
384
|
+
try {
|
|
385
|
+
const stored = await readStoredRecord(entry.store, origin.origin);
|
|
386
|
+
const left = Object.keys(stored?.grants ?? {});
|
|
387
|
+
remaining.push(...left);
|
|
388
|
+
const stillThere = targets.filter((name) => left.includes(name));
|
|
389
|
+
const pendingKept = clearsPending && (stored?.pending ?? null) !== null;
|
|
390
|
+
const kept = [...stillThere.length > 0 ? [`the login for ${stillThere.join(", ")}`] : [], ...pendingKept ? ["the login waiting for approval"] : []];
|
|
391
|
+
failed.push({ site_id: null, store: entry.store.label, reason: kept.length > 0 ? `${kept.join(" and ")} could not be removed there: ${reason}` : `The login was removed there, but the change could not be confirmed on disk: ${reason}` });
|
|
392
|
+
} catch {
|
|
393
|
+
unchecked.push({ store: entry.store.label, reason: `the delete may or may not have landed (${reason}), and the store could not be read back` });
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return { revoked, failed, remaining, unchecked };
|
|
398
|
+
}, lockOptions(login));
|
|
399
|
+
const environmentNote = environmentToken(login.env) === void 0 ? "" : `
|
|
400
|
+
${TOKEN_VARIABLE} is still set; logout does not change it.`;
|
|
401
|
+
const problems = [
|
|
402
|
+
...outcome.failed.map((entry) => entry.site_id === null ? `${entry.store}: ${entry.reason}` : `${entry.site_id} (${entry.store}): the server did not confirm revocation. Check the grant in the dashboard`),
|
|
403
|
+
...outcome.unchecked.map((entry) => `${entry.store} could not be read, so a login kept there may still work; run saturndocs logout again when it can be read`)
|
|
404
|
+
];
|
|
405
|
+
if (problems.length > 0) {
|
|
406
|
+
const code = outcome.failed.some((entry) => entry.code === "unknown_outcome") ? "unknown_outcome" : "service_unavailable";
|
|
407
|
+
throw new CliError(code, `Logout did not finish everywhere. ${problems.join(". ")}.`, { data: outcome, mutation: "unknown" });
|
|
408
|
+
}
|
|
409
|
+
process.exitCode = writer.write(successResult(context, outcome), {
|
|
410
|
+
text: `${outcome.revoked.length === 0 ? "Nothing to revoke." : `Revoked and deleted: ${[...new Set(outcome.revoked.map((entry) => entry.site_id))].join(", ")}.`}${environmentNote}`
|
|
411
|
+
});
|
|
412
|
+
} catch (error) {
|
|
413
|
+
process.exitCode = writer.write(failureResult(asCliError(error), context));
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
applyCommandHelp(logout, LOGOUT_METADATA[0]);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export {
|
|
420
|
+
LOGIN_METADATA,
|
|
421
|
+
LOGOUT_METADATA,
|
|
422
|
+
SITES_CREATE_METADATA,
|
|
423
|
+
runLogin,
|
|
424
|
+
registerLogin,
|
|
425
|
+
registerSitesCreate,
|
|
426
|
+
registerLogout
|
|
427
|
+
};
|