@foliwake/cli 0.0.0-stage → 0.7.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 (256) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +202 -0
  3. package/README.md +654 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/command-words.d.ts +13 -0
  7. package/dist/command-words.js +53 -0
  8. package/dist/commands/account/keys/create.d.ts +12 -0
  9. package/dist/commands/account/keys/create.js +36 -0
  10. package/dist/commands/account/keys/list.d.ts +9 -0
  11. package/dist/commands/account/keys/list.js +23 -0
  12. package/dist/commands/account/keys/revoke.d.ts +12 -0
  13. package/dist/commands/account/keys/revoke.js +15 -0
  14. package/dist/commands/branch/bootstrap.d.ts +11 -0
  15. package/dist/commands/branch/bootstrap.js +23 -0
  16. package/dist/commands/branch/delete.d.ts +17 -0
  17. package/dist/commands/branch/delete.js +38 -0
  18. package/dist/commands/branch/history.d.ts +14 -0
  19. package/dist/commands/branch/history.js +24 -0
  20. package/dist/commands/branch/list.d.ts +11 -0
  21. package/dist/commands/branch/list.js +15 -0
  22. package/dist/commands/branch/update.d.ts +19 -0
  23. package/dist/commands/branch/update.js +49 -0
  24. package/dist/commands/code/deploy.d.ts +15 -0
  25. package/dist/commands/code/deploy.js +78 -0
  26. package/dist/commands/code/prepare.d.ts +13 -0
  27. package/dist/commands/code/prepare.js +54 -0
  28. package/dist/commands/code/release.d.ts +19 -0
  29. package/dist/commands/code/release.js +51 -0
  30. package/dist/commands/code/rollback.d.ts +17 -0
  31. package/dist/commands/code/rollback.js +38 -0
  32. package/dist/commands/connect.d.ts +19 -0
  33. package/dist/commands/connect.js +100 -0
  34. package/dist/commands/create.d.ts +32 -0
  35. package/dist/commands/create.js +171 -0
  36. package/dist/commands/credential/list.d.ts +10 -0
  37. package/dist/commands/credential/list.js +21 -0
  38. package/dist/commands/credential/rm.d.ts +12 -0
  39. package/dist/commands/credential/rm.js +18 -0
  40. package/dist/commands/credential/set.d.ts +15 -0
  41. package/dist/commands/credential/set.js +58 -0
  42. package/dist/commands/dev.d.ts +30 -0
  43. package/dist/commands/dev.js +144 -0
  44. package/dist/commands/login.d.ts +20 -0
  45. package/dist/commands/login.js +94 -0
  46. package/dist/commands/logout.d.ts +14 -0
  47. package/dist/commands/logout.js +61 -0
  48. package/dist/commands/migration/commit.d.ts +13 -0
  49. package/dist/commands/migration/commit.js +42 -0
  50. package/dist/commands/migration/prepare.d.ts +18 -0
  51. package/dist/commands/migration/prepare.js +53 -0
  52. package/dist/commands/operation/cancel.d.ts +14 -0
  53. package/dist/commands/operation/cancel.js +21 -0
  54. package/dist/commands/operation/get.d.ts +14 -0
  55. package/dist/commands/operation/get.js +26 -0
  56. package/dist/commands/operation/list.d.ts +12 -0
  57. package/dist/commands/operation/list.js +25 -0
  58. package/dist/commands/operation/recover.d.ts +20 -0
  59. package/dist/commands/operation/recover.js +61 -0
  60. package/dist/commands/page/changes.d.ts +13 -0
  61. package/dist/commands/page/changes.js +26 -0
  62. package/dist/commands/page/check.d.ts +12 -0
  63. package/dist/commands/page/check.js +25 -0
  64. package/dist/commands/page/replace.d.ts +13 -0
  65. package/dist/commands/page/replace.js +59 -0
  66. package/dist/commands/page/unpreview.d.ts +17 -0
  67. package/dist/commands/page/unpreview.js +54 -0
  68. package/dist/commands/page/unpublish.d.ts +18 -0
  69. package/dist/commands/page/unpublish.js +36 -0
  70. package/dist/commands/project/preview.d.ts +8 -0
  71. package/dist/commands/project/preview.js +20 -0
  72. package/dist/commands/project/publish.d.ts +16 -0
  73. package/dist/commands/project/publish.js +40 -0
  74. package/dist/commands/project/unpublish.d.ts +16 -0
  75. package/dist/commands/project/unpublish.js +33 -0
  76. package/dist/commands/release/rollback.d.ts +17 -0
  77. package/dist/commands/release/rollback.js +38 -0
  78. package/dist/commands/servers/index.d.ts +20 -0
  79. package/dist/commands/servers/index.js +36 -0
  80. package/dist/commands/servers/use.d.ts +11 -0
  81. package/dist/commands/servers/use.js +30 -0
  82. package/dist/commands/site/adopt.d.ts +11 -0
  83. package/dist/commands/site/adopt.js +21 -0
  84. package/dist/commands/site/create.d.ts +18 -0
  85. package/dist/commands/site/create.js +61 -0
  86. package/dist/commands/site/edit.d.ts +11 -0
  87. package/dist/commands/site/edit.js +56 -0
  88. package/dist/commands/site/history.d.ts +11 -0
  89. package/dist/commands/site/history.js +25 -0
  90. package/dist/commands/site/link.d.ts +15 -0
  91. package/dist/commands/site/link.js +35 -0
  92. package/dist/commands/site/list.d.ts +9 -0
  93. package/dist/commands/site/list.js +29 -0
  94. package/dist/commands/site/reset-storage.d.ts +15 -0
  95. package/dist/commands/site/reset-storage.js +61 -0
  96. package/dist/commands/site/set.d.ts +16 -0
  97. package/dist/commands/site/set.js +45 -0
  98. package/dist/commands/site/show.d.ts +10 -0
  99. package/dist/commands/site/show.js +19 -0
  100. package/dist/commands/site/status.d.ts +11 -0
  101. package/dist/commands/site/status.js +15 -0
  102. package/dist/commands/site/unlink.d.ts +11 -0
  103. package/dist/commands/site/unlink.js +28 -0
  104. package/dist/commands/source/add.d.ts +32 -0
  105. package/dist/commands/source/add.js +103 -0
  106. package/dist/commands/source/adopt-pages.d.ts +14 -0
  107. package/dist/commands/source/adopt-pages.js +30 -0
  108. package/dist/commands/source/check.d.ts +17 -0
  109. package/dist/commands/source/check.js +52 -0
  110. package/dist/commands/source/list.d.ts +11 -0
  111. package/dist/commands/source/list.js +15 -0
  112. package/dist/commands/source/mappings/check.d.ts +13 -0
  113. package/dist/commands/source/mappings/check.js +69 -0
  114. package/dist/commands/source/pending.d.ts +12 -0
  115. package/dist/commands/source/pending.js +25 -0
  116. package/dist/commands/source/plugins.d.ts +6 -0
  117. package/dist/commands/source/plugins.js +17 -0
  118. package/dist/commands/source/sync.d.ts +16 -0
  119. package/dist/commands/source/sync.js +58 -0
  120. package/dist/commands/whoami.d.ts +6 -0
  121. package/dist/commands/whoami.js +22 -0
  122. package/dist/connect-prompts.d.ts +16 -0
  123. package/dist/connect-prompts.js +24 -0
  124. package/dist/connect.d.ts +133 -0
  125. package/dist/connect.js +416 -0
  126. package/dist/core-command.d.ts +99 -0
  127. package/dist/core-command.js +332 -0
  128. package/dist/core-types.d.ts +21 -0
  129. package/dist/core-types.js +1 -0
  130. package/dist/create-connect.d.ts +26 -0
  131. package/dist/create-connect.js +93 -0
  132. package/dist/dev/code-watcher.d.ts +66 -0
  133. package/dist/dev/code-watcher.js +254 -0
  134. package/dist/dev/dev-checks.d.ts +14 -0
  135. package/dist/dev/dev-checks.js +138 -0
  136. package/dist/dev/dev-reload.d.ts +51 -0
  137. package/dist/dev/dev-reload.js +345 -0
  138. package/dist/dev/flags.d.ts +19 -0
  139. package/dist/dev/flags.js +54 -0
  140. package/dist/dev/html.d.ts +30 -0
  141. package/dist/dev/html.js +106 -0
  142. package/dist/dev/kit-files.d.ts +7 -0
  143. package/dist/dev/kit-files.js +33 -0
  144. package/dist/dev/local-code.d.ts +22 -0
  145. package/dist/dev/local-code.js +101 -0
  146. package/dist/dev/remote-config.d.ts +57 -0
  147. package/dist/dev/remote-config.js +100 -0
  148. package/dist/dev/remote-dev.d.ts +41 -0
  149. package/dist/dev/remote-dev.js +527 -0
  150. package/dist/dev/remote-fetch.d.ts +5 -0
  151. package/dist/dev/remote-fetch.js +36 -0
  152. package/dist/dev/remote-html.d.ts +10 -0
  153. package/dist/dev/remote-html.js +60 -0
  154. package/dist/dev/remote-page.d.ts +34 -0
  155. package/dist/dev/remote-page.js +183 -0
  156. package/dist/dev/remote-routes.d.ts +63 -0
  157. package/dist/dev/remote-routes.js +114 -0
  158. package/dist/dev/signal-stop.d.ts +17 -0
  159. package/dist/dev/signal-stop.js +46 -0
  160. package/dist/dev/start.d.ts +18 -0
  161. package/dist/dev/start.js +80 -0
  162. package/dist/index.d.ts +6 -0
  163. package/dist/index.js +8 -0
  164. package/dist/lib/diagnostics.d.ts +15 -0
  165. package/dist/lib/diagnostics.js +12 -0
  166. package/dist/lib/front-matter.d.ts +6 -0
  167. package/dist/lib/front-matter.js +59 -0
  168. package/dist/lib/operation-result.d.ts +3 -0
  169. package/dist/lib/operation-result.js +16 -0
  170. package/dist/lib/problem-groups.d.ts +27 -0
  171. package/dist/lib/problem-groups.js +49 -0
  172. package/dist/lib/problems.d.ts +50 -0
  173. package/dist/lib/problems.js +94 -0
  174. package/dist/lib/prompts.d.ts +38 -0
  175. package/dist/lib/prompts.js +77 -0
  176. package/dist/lib/result-types.d.ts +198 -0
  177. package/dist/lib/result-types.js +3 -0
  178. package/dist/lib/rules.d.ts +15 -0
  179. package/dist/lib/rules.js +26 -0
  180. package/dist/lib/summaries.d.ts +19 -0
  181. package/dist/lib/summaries.js +22 -0
  182. package/dist/lib/sync-problems.d.ts +21 -0
  183. package/dist/lib/sync-problems.js +19 -0
  184. package/dist/local-runtime.d.ts +78 -0
  185. package/dist/local-runtime.js +11 -0
  186. package/dist/local-target.d.ts +6 -0
  187. package/dist/local-target.js +23 -0
  188. package/dist/main.d.ts +2 -0
  189. package/dist/main.js +40 -0
  190. package/dist/project-preview.d.ts +35 -0
  191. package/dist/project-preview.js +156 -0
  192. package/dist/project-publish.d.ts +28 -0
  193. package/dist/project-publish.js +173 -0
  194. package/dist/remote/connection.d.ts +8 -0
  195. package/dist/remote/connection.js +19 -0
  196. package/dist/remote/core-failure.d.ts +8 -0
  197. package/dist/remote/core-failure.js +15 -0
  198. package/dist/remote/credentials.d.ts +15 -0
  199. package/dist/remote/credentials.js +112 -0
  200. package/dist/remote/device-login.d.ts +33 -0
  201. package/dist/remote/device-login.js +161 -0
  202. package/dist/remote/remote-caller.d.ts +14 -0
  203. package/dist/remote/remote-caller.js +52 -0
  204. package/dist/remote/rpc-wire.d.ts +18 -0
  205. package/dist/remote/rpc-wire.js +57 -0
  206. package/dist/remote/servers.d.ts +80 -0
  207. package/dist/remote/servers.js +162 -0
  208. package/dist/remote/session.d.ts +53 -0
  209. package/dist/remote/session.js +132 -0
  210. package/dist/remote/sign-in-here.d.ts +5 -0
  211. package/dist/remote/sign-in-here.js +33 -0
  212. package/dist/remote/sign-in.d.ts +25 -0
  213. package/dist/remote/sign-in.js +55 -0
  214. package/dist/remote/wait-slices.d.ts +16 -0
  215. package/dist/remote/wait-slices.js +21 -0
  216. package/dist/render/add.d.ts +3 -0
  217. package/dist/render/add.js +9 -0
  218. package/dist/render/branch-write.d.ts +9 -0
  219. package/dist/render/branch-write.js +28 -0
  220. package/dist/render/branches.d.ts +5 -0
  221. package/dist/render/branches.js +28 -0
  222. package/dist/render/credentials.d.ts +5 -0
  223. package/dist/render/credentials.js +39 -0
  224. package/dist/render/operation-result.d.ts +16 -0
  225. package/dist/render/operation-result.js +65 -0
  226. package/dist/render/operation.d.ts +7 -0
  227. package/dist/render/operation.js +15 -0
  228. package/dist/render/page-changes.d.ts +3 -0
  229. package/dist/render/page-changes.js +36 -0
  230. package/dist/render/pending.d.ts +3 -0
  231. package/dist/render/pending.js +46 -0
  232. package/dist/render/plugin-list.d.ts +3 -0
  233. package/dist/render/plugin-list.js +30 -0
  234. package/dist/render/probe.d.ts +3 -0
  235. package/dist/render/probe.js +61 -0
  236. package/dist/render/problems.d.ts +35 -0
  237. package/dist/render/problems.js +64 -0
  238. package/dist/render/recovery.d.ts +2 -0
  239. package/dist/render/recovery.js +36 -0
  240. package/dist/render/reset-storage.d.ts +4 -0
  241. package/dist/render/reset-storage.js +70 -0
  242. package/dist/render/site-status.d.ts +2 -0
  243. package/dist/render/site-status.js +81 -0
  244. package/dist/render/source-list.d.ts +2 -0
  245. package/dist/render/source-list.js +37 -0
  246. package/dist/render/sync.d.ts +5 -0
  247. package/dist/render/sync.js +66 -0
  248. package/dist/settings.d.ts +10 -0
  249. package/dist/settings.js +45 -0
  250. package/dist/site-entry-edit.d.ts +5 -0
  251. package/dist/site-entry-edit.js +44 -0
  252. package/dist/source-entry.d.ts +32 -0
  253. package/dist/source-entry.js +89 -0
  254. package/dist/version.d.ts +3 -0
  255. package/dist/version.js +10 -0
  256. package/package.json +112 -3
@@ -0,0 +1,19 @@
1
+ // The link of a project folder to a site: `.foliwake/connection.json` `{ server, site, org }`, written by
2
+ // `site create` and `site link`. `server` is a server name: "cloud" or an origin.
3
+ import { readFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ export const connectionFile = (cwd) => path.join(cwd, '.foliwake', 'connection.json');
6
+ /** The folder's link, or null when it has none or the file is not a complete link. */
7
+ export function readConnection(cwd) {
8
+ let raw;
9
+ try {
10
+ raw = JSON.parse(readFileSync(connectionFile(cwd), 'utf8'));
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ const { server, site, org } = raw ?? {};
16
+ if (typeof server !== 'string' || typeof site !== 'string' || typeof org !== 'string')
17
+ return null;
18
+ return { server, site, org };
19
+ }
@@ -0,0 +1,8 @@
1
+ import type { CoreError } from '@foliwake/core-contract';
2
+ export type { CoreError };
3
+ export declare class CoreFailure extends Error {
4
+ readonly coreError: CoreError;
5
+ constructor(coreError: CoreError, cause?: unknown);
6
+ }
7
+ /** Anything thrown, as a CoreFailure: a CoreFailure as it is, anything else as INTERNAL. */
8
+ export declare function toCoreFailure(error: unknown): CoreFailure;
@@ -0,0 +1,15 @@
1
+ export class CoreFailure extends Error {
2
+ coreError;
3
+ constructor(coreError, cause) {
4
+ super(coreError.message, { cause });
5
+ this.name = 'CoreFailure';
6
+ this.coreError = coreError;
7
+ }
8
+ }
9
+ /** Anything thrown, as a CoreFailure: a CoreFailure as it is, anything else as INTERNAL. */
10
+ export function toCoreFailure(error) {
11
+ if (error instanceof CoreFailure)
12
+ return error;
13
+ const message = 'The operation failed unexpectedly.';
14
+ return new CoreFailure({ code: 'INTERNAL', category: 'internal', retryable: false, message }, error);
15
+ }
@@ -0,0 +1,15 @@
1
+ import type { CredentialStoreKind } from './servers.js';
2
+ export interface CredentialStore {
3
+ kind: CredentialStoreKind;
4
+ get(key: string): string | null;
5
+ set(key: string, token: string): void;
6
+ delete(key: string): void;
7
+ }
8
+ export declare class CredentialStoreError extends Error {
9
+ }
10
+ /** The store of this kind, as a profile names it. */
11
+ export declare function credentialStore(kind: CredentialStoreKind, env?: NodeJS.ProcessEnv): CredentialStore;
12
+ /** The store a new sign-in uses: the OS keychain, or the file only when `insecureStorage` allows it. */
13
+ export declare function storeForSignIn({ insecureStorage }: {
14
+ insecureStorage: boolean;
15
+ }, env?: NodeJS.ProcessEnv): CredentialStore;
@@ -0,0 +1,112 @@
1
+ // Where this computer keeps the CLI token of each server: the OS keychain (macOS Keychain, Linux Secret
2
+ // Service), or, only when asked for, a 0600 file. The service name and account keys are the engine CLI's,
3
+ // so either CLI reads a sign-in the other made. `FOLIWAKE_TOKEN` (CI) is read by the caller and stores nothing.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { configDir, setting } from '../settings.js';
8
+ export class CredentialStoreError extends Error {
9
+ }
10
+ const serviceName = (env) => setting('KEYCHAIN_SERVICE', env) ?? 'foliwake';
11
+ function run(command, args, input) {
12
+ const options = { input, encoding: 'utf8', stdio: 'pipe', timeout: 15_000 };
13
+ const result = spawnSync(command, args, options);
14
+ if (result.error)
15
+ throw new CredentialStoreError(`${command} could not run: ${result.error.message}`);
16
+ return { status: result.status, stdout: result.stdout };
17
+ }
18
+ /** Keys and tokens hold no quotes (a key is an origin or "cloud"; a token is base64url). */
19
+ function quoted(value) {
20
+ if (/["\\\s]/.test(value))
21
+ throw new CredentialStoreError('This value cannot be stored in the keychain.');
22
+ return `"${value}"`;
23
+ }
24
+ // Values go through `security -i` on stdin, so the token is never in a process's arguments.
25
+ function keychain(service) {
26
+ const security = '/usr/bin/security';
27
+ return {
28
+ kind: 'keychain',
29
+ get(key) {
30
+ const found = run(security, ['find-generic-password', '-s', service, '-a', key, '-w']);
31
+ return found.status === 0 ? found.stdout.trim() || null : null;
32
+ },
33
+ set(key, token) {
34
+ const command = `add-generic-password -U -s ${quoted(service)} -a ${quoted(key)} -w ${quoted(token)}\n`;
35
+ const result = run(security, ['-i'], command);
36
+ if (result.status !== 0)
37
+ throw new CredentialStoreError('The macOS Keychain refused to store the token.');
38
+ },
39
+ delete(key) {
40
+ run(security, ['delete-generic-password', '-s', service, '-a', key]);
41
+ },
42
+ };
43
+ }
44
+ function secretService(service) {
45
+ return {
46
+ kind: 'secret-service',
47
+ get(key) {
48
+ const found = run('secret-tool', ['lookup', 'service', service, 'account', key]);
49
+ return found.status === 0 ? found.stdout.trim() || null : null;
50
+ },
51
+ set(key, token) {
52
+ const args = ['store', `--label=Foliwake ${key}`, 'service', service, 'account', key];
53
+ const result = run('secret-tool', args, token);
54
+ if (result.status !== 0)
55
+ throw new CredentialStoreError('The Secret Service refused to store the token.');
56
+ },
57
+ delete(key) {
58
+ run('secret-tool', ['clear', 'service', service, 'account', key]);
59
+ },
60
+ };
61
+ }
62
+ function readFileStore(where) {
63
+ try {
64
+ return JSON.parse(readFileSync(where, 'utf8'));
65
+ }
66
+ catch (error) {
67
+ if (error.code === 'ENOENT')
68
+ return {};
69
+ throw error;
70
+ }
71
+ }
72
+ function writeFileStore(where, all) {
73
+ mkdirSync(path.dirname(where), { recursive: true, mode: 0o700 });
74
+ const temp = `${where}.${process.pid}.tmp`;
75
+ writeFileSync(temp, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
76
+ renameSync(temp, where);
77
+ }
78
+ function file(env) {
79
+ const where = path.join(configDir(env), 'credentials.json');
80
+ return {
81
+ kind: 'file',
82
+ get: (key) => readFileStore(where)[key] ?? null,
83
+ set: (key, token) => writeFileStore(where, { ...readFileStore(where), [key]: token }),
84
+ delete(key) {
85
+ const all = readFileStore(where);
86
+ if (!(key in all))
87
+ return;
88
+ delete all[key];
89
+ writeFileStore(where, all);
90
+ },
91
+ };
92
+ }
93
+ const hasSecretTool = () => spawnSync('secret-tool', ['--version'], { stdio: 'ignore' }).error === undefined;
94
+ /** The store of this kind, as a profile names it. */
95
+ export function credentialStore(kind, env = process.env) {
96
+ if (kind === 'keychain')
97
+ return keychain(serviceName(env));
98
+ if (kind === 'secret-service')
99
+ return secretService(serviceName(env));
100
+ return file(env);
101
+ }
102
+ /** The store a new sign-in uses: the OS keychain, or the file only when `insecureStorage` allows it. */
103
+ export function storeForSignIn({ insecureStorage }, env = process.env) {
104
+ if (insecureStorage)
105
+ return file(env);
106
+ if (process.platform === 'darwin')
107
+ return keychain(serviceName(env));
108
+ if (process.platform === 'linux' && hasSecretTool())
109
+ return secretService(serviceName(env));
110
+ throw new CredentialStoreError('There is no system keychain here (on Linux: install libsecret-tools). Pass --insecure-storage to keep ' +
111
+ 'the token in a 0600 file, or set FOLIWAKE_TOKEN for CI.');
112
+ }
@@ -0,0 +1,33 @@
1
+ export interface DeviceStart {
2
+ deviceCode: string;
3
+ userCode: string;
4
+ verificationUri: string;
5
+ verificationUriComplete: string;
6
+ expiresInS: number;
7
+ intervalS: number;
8
+ }
9
+ export declare class SignInError extends Error {
10
+ readonly code: string;
11
+ constructor(code: string, message: string);
12
+ }
13
+ /** A sign-in stopped on this computer (Ctrl+C) before it was approved. */
14
+ export declare class SignInCancelled extends SignInError {
15
+ constructor();
16
+ }
17
+ export declare function startDeviceSignIn(origin: string): Promise<DeviceStart>;
18
+ /** A sleep that ends early with SignInCancelled when `signal` aborts. */
19
+ export declare function abortableSleep(signal: AbortSignal): (ms: number) => Promise<void>;
20
+ export interface WaitOptions {
21
+ sleep?: (ms: number) => Promise<unknown>;
22
+ now?: () => number;
23
+ }
24
+ /**
25
+ * Polls until the sign-in is approved (the token, with the account's e-mail address when the server says
26
+ * it), denied or expired (a SignInError). A transient failure doubles the wait, up to a minute.
27
+ */
28
+ export declare function waitForSignIn(origin: string, start: DeviceStart, { sleep, now }?: WaitOptions): Promise<{
29
+ token: string;
30
+ email: string | null;
31
+ }>;
32
+ /** Revokes the token on its server. False when the server could not be asked. */
33
+ export declare function revokeToken(origin: string, token: string): Promise<boolean>;
@@ -0,0 +1,161 @@
1
+ // The CLI's side of the device flow (RFC 8628) and of logout, against a server's `/api/auth/*`.
2
+ import os from 'node:os';
3
+ import { COMMAND } from '../settings.js';
4
+ import { clientName } from '../version.js';
5
+ export class SignInError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /** A sign-in stopped on this computer (Ctrl+C) before it was approved. */
13
+ export class SignInCancelled extends SignInError {
14
+ constructor() {
15
+ super('SIGN_IN_CANCELLED', 'The sign-in was cancelled.');
16
+ }
17
+ }
18
+ /** One request is bounded: a server that hangs is a transient failure, not a stuck CLI. */
19
+ const REQUEST_TIMEOUT_MS = 15_000;
20
+ /** Backoff on transient failures while polling (RFC 8628 §3.5): doubled, at most this. */
21
+ const MAX_BACKOFF_S = 60;
22
+ async function send(origin, route, body, headers) {
23
+ try {
24
+ return await fetch(`${origin}${route}`, {
25
+ method: 'POST',
26
+ headers: { 'content-type': 'application/json', accept: 'application/json', ...headers },
27
+ body: JSON.stringify(body),
28
+ redirect: 'error',
29
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
30
+ });
31
+ }
32
+ catch {
33
+ throw new SignInError('SERVER_UNREACHABLE', `The server ${origin} cannot be reached.`);
34
+ }
35
+ }
36
+ async function post(origin, route, body, headers = {}) {
37
+ const response = await send(origin, route, body, headers);
38
+ const text = await response.text();
39
+ try {
40
+ return { status: response.status, json: text ? JSON.parse(text) : {} };
41
+ }
42
+ catch {
43
+ const message = `The server ${origin} did not answer as a Foliwake server (HTTP ${response.status}).`;
44
+ throw new SignInError('SERVER_FAILED', message);
45
+ }
46
+ }
47
+ const asString = (value, name, origin) => {
48
+ if (typeof value === 'string' && value)
49
+ return value;
50
+ throw new SignInError('SERVER_FAILED', `The server ${origin} sent no ${name}.`);
51
+ };
52
+ const positive = (value, fallback) => (Number(value) > 0 ? Number(value) : fallback);
53
+ /** The approval page; it must be on the server signed in to (a link elsewhere could collect the code). */
54
+ function approvalPages(json, origin) {
55
+ const uri = asString(json.verification_uri, 'verification address', origin);
56
+ if (new URL(uri).origin !== origin) {
57
+ throw new SignInError('SERVER_FAILED', `The server ${origin} named an approval page on another site.`);
58
+ }
59
+ const complete = json.verification_uri_complete;
60
+ const sameSite = typeof complete === 'string' && new URL(complete).origin === origin;
61
+ return { uri, complete: sameSite ? complete : uri };
62
+ }
63
+ export async function startDeviceSignIn(origin) {
64
+ const { status, json } = await post(origin, '/api/auth/device/code', { client: clientName(), host: os.hostname() });
65
+ if (status !== 200) {
66
+ const error = (json.error ?? {});
67
+ const reason = error.message ?? `HTTP ${status}`;
68
+ throw new SignInError(error.code ?? 'SIGN_IN_REFUSED', `The server refused to start a sign-in: ${reason}`);
69
+ }
70
+ const pages = approvalPages(json, origin);
71
+ return {
72
+ deviceCode: asString(json.device_code, 'device code', origin),
73
+ userCode: asString(json.user_code, 'user code', origin),
74
+ verificationUri: pages.uri,
75
+ verificationUriComplete: pages.complete,
76
+ expiresInS: positive(json.expires_in, 600),
77
+ intervalS: positive(json.interval, 5),
78
+ };
79
+ }
80
+ /** A failure worth waiting out: the network, a timeout, a gateway or an overloaded server. */
81
+ const transient = (status) => status === 429 || status >= 500;
82
+ /** A sleep that ends early with SignInCancelled when `signal` aborts. */
83
+ export function abortableSleep(signal) {
84
+ return (ms) => new Promise((resolve, reject) => {
85
+ if (signal.aborted)
86
+ return reject(new SignInCancelled());
87
+ const timer = setTimeout(() => {
88
+ signal.removeEventListener('abort', onAbort);
89
+ resolve();
90
+ }, ms);
91
+ const onAbort = () => {
92
+ clearTimeout(timer);
93
+ reject(new SignInCancelled());
94
+ };
95
+ signal.addEventListener('abort', onAbort, { once: true });
96
+ });
97
+ }
98
+ async function poll(origin, start) {
99
+ try {
100
+ return await post(origin, '/api/auth/device/token', { device_code: start.deviceCode });
101
+ }
102
+ catch (error) {
103
+ if (!(error instanceof SignInError && error.code === 'SERVER_UNREACHABLE'))
104
+ throw error;
105
+ return { status: 503, json: {} };
106
+ }
107
+ }
108
+ const EXPIRED = `The code expired before it was approved; run \`${COMMAND} login\` again.`;
109
+ function refusedSignIn({ status, json }) {
110
+ const denied = 'The sign-in was denied in the browser.';
111
+ if (json.error === 'access_denied')
112
+ return new SignInError('SIGN_IN_DENIED', denied);
113
+ if (json.error === 'expired_token')
114
+ return new SignInError('SIGN_IN_EXPIRED', EXPIRED);
115
+ const detail = typeof json.error === 'string' ? `, ${json.error}` : '';
116
+ return new SignInError('SIGN_IN_FAILED', `The server refused the sign-in (HTTP ${status}${detail}).`);
117
+ }
118
+ function signedIn(json, origin) {
119
+ const email = json.account_email;
120
+ const token = asString(json.access_token, 'token', origin);
121
+ return { token, email: typeof email === 'string' && email.length <= 320 ? email : null };
122
+ }
123
+ const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
124
+ /**
125
+ * Polls until the sign-in is approved (the token, with the account's e-mail address when the server says
126
+ * it), denied or expired (a SignInError). A transient failure doubles the wait, up to a minute.
127
+ */
128
+ export async function waitForSignIn(origin, start, { sleep = realSleep, now = Date.now } = {}) {
129
+ let intervalS = start.intervalS;
130
+ let backoffS = 0;
131
+ const deadline = now() + start.expiresInS * 1000;
132
+ while (now() < deadline) {
133
+ await sleep((backoffS || intervalS) * 1000);
134
+ const answer = await poll(origin, start);
135
+ if (transient(answer.status) && answer.json.error === undefined) {
136
+ backoffS = Math.min(MAX_BACKOFF_S, Math.max(intervalS, backoffS) * 2);
137
+ continue;
138
+ }
139
+ backoffS = 0;
140
+ if (answer.status === 200)
141
+ return signedIn(answer.json, origin);
142
+ if (answer.json.error === 'authorization_pending')
143
+ continue;
144
+ if (answer.json.error === 'slow_down') {
145
+ intervalS += 5;
146
+ continue;
147
+ }
148
+ throw refusedSignIn(answer);
149
+ }
150
+ throw new SignInError('SIGN_IN_EXPIRED', EXPIRED);
151
+ }
152
+ /** Revokes the token on its server. False when the server could not be asked. */
153
+ export async function revokeToken(origin, token) {
154
+ try {
155
+ const { status } = await post(origin, '/api/auth/logout', {}, { authorization: `Bearer ${token}` });
156
+ return status === 204;
157
+ }
158
+ catch {
159
+ return false;
160
+ }
161
+ }
@@ -0,0 +1,14 @@
1
+ import { type CoreCaller } from '@foliwake/core-contract';
2
+ export declare const RPC_PATH = "/api/rpc";
3
+ /** The header the caller names its client in; servers log it. */
4
+ export declare const CLI_HEADER = "X-Foliwake-Cli";
5
+ export interface RemoteCallerOptions {
6
+ origin: string;
7
+ token: string | null;
8
+ /** The procedures this client knows, with their kind (default: the contract's). */
9
+ manifest?: Readonly<Record<string, 'query' | 'mutation'>>;
10
+ /** Sent as X-Foliwake-Cli (default: this package's name and version). */
11
+ client?: string;
12
+ fetch?: typeof fetch;
13
+ }
14
+ export declare function createRemoteCaller(options: RemoteCallerOptions): CoreCaller;
@@ -0,0 +1,52 @@
1
+ // A core caller that calls a server: `core.sites.status(input)` becomes the tRPC query `sites.status` on
2
+ // `<server>/api/rpc`, with the sign-in token. Which procedures exist and which are queries comes from the
3
+ // contract (`@foliwake/core-contract`); a server's `CoreError` arrives as a `CoreFailure`.
4
+ import { PROCEDURES } from '@foliwake/core-contract';
5
+ import { clientName } from '../version.js';
6
+ import { CoreFailure } from './core-failure.js';
7
+ import { RpcError, RpcTransportError, rpcCall } from './rpc-wire.js';
8
+ export const RPC_PATH = '/api/rpc';
9
+ /** The header the caller names its client in; servers log it. */
10
+ export const CLI_HEADER = 'X-Foliwake-Cli';
11
+ function unreachable(origin, cause) {
12
+ const message = `The server ${origin} cannot be reached or did not answer as a Foliwake server.`;
13
+ return new CoreFailure({ code: 'SERVER_UNREACHABLE', category: 'unavailable', retryable: true, message }, cause);
14
+ }
15
+ function failureOf(error, origin) {
16
+ if (error instanceof RpcTransportError)
17
+ return unreachable(origin, error);
18
+ if (error instanceof RpcError) {
19
+ const coreError = error.data?.coreError;
20
+ if (coreError)
21
+ return new CoreFailure(coreError, error);
22
+ if (error.data == null)
23
+ return unreachable(origin, error);
24
+ }
25
+ const message = `The server ${origin} answered unexpectedly.`;
26
+ return new CoreFailure({ code: 'SERVER_FAILED', category: 'internal', retryable: false, message }, error);
27
+ }
28
+ function headersOf(token, client) {
29
+ return { [CLI_HEADER]: client, ...(token ? { authorization: `Bearer ${token}` } : {}) };
30
+ }
31
+ export function createRemoteCaller(options) {
32
+ const { origin, token, manifest = PROCEDURES, client = clientName(), fetch: fetchImpl = fetch } = options;
33
+ const headers = headersOf(token, client);
34
+ const call = async (path, input) => {
35
+ const type = Object.hasOwn(manifest, path) ? manifest[path] : undefined;
36
+ if (type === undefined)
37
+ throw new TypeError(`core has no procedure ${path}`);
38
+ const url = `${origin}${RPC_PATH}/${path}`;
39
+ try {
40
+ return await rpcCall({ url, type, input, headers, fetch: fetchImpl });
41
+ }
42
+ catch (error) {
43
+ throw failureOf(error, origin);
44
+ }
45
+ };
46
+ const node = (path) => new Proxy(() => { }, {
47
+ get: (_target, key) => (typeof key === 'string' && key !== 'then' ? node([...path, key]) : undefined),
48
+ apply: (_target, _this, args) => call(path.join('.'), args[0]),
49
+ });
50
+ // The proxy answers every path the contract's type allows; `call` refuses one the manifest lacks.
51
+ return node([]);
52
+ }
@@ -0,0 +1,18 @@
1
+ export type ProcedureType = 'query' | 'mutation';
2
+ /** The server answered with tRPC's error shape; `data` holds its `coreError`. */
3
+ export declare class RpcError extends Error {
4
+ readonly data: Record<string, unknown> | null;
5
+ constructor(message: string, data: Record<string, unknown> | null);
6
+ }
7
+ /** No answer, or one that is not tRPC's: a network failure, a proxy's page, a wrong address. */
8
+ export declare class RpcTransportError extends Error {
9
+ }
10
+ export interface RpcRequest {
11
+ url: string;
12
+ type: ProcedureType;
13
+ input: unknown;
14
+ headers: Record<string, string>;
15
+ fetch: typeof fetch;
16
+ }
17
+ /** One call; resolves to `result.data`, rejects with RpcError or RpcTransportError. */
18
+ export declare function rpcCall(request: RpcRequest): Promise<unknown>;
@@ -0,0 +1,57 @@
1
+ // tRPC's HTTP wire as a Foliwake server speaks it on `/api/rpc` (no transformer, no batching): a query is
2
+ // `GET <path>?input=<JSON>`, a mutation `POST <path>` with the JSON input; the answer is
3
+ // `{ result: { data } }` or `{ error: { message, code, data } }`. Written out here, so the CLI needs no
4
+ // tRPC packages.
5
+ /** The server answered with tRPC's error shape; `data` holds its `coreError`. */
6
+ export class RpcError extends Error {
7
+ data;
8
+ constructor(message, data) {
9
+ super(message);
10
+ this.data = data;
11
+ }
12
+ }
13
+ /** No answer, or one that is not tRPC's: a network failure, a proxy's page, a wrong address. */
14
+ export class RpcTransportError extends Error {
15
+ }
16
+ function requestOf({ url, type, input, headers }) {
17
+ if (type === 'query') {
18
+ const query = input === undefined ? '' : `?input=${encodeURIComponent(JSON.stringify(input))}`;
19
+ return { url: `${url}${query}`, init: { method: 'GET', headers } };
20
+ }
21
+ const body = input === undefined ? undefined : JSON.stringify(input);
22
+ return { url, init: { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body } };
23
+ }
24
+ async function answerOf(response) {
25
+ try {
26
+ const json = (await response.json());
27
+ if (json && typeof json === 'object')
28
+ return json;
29
+ }
30
+ catch {
31
+ // not JSON: below
32
+ }
33
+ throw new RpcTransportError(`HTTP ${response.status} without a tRPC answer`);
34
+ }
35
+ function failure(error) {
36
+ const shape = (error && typeof error === 'object' ? error : {});
37
+ const data = shape.data && typeof shape.data === 'object' ? shape.data : null;
38
+ return new RpcError(typeof shape.message === 'string' ? shape.message : 'tRPC error', data);
39
+ }
40
+ /** One call; resolves to `result.data`, rejects with RpcError or RpcTransportError. */
41
+ export async function rpcCall(request) {
42
+ const { url, init } = requestOf(request);
43
+ let response;
44
+ try {
45
+ response = await request.fetch(url, init);
46
+ }
47
+ catch (error) {
48
+ throw new RpcTransportError(error instanceof Error ? error.message : String(error));
49
+ }
50
+ const answer = await answerOf(response);
51
+ if ('error' in answer)
52
+ throw failure(answer.error);
53
+ const result = answer.result;
54
+ if (!result || typeof result !== 'object')
55
+ throw new RpcTransportError(`HTTP ${response.status}: no result`);
56
+ return result.data;
57
+ }
@@ -0,0 +1,80 @@
1
+ import type { CoreOutput } from '@foliwake/core-contract';
2
+ export type Grant = CoreOutput<'whoami'>;
3
+ export type Membership = Grant['memberships'][number];
4
+ /**
5
+ * Foliwake Cloud: the reserved server name `cloud`. The Cloud is not available yet; its origin is
6
+ * CLOUD_ORIGIN (FOLIWAKE_CLOUD_ORIGIN overrides it, for tests or a move). A sign-in to it is kept under
7
+ * "cloud", never by its URL.
8
+ */
9
+ export declare const CLOUD = "cloud";
10
+ export declare const CLOUD_ORIGIN = "https://cloud.foliwake.org";
11
+ export declare const CLOUD_TITLE = "Foliwake Cloud";
12
+ /** Said when someone names the cloud: it does not exist yet. */
13
+ export declare const CLOUD_NOTE: string;
14
+ /** True when the cloud's origin was set for this run (FOLIWAKE_CLOUD_ORIGIN): only then may `cloud` be used. */
15
+ export declare function cloudConfigured(env?: NodeJS.ProcessEnv): boolean;
16
+ export type CredentialStoreKind = 'keychain' | 'secret-service' | 'file';
17
+ export interface ServerProfile {
18
+ principal: string;
19
+ memberships: Membership[];
20
+ installation: boolean;
21
+ signedInAt: string;
22
+ store: CredentialStoreKind;
23
+ /** The account's e-mail address, when the server said it at sign-in. */
24
+ email?: string | null;
25
+ /** The origin that issued the token; its token is sent there only. Absent in old profiles kept by origin. */
26
+ origin?: string;
27
+ }
28
+ export interface Profiles {
29
+ /** The server (its name) commands call when nothing else names one: the last `login`. */
30
+ default: string | null;
31
+ servers: Record<string, ServerProfile>;
32
+ /** Servers this computer signed out of (offered again by `create`); no secrets. */
33
+ signedOut: string[];
34
+ }
35
+ export declare class ServerAddressError extends Error {
36
+ }
37
+ /** The cloud's origin: FOLIWAKE_CLOUD_ORIGIN, else CLOUD_ORIGIN. */
38
+ export declare function cloudOrigin(env?: NodeJS.ProcessEnv): string;
39
+ /** A server's origin from what a person typed: "cloud", an origin, or a host meaning https. */
40
+ export declare function serverOrigin(typed: string, env?: NodeJS.ProcessEnv): string;
41
+ /** The name this computer remembers a server by: "cloud" for the cloud's origin, else the origin. */
42
+ export declare function serverName(origin: string, env?: NodeJS.ProcessEnv): string;
43
+ /** The origin of a remembered name ("cloud" or an origin); null for a name that is neither. */
44
+ export declare function nameOrigin(name: string, env?: NodeJS.ProcessEnv): string | null;
45
+ /** How a server is printed: "cloud (https://foliwake.dev)" for the cloud, else its origin. */
46
+ export declare function serverDisplay(origin: string, env?: NodeJS.ProcessEnv): string;
47
+ export declare function readProfiles(env?: NodeJS.ProcessEnv): Profiles;
48
+ export declare function writeProfiles(profiles: Profiles, env?: NodeJS.ProcessEnv): void;
49
+ /** A remembered sign-in: its key in servers.json and the credential store, its profile, its token's issuer. */
50
+ export interface SignInEntry {
51
+ key: string;
52
+ profile: ServerProfile;
53
+ /** null: unknown (a "cloud" profile without its origin), so its token is never sent. */
54
+ issuer: string | null;
55
+ }
56
+ /** The origin that issued a profile's token: recorded, else its key when that is an origin. */
57
+ export declare function issuerOf(key: string, profile: ServerProfile): string | null;
58
+ /** The sign-in remembered for a server (by its origin), whether or not it may be used there. */
59
+ export declare function signInEntry(origin: string, env?: NodeJS.ProcessEnv, profiles?: Profiles): SignInEntry | null;
60
+ /** The profile of a server (by its origin) when its token was issued there, or null. */
61
+ export declare function profileOf(origin: string, env?: NodeJS.ProcessEnv): ServerProfile | null;
62
+ /** Why the sign-in kept for this origin may not be used there (issued by another origin); null otherwise. */
63
+ export declare function signInMoved(origin: string, env?: NodeJS.ProcessEnv): string | null;
64
+ /** Makes a signed-in server the default; false when this computer is not signed in to it. */
65
+ export declare function useServer(origin: string, env?: NodeJS.ProcessEnv): boolean;
66
+ /** The origin of the default server (the last `login`), or null. */
67
+ export declare function defaultOrigin(env?: NodeJS.ProcessEnv): string | null;
68
+ /** The server a command calls, and what named it. */
69
+ export interface Target {
70
+ origin: string;
71
+ from: 'flag' | 'connection' | 'environment' | 'login';
72
+ }
73
+ /**
74
+ * `--server`, then the folder's `.foliwake/connection.json`, then `FOLIWAKE_SERVER`, then the last `login`.
75
+ * Null: nothing names a server. Unlike the engine's CLI, nothing here is local: FOLIWAKE_CONFIG and
76
+ * foliwake.config.json are not read.
77
+ */
78
+ export declare function resolveTarget({ server }: {
79
+ server?: string | undefined;
80
+ }, env?: NodeJS.ProcessEnv, cwd?: string): Target | null;