screw-bugs 0.1.1 → 0.1.3
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 +70 -20
- package/dist/browser-playwright/launch.js +3 -1
- package/dist/browser-playwright/page.d.ts +3 -11
- package/dist/browser-playwright/page.js +17 -1
- package/dist/browser-playwright/sign-in.d.ts +77 -0
- package/dist/browser-playwright/sign-in.js +217 -0
- package/dist/build-info.json +3 -3
- package/dist/cli/app.js +4 -1
- package/dist/cli/commands.js +68 -3
- package/dist/cli/exit-codes.d.ts +6 -0
- package/dist/cli/exit-codes.js +6 -0
- package/dist/cli/mcp.js +17 -3
- package/dist/cli/operations.d.ts +31 -3
- package/dist/cli/operations.js +95 -3
- package/dist/cli/sign-in.d.ts +79 -0
- package/dist/cli/sign-in.js +305 -0
- package/dist/core/accounts.d.ts +40 -0
- package/dist/core/accounts.js +95 -0
- package/dist/core/engine.d.ts +8 -4
- package/dist/core/engine.js +39 -9
- package/dist/core/errors.d.ts +19 -0
- package/dist/core/errors.js +6 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.js +1 -0
- package/dist/core/services.d.ts +77 -8
- package/dist/core/services.js +4 -1
- package/dist/report/bug.d.ts +2 -2
- package/dist/report/bug.js +5 -4
- package/dist/report/html.d.ts +1 -1
- package/dist/report/html.js +3 -2
- package/dist/report/icons.d.ts +2 -0
- package/dist/report/icons.js +4 -3
- package/dist/report/index.d.ts +2 -1
- package/dist/report/index.js +2 -1
- package/dist/report/markup.d.ts +2 -13
- package/dist/report/markup.js +8 -62
- package/dist/report/menu-bar.d.ts +60 -0
- package/dist/report/menu-bar.js +153 -0
- package/dist/report/player.d.ts +9 -4
- package/dist/report/player.js +24 -13
- package/dist/report/sign-in.d.ts +41 -0
- package/dist/report/sign-in.js +539 -0
- package/dist/report/styles.js +10 -34
- package/dist/report/walkthrough.d.ts +3 -2
- package/dist/report/walkthrough.js +50 -40
- package/dist/schema/accounts.d.ts +137 -0
- package/dist/schema/accounts.js +112 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/index.js +1 -0
- package/dist/schema/job.d.ts +27 -6
- package/dist/schema/job.js +12 -2
- package/dist/schema/ledger.d.ts +5 -1
- package/dist/store-local/accounts.d.ts +8 -4
- package/dist/store-local/accounts.js +82 -7
- package/dist/store-local/paths.d.ts +4 -1
- package/dist/store-local/paths.js +4 -1
- package/package.json +2 -2
package/dist/cli/mcp.js
CHANGED
|
@@ -3,7 +3,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
|
3
3
|
import { Effect, Option, Path, Schema } from 'effect';
|
|
4
4
|
import { describeOnScreen } from '../core/index.js';
|
|
5
5
|
import { LEDGER_FILE } from '../store-local/index.js';
|
|
6
|
-
import { CaseSpec, Device, Findings, REASON_MAX, } from '../schema/index.js';
|
|
6
|
+
import { CaseSpec, Device, Findings, JobAccount, REASON_MAX, } from '../schema/index.js';
|
|
7
7
|
import { MAX_WAIT_SECONDS, Operations } from './operations.js';
|
|
8
8
|
import { PackageInfo } from './package-info.js';
|
|
9
9
|
import { ReportServer } from './report-server.js';
|
|
@@ -15,7 +15,9 @@ import { UpdateCheck } from './update-check.js';
|
|
|
15
15
|
* and reason, screenshot IDs, timecodes, a few page facts and the steps whose element did not show
|
|
16
16
|
* on the screen (see `formatEvidence`), each field capped; the full pack is evidence.json. start_run whose upload files are missing or
|
|
17
17
|
* unusable starts nothing and lists the files needed, one line each (`formatFilesNeeded`), then
|
|
18
|
-
* one sentence asking the agent to create them, then the project folder.
|
|
18
|
+
* one sentence asking the agent to create them, then the project folder. start_run whose test
|
|
19
|
+
* account has no session to start from starts nothing either: one sentence, then the link of the
|
|
20
|
+
* sign-in it opened for the user, then `accounts.json`.
|
|
19
21
|
* Wherever the report is given, it is its http://127.0.0.1 URL (see `ReportServer`) in place of
|
|
20
22
|
* its path, for browsers built into coding tools, which cannot open file:// pages and whose file
|
|
21
23
|
* viewers do not play its video; the path only when there is no URL. Then the run's walkthrough
|
|
@@ -243,6 +245,18 @@ const StartRunInput = Schema.Struct({
|
|
|
243
245
|
'Bad: {"action":"expectText","text":"Email"} (a field label, there before and after).',
|
|
244
246
|
})),
|
|
245
247
|
device: Schema.optionalKey(Device),
|
|
248
|
+
account: Schema.optionalKey(JobAccount.annotate({
|
|
249
|
+
description: 'Leave it out to run signed out: a fresh browser with no cookies or storage, even when ' +
|
|
250
|
+
'accounts are saved (for public pages, the sign-up or sign-in flow itself, or what a ' +
|
|
251
|
+
'visitor sees). Give it to run signed in as a test account: ' +
|
|
252
|
+
'the label of one in .screw-bugs/accounts.json (in the ' +
|
|
253
|
+
'project; read it to pick the one whose about fits, such as a user on a trial or a paying ' +
|
|
254
|
+
'one), or {"label":"paid-user","about":"Pro plan, paying monthly"} for one the user signs ' +
|
|
255
|
+
"in to first. Every case starts signed in. When it has no saved session for this URL's " +
|
|
256
|
+
'origin, nothing starts and the reply gives a link: ask the user to sign in there, then ' +
|
|
257
|
+
'start the same job again. If its session stopped working (the run lands on a sign-in ' +
|
|
258
|
+
'page), give {"label":…,"renew":true} once to have the user sign in again.',
|
|
259
|
+
})),
|
|
246
260
|
});
|
|
247
261
|
const RunStatusInput = Schema.Struct({
|
|
248
262
|
jobId: Schema.NonEmptyString,
|
|
@@ -305,7 +319,7 @@ export const makeMcpServer = Effect.gen(function* () {
|
|
|
305
319
|
server.registerTool('start_run', {
|
|
306
320
|
description: 'Run your QA cases (structured steps) in a headless browser; returns a job ID immediately. Upload files are yours to create in the project (such as fixtures/), with synthetic content.',
|
|
307
321
|
inputSchema: input(StartRunInput),
|
|
308
|
-
}, (args) => run(ops.startRun({ spec: args }, { requireConfig: false }), ({ jobId, runDir }) => reply(`Started job ${jobId}; check it with run_status.`, [runDir])));
|
|
322
|
+
}, (args) => run(ops.startRun({ spec: args }, { requireConfig: false, signIn: 'serve' }), ({ jobId, runDir }) => reply(`Started job ${jobId}; check it with run_status.`, [runDir])));
|
|
309
323
|
server.registerTool('run_status', {
|
|
310
324
|
description: 'Get the state and case results of a run by job ID; an ended run gives its report and video walkthrough URLs.',
|
|
311
325
|
inputSchema: input(RunStatusInput),
|
package/dist/cli/operations.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Context, Effect, FileSystem, Layer, Path } from 'effect';
|
|
2
|
-
import { Browser, Engine, type RunSummary, Storage } from '../core/index.js';
|
|
3
|
-
import { type CaseLedger, type Device, type DoctorReport, type EvidencePack, JobId, type JobRecord, type PlacedMark, type ReportBundle } from '../schema/index.js';
|
|
2
|
+
import { AccountBook, Browser, Engine, type RunSummary, Storage } from '../core/index.js';
|
|
3
|
+
import { type AccountEntry, type CaseLedger, type Device, type DoctorReport, type EvidencePack, JobId, type JobRecord, type PlacedMark, type ReportBundle } from '../schema/index.js';
|
|
4
4
|
import { Failure } from './failure.js';
|
|
5
5
|
import { PackageInfo } from './package-info.js';
|
|
6
|
+
import { type SignInOutcome } from './sign-in.js';
|
|
6
7
|
/** How often a status call that waits rereads the ledger. */
|
|
7
8
|
export declare const STATUS_POLL_MS = 500;
|
|
8
9
|
/** The longest a status call may wait for a run to end. */
|
|
@@ -25,6 +26,12 @@ export interface AnswerInput {
|
|
|
25
26
|
readonly questionId: string;
|
|
26
27
|
readonly text: string;
|
|
27
28
|
}
|
|
29
|
+
export interface SignInInput {
|
|
30
|
+
readonly label: string;
|
|
31
|
+
/** Where the browser opens; the account is saved for its origin. */
|
|
32
|
+
readonly url: string;
|
|
33
|
+
readonly about?: string | undefined;
|
|
34
|
+
}
|
|
28
35
|
export interface InitInput {
|
|
29
36
|
readonly baseUrl?: string | undefined;
|
|
30
37
|
/** Overwrite an existing screw-bugs.json. */
|
|
@@ -62,12 +69,33 @@ declare const Operations_base: Context.ServiceClass<Operations, "screw-bugs/Oper
|
|
|
62
69
|
readonly init: (input: InitInput) => Effect.Effect<{
|
|
63
70
|
readonly path: string;
|
|
64
71
|
}, Failure>;
|
|
72
|
+
/**
|
|
73
|
+
* Starts a run. A job whose test account needs a person to sign in first starts nothing and
|
|
74
|
+
* fails with `SignInNeeded`: with `signIn: 'serve'` (a process that lives on, the MCP
|
|
75
|
+
* server), a sign-in is opened and its link given; otherwise the command that opens one.
|
|
76
|
+
*/
|
|
65
77
|
readonly startRun: (input: StartRunInput, options: {
|
|
66
78
|
readonly requireConfig: boolean;
|
|
79
|
+
readonly signIn?: 'serve' | 'command';
|
|
67
80
|
}) => Effect.Effect<{
|
|
68
81
|
readonly jobId: JobId;
|
|
69
82
|
readonly runDir: string;
|
|
70
83
|
}, Failure>;
|
|
84
|
+
/** The saved test accounts and the file that lists them. */
|
|
85
|
+
readonly accounts: Effect.Effect<{
|
|
86
|
+
readonly file: string;
|
|
87
|
+
readonly accounts: ReadonlyArray<AccountEntry>;
|
|
88
|
+
}, Failure>;
|
|
89
|
+
/**
|
|
90
|
+
* Opens a sign-in for an account (see `SignIns`): resolves with its link, and with the wait
|
|
91
|
+
* until the person saves, cancels or leaves it.
|
|
92
|
+
*/
|
|
93
|
+
readonly signIn: (input: SignInInput) => Effect.Effect<{
|
|
94
|
+
readonly link: string;
|
|
95
|
+
readonly done: Effect.Effect<SignInOutcome | undefined>;
|
|
96
|
+
}, Failure>;
|
|
97
|
+
/** Removes a saved account and its session; false when there was none. */
|
|
98
|
+
readonly removeAccount: (label: string) => Effect.Effect<boolean, Failure>;
|
|
71
99
|
/** Waits for a run started by this process to end. */
|
|
72
100
|
readonly awaitRun: (jobId: JobId) => Effect.Effect<RunResult, Failure>;
|
|
73
101
|
/** Stops a run started by this process and waits for its final report and ledger. */
|
|
@@ -120,7 +148,7 @@ declare const Operations_base: Context.ServiceClass<Operations, "screw-bugs/Oper
|
|
|
120
148
|
* server has no logic of its own.
|
|
121
149
|
*/
|
|
122
150
|
export declare class Operations extends Operations_base {
|
|
123
|
-
static readonly layer: (projectRoot: string) => Layer.Layer<Operations, never, Browser | Engine | FileSystem.FileSystem | PackageInfo | Path.Path | Storage>;
|
|
151
|
+
static readonly layer: (projectRoot: string) => Layer.Layer<Operations, never, AccountBook | Browser | Engine | FileSystem.FileSystem | PackageInfo | Path.Path | Storage>;
|
|
124
152
|
}
|
|
125
153
|
/**
|
|
126
154
|
* A Schema error message as one line per problem, in the form `checkFindings` uses:
|
package/dist/cli/operations.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Cause, Clock, Context, Duration, Effect, FileSystem, Layer, Option, Path, Predicate, Schedule, Schema, } from 'effect';
|
|
2
|
-
import { Browser, Engine, evidencePackOf, REPORT_STALE_MS, staleFor, Storage, } from '../core/index.js';
|
|
3
|
-
import { Findings, JobId, NewJobSpec, ProjectConfig, runFiles, } from '../schema/index.js';
|
|
2
|
+
import { AccountBook, Browser, describeSignInWhy, Engine, originOf, evidencePackOf, REPORT_STALE_MS, staleFor, Storage, } from '../core/index.js';
|
|
3
|
+
import { AccountAbout, AccountLabel, Findings, JobId, NewJobSpec, ProjectConfig, runFiles, } from '../schema/index.js';
|
|
4
4
|
import { CONFIG_FILE, loadConfig, missingConfig } from './config.js';
|
|
5
5
|
import { runDoctor } from './doctor.js';
|
|
6
6
|
import { ExitCode } from './exit-codes.js';
|
|
@@ -8,6 +8,8 @@ import { Failure, fromNotImplemented } from './failure.js';
|
|
|
8
8
|
import { PackageInfo } from './package-info.js';
|
|
9
9
|
import { UpdateCheck } from './update-check.js';
|
|
10
10
|
import { checkUploads, filesNeeded } from './uploads.js';
|
|
11
|
+
import { shellWord } from './install-method.js';
|
|
12
|
+
import { SignIns } from './sign-in.js';
|
|
11
13
|
/** How often a status call that waits rereads the ledger. */
|
|
12
14
|
export const STATUS_POLL_MS = 500;
|
|
13
15
|
/** The longest a status call may wait for a run to end. */
|
|
@@ -28,6 +30,8 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
|
|
|
28
30
|
const path = yield* Path.Path;
|
|
29
31
|
const packageInfo = yield* PackageInfo;
|
|
30
32
|
const updateCheck = yield* Effect.serviceOption(UpdateCheck);
|
|
33
|
+
const accountBook = yield* AccountBook;
|
|
34
|
+
const signIns = yield* Effect.serviceOption(SignIns);
|
|
31
35
|
/** What the operations below read and write the project with. */
|
|
32
36
|
const platform = (effect) => effect.pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.provideService(PackageInfo, packageInfo));
|
|
33
37
|
const decodeJobId = (raw) => Schema.decodeUnknownEffect(JobId)(raw).pipe(Effect.mapError(() => new Failure({
|
|
@@ -175,6 +179,61 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
|
|
|
175
179
|
`Run \`${video.command}\` to download it, then start the run again.`,
|
|
176
180
|
details: { command: video.command },
|
|
177
181
|
});
|
|
182
|
+
const decodeLabel = (raw) => Schema.decodeUnknownEffect(AccountLabel)(raw).pipe(Effect.mapError(() => new Failure({
|
|
183
|
+
code: ExitCode.Usage,
|
|
184
|
+
reason: 'invalid_account',
|
|
185
|
+
message: `"${raw}" is not an account label: use 1-40 lower-case letters, digits or dashes.`,
|
|
186
|
+
})));
|
|
187
|
+
/** The command a person runs to sign in to the account a job needs. */
|
|
188
|
+
const signInCommand = (needed) => [
|
|
189
|
+
'npx screw-bugs accounts sign-in',
|
|
190
|
+
needed.label,
|
|
191
|
+
'--url',
|
|
192
|
+
shellWord(needed.url),
|
|
193
|
+
...(needed.about !== undefined ? ['--about', shellWord(needed.about)] : []),
|
|
194
|
+
].join(' ');
|
|
195
|
+
/**
|
|
196
|
+
* Nothing started: a person has to sign in to the job's account first. A process that
|
|
197
|
+
* stays (`serve`) opens the sign-in now and gives its link; otherwise the command.
|
|
198
|
+
*/
|
|
199
|
+
const signInNeeded = (needed, mode) => Effect.gen(function* () {
|
|
200
|
+
const account = `test account "${needed.label}"` +
|
|
201
|
+
(needed.about !== undefined ? ` (${needed.about})` : '');
|
|
202
|
+
const why = describeSignInWhy(needed.why);
|
|
203
|
+
const details = {
|
|
204
|
+
account: needed.label,
|
|
205
|
+
...(needed.about !== undefined ? { about: needed.about } : {}),
|
|
206
|
+
origin: needed.origin,
|
|
207
|
+
why: needed.why._tag,
|
|
208
|
+
accountsFile: accountBook.file,
|
|
209
|
+
};
|
|
210
|
+
if (mode === 'serve' && Option.isSome(signIns)) {
|
|
211
|
+
const { link } = yield* signIns.value.begin({
|
|
212
|
+
label: needed.label,
|
|
213
|
+
about: needed.about,
|
|
214
|
+
origin: needed.origin,
|
|
215
|
+
url: needed.url,
|
|
216
|
+
});
|
|
217
|
+
return yield* new Failure({
|
|
218
|
+
code: ExitCode.SignInNeeded,
|
|
219
|
+
reason: 'sign_in_needed',
|
|
220
|
+
message: `Nothing was started: ${account} ${why}. Ask the user to open the link below, ` +
|
|
221
|
+
'sign in there as that user and press Save sign-in, then start the same job again.',
|
|
222
|
+
paths: [link, accountBook.file],
|
|
223
|
+
details: { ...details, signInUrl: link },
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
const command = signInCommand(needed);
|
|
227
|
+
return yield* new Failure({
|
|
228
|
+
code: ExitCode.SignInNeeded,
|
|
229
|
+
reason: 'sign_in_needed',
|
|
230
|
+
message: `Nothing was started: ${account} ${why}. Run \`${command}\`, sign in as that ` +
|
|
231
|
+
'user in the page it links and press Save sign-in, then start the run again.',
|
|
232
|
+
paths: [accountBook.file],
|
|
233
|
+
details: { ...details, command },
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
const accountsFailure = (error) => storageFailure(error);
|
|
178
237
|
return Operations.of({
|
|
179
238
|
doctor: runDoctor(projectRoot, undefined, Option.getOrUndefined(Option.map(updateCheck, (check) => check.doctorCheck))).pipe(Effect.provideService(Browser, browser), platform),
|
|
180
239
|
init: (input) => Effect.gen(function* () {
|
|
@@ -234,7 +293,7 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
|
|
|
234
293
|
if (uploads.needed.length > 0)
|
|
235
294
|
return yield* filesNeeded(projectRoot, uploads.needed);
|
|
236
295
|
const jobId = yield* engine.startRun(spec, { uploads: uploads.sources }).pipe(Effect.catchTags({
|
|
237
|
-
|
|
296
|
+
SignInNeeded: (e) => signInNeeded(e, options.signIn ?? 'command'),
|
|
238
297
|
StorageFailed: (e) => Effect.fail(storageFailure(e)),
|
|
239
298
|
}));
|
|
240
299
|
return { jobId, runDir: storage.runDir(jobId) };
|
|
@@ -322,6 +381,39 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
|
|
|
322
381
|
const path = yield* engine.writeWalkthrough(jobId).pipe(orRunNotFound(jobId));
|
|
323
382
|
return { path, reportPath: found };
|
|
324
383
|
}),
|
|
384
|
+
accounts: accountBook.list.pipe(Effect.map((accounts) => ({ file: accountBook.file, accounts })), Effect.mapError(accountsFailure)),
|
|
385
|
+
signIn: (input) => Effect.gen(function* () {
|
|
386
|
+
const label = yield* decodeLabel(input.label);
|
|
387
|
+
const about = input.about === undefined
|
|
388
|
+
? undefined
|
|
389
|
+
: yield* Schema.decodeUnknownEffect(AccountAbout)(input.about).pipe(Effect.mapError((error) => new Failure({
|
|
390
|
+
code: ExitCode.Usage,
|
|
391
|
+
reason: 'invalid_account',
|
|
392
|
+
message: `--about: ${error.message}`,
|
|
393
|
+
})));
|
|
394
|
+
const origin = originOf(input.url);
|
|
395
|
+
if (origin === undefined || !/^https?:$/.test(URL.parse(input.url)?.protocol ?? ''))
|
|
396
|
+
return yield* new Failure({
|
|
397
|
+
code: ExitCode.Usage,
|
|
398
|
+
reason: 'missing_url',
|
|
399
|
+
message: `"${input.url}" is not an http or https URL to sign in on.`,
|
|
400
|
+
});
|
|
401
|
+
if (Option.isNone(signIns))
|
|
402
|
+
return yield* new Failure({
|
|
403
|
+
code: ExitCode.Internal,
|
|
404
|
+
reason: 'sign_in_unavailable',
|
|
405
|
+
message: 'This process cannot open a sign-in.',
|
|
406
|
+
});
|
|
407
|
+
const saved = (yield* accountBook.list.pipe(Effect.mapError(accountsFailure))).find((a) => a.label === label);
|
|
408
|
+
const { link } = yield* signIns.value.begin({
|
|
409
|
+
label,
|
|
410
|
+
about: about ?? saved?.about,
|
|
411
|
+
origin,
|
|
412
|
+
url: input.url,
|
|
413
|
+
});
|
|
414
|
+
return { link, done: signIns.value.wait(label) };
|
|
415
|
+
}),
|
|
416
|
+
removeAccount: (raw) => decodeLabel(raw).pipe(Effect.flatMap((label) => accountBook.remove(label).pipe(Effect.mapError(accountsFailure)))),
|
|
325
417
|
listRuns: (limit) => storage.listRuns(limit).pipe(Effect.mapError(storageFailure)),
|
|
326
418
|
answer: (input) => Effect.gen(function* () {
|
|
327
419
|
const jobId = yield* decodeJobId(input.jobId);
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { Context, Deferred, Duration, Effect, Layer, Semaphore } from 'effect';
|
|
2
|
+
import { HttpClient, HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
3
|
+
import { AccountBook, Browser, type SignInBrowser } from '../core/index.js';
|
|
4
|
+
import { Failure } from './failure.js';
|
|
5
|
+
/** How long a sign-in waits without a request from its page before it ends. */
|
|
6
|
+
export declare const SIGN_IN_IDLE: Duration.Duration;
|
|
7
|
+
/** How long a request for the next frame waits for one (the page asks again right away). */
|
|
8
|
+
export declare const FRAME_WAIT_MS = 15000;
|
|
9
|
+
/** How long fetching the app's icon may take in all; the sign-in opens without it after. */
|
|
10
|
+
export declare const SIGN_IN_ICON_TIMEOUT: Duration.Duration;
|
|
11
|
+
/**
|
|
12
|
+
* `SCREW_BUGS_SIGN_IN_HOST`: the address the sign-in server listens on, and the host in its link.
|
|
13
|
+
* 127.0.0.1 unless set; set it to this machine's tailnet IP or name to sign in from another device.
|
|
14
|
+
*/
|
|
15
|
+
export declare const signInHost: Effect.Effect<string, never, never>;
|
|
16
|
+
/** How a sign-in ended. */
|
|
17
|
+
export type SignInOutcome = 'saved' | 'cancelled' | 'idle';
|
|
18
|
+
export interface SignInRequest {
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly about: string | undefined;
|
|
21
|
+
/** Where the session is saved for, and the site whose cookies are kept. */
|
|
22
|
+
readonly origin: string;
|
|
23
|
+
/** Where the browser opens. */
|
|
24
|
+
readonly url: string;
|
|
25
|
+
}
|
|
26
|
+
/** The app as the live view shows it: its title and its icon as an image data URL. */
|
|
27
|
+
export interface SignInSiteView {
|
|
28
|
+
readonly title: string | undefined;
|
|
29
|
+
readonly icon: string | undefined;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The app's icon as a `data:image/…` URL: the first of `urls` on `origin` that answers 200 with a
|
|
33
|
+
* shown image type (`siteIconType`), unencoded, of 1 to `SITE_ICON_BYTES_MAX` bytes. Fetched
|
|
34
|
+
* without cookies and without following redirects, reading no further than the chunk that crosses
|
|
35
|
+
* the limit, and given up after `SIGN_IN_ICON_TIMEOUT` in all; undefined when none.
|
|
36
|
+
*/
|
|
37
|
+
export declare const fetchSiteIcon: (origin: string, urls: ReadonlyArray<string>) => Effect.Effect<string | undefined, never, HttpClient.HttpClient>;
|
|
38
|
+
/**
|
|
39
|
+
* The live view's routes, under `/<token>/`: the page, `frame?after=<seq>` (the next frame, long
|
|
40
|
+
* polled; 204 when none came), and the posts `input`, `save` and `cancel`. Posts must be JSON
|
|
41
|
+
* (so another site's page cannot send one without a preflight, which is never answered) and come
|
|
42
|
+
* from the page itself (`Sec-Fetch-Site`, `Origin`). Every route answers 410 once the sign-in
|
|
43
|
+
* ended. Inputs, the save and the cancel run one at a time under `lock` (which whatever else ends
|
|
44
|
+
* the sign-in takes too), each checking first that it has not ended: a save sees every input
|
|
45
|
+
* played before it, and nothing is saved once it was cancelled, replaced or left idle.
|
|
46
|
+
*/
|
|
47
|
+
export declare const makeSignInApp: (options: {
|
|
48
|
+
readonly token: string;
|
|
49
|
+
readonly hosts: ReadonlySet<string>;
|
|
50
|
+
readonly request: SignInRequest;
|
|
51
|
+
readonly live: SignInBrowser;
|
|
52
|
+
/** The app's title and icon, shown on the page. */
|
|
53
|
+
readonly site: SignInSiteView;
|
|
54
|
+
readonly done: Deferred.Deferred<SignInOutcome>;
|
|
55
|
+
readonly lock: Semaphore.Semaphore;
|
|
56
|
+
/** Called on every request with the token, for the idle timer. */
|
|
57
|
+
readonly seen: Effect.Effect<void>;
|
|
58
|
+
readonly save: (session: string) => Effect.Effect<void, Failure>;
|
|
59
|
+
}) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, HttpServerRequest.HttpServerRequest>;
|
|
60
|
+
declare const SignIns_base: Context.ServiceClass<SignIns, "screw-bugs/SignIns", {
|
|
61
|
+
/**
|
|
62
|
+
* Opens a sign-in for the account, or gives the link of the one already open for it at the
|
|
63
|
+
* same origin (another origin's is ended first). Resolves with its link at once.
|
|
64
|
+
*/
|
|
65
|
+
readonly begin: (request: SignInRequest) => Effect.Effect<{
|
|
66
|
+
readonly link: string;
|
|
67
|
+
}, Failure>;
|
|
68
|
+
/** Waits for the sign-in open for `label` to end; undefined when none is open. */
|
|
69
|
+
readonly wait: (label: string) => Effect.Effect<SignInOutcome | undefined>;
|
|
70
|
+
}>;
|
|
71
|
+
/**
|
|
72
|
+
* The sign-ins this process holds open, one per account label. A long-lived process (the MCP
|
|
73
|
+
* server) gives the link in its reply and keeps the sign-in open until the person is done; the
|
|
74
|
+
* CLI waits for it (`screw-bugs accounts sign-in`).
|
|
75
|
+
*/
|
|
76
|
+
export declare class SignIns extends SignIns_base {
|
|
77
|
+
static readonly layer: Layer.Layer<SignIns, never, AccountBook | Browser | HttpClient.HttpClient>;
|
|
78
|
+
}
|
|
79
|
+
export {};
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { NodeHttpServer } from '@effect/platform-node';
|
|
2
|
+
// Boundary: NodeHttpServer serves a Node `http.Server`, made here.
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { Clock, Config, Context, DateTime, Deferred, Duration, Effect, Exit, Layer, Option, Schema, Scope, Semaphore, Stream, } from 'effect';
|
|
5
|
+
import { Base64 } from 'effect/encoding';
|
|
6
|
+
import { HttpClient, HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
7
|
+
import { SecureRandom } from 'effect/crypto';
|
|
8
|
+
import { AccountBook, Browser, SITE_ICON_BYTES_MAX, siteIconType, } from '../core/index.js';
|
|
9
|
+
import { hex, renderSignInPage, SIGN_IN_CSP } from '../report/index.js';
|
|
10
|
+
import { SignInInputs } from '../schema/index.js';
|
|
11
|
+
import { ExitCode } from './exit-codes.js';
|
|
12
|
+
import { Failure } from './failure.js';
|
|
13
|
+
/*
|
|
14
|
+
* Signing in to a test account: a headless browser at the app, which a person drives from a web
|
|
15
|
+
* page (the live view, `renderSignInPage`) in whatever browser reaches this machine: the one built
|
|
16
|
+
* into their coding tool, or a phone on their tailnet. Each sign-in gets a server of its own on a
|
|
17
|
+
* free port, bound to `SCREW_BUGS_SIGN_IN_HOST` (127.0.0.1 unless set), answering only under a
|
|
18
|
+
* random token and only to its own Host; it ends when the person saves or cancels, after
|
|
19
|
+
* `SIGN_IN_IDLE` without a request, or with the process. Only the session is kept: the cookies
|
|
20
|
+
* the browser sends to the app and its origin's storage, in the account book. Nothing typed is
|
|
21
|
+
* recorded.
|
|
22
|
+
*/
|
|
23
|
+
/** How long a sign-in waits without a request from its page before it ends. */
|
|
24
|
+
export const SIGN_IN_IDLE = Duration.minutes(15);
|
|
25
|
+
/** How long a request for the next frame waits for one (the page asks again right away). */
|
|
26
|
+
export const FRAME_WAIT_MS = 15_000;
|
|
27
|
+
/** How long fetching the app's icon may take in all; the sign-in opens without it after. */
|
|
28
|
+
export const SIGN_IN_ICON_TIMEOUT = Duration.seconds(3);
|
|
29
|
+
/** The largest input request taken: a few hundred inputs. */
|
|
30
|
+
const INPUT_BYTES_MAX = 256 * 1024;
|
|
31
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
32
|
+
/**
|
|
33
|
+
* `SCREW_BUGS_SIGN_IN_HOST`: the address the sign-in server listens on, and the host in its link.
|
|
34
|
+
* 127.0.0.1 unless set; set it to this machine's tailnet IP or name to sign in from another device.
|
|
35
|
+
*/
|
|
36
|
+
export const signInHost = Config.String('SCREW_BUGS_SIGN_IN_HOST').pipe(Config.map((value) => value.trim()), Config.withDefault('127.0.0.1'), Effect.orDie);
|
|
37
|
+
/** A host as it goes in a URL: an IPv6 address in brackets. */
|
|
38
|
+
const urlHost = (host) => (host.includes(':') ? `[${host}]` : host);
|
|
39
|
+
const randomToken = SecureRandom.SecureRandom.use((random) => random.randomBytes(32)).pipe(Effect.map(hex), Effect.provide(SecureRandom.layerWebCrypto));
|
|
40
|
+
/** Compares in time that does not depend on where the strings differ. */
|
|
41
|
+
const sameText = (a, b) => {
|
|
42
|
+
if (a.length !== b.length)
|
|
43
|
+
return false;
|
|
44
|
+
let diff = 0;
|
|
45
|
+
for (let i = 0; i < a.length; i++)
|
|
46
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
47
|
+
return diff === 0;
|
|
48
|
+
};
|
|
49
|
+
const decodeInputs = Schema.decodeUnknownEffect(SignInInputs);
|
|
50
|
+
/**
|
|
51
|
+
* The app's icon as a `data:image/…` URL: the first of `urls` on `origin` that answers 200 with a
|
|
52
|
+
* shown image type (`siteIconType`), unencoded, of 1 to `SITE_ICON_BYTES_MAX` bytes. Fetched
|
|
53
|
+
* without cookies and without following redirects, reading no further than the chunk that crosses
|
|
54
|
+
* the limit, and given up after `SIGN_IN_ICON_TIMEOUT` in all; undefined when none.
|
|
55
|
+
*/
|
|
56
|
+
export const fetchSiteIcon = (origin, urls) => Effect.gen(function* () {
|
|
57
|
+
// Each request ends with its attempt's scope, also one whose body was never read.
|
|
58
|
+
const client = HttpClient.withScope(yield* HttpClient.HttpClient);
|
|
59
|
+
for (const url of urls) {
|
|
60
|
+
if (URL.parse(url)?.origin !== origin)
|
|
61
|
+
continue;
|
|
62
|
+
const icon = yield* client
|
|
63
|
+
.get(url, { headers: { accept: 'image/*', 'accept-encoding': 'identity' } })
|
|
64
|
+
.pipe(Effect.flatMap((response) => {
|
|
65
|
+
const type = siteIconType(response.headers['content-type']);
|
|
66
|
+
const encoding = response.headers['content-encoding'];
|
|
67
|
+
if (response.status !== 200 ||
|
|
68
|
+
type === undefined ||
|
|
69
|
+
(encoding !== undefined && encoding.toLowerCase() !== 'identity'))
|
|
70
|
+
return Effect.succeed(undefined);
|
|
71
|
+
const chunks = [];
|
|
72
|
+
let size = 0;
|
|
73
|
+
return Stream.runForEachWhile(response.stream, (chunk) => Effect.sync(() => {
|
|
74
|
+
size += chunk.length;
|
|
75
|
+
if (size <= SITE_ICON_BYTES_MAX)
|
|
76
|
+
chunks.push(chunk);
|
|
77
|
+
return size <= SITE_ICON_BYTES_MAX;
|
|
78
|
+
})).pipe(Effect.map(() => {
|
|
79
|
+
if (size === 0 || size > SITE_ICON_BYTES_MAX)
|
|
80
|
+
return undefined;
|
|
81
|
+
const bytes = new Uint8Array(size);
|
|
82
|
+
let at = 0;
|
|
83
|
+
for (const chunk of chunks) {
|
|
84
|
+
bytes.set(chunk, at);
|
|
85
|
+
at += chunk.length;
|
|
86
|
+
}
|
|
87
|
+
return `data:${type};base64,${Base64.encode(bytes)}`;
|
|
88
|
+
}));
|
|
89
|
+
}), Effect.scoped, Effect.orElseSucceed(() => undefined));
|
|
90
|
+
if (icon !== undefined)
|
|
91
|
+
return icon;
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}).pipe(Effect.timeoutOption(SIGN_IN_ICON_TIMEOUT), Effect.map(Option.getOrUndefined));
|
|
95
|
+
const noStore = {
|
|
96
|
+
'cache-control': 'no-store',
|
|
97
|
+
'referrer-policy': 'no-referrer',
|
|
98
|
+
'x-content-type-options': 'nosniff',
|
|
99
|
+
'x-frame-options': 'DENY',
|
|
100
|
+
};
|
|
101
|
+
const text = (body, status) => HttpServerResponse.text(body, { status, headers: noStore });
|
|
102
|
+
/**
|
|
103
|
+
* The live view's routes, under `/<token>/`: the page, `frame?after=<seq>` (the next frame, long
|
|
104
|
+
* polled; 204 when none came), and the posts `input`, `save` and `cancel`. Posts must be JSON
|
|
105
|
+
* (so another site's page cannot send one without a preflight, which is never answered) and come
|
|
106
|
+
* from the page itself (`Sec-Fetch-Site`, `Origin`). Every route answers 410 once the sign-in
|
|
107
|
+
* ended. Inputs, the save and the cancel run one at a time under `lock` (which whatever else ends
|
|
108
|
+
* the sign-in takes too), each checking first that it has not ended: a save sees every input
|
|
109
|
+
* played before it, and nothing is saved once it was cancelled, replaced or left idle.
|
|
110
|
+
*/
|
|
111
|
+
export const makeSignInApp = (options) => Effect.gen(function* () {
|
|
112
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
113
|
+
const host = request.headers['host'] ?? '';
|
|
114
|
+
if (!options.hosts.has(host))
|
|
115
|
+
return text('Forbidden', 403);
|
|
116
|
+
const [pathname = '', query = ''] = request.url.split('?', 2);
|
|
117
|
+
const prefix = `/${options.token}`;
|
|
118
|
+
const token = pathname.slice(1, 1 + options.token.length);
|
|
119
|
+
if (!sameText(token, options.token))
|
|
120
|
+
return text('Not found', 404);
|
|
121
|
+
const route = pathname.slice(prefix.length);
|
|
122
|
+
yield* options.seen;
|
|
123
|
+
if (route === '' && request.method === 'GET')
|
|
124
|
+
return HttpServerResponse.redirect(`${prefix}/`, { status: 302, headers: noStore });
|
|
125
|
+
if (yield* Deferred.isDone(options.done))
|
|
126
|
+
return text('This sign-in has ended.', 410);
|
|
127
|
+
if (request.method === 'GET') {
|
|
128
|
+
if (route === '/')
|
|
129
|
+
return HttpServerResponse.text(renderSignInPage({
|
|
130
|
+
...options.request,
|
|
131
|
+
site: options.site,
|
|
132
|
+
}), {
|
|
133
|
+
contentType: 'text/html; charset=utf-8',
|
|
134
|
+
headers: { ...noStore, 'content-security-policy': SIGN_IN_CSP },
|
|
135
|
+
});
|
|
136
|
+
// For the page to tell, before it starts, that the sign-in is still open (410 if not).
|
|
137
|
+
if (route === '/status')
|
|
138
|
+
return HttpServerResponse.empty({ status: 204, headers: noStore });
|
|
139
|
+
if (route === '/frame') {
|
|
140
|
+
const after = Number.parseInt(new URLSearchParams(query).get('after') ?? '0', 10);
|
|
141
|
+
const frame = yield* options.live.frame(Number.isFinite(after) ? after : 0, FRAME_WAIT_MS);
|
|
142
|
+
if (frame === undefined)
|
|
143
|
+
return HttpServerResponse.empty({ status: 204, headers: noStore });
|
|
144
|
+
return HttpServerResponse.jsonUnsafe(frame, { headers: noStore });
|
|
145
|
+
}
|
|
146
|
+
return text('Not found', 404);
|
|
147
|
+
}
|
|
148
|
+
if (request.method !== 'POST')
|
|
149
|
+
return text('Method not allowed', 405);
|
|
150
|
+
const site = request.headers['sec-fetch-site'];
|
|
151
|
+
const origin = request.headers['origin'];
|
|
152
|
+
const json = (request.headers['content-type'] ?? '').startsWith('application/json');
|
|
153
|
+
if (!json || (site !== undefined && site !== 'same-origin'))
|
|
154
|
+
return text('Forbidden', 403);
|
|
155
|
+
if (origin !== undefined && origin !== `http://${host}`)
|
|
156
|
+
return text('Forbidden', 403);
|
|
157
|
+
const length = Number(request.headers['content-length'] ?? '0');
|
|
158
|
+
if (!(length <= INPUT_BYTES_MAX))
|
|
159
|
+
return text('Too large', 413);
|
|
160
|
+
/** Runs `act` alone, unless the sign-in ended meanwhile. */
|
|
161
|
+
const alone = (act) => Effect.gen(function* () {
|
|
162
|
+
if (yield* Deferred.isDone(options.done))
|
|
163
|
+
return text('This sign-in has ended.', 410);
|
|
164
|
+
return yield* act;
|
|
165
|
+
}).pipe(Semaphore.withPermit(options.lock));
|
|
166
|
+
if (route === '/input') {
|
|
167
|
+
const body = yield* request.json.pipe(Effect.orElseSucceed(() => undefined));
|
|
168
|
+
const inputs = yield* decodeInputs(body).pipe(Effect.option);
|
|
169
|
+
if (inputs._tag === 'None')
|
|
170
|
+
return text('Not a list of inputs', 400);
|
|
171
|
+
return yield* alone(Effect.forEach(inputs.value, options.live.input).pipe(Effect.map((played) => played.every(Boolean)
|
|
172
|
+
? HttpServerResponse.empty({ status: 204, headers: noStore })
|
|
173
|
+
: text('Some input could not be played in the browser.', 502))));
|
|
174
|
+
}
|
|
175
|
+
if (route === '/save')
|
|
176
|
+
return yield* alone(Effect.gen(function* () {
|
|
177
|
+
const session = yield* options.live.save(options.request.origin).pipe(Effect.option);
|
|
178
|
+
if (session._tag === 'None')
|
|
179
|
+
return text('The browser could not give its session.', 500);
|
|
180
|
+
const saved = yield* options.save(session.value).pipe(Effect.result);
|
|
181
|
+
if (saved._tag === 'Failure')
|
|
182
|
+
return text(saved.failure.message, 500);
|
|
183
|
+
yield* Deferred.succeed(options.done, 'saved');
|
|
184
|
+
return HttpServerResponse.jsonUnsafe({ ok: true }, { headers: noStore });
|
|
185
|
+
}));
|
|
186
|
+
if (route === '/cancel')
|
|
187
|
+
return yield* alone(Deferred.succeed(options.done, 'cancelled').pipe(Effect.as(HttpServerResponse.jsonUnsafe({ ok: true }, { headers: noStore }))));
|
|
188
|
+
return text('Not found', 404);
|
|
189
|
+
}).pipe(Effect.catchCause(() => Effect.succeed(text('Error', 500))));
|
|
190
|
+
/**
|
|
191
|
+
* The sign-ins this process holds open, one per account label. A long-lived process (the MCP
|
|
192
|
+
* server) gives the link in its reply and keeps the sign-in open until the person is done; the
|
|
193
|
+
* CLI waits for it (`screw-bugs accounts sign-in`).
|
|
194
|
+
*/
|
|
195
|
+
export class SignIns extends Context.Service()('screw-bugs/SignIns') {
|
|
196
|
+
static layer = Layer.effect(SignIns, Effect.gen(function* () {
|
|
197
|
+
const browser = yield* Browser;
|
|
198
|
+
const accounts = yield* AccountBook;
|
|
199
|
+
const http = yield* HttpClient.HttpClient;
|
|
200
|
+
const scope = yield* Scope.Scope;
|
|
201
|
+
const lock = yield* Semaphore.make(1);
|
|
202
|
+
const pending = new Map();
|
|
203
|
+
const open = (request) => Effect.gen(function* () {
|
|
204
|
+
const host = yield* signInHost;
|
|
205
|
+
if (host === '' || host === '0.0.0.0' || host === '::')
|
|
206
|
+
return yield* new Failure({
|
|
207
|
+
code: ExitCode.Usage,
|
|
208
|
+
reason: 'sign_in_host',
|
|
209
|
+
message: `SCREW_BUGS_SIGN_IN_HOST is "${host}"; give one address of this machine, such ` +
|
|
210
|
+
'as 127.0.0.1 or its tailnet IP, never every interface.',
|
|
211
|
+
});
|
|
212
|
+
const own = yield* Scope.fork(scope);
|
|
213
|
+
const opened = yield* Effect.gen(function* () {
|
|
214
|
+
const live = yield* browser.signIn(request.url).pipe(Effect.mapError((error) => new Failure({
|
|
215
|
+
code: ExitCode.NotReady,
|
|
216
|
+
reason: 'sign_in_browser',
|
|
217
|
+
message: error._tag === 'BrowserNotFound'
|
|
218
|
+
? 'No browser could be started to sign in with; run `npx screw-bugs doctor` to see what is missing.'
|
|
219
|
+
: `The browser to sign in with could not open: ${error.message}`,
|
|
220
|
+
})));
|
|
221
|
+
const icon = yield* fetchSiteIcon(request.origin, live.site.icons).pipe(Effect.provideService(HttpClient.HttpClient, http));
|
|
222
|
+
const done = yield* Deferred.make();
|
|
223
|
+
const steps = yield* Semaphore.make(1);
|
|
224
|
+
/** Ends it once whatever input or save is in progress is over. */
|
|
225
|
+
const end = (outcome) => Deferred.succeed(done, outcome).pipe(Effect.asVoid, Semaphore.withPermit(steps));
|
|
226
|
+
const token = yield* randomToken;
|
|
227
|
+
let lastSeen = yield* Clock.currentTimeMillis;
|
|
228
|
+
const seen = Clock.currentTimeMillis.pipe(Effect.map((now) => {
|
|
229
|
+
lastSeen = now;
|
|
230
|
+
}));
|
|
231
|
+
let port = 0;
|
|
232
|
+
const hosts = new Set();
|
|
233
|
+
const save = (session) => DateTime.now.pipe(Effect.flatMap((now) => accounts.save({
|
|
234
|
+
label: request.label,
|
|
235
|
+
...(request.about !== undefined ? { about: request.about } : {}),
|
|
236
|
+
origin: request.origin,
|
|
237
|
+
savedAt: DateTime.formatIso(now),
|
|
238
|
+
}, session)), Effect.mapError((error) => new Failure({
|
|
239
|
+
code: ExitCode.Internal,
|
|
240
|
+
reason: 'storage_failed',
|
|
241
|
+
message: error.message,
|
|
242
|
+
})));
|
|
243
|
+
const app = makeSignInApp({
|
|
244
|
+
token,
|
|
245
|
+
hosts,
|
|
246
|
+
request,
|
|
247
|
+
live,
|
|
248
|
+
site: { title: live.site.title, icon },
|
|
249
|
+
done,
|
|
250
|
+
lock: steps,
|
|
251
|
+
seen,
|
|
252
|
+
save,
|
|
253
|
+
});
|
|
254
|
+
const server = yield* NodeHttpServer.make(() => createServer(), { port: 0, host }).pipe(Effect.mapError((error) => new Failure({
|
|
255
|
+
code: ExitCode.Usage,
|
|
256
|
+
reason: 'sign_in_serve',
|
|
257
|
+
message: `Could not serve the sign-in page on ${host} (check SCREW_BUGS_SIGN_IN_HOST): ` +
|
|
258
|
+
String(error.cause),
|
|
259
|
+
})));
|
|
260
|
+
if ('port' in server.address)
|
|
261
|
+
port = server.address.port;
|
|
262
|
+
hosts.add(`${urlHost(host)}:${port}`);
|
|
263
|
+
if (LOOPBACK.has(host))
|
|
264
|
+
for (const name of ['127.0.0.1', 'localhost', '[::1]'])
|
|
265
|
+
hosts.add(`${name}:${port}`);
|
|
266
|
+
yield* server.serve(app).pipe(Effect.provide(NodeHttpServer.layerHttpServices));
|
|
267
|
+
// Ends a sign-in nobody looks at any more.
|
|
268
|
+
yield* Effect.gen(function* () {
|
|
269
|
+
while (true) {
|
|
270
|
+
yield* Effect.sleep(Duration.seconds(30));
|
|
271
|
+
const idle = (yield* Clock.currentTimeMillis) - lastSeen;
|
|
272
|
+
if (idle >= Duration.toMillis(SIGN_IN_IDLE))
|
|
273
|
+
yield* end('idle');
|
|
274
|
+
}
|
|
275
|
+
}).pipe(Effect.forkIn(own));
|
|
276
|
+
return { link: `http://${urlHost(host)}:${port}/${token}/`, done, end };
|
|
277
|
+
}).pipe(Scope.provide(own), Effect.onError(() => Scope.close(own, Exit.void)));
|
|
278
|
+
const entry = { origin: request.origin, ...opened };
|
|
279
|
+
pending.set(request.label, entry);
|
|
280
|
+
// Once it ended, the browser and server go, a moment later so the last answer gets out.
|
|
281
|
+
yield* Deferred.await(opened.done).pipe(Effect.andThen(Effect.sleep(Duration.seconds(1))), Effect.andThen(Scope.close(own, Exit.void)), Effect.andThen(Effect.sync(() => {
|
|
282
|
+
if (pending.get(request.label) === entry)
|
|
283
|
+
pending.delete(request.label);
|
|
284
|
+
})), Effect.forkIn(scope));
|
|
285
|
+
return entry;
|
|
286
|
+
});
|
|
287
|
+
return SignIns.of({
|
|
288
|
+
begin: (request) => Effect.gen(function* () {
|
|
289
|
+
const open_ = pending.get(request.label);
|
|
290
|
+
if (open_ !== undefined && !(yield* Deferred.isDone(open_.done))) {
|
|
291
|
+
if (open_.origin === request.origin)
|
|
292
|
+
return { link: open_.link };
|
|
293
|
+
// After a save in progress, which then stands until this one saves.
|
|
294
|
+
yield* open_.end('cancelled');
|
|
295
|
+
}
|
|
296
|
+
const opened = yield* open(request);
|
|
297
|
+
return { link: opened.link };
|
|
298
|
+
}).pipe(Semaphore.withPermit(lock)),
|
|
299
|
+
wait: (label) => Effect.suspend(() => {
|
|
300
|
+
const open_ = pending.get(label);
|
|
301
|
+
return open_ === undefined ? Effect.succeed(undefined) : Deferred.await(open_.done);
|
|
302
|
+
}),
|
|
303
|
+
});
|
|
304
|
+
}));
|
|
305
|
+
}
|