@theholocron/dagobah 5.0.0-alpha.343 → 5.0.0-alpha.345

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,3 +29,9 @@ await serveHandler({
29
29
  - `superviseProcesses({ primary, companion })`: runs two processes in the foreground, each with its own extra
30
30
  environment; stops one when the other ends; Ctrl-C and a termination signal go to both and are not a failure. Resolves
31
31
  `{ exitCode, endedFirst, interrupted }`; rejects naming a program that is missing or cannot start.
32
+ - The GitHub App manifest flow, for creating an App from a manifest file: `buildAppManifest({ base, name, webhookUrl,
33
+ redirectUrl })` checks the shared part and adds the per-instance part (the webhook must be `https`);
34
+ `appManifestPage(action, manifest)` is the page that posts it to GitHub; `serveAppManifest({ state, page })` is a
35
+ one-shot loopback server that takes the one-time code (only with its `state`, and only for its own address);
36
+ `convertAppManifest(code)` exchanges the code for the App's id, private key and webhook secret. Names, permissions
37
+ and webhook URLs are arguments; nothing is Holocron-specific.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,71 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
+ /** The part of a GitHub App manifest that is the same for every instance of an App: what it may do and hear about. */
3
+ interface AppManifestBase {
4
+ /** The App's description. */
5
+ description?: string;
6
+ /** The App's homepage. */
7
+ url?: string;
8
+ /** Whether anyone can install it. Defaults to `false`. */
9
+ public?: boolean;
10
+ /** Permission name to `read`, `write` or `admin`. */
11
+ default_permissions: Record<string, string>;
12
+ /** Webhook events the App subscribes to. */
13
+ default_events: string[];
14
+ }
15
+ /** A GitHub App manifest as the manifest flow takes it. */
16
+ interface AppManifest extends AppManifestBase {
17
+ /** The App's name, unique across all of GitHub. */
18
+ name: string;
19
+ /** Where GitHub sends the browser, with the one-time code, after the App is created. */
20
+ redirect_url: string;
21
+ /** The webhook GitHub delivers events to. */
22
+ hook_attributes: {
23
+ /** The `https` URL events are delivered to. */
24
+ url: string;
25
+ /** Whether GitHub delivers events; always on for a new App. */
26
+ active: true;
27
+ };
28
+ }
29
+ /** What differs per instance of the App, with the shared part read from a file. */
30
+ interface BuildAppManifestInput {
31
+ /** The parsed manifest file: `default_permissions`, `default_events` and optionally `description`, `url`, `public`. */
32
+ base: unknown;
33
+ /** The App's name. */
34
+ name: string;
35
+ /** The `https` URL GitHub delivers webhooks to. */
36
+ webhookUrl: string;
37
+ /** Where GitHub sends the browser after the App is created. */
38
+ redirectUrl: string;
39
+ }
40
+ /**
41
+ * The manifest to post to GitHub: the shared part read from a file, with this instance's name, webhook and redirect.
42
+ * Throws a message that names the problem when the file or the webhook URL is not usable, so nothing reaches GitHub.
43
+ */
44
+ export declare function buildAppManifest(input: BuildAppManifestInput): AppManifest;
45
+ /**
46
+ * The page the local server shows: a form that posts the manifest to GitHub on load (the manifest flow takes a form
47
+ * post, not a link), with a button for a browser that blocks the script.
48
+ */
49
+ export declare function appManifestPage(action: string, manifest: AppManifest): string;
50
+ /** The App GitHub created, as far as this command keeps it. The client id and secret are left out: nothing uses them. */
51
+ interface ConvertedApp {
52
+ /** The numeric App id (`GITHUB_APP_ID`). Not a secret. */
53
+ id: number;
54
+ /** The App's URL name. */
55
+ slug: string;
56
+ /** The App's page. */
57
+ htmlUrl: string;
58
+ /** The private key, PEM. Shown by GitHub once. A secret. */
59
+ pem: string;
60
+ /** The secret webhook deliveries are signed with. A secret. */
61
+ webhookSecret: string;
62
+ }
63
+ /**
64
+ * Exchanges the one-time code from the manifest flow for the App's id, private key and webhook secret
65
+ * (`POST /app-manifests/{code}/conversions`, which takes no token). The code works once, and GitHub shows the key
66
+ * once. An error names the status, never the body: the body of a success is the secrets.
67
+ */
68
+ export declare function convertAppManifest(code: string, fetchImpl?: typeof fetch): Promise<ConvertedApp>;
2
69
  /** What {@link loadDevEnv} needs: which 1Password Environment holds the secrets, and which variables must be set. */
3
70
  interface LoadDevEnvInput<K extends string = string> {
4
71
  /** The name of the 1Password Environment, e.g. `Sentinel - dev`. */
@@ -59,6 +126,30 @@ interface DevServer {
59
126
  * signature, token or payload reaches the terminal.
60
127
  */
61
128
  export declare function startDevServer<E>(input: DevServerInput<E>): Promise<DevServer>;
129
+ /** What the local server needs: the nonce GitHub must echo back, and how to draw the page once the port is known. */
130
+ interface ServeAppManifestInput {
131
+ /** The `state` GitHub must send back with the code. */
132
+ state: string;
133
+ /** The page for `/`, given the redirect URL on this server. */
134
+ page: (redirectUrl: string) => string;
135
+ /** How long to wait for GitHub's redirect, in milliseconds. Defaults to five minutes. */
136
+ timeoutMs?: number | undefined;
137
+ }
138
+ /** A running one-shot server. */
139
+ interface AppManifestServer {
140
+ /** The address to open in the browser. */
141
+ url: string;
142
+ /** Resolves with the one-time code GitHub sends back; rejects on timeout. */
143
+ code: Promise<string>;
144
+ /** Stops the server. Safe to call twice. */
145
+ close: () => void;
146
+ }
147
+ /**
148
+ * A one-shot server on a random loopback port: `/` shows the page that posts the manifest to GitHub, `/callback` takes
149
+ * the one-time code GitHub redirects back with. The code is only accepted with the `state` it was started with, and a
150
+ * request that does not name this server's own address (a DNS-rebinding page) is refused.
151
+ */
152
+ export declare function serveAppManifest(input: ServeAppManifestInput): Promise<AppManifestServer>;
62
153
  /** What {@link serveHandler} needs. */
63
154
  interface ServeHandlerInput<K extends string> {
64
155
  /** The 1Password Environment holding the secrets, unless the process already has every `required` variable. */
@@ -123,4 +214,4 @@ interface SuperviseProcessesResult {
123
214
  * that cannot be started stops the other and rejects, saying which program it was.
124
215
  */
125
216
  export declare function superviseProcesses(input: SuperviseProcessesInput): Promise<SuperviseProcessesResult>;
126
- export type { DescribeLoggingOptions, DevEnv, DevServer, DevServerInput, LoadDevEnvInput, ServeHandlerInput, SuperviseProcessesInput, SuperviseProcessesResult, SupervisedProcess };
217
+ export type { AppManifest, AppManifestBase, AppManifestServer, BuildAppManifestInput, ConvertedApp, DescribeLoggingOptions, DevEnv, DevServer, DevServerInput, LoadDevEnvInput, ServeAppManifestInput, ServeHandlerInput, SuperviseProcessesInput, SuperviseProcessesResult, SupervisedProcess };
package/dist/index.mjs CHANGED
@@ -1,6 +1,92 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { parse } from "dotenv";
3
3
  import { createServer } from "node:http";
4
+ // src/app-manifest-page/app-manifest-page.ts
5
+ const ESCAPES = {
6
+ "&": "&amp;",
7
+ "<": "&lt;",
8
+ ">": "&gt;",
9
+ "\"": "&quot;",
10
+ "'": "&#39;"
11
+ };
12
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => ESCAPES[c]);
13
+ /**
14
+ * The page the local server shows: a form that posts the manifest to GitHub on load (the manifest flow takes a form
15
+ * post, not a link), with a button for a browser that blocks the script.
16
+ */
17
+ function appManifestPage(action, manifest) {
18
+ return `<!doctype html>
19
+ <html lang="en">
20
+ <head><meta charset="utf-8"><title>Create ${escapeHtml(manifest.name)}</title></head>
21
+ <body>
22
+ <form id="form" method="post" action="${escapeHtml(action)}">
23
+ <input type="hidden" name="manifest" value="${escapeHtml(JSON.stringify(manifest))}">
24
+ <p>Sending the manifest to GitHub. If nothing happens, <button type="submit">continue</button>.</p>
25
+ </form>
26
+ <script>document.getElementById("form").submit();<\/script>
27
+ </body>
28
+ </html>
29
+ `;
30
+ }
31
+ // src/build-app-manifest/build-app-manifest.ts
32
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
33
+ /**
34
+ * The manifest to post to GitHub: the shared part read from a file, with this instance's name, webhook and redirect.
35
+ * Throws a message that names the problem when the file or the webhook URL is not usable, so nothing reaches GitHub.
36
+ */
37
+ function buildAppManifest(input) {
38
+ const { base } = input;
39
+ if (!isRecord(base)) throw new Error("the manifest file must hold a JSON object");
40
+ const permissions = base["default_permissions"];
41
+ if (!isRecord(permissions) || !Object.values(permissions).every((access) => typeof access === "string")) throw new Error("the manifest file needs a default_permissions object of permission name to access");
42
+ const events = base["default_events"];
43
+ if (!Array.isArray(events) || !events.every((event) => typeof event === "string")) throw new Error("the manifest file needs a default_events list of event names");
44
+ let webhook;
45
+ try {
46
+ webhook = new URL(input.webhookUrl);
47
+ } catch {
48
+ throw new Error(`the webhook URL is not a URL: ${input.webhookUrl}`);
49
+ }
50
+ if (webhook.protocol !== "https:") throw new Error("the webhook URL must be https: GitHub only delivers to one");
51
+ return {
52
+ name: input.name,
53
+ ...typeof base["description"] === "string" ? { description: base["description"] } : {},
54
+ ...typeof base["url"] === "string" ? { url: base["url"] } : {},
55
+ public: base["public"] === true,
56
+ redirect_url: input.redirectUrl,
57
+ hook_attributes: {
58
+ url: webhook.href,
59
+ active: true
60
+ },
61
+ default_permissions: permissions,
62
+ default_events: events
63
+ };
64
+ }
65
+ // src/convert-app-manifest/convert-app-manifest.ts
66
+ /**
67
+ * Exchanges the one-time code from the manifest flow for the App's id, private key and webhook secret
68
+ * (`POST /app-manifests/{code}/conversions`, which takes no token). The code works once, and GitHub shows the key
69
+ * once. An error names the status, never the body: the body of a success is the secrets.
70
+ */
71
+ async function convertAppManifest(code, fetchImpl = fetch) {
72
+ const response = await fetchImpl(`https://api.github.com/app-manifests/${encodeURIComponent(code)}/conversions`, {
73
+ method: "POST",
74
+ headers: {
75
+ accept: "application/vnd.github+json",
76
+ "x-github-api-version": "2022-11-28"
77
+ }
78
+ });
79
+ if (!response.ok) throw new Error(`GitHub did not convert the manifest (HTTP ${response.status})`);
80
+ const { id, slug, html_url: htmlUrl, pem, webhook_secret: webhookSecret } = await response.json();
81
+ if (typeof id !== "number" || typeof slug !== "string" || typeof htmlUrl !== "string" || typeof pem !== "string" || typeof webhookSecret !== "string") throw new Error("GitHub's answer did not hold the App id, private key and webhook secret");
82
+ return {
83
+ id,
84
+ slug,
85
+ htmlUrl,
86
+ pem,
87
+ webhookSecret
88
+ };
89
+ }
4
90
  // src/quote-pem/quote-pem.ts
5
91
  /**
6
92
  * Wrap an unquoted PEM block in double quotes. `op environment secret list --format=dotenv` prints a multi-line
@@ -63,7 +149,7 @@ function describeLogging(env, options) {
63
149
  return token && dataset ? `logs: shipped to Axiom, dataset "${dataset}"` : `logs: not shipped to Axiom (${options.tokenVar} and ${options.datasetVar} are not both set)`;
64
150
  }
65
151
  // src/dev-server/dev-server.ts
66
- const LOOPBACK = "127.0.0.1";
152
+ const LOOPBACK$1 = "127.0.0.1";
67
153
  /** GitHub caps a webhook payload at 25 MB; anything larger is not one. */
68
154
  const MAX_BODY = 27262976;
69
155
  /** The request body, or `undefined` when it is larger than a webhook can be. */
@@ -88,7 +174,7 @@ async function startDevServer(input) {
88
174
  const log = input.log ?? (() => {});
89
175
  const server = createServer(async (req, res) => {
90
176
  const method = req.method;
91
- const url = new URL(req.url, `http://${LOOPBACK}`);
177
+ const url = new URL(req.url, `http://${LOOPBACK$1}`);
92
178
  const reply = (status, body, headers = {}) => {
93
179
  log(`${method} ${url.pathname} ${status}`);
94
180
  res.writeHead(status, headers);
@@ -111,16 +197,66 @@ async function startDevServer(input) {
111
197
  reply(500, "Internal Server Error");
112
198
  }
113
199
  });
114
- await new Promise((resolve) => server.listen(input.port, LOOPBACK, resolve));
200
+ await new Promise((resolve) => server.listen(input.port, LOOPBACK$1, resolve));
115
201
  const { port } = server.address();
116
202
  return {
117
- url: `http://${LOOPBACK}:${port}${path}`,
203
+ url: `http://${LOOPBACK$1}:${port}${path}`,
118
204
  close: () => new Promise((resolve) => {
119
205
  server.close(() => resolve());
120
206
  server.closeAllConnections();
121
207
  })
122
208
  };
123
209
  }
210
+ // src/serve-app-manifest/serve-app-manifest.ts
211
+ const LOOPBACK = "127.0.0.1";
212
+ const FIVE_MINUTES = 3e5;
213
+ /**
214
+ * A one-shot server on a random loopback port: `/` shows the page that posts the manifest to GitHub, `/callback` takes
215
+ * the one-time code GitHub redirects back with. The code is only accepted with the `state` it was started with, and a
216
+ * request that does not name this server's own address (a DNS-rebinding page) is refused.
217
+ */
218
+ async function serveAppManifest(input) {
219
+ let resolveCode;
220
+ let rejectCode;
221
+ const code = new Promise((resolve, reject) => {
222
+ resolveCode = resolve;
223
+ rejectCode = reject;
224
+ });
225
+ code.catch(() => {});
226
+ const server = createServer((req, res) => {
227
+ const reply = (status, type, body) => {
228
+ res.writeHead(status, {
229
+ "content-type": `${type}; charset=utf-8`,
230
+ "cache-control": "no-store"
231
+ });
232
+ res.end(body);
233
+ };
234
+ const { port } = server.address();
235
+ if (req.headers.host !== `${LOOPBACK}:${port}`) return reply(403, "text/plain", "forbidden");
236
+ const url = new URL(req.url, `http://${LOOPBACK}:${port}`);
237
+ if (url.pathname === "/") return reply(200, "text/html", input.page(`http://${LOOPBACK}:${port}/callback`));
238
+ if (url.pathname === "/callback") {
239
+ const got = url.searchParams.get("code");
240
+ if (url.searchParams.get("state") !== input.state || !got) return reply(400, "text/plain", "bad request");
241
+ reply(200, "text/plain", "Done. You can close this tab and go back to the terminal.");
242
+ resolveCode(got);
243
+ return;
244
+ }
245
+ reply(404, "text/plain", "not found");
246
+ });
247
+ await new Promise((resolve) => server.listen(0, LOOPBACK, resolve));
248
+ const timer = setTimeout(() => rejectCode(/* @__PURE__ */ new Error("timed out waiting for GitHub: the App was not created")), input.timeoutMs ?? FIVE_MINUTES);
249
+ const close = () => {
250
+ clearTimeout(timer);
251
+ server.close();
252
+ server.closeAllConnections();
253
+ };
254
+ return {
255
+ url: `http://${LOOPBACK}:${server.address().port}/`,
256
+ code,
257
+ close
258
+ };
259
+ }
124
260
  // src/serve-handler/serve-handler.ts
125
261
  /**
126
262
  * Runs a web-standard handler locally: loads its environment, puts it in `process.env`, imports the handler, serves
@@ -222,4 +358,4 @@ function superviseProcesses(input) {
222
358
  }
223
359
  });
224
360
  }
225
- export { describeLogging, loadDevEnv, serveHandler, startDevServer, superviseProcesses };
361
+ export { appManifestPage, buildAppManifest, convertAppManifest, describeLogging, loadDevEnv, serveAppManifest, serveHandler, startDevServer, superviseProcesses };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/dagobah",
3
- "version": "5.0.0-alpha.343",
3
+ "version": "5.0.0-alpha.345",
4
4
  "description": "Local development server for a web-standard handler: loads its secrets from a 1Password Environment and serves it over HTTP behind a tunnel.",
5
5
  "keywords": [
6
6
  "dev-server",
@@ -43,8 +43,8 @@
43
43
  "typescript": "^5.9.3",
44
44
  "vitest": "^5.0.5",
45
45
  "@theholocron/tsconfig": "^8.9.0-alpha.8",
46
- "@theholocron/eslint-config": "^8.9.0-alpha.8",
47
46
  "@theholocron/tsdown-config": "^8.9.0-alpha.8",
47
+ "@theholocron/eslint-config": "^8.9.0-alpha.8",
48
48
  "@theholocron/vitest-config": "^8.9.0-alpha.8"
49
49
  },
50
50
  "engines": {