@acryldev/blends-frame 0.2.8 → 0.2.10

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/lib/contract.d.ts CHANGED
@@ -439,9 +439,12 @@ export interface PulledPluginView {
439
439
  /** @throws when the value is not what a pull answers. */
440
440
  export declare function parsePulledPlugin(value: unknown): PulledPluginView;
441
441
  /** Whether the person can share to GitHub now, and when not, the single thing to do about it. */
442
- export type GithubReadiness = {
442
+ export type GithubReadiness =
443
+ /** `via: 'acryl'`: the connection made with ACRYL's own sign-in (shared with Control Center), which the person can disconnect; absent: gh's own login or the person's own token. */
444
+ {
443
445
  readonly status: 'ready';
444
446
  readonly account: string;
447
+ readonly via?: 'acryl';
445
448
  } | {
446
449
  readonly status: 'signed-out';
447
450
  readonly say: string;
@@ -1,44 +1,61 @@
1
1
  /**
2
- * Connect GitHub from the app, for a person who has never opened a terminal: GitHub's own browser sign-in (`gh auth login --web`), started by a button.
3
- *
4
- * gh prints a one-time code and the address github.com/login/device, then waits until the person enters the code there and says yes. This module runs
5
- * that one gh process, reads the code from what it prints, and reports where the sign-in is. No password or token passes through the app: the person
6
- * signs in on github.com, and gh keeps its credential where it always does. When the sign-in succeeded, `gh auth setup-git` lets git push over HTTPS
7
- * with the same account, which a share needs.
2
+ * Connect GitHub from the app, for a person who has never opened a terminal: the same GitHub sign-in ACRYL Control Center has (one implementation, in
3
+ * `@acryldev/app-persistence`), started by a button. GitHub's device flow gives a one-time code and the address github.com/login/device; this module shows them,
4
+ * asks GitHub every few seconds whether the person approved, and then the token is in `<ACRYL home>/github.json`, the file Control Center reads too, so signing
5
+ * in once counts in both. The token never passes through the page. The process's own `GH_TOKEN` is then that token, so the `gh` and `git` a share starts use it.
8
6
  *
9
7
  * One sign-in at a time. The owner (the frame's Host) disposes it with the plugin, which ends a sign-in still waiting.
10
8
  */
11
- import { type ChildProcess } from 'node:child_process';
9
+ import { type GithubConnection } from '@acryldev/app-persistence';
12
10
  import type { GithubConnectState } from './contract.ts';
13
11
  export type { GithubConnectState };
14
- /** What this module needs from the computer: start gh's sign-in, and run one gh command to the end. Tests give their own. */
12
+ type FetchLike = typeof fetch;
13
+ /** What this module needs from the computer. Tests give their own. */
15
14
  export interface GithubConnectPorts {
16
- /** Start `gh auth login --web`; undefined when gh is not installed. */
17
- readonly startLogin: () => ChildProcess | undefined;
18
- /** Run `gh <args>` to the end; the exit status (non-zero when gh is missing). */
19
- readonly run: (args: readonly string[]) => number;
15
+ /** ACRYL's home: where `github.json` is, the same one Control Center uses. */
16
+ readonly home: string;
17
+ /** The process environment: its `GH_TOKEN` is what the `gh` and `git` a share starts read. */
18
+ readonly env: Record<string, string | undefined>;
19
+ /** The OAuth client id; undefined when none is valid. */
20
+ readonly clientId?: () => string | undefined;
21
+ readonly fetch?: FetchLike;
22
+ }
23
+ export interface GithubConnectOptions {
24
+ /** How long a code is waited for before giving up (GitHub's own is 15 minutes). */
25
+ readonly giveUpMs?: number;
26
+ /** Milliseconds between asking GitHub; GitHub's own interval when absent (a test sets it short). */
27
+ readonly pollMs?: number;
20
28
  }
21
- export declare const GITHUB_CONNECT_MISSING = "Connecting needs a free helper program from GitHub, and it is not installed on this computer. Install it from cli.github.com, then try again.";
22
- /** The gh this computer has, without a terminal: no prompts, no browser opened by gh itself (the page offers the link). */
23
- export declare function githubConnectPorts(): GithubConnectPorts;
29
+ export declare const GITHUB_CONNECT_UNAVAILABLE = "GitHub could not be reached. Check your internet connection and try again.";
30
+ export declare const GITHUB_CONNECT_NO_CLIENT = "GitHub sign-in is not set up in this copy of ACRYL.";
24
31
  export declare class GithubConnect {
25
32
  private readonly ports;
26
- private readonly giveUpMs;
33
+ private readonly options;
27
34
  private current;
28
- private child;
29
35
  private timer;
36
+ private giveUp;
37
+ /** Counts sign-ins: a poll still in flight when the sign-in ended or a new one began must not touch the state. */
38
+ private generation;
30
39
  private disposed;
31
- constructor(ports: GithubConnectPorts, giveUpMs?: number);
40
+ /** The token this process took into its environment from the file; a token the person's own environment named is never replaced. */
41
+ private adopted;
42
+ constructor(ports: GithubConnectPorts, options?: GithubConnectOptions);
32
43
  state(): GithubConnectState;
44
+ /** The stored connection, `{ token, login }`, or undefined. */
45
+ connection(): GithubConnection | undefined;
33
46
  /**
34
- * Start a sign-in, or return the one already waiting. Resolves when the code is known (or the start failed), which is well before the person
35
- * finishes on github.com; ask `state()` for the rest.
47
+ * Make the stored connection the one `gh` and `git` use in this process, unless the environment already names a token of the person's own.
48
+ * Returns whether the stored connection is the one in use.
36
49
  */
50
+ adopt(): boolean;
51
+ /** Forget the connection for every ACRYL place, and stop this process using it. Returns whether there was one. */
52
+ disconnect(): boolean;
53
+ /** Start a sign-in, or return the one already waiting. Resolves when the code is known (or the start failed); ask `state()` for the rest. */
37
54
  start(): Promise<GithubConnectState>;
38
55
  /** End a waiting sign-in (the person closed the chooser, or the plugin unloads). Nothing on GitHub changes. */
39
56
  cancel(): void;
40
57
  dispose(): void;
58
+ private schedule;
59
+ private poll;
41
60
  private finish;
42
- /** The code usually arrives within a second; give up waiting for it after a few, and let the page ask again. */
43
- private waitForCode;
44
61
  }
package/lib/index.d.ts CHANGED
@@ -78,6 +78,8 @@ export interface PluginsPort {
78
78
  start(): Promise<GithubConnectState>;
79
79
  state(): GithubConnectState;
80
80
  cancel(): void;
81
+ /** Forget the connection ACRYL made, for every ACRYL place; answers with the readiness that is left. */
82
+ disconnect(): Promise<GithubReadiness>;
81
83
  };
82
84
  }
83
85
  /** A note's screenshot as the frame serves it: the bytes and their image type. */
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { appGeneration } from "./app-generation.js";
2
2
  import { createRequire } from "node:module";
3
- import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
3
+ import { execFile, execFileSync, spawn } from "node:child_process";
4
4
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
5
5
  import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -16,6 +16,7 @@ import { digestFolder } from "@acryldev/blends-core";
16
16
  import { parseDocument } from "yaml";
17
17
  import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
18
18
  import { randomBytes } from "node:crypto";
19
+ import { clearGithub, githubClientId, githubHome, pollGithubSignIn, readGithub, startGithubSignIn } from "@acryldev/app-persistence";
19
20
  // src/contract.ts
20
21
  /** The one route the frame's client reads: what the frame shows around the app, from the Host that serves it. */
21
22
  const FRAME_API_PREFIX = "/api/acryl-blends-frame";
@@ -3213,153 +3214,139 @@ async function upstreamHead(git, root) {
3213
3214
  }
3214
3215
  // src/github-connect.ts
3215
3216
  /**
3216
- * Connect GitHub from the app, for a person who has never opened a terminal: GitHub's own browser sign-in (`gh auth login --web`), started by a button.
3217
- *
3218
- * gh prints a one-time code and the address github.com/login/device, then waits until the person enters the code there and says yes. This module runs
3219
- * that one gh process, reads the code from what it prints, and reports where the sign-in is. No password or token passes through the app: the person
3220
- * signs in on github.com, and gh keeps its credential where it always does. When the sign-in succeeded, `gh auth setup-git` lets git push over HTTPS
3221
- * with the same account, which a share needs.
3217
+ * Connect GitHub from the app, for a person who has never opened a terminal: the same GitHub sign-in ACRYL Control Center has (one implementation, in
3218
+ * `@acryldev/app-persistence`), started by a button. GitHub's device flow gives a one-time code and the address github.com/login/device; this module shows them,
3219
+ * asks GitHub every few seconds whether the person approved, and then the token is in `<ACRYL home>/github.json`, the file Control Center reads too, so signing
3220
+ * in once counts in both. The token never passes through the page. The process's own `GH_TOKEN` is then that token, so the `gh` and `git` a share starts use it.
3222
3221
  *
3223
3222
  * One sign-in at a time. The owner (the frame's Host) disposes it with the plugin, which ends a sign-in still waiting.
3224
3223
  */
3225
- const DEVICE_URL = "https://github.com/login/device";
3226
- const CODE = /\b([A-Z0-9]{4}-[A-Z0-9]{4})\b/u;
3227
- const URL_IN_TEXT = /https:\/\/github\.com\/login\/device\b/u;
3228
- /** How long a code stays usable on GitHub's side (15 minutes); after that this gives up and the person starts again. */
3229
- const GIVE_UP_MS = 9e5;
3230
- const GITHUB_CONNECT_MISSING = "Connecting needs a free helper program from GitHub, and it is not installed on this computer. Install it from cli.github.com, then try again.";
3231
- /** The gh this computer has, without a terminal: no prompts, no browser opened by gh itself (the page offers the link). */
3232
- function githubConnectPorts() {
3233
- const env = {
3234
- ...process.env,
3235
- GH_BROWSER: "true",
3236
- GH_PROMPT_DISABLED: "1",
3237
- GIT_TERMINAL_PROMPT: "0"
3238
- };
3239
- return {
3240
- startLogin: () => {
3241
- if (spawnSync("gh", ["--version"], {
3242
- env,
3243
- encoding: "utf8"
3244
- }).error !== void 0) return void 0;
3245
- return spawn("gh", [
3246
- "auth",
3247
- "login",
3248
- "--hostname",
3249
- "github.com",
3250
- "--git-protocol",
3251
- "https",
3252
- "--web",
3253
- "--skip-ssh-key"
3254
- ], {
3255
- env,
3256
- stdio: [
3257
- "pipe",
3258
- "pipe",
3259
- "pipe"
3260
- ]
3261
- });
3262
- },
3263
- run: (args) => {
3264
- const result = spawnSync("gh", [...args], {
3265
- env,
3266
- encoding: "utf8"
3267
- });
3268
- return result.error !== void 0 ? 1 : result.status ?? 1;
3269
- }
3270
- };
3271
- }
3224
+ const GITHUB_CONNECT_UNAVAILABLE = "GitHub could not be reached. Check your internet connection and try again.";
3225
+ const GITHUB_CONNECT_NO_CLIENT = "GitHub sign-in is not set up in this copy of ACRYL.";
3272
3226
  var GithubConnect = class {
3273
3227
  ports;
3274
- giveUpMs;
3228
+ options;
3275
3229
  current = { status: "idle" };
3276
- child;
3277
3230
  timer;
3231
+ giveUp;
3232
+ /** Counts sign-ins: a poll still in flight when the sign-in ended or a new one began must not touch the state. */
3233
+ generation = 0;
3278
3234
  disposed = false;
3279
- constructor(ports, giveUpMs = GIVE_UP_MS) {
3235
+ /** The token this process took into its environment from the file; a token the person's own environment named is never replaced. */
3236
+ adopted;
3237
+ constructor(ports, options = {}) {
3280
3238
  this.ports = ports;
3281
- this.giveUpMs = giveUpMs;
3239
+ this.options = options;
3282
3240
  }
3283
3241
  state() {
3284
3242
  return this.current;
3285
3243
  }
3244
+ /** The stored connection, `{ token, login }`, or undefined. */
3245
+ connection() {
3246
+ return readGithub(this.ports.home);
3247
+ }
3286
3248
  /**
3287
- * Start a sign-in, or return the one already waiting. Resolves when the code is known (or the start failed), which is well before the person
3288
- * finishes on github.com; ask `state()` for the rest.
3249
+ * Make the stored connection the one `gh` and `git` use in this process, unless the environment already names a token of the person's own.
3250
+ * Returns whether the stored connection is the one in use.
3289
3251
  */
3252
+ adopt() {
3253
+ const stored = readGithub(this.ports.home);
3254
+ if (stored === void 0) return false;
3255
+ const env = this.ports.env;
3256
+ if (env["GITHUB_TOKEN"] || env["GH_TOKEN"] && env["GH_TOKEN"] !== this.adopted && env["GH_TOKEN"] !== stored.token) return false;
3257
+ env["GH_TOKEN"] = stored.token;
3258
+ this.adopted = stored.token;
3259
+ return true;
3260
+ }
3261
+ /** Forget the connection for every ACRYL place, and stop this process using it. Returns whether there was one. */
3262
+ disconnect() {
3263
+ const stored = readGithub(this.ports.home);
3264
+ const had = clearGithub(this.ports.home);
3265
+ const env = this.ports.env;
3266
+ if (stored !== void 0 && (env["GH_TOKEN"] === stored.token || env["GH_TOKEN"] === this.adopted)) delete env["GH_TOKEN"];
3267
+ this.adopted = void 0;
3268
+ return had;
3269
+ }
3270
+ /** Start a sign-in, or return the one already waiting. Resolves when the code is known (or the start failed); ask `state()` for the rest. */
3290
3271
  async start() {
3291
3272
  if (this.disposed) return this.current;
3292
- if (this.child !== void 0) return this.waitForCode();
3293
- const child = this.ports.startLogin();
3294
- if (child === void 0) {
3273
+ if (this.current.status === "code" || this.current.status === "starting") return this.current;
3274
+ const clientId = (this.ports.clientId ?? githubClientId)();
3275
+ if (clientId === void 0) {
3295
3276
  this.current = {
3296
3277
  status: "failed",
3297
- say: GITHUB_CONNECT_MISSING
3278
+ say: GITHUB_CONNECT_NO_CLIENT
3298
3279
  };
3299
3280
  return this.current;
3300
3281
  }
3301
- this.child = child;
3282
+ const mine = ++this.generation;
3302
3283
  this.current = { status: "starting" };
3303
- let said = "";
3304
- const read = (chunk) => {
3305
- said += String(chunk);
3306
- if (this.current.status !== "starting") return;
3307
- const code = CODE.exec(said)?.[1];
3308
- if (code !== void 0) this.current = {
3284
+ try {
3285
+ const code = await startGithubSignIn(clientId, this.ports.fetch);
3286
+ if (mine !== this.generation) return this.current;
3287
+ const url = code.verificationUri.startsWith("https://github.com/") ? code.verificationUri : "https://github.com/login/device";
3288
+ this.current = {
3309
3289
  status: "code",
3310
- code,
3311
- url: URL_IN_TEXT.exec(said)?.[0] ?? DEVICE_URL
3290
+ code: code.userCode,
3291
+ url
3312
3292
  };
3313
- };
3314
- child.stdout?.on("data", read);
3315
- child.stderr?.on("data", read);
3316
- child.stdin?.on("error", () => {});
3317
- child.stdin?.write("\n");
3318
- child.on("error", (cause) => this.finish({
3319
- status: "failed",
3320
- say: GITHUB_CONNECT_MISSING,
3321
- details: cause.message
3322
- }));
3323
- child.on("exit", (status) => {
3324
- if (status === 0) {
3325
- this.ports.run(["auth", "setup-git"]);
3326
- this.finish({ status: "connected" });
3327
- } else if (this.current.status !== "failed") this.finish({
3328
- status: "failed",
3329
- say: "GitHub did not finish connecting. Press Connect GitHub to try again.",
3330
- details: said.trim().split("\n").at(-1) ?? ""
3331
- });
3332
- });
3333
- this.timer = setTimeout(() => {
3334
- this.finish({
3293
+ this.giveUp = setTimeout(() => {
3294
+ this.finish({
3295
+ status: "failed",
3296
+ say: "The code ran out before GitHub was connected. Press Connect GitHub to get a new one."
3297
+ });
3298
+ }, this.options.giveUpMs ?? Math.min(code.expiresIn * 1e3, 9e5));
3299
+ this.schedule(clientId, code.deviceCode, this.options.pollMs ?? code.interval * 1e3, mine);
3300
+ } catch (cause) {
3301
+ if (mine !== this.generation) return this.current;
3302
+ this.current = {
3335
3303
  status: "failed",
3336
- say: "The code ran out before GitHub was connected. Press Connect GitHub to get a new one."
3337
- });
3338
- }, this.giveUpMs);
3339
- return this.waitForCode();
3304
+ say: GITHUB_CONNECT_UNAVAILABLE,
3305
+ details: cause instanceof Error ? cause.message : String(cause)
3306
+ };
3307
+ }
3308
+ return this.current;
3340
3309
  }
3341
3310
  /** End a waiting sign-in (the person closed the chooser, or the plugin unloads). Nothing on GitHub changes. */
3342
3311
  cancel() {
3343
- if (this.child === void 0) return;
3312
+ if (this.current.status !== "code" && this.current.status !== "starting") return;
3344
3313
  this.finish({ status: "idle" });
3345
3314
  }
3346
3315
  dispose() {
3347
3316
  this.disposed = true;
3348
3317
  this.cancel();
3349
3318
  }
3319
+ schedule(clientId, deviceCode, waitMs, mine) {
3320
+ this.timer = setTimeout(() => {
3321
+ this.poll(clientId, deviceCode, waitMs, mine);
3322
+ }, waitMs);
3323
+ }
3324
+ async poll(clientId, deviceCode, waitMs, mine) {
3325
+ if (mine !== this.generation) return;
3326
+ try {
3327
+ const answer = await pollGithubSignIn(this.ports.home, clientId, deviceCode, this.ports.fetch);
3328
+ if (mine !== this.generation) return;
3329
+ if (answer.state === "pending") this.schedule(clientId, deviceCode, answer.interval === void 0 || this.options.pollMs !== void 0 ? waitMs : answer.interval * 1e3, mine);
3330
+ else if (answer.state === "connected") {
3331
+ this.adopt();
3332
+ this.finish({ status: "connected" });
3333
+ } else this.finish({
3334
+ status: "failed",
3335
+ say: `GitHub was not connected: ${answer.reason}. Press Connect GitHub to try again.`
3336
+ });
3337
+ } catch (cause) {
3338
+ if (mine !== this.generation) return;
3339
+ this.schedule(clientId, deviceCode, waitMs, mine);
3340
+ }
3341
+ }
3350
3342
  finish(next) {
3343
+ this.generation += 1;
3351
3344
  if (this.timer !== void 0) clearTimeout(this.timer);
3345
+ if (this.giveUp !== void 0) clearTimeout(this.giveUp);
3352
3346
  this.timer = void 0;
3353
- const child = this.child;
3354
- this.child = void 0;
3355
- if (child !== void 0 && child.exitCode === null && child.signalCode === null) child.kill();
3347
+ this.giveUp = void 0;
3356
3348
  this.current = next;
3357
3349
  }
3358
- /** The code usually arrives within a second; give up waiting for it after a few, and let the page ask again. */
3359
- async waitForCode() {
3360
- for (let waited = 0; waited < 5e3 && this.current.status === "starting"; waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
3361
- return this.current;
3362
- }
3363
3350
  };
3364
3351
  // src/app-snapshot.ts
3365
3352
  /**
@@ -3914,6 +3901,14 @@ function frameRoutes({ state, report = () => {}, plugins, graph, feedback, branc
3914
3901
  });
3915
3902
  app.post(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, async (c) => c.json(await plugins.connect.start()));
3916
3903
  app.get(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, (c) => c.json(plugins.connect.state()));
3904
+ app.delete(FRAME_PLUGINS_GITHUB_PATH, ownPage, async (c) => {
3905
+ try {
3906
+ return c.json(await plugins.connect.disconnect());
3907
+ } catch (cause) {
3908
+ report(cause);
3909
+ return c.json(error("GitHub could not be disconnected"), 500);
3910
+ }
3911
+ });
3917
3912
  app.delete(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, (c) => {
3918
3913
  plugins.connect.cancel();
3919
3914
  return c.json(plugins.connect.state());
@@ -4139,7 +4134,20 @@ function apply(ctx, config = {}) {
4139
4134
  fiberState: entry.fiber?.state
4140
4135
  }));
4141
4136
  };
4142
- const githubConnect = new GithubConnect(githubConnectPorts());
4137
+ const githubConnect = new GithubConnect({
4138
+ home: githubHome(process.env),
4139
+ env: process.env
4140
+ });
4141
+ githubConnect.adopt();
4142
+ const githubNow = async () => {
4143
+ const stored = githubConnect.connection();
4144
+ const inUse = stored !== void 0 && process.env["GH_TOKEN"] === stored.token;
4145
+ const ready = githubReadiness(() => inUse && stored.login !== "" ? stored.login : githubSharePorts().host.login());
4146
+ return ready.status === "ready" && inUse ? {
4147
+ ...ready,
4148
+ via: "acryl"
4149
+ } : ready;
4150
+ };
4143
4151
  ctx.effect(() => () => {
4144
4152
  githubConnect.dispose();
4145
4153
  }, "@acryldev/blends-frame: connecting GitHub");
@@ -4168,8 +4176,18 @@ function apply(ctx, config = {}) {
4168
4176
  ...owner === void 0 ? {} : { owner }
4169
4177
  }, githubSharePorts()),
4170
4178
  save: async (name) => saveAppPlugin(root, ctx.appInstance.home, name),
4171
- github: async () => githubReadiness(() => githubSharePorts().host.login()),
4172
- connect: githubConnect,
4179
+ github: githubNow,
4180
+ connect: {
4181
+ start: () => githubConnect.start(),
4182
+ state: () => githubConnect.state(),
4183
+ cancel: () => {
4184
+ githubConnect.cancel();
4185
+ },
4186
+ disconnect: async () => {
4187
+ githubConnect.disconnect();
4188
+ return githubNow();
4189
+ }
4190
+ },
4173
4191
  registry: async () => readRegistryView(registryRead, async () => registryMarks()),
4174
4192
  pull: async (source) => {
4175
4193
  const share = pluginShareOf(() => ctx.get("pluginShare"));
@@ -4191,7 +4209,7 @@ function apply(ctx, config = {}) {
4191
4209
  const names = /* @__PURE__ */ new Set([...frameRows().map((row) => bareName(row.name)), ...listed.map((info) => bareName(info.name))]);
4192
4210
  const repos = new Set(listed.flatMap((info) => info.pulledFrom === void 0 ? [] : [repoOfSource(info.pulledFrom) ?? ""]).filter((repo) => repo !== ""));
4193
4211
  if (signedIn === void 0 || Date.now() - signedIn.at > 6e4) {
4194
- const ready = githubReadiness(() => githubSharePorts().host.login());
4212
+ const ready = await githubNow();
4195
4213
  signedIn = {
4196
4214
  at: Date.now(),
4197
4215
  account: ready.status === "ready" ? ready.account : void 0