scrollport 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.
Files changed (54) hide show
  1. package/README.md +147 -0
  2. package/dist/args.d.ts +21 -0
  3. package/dist/args.d.ts.map +1 -0
  4. package/dist/args.js +122 -0
  5. package/dist/args.js.map +1 -0
  6. package/dist/browser.d.ts +38 -0
  7. package/dist/browser.d.ts.map +1 -0
  8. package/dist/browser.js +88 -0
  9. package/dist/browser.js.map +1 -0
  10. package/dist/cli.d.ts +3 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +122 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/commands/logout.d.ts +15 -0
  15. package/dist/commands/logout.d.ts.map +1 -0
  16. package/dist/commands/logout.js +25 -0
  17. package/dist/commands/logout.js.map +1 -0
  18. package/dist/commands/setup.d.ts +18 -0
  19. package/dist/commands/setup.d.ts.map +1 -0
  20. package/dist/commands/setup.js +171 -0
  21. package/dist/commands/setup.js.map +1 -0
  22. package/dist/commands/status.d.ts +21 -0
  23. package/dist/commands/status.d.ts.map +1 -0
  24. package/dist/commands/status.js +85 -0
  25. package/dist/commands/status.js.map +1 -0
  26. package/dist/credentials.d.ts +54 -0
  27. package/dist/credentials.d.ts.map +1 -0
  28. package/dist/credentials.js +197 -0
  29. package/dist/credentials.js.map +1 -0
  30. package/dist/device-client.d.ts +24 -0
  31. package/dist/device-client.d.ts.map +1 -0
  32. package/dist/device-client.js +82 -0
  33. package/dist/device-client.js.map +1 -0
  34. package/dist/device-flow.d.ts +70 -0
  35. package/dist/device-flow.d.ts.map +1 -0
  36. package/dist/device-flow.js +128 -0
  37. package/dist/device-flow.js.map +1 -0
  38. package/dist/errors.d.ts +58 -0
  39. package/dist/errors.d.ts.map +1 -0
  40. package/dist/errors.js +61 -0
  41. package/dist/errors.js.map +1 -0
  42. package/dist/http.d.ts +76 -0
  43. package/dist/http.d.ts.map +1 -0
  44. package/dist/http.js +163 -0
  45. package/dist/http.js.map +1 -0
  46. package/dist/output.d.ts +31 -0
  47. package/dist/output.d.ts.map +1 -0
  48. package/dist/output.js +27 -0
  49. package/dist/output.js.map +1 -0
  50. package/dist/verify.d.ts +4 -0
  51. package/dist/verify.d.ts.map +1 -0
  52. package/dist/verify.js +27 -0
  53. package/dist/verify.js.map +1 -0
  54. package/package.json +31 -0
@@ -0,0 +1,171 @@
1
+ /**
2
+ * `scrollport setup` — the load-bearing command.
3
+ *
4
+ * The API's own 401 hint names it verbatim ("run `scrollport setup` to provision
5
+ * one", apps/api/src/http/router.ts), so this is the one path a user is *told*
6
+ * to walk, usually by a machine, usually while confused.
7
+ *
8
+ * The shape of it (issue #9): paste one line → the CLI prints a URL with the
9
+ * code already in it → the human clicks the link and clicks approve → the CLI's
10
+ * poll collects the key and writes it to a `0600` file. Two clicks; the human
11
+ * types nothing; the key never appears on a screen.
12
+ *
13
+ * The code IS displayed, and that is the anti-phishing property, not an
14
+ * oversight: an agent can print any URL it likes, so the only thing tying the
15
+ * consent screen in front of the human to the terminal in front of them is a
16
+ * code they can compare by eye. (Which is why the server's alphabet has no
17
+ * confusable characters — see device-flow.ts on the API side.)
18
+ */
19
+ import { awaitAuthorization } from "../device-flow.js";
20
+ import { pollDeviceToken, startDeviceAuthorization } from "../device-client.js";
21
+ import { assertSafeUrl, openInBrowser, shouldOpenBrowser } from "../browser.js";
22
+ import { credentialsPath, maskKey, resolveApiKey, saveCredentials, } from "../credentials.js";
23
+ import { CliError, EXIT_ERROR } from "../errors.js";
24
+ import { verifyKey } from "../verify.js";
25
+ /** How often to reassure a waiting human. Every 5s poll would be noise. */
26
+ const PROGRESS_EVERY_MS = 30_000;
27
+ export async function runSetup(deps, opts) {
28
+ const { client, reporter, env } = deps;
29
+ const path = credentialsPath(env);
30
+ const existing = resolveApiKey(env);
31
+ if (existing?.source === "env") {
32
+ // Warn rather than refuse: writing the file is still the right outcome, but
33
+ // the environment wins on every later read, so saying nothing would leave
34
+ // someone debugging why their new key "did not take".
35
+ reporter.progress("note: SCROLLPORT_API_KEY is set in this environment and takes precedence over the stored key.");
36
+ reporter.progress(" Unset it if you want the key provisioned here to be the one used.");
37
+ }
38
+ if (existing?.source === "file" && !opts.force) {
39
+ const state = await verifyKey(client, existing.apiKey);
40
+ if (state === "ok") {
41
+ return {
42
+ json: {
43
+ already_configured: true,
44
+ account_id: existing.accountId,
45
+ api_key_masked: maskKey(existing.apiKey),
46
+ api_url: existing.apiUrl ?? client.baseUrl,
47
+ credentials_path: path,
48
+ verified: true,
49
+ },
50
+ human: [
51
+ `Already set up. ${path} holds a working key (${maskKey(existing.apiKey)}).`,
52
+ "Re-run with --force to provision a new one.",
53
+ ],
54
+ };
55
+ }
56
+ if (state === "rejected") {
57
+ reporter.progress("note: the stored key was rejected by the API (revoked, or minted against another environment).");
58
+ reporter.progress(" Provisioning a new one.");
59
+ }
60
+ }
61
+ // ── 1. Ask for a code ────────────────────────────────────────────────────
62
+ const auth = await startDeviceAuthorization(client);
63
+ const verificationUrl = assertSafeUrl(auth.verification_uri_complete);
64
+ const minutes = Math.max(1, Math.round(auth.expires_in / 60));
65
+ reporter.progress("");
66
+ reporter.progress(" 1. Open this link:");
67
+ reporter.progress("");
68
+ reporter.progress(` ${verificationUrl.href}`);
69
+ reporter.progress("");
70
+ reporter.progress(` 2. Check the page shows this code, then approve: ${auth.user_code}`);
71
+ reporter.progress("");
72
+ reporter.progress(" The code is already in the link — you never type it. It is shown so you");
73
+ reporter.progress(" can confirm the page in your browser is approving THIS terminal.");
74
+ reporter.progress("");
75
+ if (shouldOpenBrowser(env, opts.noBrowser)) {
76
+ const opened = openInBrowser(verificationUrl);
77
+ reporter.progress(opened
78
+ ? "Opening your browser… (use --no-browser to skip)"
79
+ : "Could not open a browser — open the link above yourself.");
80
+ }
81
+ reporter.progress(`Waiting for approval — the link is good for ${minutes} minutes. Ctrl-C to stop.`);
82
+ // ── 2. Wait for the human ────────────────────────────────────────────────
83
+ let lastProgressAt = deps.now();
84
+ const onWait = (event) => {
85
+ // Backoff and outages are always worth saying out loud: they change how long
86
+ // this will take, and silence during them reads as a hang.
87
+ if (event.reason === "slow_down") {
88
+ reporter.progress(`Server asked us to slow down; polling every ${event.waitSeconds}s.`);
89
+ lastProgressAt = deps.now();
90
+ return;
91
+ }
92
+ if (event.reason === "transient") {
93
+ reporter.progress(`Could not reach the API (attempt ${event.failures ?? 1}); retrying in ${event.waitSeconds}s.`);
94
+ lastProgressAt = deps.now();
95
+ return;
96
+ }
97
+ if (deps.now() - lastProgressAt >= PROGRESS_EVERY_MS) {
98
+ reporter.progress(`Still waiting… ${formatRemaining(event.secondsRemaining)} left.`);
99
+ lastProgressAt = deps.now();
100
+ }
101
+ };
102
+ const granted = await awaitAuthorization(auth, {
103
+ poll: (deviceCode) => pollDeviceToken(client, deviceCode),
104
+ sleep: deps.sleep,
105
+ now: deps.now,
106
+ onWait,
107
+ });
108
+ // ── 3. Store it before anything else can fail ────────────────────────────
109
+ // The key is minted exactly once (the server's grant is spent). If we lose it
110
+ // now it is gone for good, so it goes to disk before we do anything clever.
111
+ const storedAt = saveCredentials({
112
+ api_key: granted.apiKey,
113
+ account_id: granted.accountId,
114
+ api_url: client.baseUrl,
115
+ created_at: new Date().toISOString(),
116
+ }, env);
117
+ // ── 4. Prove it works ────────────────────────────────────────────────────
118
+ const state = await verifyKey(client, granted.apiKey);
119
+ // `SCROLLPORT_API_KEY` outranks the file (see resolveApiKey), so if it is set
120
+ // the key we just minted is shadowed the moment this command exits: setup
121
+ // reports success, and every later command silently keeps using the old key.
122
+ // Warn rather than refuse — the env var is the CI escape hatch and overriding
123
+ // it here would break that — but say it plainly, because the failure is
124
+ // otherwise invisible and looks like the new key not working.
125
+ const shadowedByEnv = Boolean(env["SCROLLPORT_API_KEY"]?.trim());
126
+ const envWarning = shadowedByEnv
127
+ ? `Note: SCROLLPORT_API_KEY is set in your environment and takes precedence over the stored key, so this new key will not be used until you unset it.`
128
+ : null;
129
+ const base = {
130
+ already_configured: false,
131
+ account_id: granted.accountId,
132
+ api_key_masked: maskKey(granted.apiKey),
133
+ api_url: client.baseUrl,
134
+ credentials_path: storedAt,
135
+ };
136
+ if (state === "rejected") {
137
+ throw new CliError("key_rejected", "A key was issued, but the API immediately refused it.", {
138
+ hint: `The key is saved at ${storedAt} — run \`scrollport status\` to retry the check before provisioning another. If it keeps failing, this is a bug worth reporting.`,
139
+ exitCode: EXIT_ERROR,
140
+ });
141
+ }
142
+ if (state === "unreachable") {
143
+ return {
144
+ json: { ...base, verified: false, shadowed_by_env: shadowedByEnv },
145
+ human: [
146
+ `Connected. Key stored in ${storedAt} (${base.api_key_masked}).`,
147
+ `Account: ${granted.accountId}`,
148
+ "Could not reach the API to confirm the key works — run `scrollport status` when the connection is back.",
149
+ ...(envWarning ? [envWarning] : []),
150
+ ],
151
+ };
152
+ }
153
+ return {
154
+ json: { ...base, verified: true, shadowed_by_env: shadowedByEnv },
155
+ human: [
156
+ `Connected. Key stored in ${storedAt} (${base.api_key_masked}).`,
157
+ `Account: ${granted.accountId}`,
158
+ `Verified against ${client.baseUrl} — the key works.`,
159
+ ...(envWarning ? [envWarning] : []),
160
+ ],
161
+ };
162
+ }
163
+ function formatRemaining(seconds) {
164
+ if (seconds >= 60) {
165
+ const mins = Math.floor(seconds / 60);
166
+ const rest = seconds % 60;
167
+ return rest ? `${mins}m ${rest}s` : `${mins}m`;
168
+ }
169
+ return `${Math.max(seconds, 0)}s`;
170
+ }
171
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../src/commands/setup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,kBAAkB,EAAkB,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,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,QAAQ,EAAE,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE;YAClE,KAAK,EAAE;gBACL,4BAA4B,QAAQ,KAAK,IAAI,CAAC,cAAc,IAAI;gBAChE,YAAY,OAAO,CAAC,SAAS,EAAE;gBAC/B,yGAAyG;gBACzG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aACpC;SACF,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI,EAAE,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,eAAe,EAAE,aAAa,EAAE;QACjE,KAAK,EAAE;YACL,4BAA4B,QAAQ,KAAK,IAAI,CAAC,cAAc,IAAI;YAChE,YAAY,OAAO,CAAC,SAAS,EAAE;YAC/B,oBAAoB,MAAM,CAAC,OAAO,mBAAmB;YACrD,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,OAAe;IACtC,IAAI,OAAO,IAAI,EAAE,EAAE,CAAC;QAClB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACtC,MAAM,IAAI,GAAG,OAAO,GAAG,EAAE,CAAC;QAC1B,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC;IACjD,CAAC;IACD,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC;AACpC,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `scrollport status` — "am I set up, and does the key still work?"
3
+ *
4
+ * The read-side pair of `setup`, and the first thing worth running when
5
+ * something 401s. It exists mainly so the answer to "is my key still good?" is
6
+ * never "try a billable run and see".
7
+ */
8
+ import { type Env } from "../credentials.js";
9
+ import type { ApiClient } from "../http.js";
10
+ import type { CommandResult, Reporter } from "../output.js";
11
+ export interface StatusDeps {
12
+ client: ApiClient;
13
+ reporter: Reporter;
14
+ env: Env;
15
+ }
16
+ export interface StatusOptions {
17
+ /** Skip the network check and report only what is on disk. */
18
+ offline: boolean;
19
+ }
20
+ export declare function runStatus(deps: StatusDeps, opts: StatusOptions): Promise<CommandResult>;
21
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../src/commands/status.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAML,KAAK,GAAG,EACT,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAG5D,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,GAAG,EAAE,GAAG,CAAC;CACV;AAED,MAAM,WAAW,aAAa;IAC5B,8DAA8D;IAC9D,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAiF7F"}
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `scrollport status` — "am I set up, and does the key still work?"
3
+ *
4
+ * The read-side pair of `setup`, and the first thing worth running when
5
+ * something 401s. It exists mainly so the answer to "is my key still good?" is
6
+ * never "try a billable run and see".
7
+ */
8
+ import { credentialsMode, credentialsPath, isTooOpen, maskKey, resolveApiKey, } from "../credentials.js";
9
+ import { CliError, EXIT_UNAUTHENTICATED } from "../errors.js";
10
+ import { verifyKey } from "../verify.js";
11
+ export async function runStatus(deps, opts) {
12
+ const { client, reporter, env } = deps;
13
+ const path = credentialsPath(env);
14
+ const resolved = resolveApiKey(env);
15
+ if (!resolved) {
16
+ throw new CliError("not_authenticated", `No scrollport key on this machine (looked in ${path}).`, {
17
+ hint: "Run `scrollport setup` — it takes two clicks and provisions one.",
18
+ exitCode: EXIT_UNAUTHENTICATED,
19
+ });
20
+ }
21
+ // A key anyone on the box can read is a key that has to be treated as leaked.
22
+ // Say so every time, not once.
23
+ const mode = resolved.source === "file" ? credentialsMode(env) : null;
24
+ const permissive = mode !== null && isTooOpen(mode);
25
+ if (permissive) {
26
+ reporter.progress(`warning: ${path} is mode ${mode.toString(8).padStart(4, "0")} — readable beyond its owner.`);
27
+ reporter.progress(` Fix with: chmod 600 ${path}`);
28
+ }
29
+ const masked = maskKey(resolved.apiKey);
30
+ const apiUrl = resolved.apiUrl ?? client.baseUrl;
31
+ if (opts.offline) {
32
+ return {
33
+ json: {
34
+ authenticated: true,
35
+ source: resolved.source,
36
+ account_id: resolved.accountId,
37
+ api_key_masked: masked,
38
+ api_url: apiUrl,
39
+ credentials_path: resolved.source === "file" ? path : null,
40
+ verified: null,
41
+ ...(permissive ? { permissions_warning: mode.toString(8).padStart(4, "0") } : {}),
42
+ },
43
+ human: [
44
+ `Key present (${masked}), from ${describeSource(resolved.source, path)}.`,
45
+ "Not checked against the API (--offline).",
46
+ ],
47
+ };
48
+ }
49
+ const state = await verifyKey(client, resolved.apiKey);
50
+ const json = {
51
+ source: resolved.source,
52
+ account_id: resolved.accountId,
53
+ api_key_masked: masked,
54
+ api_url: apiUrl,
55
+ credentials_path: resolved.source === "file" ? path : null,
56
+ ...(permissive ? { permissions_warning: mode.toString(8).padStart(4, "0") } : {}),
57
+ };
58
+ if (state === "rejected") {
59
+ throw new CliError("key_rejected", `The API rejected this key (${masked}).`, {
60
+ hint: "It was revoked, or it belongs to a different environment. Run `scrollport setup --force` to provision a new one.",
61
+ exitCode: EXIT_UNAUTHENTICATED,
62
+ });
63
+ }
64
+ if (state === "unreachable") {
65
+ return {
66
+ json: { ...json, authenticated: true, verified: null },
67
+ human: [
68
+ `Key present (${masked}), from ${describeSource(resolved.source, path)}.`,
69
+ `Could not reach ${apiUrl} to check it.`,
70
+ ],
71
+ };
72
+ }
73
+ return {
74
+ json: { ...json, authenticated: true, verified: true },
75
+ human: [
76
+ `Key present (${masked}), from ${describeSource(resolved.source, path)}.`,
77
+ `Verified against ${apiUrl} — the key works.`,
78
+ ...(resolved.accountId ? [`Account: ${resolved.accountId}`] : []),
79
+ ],
80
+ };
81
+ }
82
+ function describeSource(source, path) {
83
+ return source === "env" ? "$SCROLLPORT_API_KEY" : path;
84
+ }
85
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.js","sourceRoot":"","sources":["../../src/commands/status.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,eAAe,EACf,eAAe,EACf,SAAS,EACT,OAAO,EACP,aAAa,GAEd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAG9D,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAazC,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,IAAgB,EAAE,IAAmB;IACnE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACvC,MAAM,IAAI,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;IAEpC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,QAAQ,CAAC,mBAAmB,EAAE,gDAAgD,IAAI,IAAI,EAAE;YAChG,IAAI,EAAE,kEAAkE;YACxE,QAAQ,EAAE,oBAAoB;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,8EAA8E;IAC9E,+BAA+B;IAC/B,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,K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ACzE,oBAAoB,MAAM,mBAAmB;YAC7C,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,YAAY,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;SAClE;KACF,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,MAAsB,EAAE,IAAY;IAC1D,OAAO,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,IAAI,CAAC;AACzD,CAAC"}
@@ -0,0 +1,54 @@
1
+ export declare const CONFIG_DIR_MODE = 448;
2
+ export declare const CREDENTIALS_FILE_MODE = 384;
3
+ export declare const CREDENTIALS_FILENAME = "credentials.json";
4
+ /** Read-only environment view, so tests never have to mutate `process.env`. */
5
+ export type Env = Record<string, string | undefined>;
6
+ /** What we persist. Deliberately small — no cached balances, no derived state. */
7
+ export interface StoredCredentials {
8
+ /** `sp_live_…`. The whole reason this file has a mode. */
9
+ api_key: string;
10
+ account_id: string;
11
+ /** The API this key was minted against; a key is meaningless without it. */
12
+ api_url: string;
13
+ /** ISO 8601. For "when did I set this up?", nothing more. */
14
+ created_at: string;
15
+ }
16
+ export interface ResolvedKey {
17
+ apiKey: string;
18
+ source: "env" | "file";
19
+ accountId: string | null;
20
+ apiUrl: string | null;
21
+ }
22
+ /** `~/.scrollport`, or `SCROLLPORT_HOME` when set (tests, and multi-account users). */
23
+ export declare function configDir(env?: Env): string;
24
+ export declare function credentialsPath(env?: Env): string;
25
+ /**
26
+ * Persist the key. Atomic: the temp file is created with `0600` already set (not
27
+ * chmod'd afterwards), so there is no window in which the key sits at the
28
+ * process umask, and the rename is what makes it visible under its real name.
29
+ */
30
+ export declare function saveCredentials(creds: StoredCredentials, env?: Env): string;
31
+ /** The stored credentials, or `null` when there are none. Corrupt files teach. */
32
+ export declare function loadCredentials(env?: Env): StoredCredentials | null;
33
+ /** Remove the stored key. Returns false when there was nothing to remove. */
34
+ export declare function deleteCredentials(env?: Env): boolean;
35
+ /** The credentials file's POSIX mode bits, or null if it does not exist. */
36
+ export declare function credentialsMode(env?: Env): number | null;
37
+ /** True when anyone but the owner can read the file. */
38
+ export declare function isTooOpen(mode: number): boolean;
39
+ /**
40
+ * The key this machine would actually use, and where it came from.
41
+ *
42
+ * The environment wins over the file, deliberately: `SCROLLPORT_API_KEY` is how
43
+ * CI and containers inject a key, and a stale file left in an image must not be
44
+ * able to override the one the operator set.
45
+ */
46
+ export declare function resolveApiKey(env?: Env): ResolvedKey | null;
47
+ /**
48
+ * The only form of a key that is allowed on a screen: the `sp_live_` prefix (so
49
+ * you can see it is the right *kind* of key) and the last four (so you can tell
50
+ * two keys apart), with the secret middle gone. Never log the whole thing —
51
+ * terminal scrollback outlives every threat model that assumes it does not.
52
+ */
53
+ export declare function maskKey(key: string): string;
54
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AA8CA,eAAO,MAAM,eAAe,MAAQ,CAAC;AACrC,eAAO,MAAM,qBAAqB,MAAQ,CAAC;AAC3C,eAAO,MAAM,oBAAoB,qBAAqB,CAAC;AAEvD,+EAA+E;AAC/E,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAErD,kFAAkF;AAClF,MAAM,WAAW,iBAAiB;IAChC,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,uFAAuF;AACvF,wBAAgB,SAAS,CAAC,GAAG,GAAE,GAAiB,GAAG,MAAM,CAIxD;AAED,wBAAgB,eAAe,CAAC,GAAG,GAAE,GAAiB,GAAG,MAAM,CAE9D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,iBAAiB,EAAE,GAAG,GAAE,GAAiB,GAAG,MAAM,CAkCxF;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,GAAG,GAAE,GAAiB,GAAG,iBAAiB,GAAG,IAAI,CAoChF;AAED,6EAA6E;AAC7E,wBAAgB,iBAAiB,CAAC,GAAG,GAAE,GAAiB,GAAG,OAAO,CASjE;AAED,4EAA4E;AAC5E,wBAAgB,eAAe,CAAC,GAAG,GAAE,GAAiB,GAAG,MAAM,GAAG,IAAI,CAMrE;AAED,wDAAwD;AACxD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE/C;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,GAAG,GAAE,GAAiB,GAAG,WAAW,GAAG,IAAI,CAexE;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAM3C"}
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Where the key lives: `~/.scrollport/credentials.json`, directory `0700`, file
3
+ * `0600`, written atomically.
4
+ *
5
+ * ## Why a file and not the OS keychain
6
+ *
7
+ * The keychain is the better *desktop* answer and the worse answer for us, for
8
+ * one reason: agents do not run on desktops. macOS Keychain, libsecret and
9
+ * Windows Credential Manager all need a logged-in, unlocked user session —
10
+ * `security` pops a GUI unlock prompt, libsecret needs D-Bus and an unlocked
11
+ * keyring. In a container, over SSH, or in CI, that is not a degraded
12
+ * experience, it is a hang with no visible prompt, on exactly the surface where
13
+ * scrollport is meant to be used. Issue #9's criterion is "fresh machine → 2
14
+ * clicks → working key in under 60 seconds"; a native keychain would make that
15
+ * criterion untestable in the environments that matter, and every keychain
16
+ * binding (keytar and successors) drags in a native module whose prebuilt
17
+ * binaries are a recurring `npx` failure mode.
18
+ *
19
+ * So: a file, which is what issue #12 specifies (`~/.scrollport`) and what the
20
+ * gh/aws/fly CLIs all do for the same reasons. What the file must then earn:
21
+ *
22
+ * - **`0600`, in a `0700` directory** — not world- or group-readable. Verified
23
+ * on read; a loose mode is warned about loudly rather than silently accepted.
24
+ * - **Written atomically** (temp file with the mode already set, then rename),
25
+ * so the key is never briefly visible at the default umask and an interrupted
26
+ * write cannot leave a half-file.
27
+ * - **Never on the command line, never echoed.** The CLI writes the key itself,
28
+ * straight from the poll response; it is never a flag, never printed, and so
29
+ * never lands in shell history or terminal scrollback. `maskKey` is the only
30
+ * form that reaches a screen.
31
+ * - **`SCROLLPORT_API_KEY` is read but never written** — the escape hatch for
32
+ * CI, where the right store is the platform's secret manager, not our file.
33
+ *
34
+ * The residual risk is honest and worth stating: anything running as this user
35
+ * can read this file. A keychain narrows that to "anything running as this user
36
+ * that can also satisfy an unlock prompt", which is a real improvement for a
37
+ * human's laptop. If we ever ship a desktop-first surface, the keychain belongs
38
+ * behind this same interface as an alternative backend — nothing above assumes
39
+ * a file except this module.
40
+ */
41
+ import { randomBytes } from "node:crypto";
42
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
43
+ import { homedir } from "node:os";
44
+ import { join, resolve } from "node:path";
45
+ import { CliError } from "./errors.js";
46
+ export const CONFIG_DIR_MODE = 0o700;
47
+ export const CREDENTIALS_FILE_MODE = 0o600;
48
+ export const CREDENTIALS_FILENAME = "credentials.json";
49
+ /** `~/.scrollport`, or `SCROLLPORT_HOME` when set (tests, and multi-account users). */
50
+ export function configDir(env = process.env) {
51
+ const override = env["SCROLLPORT_HOME"]?.trim();
52
+ if (override)
53
+ return resolve(override);
54
+ return join(homedir(), ".scrollport");
55
+ }
56
+ export function credentialsPath(env = process.env) {
57
+ return join(configDir(env), CREDENTIALS_FILENAME);
58
+ }
59
+ /**
60
+ * Persist the key. Atomic: the temp file is created with `0600` already set (not
61
+ * chmod'd afterwards), so there is no window in which the key sits at the
62
+ * process umask, and the rename is what makes it visible under its real name.
63
+ */
64
+ export function saveCredentials(creds, env = process.env) {
65
+ const dir = configDir(env);
66
+ const path = join(dir, CREDENTIALS_FILENAME);
67
+ mkdirSync(dir, { recursive: true, mode: CONFIG_DIR_MODE });
68
+ // `mkdirSync`'s mode applies on creation only; an already-existing directory
69
+ // (an older version's, or one the user made) keeps whatever it had. Tighten
70
+ // it. Best-effort: Windows has no POSIX mode and throws nothing useful here.
71
+ try {
72
+ chmodSync(dir, CONFIG_DIR_MODE);
73
+ }
74
+ catch {
75
+ /* not POSIX; the file mode below is still applied where it means anything */
76
+ }
77
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
78
+ try {
79
+ writeFileSync(tmp, `${JSON.stringify(creds, null, 2)}\n`, {
80
+ mode: CREDENTIALS_FILE_MODE,
81
+ flag: "wx",
82
+ });
83
+ renameSync(tmp, path);
84
+ }
85
+ catch (cause) {
86
+ try {
87
+ rmSync(tmp, { force: true });
88
+ }
89
+ catch {
90
+ /* the rename already consumed it, or we never got that far */
91
+ }
92
+ throw new CliError("credentials_write_failed", `Could not write ${path}.`, {
93
+ hint: `Check that ${dir} is writable by this user, or set SCROLLPORT_HOME to a directory that is. Cause: ${cause instanceof Error ? cause.message : String(cause)}`,
94
+ cause,
95
+ });
96
+ }
97
+ return path;
98
+ }
99
+ /** The stored credentials, or `null` when there are none. Corrupt files teach. */
100
+ export function loadCredentials(env = process.env) {
101
+ const path = credentialsPath(env);
102
+ let raw;
103
+ try {
104
+ raw = readFileSync(path, "utf8");
105
+ }
106
+ catch (cause) {
107
+ if (cause.code === "ENOENT")
108
+ return null;
109
+ throw new CliError("credentials_read_failed", `Could not read ${path}.`, {
110
+ hint: "Check the file's permissions, or run `scrollport logout` and then `scrollport setup` to start clean.",
111
+ cause,
112
+ });
113
+ }
114
+ let parsed;
115
+ try {
116
+ parsed = JSON.parse(raw);
117
+ }
118
+ catch {
119
+ throw new CliError("credentials_corrupt", `${path} is not valid JSON.`, {
120
+ hint: "Run `scrollport logout` to remove it, then `scrollport setup` to provision a fresh key.",
121
+ });
122
+ }
123
+ const creds = parsed;
124
+ if (!creds || typeof creds.api_key !== "string" || !creds.api_key) {
125
+ throw new CliError("credentials_corrupt", `${path} has no api_key.`, {
126
+ hint: "Run `scrollport logout` to remove it, then `scrollport setup` to provision a fresh key.",
127
+ });
128
+ }
129
+ return {
130
+ api_key: creds.api_key,
131
+ account_id: typeof creds.account_id === "string" ? creds.account_id : "",
132
+ api_url: typeof creds.api_url === "string" ? creds.api_url : "",
133
+ created_at: typeof creds.created_at === "string" ? creds.created_at : "",
134
+ };
135
+ }
136
+ /** Remove the stored key. Returns false when there was nothing to remove. */
137
+ export function deleteCredentials(env = process.env) {
138
+ const path = credentialsPath(env);
139
+ try {
140
+ statSync(path);
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ rmSync(path, { force: true });
146
+ return true;
147
+ }
148
+ /** The credentials file's POSIX mode bits, or null if it does not exist. */
149
+ export function credentialsMode(env = process.env) {
150
+ try {
151
+ return statSync(credentialsPath(env)).mode & 0o777;
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ }
157
+ /** True when anyone but the owner can read the file. */
158
+ export function isTooOpen(mode) {
159
+ return (mode & 0o077) !== 0;
160
+ }
161
+ /**
162
+ * The key this machine would actually use, and where it came from.
163
+ *
164
+ * The environment wins over the file, deliberately: `SCROLLPORT_API_KEY` is how
165
+ * CI and containers inject a key, and a stale file left in an image must not be
166
+ * able to override the one the operator set.
167
+ */
168
+ export function resolveApiKey(env = process.env) {
169
+ const fromEnv = env["SCROLLPORT_API_KEY"]?.trim();
170
+ if (fromEnv) {
171
+ return { apiKey: fromEnv, source: "env", accountId: null, apiUrl: null };
172
+ }
173
+ const stored = loadCredentials(env);
174
+ if (!stored)
175
+ return null;
176
+ return {
177
+ apiKey: stored.api_key,
178
+ source: "file",
179
+ accountId: stored.account_id || null,
180
+ apiUrl: stored.api_url || null,
181
+ };
182
+ }
183
+ /**
184
+ * The only form of a key that is allowed on a screen: the `sp_live_` prefix (so
185
+ * you can see it is the right *kind* of key) and the last four (so you can tell
186
+ * two keys apart), with the secret middle gone. Never log the whole thing —
187
+ * terminal scrollback outlives every threat model that assumes it does not.
188
+ */
189
+ export function maskKey(key) {
190
+ const prefixMatch = /^(sp_[a-z]+_)/.exec(key);
191
+ const prefix = prefixMatch?.[1] ?? "";
192
+ const secret = key.slice(prefix.length);
193
+ if (secret.length <= 4)
194
+ return `${prefix}…`;
195
+ return `${prefix}…${secret.slice(-4)}`;
196
+ }
197
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC1G,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAC3C,MAAM,CAAC,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAuBvD,uFAAuF;AACvF,MAAM,UAAU,SAAS,CAAC,MAAW,OAAO,CAAC,GAAG;IAC9C,MAAM,QAAQ,GAAG,GAAG,CAAC,iBAAi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,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,MAAW,OAAO,CAAC,GAAG;IAClD,MAAM,OAAO,GAAG,GAAG,CAAC,oBAAoB,CAAC,EAAE,IAAI,EAAE,CAAC;IAClD,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAC3E,CAAC;IAED,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,OAAO;QACtB,MAAM,EAAE,MAAM;QACd,SAAS,EAAE,MAAM,CAAC,UAAU,IAAI,IAAI;QACpC,MAAM,EAAE,MAAM,CAAC,OAAO,IAAI,IAAI;KAC/B,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,MAAM,WAAW,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACtC,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC;QAAE,OAAO,GAAG,MAAM,GAAG,CAAC;IAC5C,OAAO,GAAG,MAAM,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACzC,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { ApiClient } from "./http.js";
2
+ import type { DeviceAuthorizationStart, PollOutcome } from "./device-flow.js";
3
+ /** Shown on the consent screen so the human can see what they are approving. */
4
+ export declare const CLIENT_NAME = "scrollport CLI";
5
+ /**
6
+ * `POST /v1/auth/device`. Returns both plaintext codes — the only time they
7
+ * exist. The device code is a credential and is never displayed; the user code
8
+ * is displayed precisely so the human can compare it with the consent screen.
9
+ */
10
+ export declare function startDeviceAuthorization(client: ApiClient, opts?: {
11
+ clientName?: string;
12
+ scopes?: string[];
13
+ }): Promise<DeviceAuthorizationStart>;
14
+ /**
15
+ * One poll of `POST /v1/auth/token`.
16
+ *
17
+ * Never throws for an expected outcome — pending, slow_down, denial, expiry and
18
+ * "the network is having a moment" are all values. Only a genuinely unexpected
19
+ * response (a 400 we do not recognise, a 401) throws, because that is a bug
20
+ * rather than a state, and the API's own teaching error is the best thing to
21
+ * show for it.
22
+ */
23
+ export declare function pollDeviceToken(client: ApiClient, deviceCode: string): Promise<PollOutcome>;
24
+ //# sourceMappingURL=device-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device-client.d.ts","sourceRoot":"","sources":["../src/device-client.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,wBAAwB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE9E,gFAAgF;AAChF,eAAO,MAAM,WAAW,mBAAmB,CAAC;AAE5C;;;;GAIG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,SAAS,EACjB,IAAI,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,GACpD,OAAO,CAAC,wBAAwB,CAAC,CAUnC;AAED;;;;;;;;GAQG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,SAAS,EACjB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,WAAW,CAAC,CAkDtB"}