@enhance-eng/enhance 0.1.4 → 0.1.5
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/dist/main.mjs +306 -29
- package/package.json +3 -1
package/dist/main.mjs
CHANGED
|
@@ -2,15 +2,17 @@
|
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { FailedToExitError, createCli, parseRouter } from "trpc-cli";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { setTimeout } from "node:timers/promises";
|
|
5
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
6
|
+
import { homedir, hostname, tmpdir } from "node:os";
|
|
6
7
|
import process from "node:process";
|
|
7
8
|
import { createInterface } from "node:readline";
|
|
8
9
|
import { chmodSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
9
10
|
import path from "node:path";
|
|
10
11
|
import { TRPCClientError, createTRPCUntypedClient, httpLink } from "@trpc/client";
|
|
11
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
12
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
12
13
|
import { chmod, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
13
|
-
import {
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { createServer } from "node:http";
|
|
14
16
|
import { Readable, Transform } from "node:stream";
|
|
15
17
|
import { pipeline } from "node:stream/promises";
|
|
16
18
|
import { ZipFile } from "yazl";
|
|
@@ -95,6 +97,7 @@ const viewerCapabilitySchema = z.object({
|
|
|
95
97
|
"sign-in",
|
|
96
98
|
"no"
|
|
97
99
|
]),
|
|
100
|
+
share: z.boolean(),
|
|
98
101
|
manage: z.boolean()
|
|
99
102
|
});
|
|
100
103
|
const canvasSchema = z.object({
|
|
@@ -340,6 +343,7 @@ const canvasBlendModeSchema = z.enum([
|
|
|
340
343
|
"overlay",
|
|
341
344
|
"darken",
|
|
342
345
|
"lighten",
|
|
346
|
+
"plus-lighter",
|
|
343
347
|
"color-dodge",
|
|
344
348
|
"color-burn",
|
|
345
349
|
"hard-light",
|
|
@@ -856,8 +860,8 @@ const emptyCanvasSceneDocument = () => ({
|
|
|
856
860
|
});
|
|
857
861
|
//#endregion
|
|
858
862
|
//#region ../../packages/contract/src/canvas/canvas-conversion.schema.ts
|
|
859
|
-
const MAX_CANVAS_CONVERSION_NODES =
|
|
860
|
-
const MAX_CANVAS_CONVERSION_SOURCE_NODES =
|
|
863
|
+
const MAX_CANVAS_CONVERSION_NODES = 3e4;
|
|
864
|
+
const MAX_CANVAS_CONVERSION_SOURCE_NODES = 5e4;
|
|
861
865
|
const MAX_CANVAS_HTML_SOURCE_LENGTH = 262144;
|
|
862
866
|
const MAX_CANVAS_ID_PREFIX_LENGTH = 80;
|
|
863
867
|
const temporaryIdSchema = z.string().min(1).max(200);
|
|
@@ -1745,7 +1749,8 @@ const canvasPresencePatchSchema = z.object({
|
|
|
1745
1749
|
focused: z.boolean().optional(),
|
|
1746
1750
|
selectedNodeIds: z.array(z.string().min(1).max(MAX_NODE_ID_LENGTH$1)).max(MAX_SELECTION_SIZE).optional(),
|
|
1747
1751
|
visibleWorldBox: visibleWorldBoxSchema.optional(),
|
|
1748
|
-
gesture: gesturePreviewSchema.nullable().optional()
|
|
1752
|
+
gesture: gesturePreviewSchema.nullable().optional(),
|
|
1753
|
+
cursorChat: z.string().max(140).nullable().optional()
|
|
1749
1754
|
}).refine((patch) => Object.keys(patch).length > 0, "presence patch cannot be empty");
|
|
1750
1755
|
const canvasPresenceSchema = z.object({
|
|
1751
1756
|
actor: canvasRoomActorSchema,
|
|
@@ -1760,6 +1765,7 @@ const canvasPresenceSchema = z.object({
|
|
|
1760
1765
|
selectedNodeIds: z.array(z.string().min(1).max(MAX_NODE_ID_LENGTH$1)).max(MAX_SELECTION_SIZE),
|
|
1761
1766
|
visibleWorldBox: visibleWorldBoxSchema.nullable(),
|
|
1762
1767
|
gesture: gesturePreviewSchema.nullable(),
|
|
1768
|
+
cursorChat: z.string().max(140).nullable().default(null),
|
|
1763
1769
|
expiresAt: z.iso.datetime()
|
|
1764
1770
|
});
|
|
1765
1771
|
const canvasAgentActivityPhaseSchema = z.enum([
|
|
@@ -2301,6 +2307,16 @@ const commentAuthorSchema = z.object({
|
|
|
2301
2307
|
/** Non-null only for an agent. An attribution product may not let a machine pass as one. */
|
|
2302
2308
|
tokenLabel: z.string().max(120).nullable()
|
|
2303
2309
|
});
|
|
2310
|
+
const commentMentionSchema = z.object({
|
|
2311
|
+
personId: z.uuid(),
|
|
2312
|
+
name: z.string().min(1).max(120)
|
|
2313
|
+
});
|
|
2314
|
+
const MAX_REACTION_EMOJI_LENGTH = 16;
|
|
2315
|
+
const MAX_MENTIONS_PER_MESSAGE = 10;
|
|
2316
|
+
const commentReactionSchema = z.object({
|
|
2317
|
+
emoji: z.string().min(1).max(MAX_REACTION_EMOJI_LENGTH),
|
|
2318
|
+
people: z.array(commentMentionSchema).min(1)
|
|
2319
|
+
});
|
|
2304
2320
|
const commentMessageSchema = z.object({
|
|
2305
2321
|
messageId: z.uuid(),
|
|
2306
2322
|
seq: z.number().int().min(1),
|
|
@@ -2308,7 +2324,9 @@ const commentMessageSchema = z.object({
|
|
|
2308
2324
|
author: commentAuthorSchema,
|
|
2309
2325
|
createdAt: z.iso.datetime(),
|
|
2310
2326
|
/** A comment that changed after somebody read it should say so. */
|
|
2311
|
-
editedAt: z.iso.datetime().nullable()
|
|
2327
|
+
editedAt: z.iso.datetime().nullable(),
|
|
2328
|
+
mentions: z.array(commentMentionSchema),
|
|
2329
|
+
reactions: z.array(commentReactionSchema)
|
|
2312
2330
|
});
|
|
2313
2331
|
const commentResolverSchema = z.object({
|
|
2314
2332
|
kind: z.enum(["person", "agent"]),
|
|
@@ -2351,19 +2369,30 @@ const startCommentInputSchema = z.object({
|
|
|
2351
2369
|
*/
|
|
2352
2370
|
clientThreadId: z.uuid(),
|
|
2353
2371
|
anchor: commentAnchorSchema,
|
|
2354
|
-
body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
|
|
2372
|
+
body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
|
|
2373
|
+
mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
|
|
2355
2374
|
});
|
|
2356
2375
|
const replyCommentInputSchema = z.object({
|
|
2357
2376
|
canvasId: z.uuid(),
|
|
2358
2377
|
threadId: z.uuid(),
|
|
2359
2378
|
clientMessageId: z.uuid(),
|
|
2360
|
-
body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
|
|
2379
|
+
body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
|
|
2380
|
+
mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
|
|
2361
2381
|
});
|
|
2362
2382
|
const editCommentInputSchema = z.object({
|
|
2363
2383
|
canvasId: z.uuid(),
|
|
2364
2384
|
threadId: z.uuid(),
|
|
2365
2385
|
messageId: z.uuid(),
|
|
2366
|
-
body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
|
|
2386
|
+
body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
|
|
2387
|
+
mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
|
|
2388
|
+
});
|
|
2389
|
+
/** A target state, so a retried click cannot invert somebody's reaction. */
|
|
2390
|
+
const reactToCommentInputSchema = z.object({
|
|
2391
|
+
canvasId: z.uuid(),
|
|
2392
|
+
threadId: z.uuid(),
|
|
2393
|
+
messageId: z.uuid(),
|
|
2394
|
+
emoji: z.string().trim().min(1).max(MAX_REACTION_EMOJI_LENGTH),
|
|
2395
|
+
reacted: z.boolean()
|
|
2367
2396
|
});
|
|
2368
2397
|
const moveCommentInputSchema = z.object({
|
|
2369
2398
|
canvasId: z.uuid(),
|
|
@@ -2573,6 +2602,12 @@ const revokeAgentTokenOutputSchema = z.object({
|
|
|
2573
2602
|
tokenId: z.uuid(),
|
|
2574
2603
|
revoked: z.literal(true)
|
|
2575
2604
|
});
|
|
2605
|
+
const cliAuthConfigurationSchema = z.discriminatedUnion("method", [z.object({ method: z.literal("token") }), z.object({
|
|
2606
|
+
method: z.literal("browser"),
|
|
2607
|
+
issuer: z.url(),
|
|
2608
|
+
clientId: z.string().min(1),
|
|
2609
|
+
scope: z.literal("openid")
|
|
2610
|
+
})]);
|
|
2576
2611
|
//#endregion
|
|
2577
2612
|
//#region ../../packages/contract/src/person/person.schema.ts
|
|
2578
2613
|
const personSchema = z.object({
|
|
@@ -3751,7 +3786,7 @@ var CliError = class extends Error {
|
|
|
3751
3786
|
const TOKEN = /^enh_[\w-]{43}$/;
|
|
3752
3787
|
const authenticated = (value) => {
|
|
3753
3788
|
const parsed = getMeOutputSchema.parse(value);
|
|
3754
|
-
if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "
|
|
3789
|
+
if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "Run 'enhance auth login' and complete authentication in the browser.");
|
|
3755
3790
|
return {
|
|
3756
3791
|
authenticated: true,
|
|
3757
3792
|
personId: parsed.person.id,
|
|
@@ -3761,13 +3796,31 @@ const authenticated = (value) => {
|
|
|
3761
3796
|
expiresAt: parsed.authentication.expiresAt
|
|
3762
3797
|
};
|
|
3763
3798
|
};
|
|
3764
|
-
const createAuthUseCase = (credentials, remote) => ({
|
|
3765
|
-
|
|
3766
|
-
if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass
|
|
3799
|
+
const createAuthUseCase = (credentials, remote, browser) => ({
|
|
3800
|
+
loginWithToken: async (token) => {
|
|
3801
|
+
if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass a manual token from Settings to 'enhance auth login' through stdin.");
|
|
3767
3802
|
const status = authenticated(await remote.queryWithToken("person.me", {}, token));
|
|
3768
3803
|
await credentials.write(token);
|
|
3769
3804
|
return status;
|
|
3770
3805
|
},
|
|
3806
|
+
loginWithBrowser: async (input) => {
|
|
3807
|
+
const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
|
|
3808
|
+
if (configuration.method === "token") throw new CliError("BAD_REQUEST", "Browser authentication is not configured for this Enhance environment.", "Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.");
|
|
3809
|
+
const accessToken = await browser.authorize({
|
|
3810
|
+
issuer: configuration.issuer,
|
|
3811
|
+
clientId: configuration.clientId,
|
|
3812
|
+
scope: configuration.scope,
|
|
3813
|
+
openBrowser: input.openBrowser,
|
|
3814
|
+
onReady: input.onReady
|
|
3815
|
+
});
|
|
3816
|
+
const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
|
|
3817
|
+
label: input.label,
|
|
3818
|
+
expiresAt: null
|
|
3819
|
+
}, accessToken));
|
|
3820
|
+
const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
|
|
3821
|
+
await credentials.write(created.token);
|
|
3822
|
+
return status;
|
|
3823
|
+
},
|
|
3771
3824
|
status: async () => {
|
|
3772
3825
|
if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
|
|
3773
3826
|
return authenticated(await remote.query("person.me", {}));
|
|
@@ -3803,7 +3856,7 @@ const waitUntilSettled = async (remote, input) => {
|
|
|
3803
3856
|
if (!parsed.success) throw invalidResponse$2("status");
|
|
3804
3857
|
if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
|
|
3805
3858
|
if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
|
|
3806
|
-
await setTimeout(pollMs);
|
|
3859
|
+
await setTimeout$1(pollMs);
|
|
3807
3860
|
pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
|
|
3808
3861
|
}
|
|
3809
3862
|
throw new Error("prototype ingestion is still running");
|
|
@@ -4038,12 +4091,41 @@ const readToken = async (offered, command) => {
|
|
|
4038
4091
|
}
|
|
4039
4092
|
throw new CliError("BAD_REQUEST", "A token is required.", `Pass '--token <token>' or pipe one line to '${command}'.`);
|
|
4040
4093
|
};
|
|
4094
|
+
const readOptionalToken = async (offered) => {
|
|
4095
|
+
if (offered !== void 0) return offered.trim();
|
|
4096
|
+
if (process.stdin.isTTY) return null;
|
|
4097
|
+
const lines = createInterface({
|
|
4098
|
+
input: process.stdin,
|
|
4099
|
+
crlfDelay: Infinity
|
|
4100
|
+
});
|
|
4101
|
+
for await (const line of lines) {
|
|
4102
|
+
lines.close();
|
|
4103
|
+
const piped = line.trim();
|
|
4104
|
+
return piped === "" ? null : piped;
|
|
4105
|
+
}
|
|
4106
|
+
return null;
|
|
4107
|
+
};
|
|
4041
4108
|
//#endregion
|
|
4042
4109
|
//#region src/infrastructure/auth.program.ts
|
|
4110
|
+
const MAX_TOKEN_LABEL_CHARACTERS = 120;
|
|
4043
4111
|
const registerAuthProgram = (program, auth, output) => {
|
|
4044
4112
|
const command = program.command("auth").description("Store and inspect the agent credential.");
|
|
4045
|
-
command.command("login").description("
|
|
4046
|
-
|
|
4113
|
+
command.command("login").description("Authenticate in a browser, then store a revocable agent credential.").option("--token <token>", "Use an existing agent token instead of browser authentication.").option("--no-open", "Print the authorization URL without opening the browser.").action(async (options) => {
|
|
4114
|
+
const token = await readOptionalToken(options.token);
|
|
4115
|
+
if (token !== null) {
|
|
4116
|
+
output.result(await auth.loginWithToken(token));
|
|
4117
|
+
return;
|
|
4118
|
+
}
|
|
4119
|
+
output.result(await auth.loginWithBrowser({
|
|
4120
|
+
label: `CLI on ${hostname()}`.slice(0, MAX_TOKEN_LABEL_CHARACTERS),
|
|
4121
|
+
openBrowser: options.open,
|
|
4122
|
+
onReady: (url) => {
|
|
4123
|
+
output.result({
|
|
4124
|
+
status: "waiting_for_browser",
|
|
4125
|
+
url
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
4128
|
+
}));
|
|
4047
4129
|
});
|
|
4048
4130
|
command.command("status").description("Resolve the stored token to its person, label, and expiry.").action(async () => {
|
|
4049
4131
|
output.result(await auth.status());
|
|
@@ -5837,6 +5919,7 @@ const PROCEDURE_DESCRIPTIONS = {
|
|
|
5837
5919
|
"comment.start": "Start a comment thread anchored to a canvas location.",
|
|
5838
5920
|
"comment.resolve": "Set a thread resolved or reopened with an explicit target state.",
|
|
5839
5921
|
"comment.reply": "Add a reply to an existing comment thread.",
|
|
5922
|
+
"comment.react": "Set or remove one emoji reaction on a comment message.",
|
|
5840
5923
|
"comment.edit": "Replace the body of a comment message authored by this person.",
|
|
5841
5924
|
"comment.move": "Move a comment thread anchor to a new canvas location.",
|
|
5842
5925
|
"comment.delete": "Delete an entire comment thread, or tombstone one message when its id is set.",
|
|
@@ -5920,7 +6003,10 @@ const OPTION_DESCRIPTIONS = {
|
|
|
5920
6003
|
"--query": "Text to search for in the resources returned by this command.",
|
|
5921
6004
|
"--client-thread-id": "Client-minted UUID; reuse it when retrying this thread creation.",
|
|
5922
6005
|
"--client-message-id": "Client-minted UUID; reuse it when retrying this reply.",
|
|
6006
|
+
"--mentioned-person-ids": "Person UUIDs to mention; get them from the relevant people or participants list.",
|
|
5923
6007
|
"--resolved": "Target state: true resolves the thread; false reopens it.",
|
|
6008
|
+
"--emoji": "Single emoji to add to or remove from the comment message.",
|
|
6009
|
+
"--reacted": "Target state: true adds this person’s reaction; false removes it.",
|
|
5924
6010
|
"--review-state": "Review state to store: not-started, in-progress, or done.",
|
|
5925
6011
|
"--confirmation": "Exact current canvas title; get it from the deleted canvas list.",
|
|
5926
6012
|
"--document": "Complete opaque canvas document as one JSON object.",
|
|
@@ -5946,7 +6032,7 @@ const OPTION_DESCRIPTIONS = {
|
|
|
5946
6032
|
"--arrived": "Uploaded asset objects as JSON: url, etag, and byteSize.",
|
|
5947
6033
|
"--provenance": "Origin JSON `{\"sourceRecordingId\":\"UUID\",\"atMs\":0}`, or null for a standalone screen.",
|
|
5948
6034
|
"--json": "Complete procedure input as JSON; do not combine it with field flags.",
|
|
5949
|
-
"auth login --token": "
|
|
6035
|
+
"auth login --token": "Existing agent token for CI or headless fallback; omit it to authenticate in a browser.",
|
|
5950
6036
|
"canvas.create --organisation-id": "Team UUID from `enhance organisation list`; omit it to create on the personal shelf.",
|
|
5951
6037
|
"canvas.move --organisation-id": "Destination team UUID from `enhance organisation list`, or the literal `personal`.",
|
|
5952
6038
|
"canvas.duplicate --organisation-id": "Destination team UUID from `enhance organisation list`, or the literal `personal`.",
|
|
@@ -6259,7 +6345,7 @@ const REFUSALS = /* @__PURE__ */ new Set([
|
|
|
6259
6345
|
const remediationFor = (code) => {
|
|
6260
6346
|
switch (code) {
|
|
6261
6347
|
case "BAD_REQUEST": return "Run the command with '--help', then rewrite every rejected argument.";
|
|
6262
|
-
case "UNAUTHORIZED": return "
|
|
6348
|
+
case "UNAUTHORIZED": return "Run 'enhance auth login' and complete authentication in the browser.";
|
|
6263
6349
|
case "FORBIDDEN": return "Run 'enhance canvas list --scope mine' and choose a target you can change.";
|
|
6264
6350
|
case "NOT_FOUND": return "List the resource again and retry with an identifier from that result.";
|
|
6265
6351
|
case "CONFLICT": return "Read the resource again before retrying the change.";
|
|
@@ -6398,6 +6484,129 @@ const registerFixtureProgram = (program, composites, output) => {
|
|
|
6398
6484
|
registerWorldFixture(fixture, composites.world, output);
|
|
6399
6485
|
};
|
|
6400
6486
|
//#endregion
|
|
6487
|
+
//#region src/infrastructure/oauth-loopback.adapter.ts
|
|
6488
|
+
const CALLBACK_PATH = "/callback";
|
|
6489
|
+
const AUTHORIZATION_TIMEOUT_MS = 12e4;
|
|
6490
|
+
const ENTROPY_BYTES = 32;
|
|
6491
|
+
const HTTP_OK = 200;
|
|
6492
|
+
const HTTP_BAD_REQUEST = 400;
|
|
6493
|
+
const HTTP_NOT_FOUND = 404;
|
|
6494
|
+
const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
|
|
6495
|
+
const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
|
|
6496
|
+
const launchBrowser = (url) => {
|
|
6497
|
+
const command = process.platform === "darwin" ? {
|
|
6498
|
+
executable: "open",
|
|
6499
|
+
arguments: [url]
|
|
6500
|
+
} : process.platform === "win32" ? {
|
|
6501
|
+
executable: "rundll32.exe",
|
|
6502
|
+
arguments: ["url.dll,FileProtocolHandler", url]
|
|
6503
|
+
} : {
|
|
6504
|
+
executable: "xdg-open",
|
|
6505
|
+
arguments: [url]
|
|
6506
|
+
};
|
|
6507
|
+
const child = spawn(command.executable, command.arguments, {
|
|
6508
|
+
detached: true,
|
|
6509
|
+
stdio: "ignore"
|
|
6510
|
+
});
|
|
6511
|
+
child.once("error", () => false);
|
|
6512
|
+
child.unref();
|
|
6513
|
+
};
|
|
6514
|
+
const handleCallback = (input, request, response) => {
|
|
6515
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
6516
|
+
if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
|
|
6517
|
+
response.writeHead(HTTP_NOT_FOUND).end();
|
|
6518
|
+
return;
|
|
6519
|
+
}
|
|
6520
|
+
if (url.searchParams.get("state") !== input.state) {
|
|
6521
|
+
response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
|
|
6522
|
+
return;
|
|
6523
|
+
}
|
|
6524
|
+
const error = url.searchParams.get("error");
|
|
6525
|
+
const received = url.searchParams.get("code");
|
|
6526
|
+
if (error !== null || received === null || received === "") {
|
|
6527
|
+
response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
|
|
6528
|
+
input.completion.reject(new Error(error ?? "the authorization response carried no code"));
|
|
6529
|
+
return;
|
|
6530
|
+
}
|
|
6531
|
+
response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
|
|
6532
|
+
input.completion.resolve(received);
|
|
6533
|
+
};
|
|
6534
|
+
const authorizeUrl = (input) => {
|
|
6535
|
+
const authorize = endpoint(input.issuer, "oauth/authorize");
|
|
6536
|
+
authorize.search = new URLSearchParams({
|
|
6537
|
+
response_type: "code",
|
|
6538
|
+
client_id: input.clientId,
|
|
6539
|
+
redirect_uri: input.redirectUri,
|
|
6540
|
+
scope: input.scope,
|
|
6541
|
+
state: input.state,
|
|
6542
|
+
code_challenge: input.challenge,
|
|
6543
|
+
code_challenge_method: "S256"
|
|
6544
|
+
}).toString();
|
|
6545
|
+
return authorize.href;
|
|
6546
|
+
};
|
|
6547
|
+
const authorizationCode = async (input) => {
|
|
6548
|
+
const completion = Promise.withResolvers();
|
|
6549
|
+
const server = createServer((request, response) => {
|
|
6550
|
+
handleCallback({
|
|
6551
|
+
state: input.state,
|
|
6552
|
+
completion
|
|
6553
|
+
}, request, response);
|
|
6554
|
+
});
|
|
6555
|
+
await new Promise((resolve, reject) => {
|
|
6556
|
+
server.once("error", reject);
|
|
6557
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
6558
|
+
});
|
|
6559
|
+
const address = server.address();
|
|
6560
|
+
if (address === null || typeof address === "string") {
|
|
6561
|
+
server.close();
|
|
6562
|
+
throw new Error("the OAuth callback listener has no TCP port");
|
|
6563
|
+
}
|
|
6564
|
+
const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
|
|
6565
|
+
const url = authorizeUrl({
|
|
6566
|
+
...input,
|
|
6567
|
+
redirectUri
|
|
6568
|
+
});
|
|
6569
|
+
input.onReady(url);
|
|
6570
|
+
if (input.openBrowser) launchBrowser(url);
|
|
6571
|
+
const timeout = setTimeout(() => {
|
|
6572
|
+
completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
|
|
6573
|
+
}, AUTHORIZATION_TIMEOUT_MS);
|
|
6574
|
+
try {
|
|
6575
|
+
return {
|
|
6576
|
+
code: await completion.promise,
|
|
6577
|
+
redirectUri
|
|
6578
|
+
};
|
|
6579
|
+
} finally {
|
|
6580
|
+
clearTimeout(timeout);
|
|
6581
|
+
await new Promise((resolve) => {
|
|
6582
|
+
server.close(() => {
|
|
6583
|
+
resolve();
|
|
6584
|
+
});
|
|
6585
|
+
});
|
|
6586
|
+
}
|
|
6587
|
+
};
|
|
6588
|
+
const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
|
|
6589
|
+
try {
|
|
6590
|
+
const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
|
|
6591
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
6592
|
+
const state = randomBytes(ENTROPY_BYTES).toString("base64url");
|
|
6593
|
+
const authorized = await authorizationCode({
|
|
6594
|
+
...input,
|
|
6595
|
+
challenge,
|
|
6596
|
+
state
|
|
6597
|
+
});
|
|
6598
|
+
return await remote.exchangeOauthCode({
|
|
6599
|
+
issuer: input.issuer,
|
|
6600
|
+
clientId: input.clientId,
|
|
6601
|
+
code: authorized.code,
|
|
6602
|
+
redirectUri: authorized.redirectUri,
|
|
6603
|
+
verifier
|
|
6604
|
+
});
|
|
6605
|
+
} catch (error) {
|
|
6606
|
+
throw new CliError("UNAUTHORIZED", error instanceof Error ? `Browser authentication failed: ${error.message}.` : "Browser authentication failed.", "Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.");
|
|
6607
|
+
}
|
|
6608
|
+
} });
|
|
6609
|
+
//#endregion
|
|
6401
6610
|
//#region src/infrastructure/prototype.program.ts
|
|
6402
6611
|
const finiteNumber = (value) => z.coerce.number().parse(value);
|
|
6403
6612
|
const positiveNumber = (value) => z.coerce.number().positive().parse(value);
|
|
@@ -7100,6 +7309,14 @@ const canvasCommenterProcedure = canvasReaderProcedure.use(async ({ ctx, next })
|
|
|
7100
7309
|
viewer: ctx.viewer
|
|
7101
7310
|
} });
|
|
7102
7311
|
});
|
|
7312
|
+
/** A direct recipient may invite onward without receiving any owner-level management power. */
|
|
7313
|
+
const canvasSharerProcedure = canvasReaderProcedure.use(async ({ ctx, next }) => {
|
|
7314
|
+
if (!ctx.canvasAccess.canShare || ctx.viewer.kind === "anonymous" || ctx.viewer.kind === "render") throw toTrpcError(appError$1("FORBIDDEN", "only a canvas recipient can share this"));
|
|
7315
|
+
return next({ ctx: {
|
|
7316
|
+
...ctx,
|
|
7317
|
+
viewer: ctx.viewer
|
|
7318
|
+
} });
|
|
7319
|
+
});
|
|
7103
7320
|
/**
|
|
7104
7321
|
* Managing narrows the viewer for the same reason commenting does: `canManage` is only ever
|
|
7105
7322
|
* true for a member, and a member is somebody.
|
|
@@ -7183,6 +7400,7 @@ const toCanvasContract = (view) => ({
|
|
|
7183
7400
|
viewerCan: {
|
|
7184
7401
|
read: view.reach.canRead,
|
|
7185
7402
|
comment: view.reach.canComment ? "yes" : view.reach.commentNeedsSignIn ? "sign-in" : "no",
|
|
7403
|
+
share: view.reach.canShare,
|
|
7186
7404
|
manage: view.reach.canManage
|
|
7187
7405
|
},
|
|
7188
7406
|
createdAt: view.canvas.createdAt.toISOString(),
|
|
@@ -7283,7 +7501,8 @@ const create$2 = (handlers) => personProcedure.input(createCanvasInputSchema).ou
|
|
|
7283
7501
|
title: input.title,
|
|
7284
7502
|
creatorPersonId: ctx.viewer.personId,
|
|
7285
7503
|
organisationId: input.organisationId,
|
|
7286
|
-
sourceUrl: input.sourceUrl
|
|
7504
|
+
sourceUrl: input.sourceUrl,
|
|
7505
|
+
origin: ctx.viewer.kind === "agent" ? "agent" : "dashboard"
|
|
7287
7506
|
}))));
|
|
7288
7507
|
const get$1 = (handlers) => canvasReaderProcedure.input(getCanvasInputSchema).output(canvasSchema).query(async ({ input, ctx }) => {
|
|
7289
7508
|
const view = orThrow(await handlers.get.execute({
|
|
@@ -8115,7 +8334,7 @@ const toInviteContract = (invite, at) => ({
|
|
|
8115
8334
|
});
|
|
8116
8335
|
//#endregion
|
|
8117
8336
|
//#region ../api/src/canvas/infrastructure/canvas-invite.router.ts
|
|
8118
|
-
const create$1 = (handlers, shouldExposeTokens) =>
|
|
8337
|
+
const create$1 = (handlers, shouldExposeTokens) => canvasSharerProcedure.input(createInviteInputSchema).output(createInviteOutputSchema).mutation(async ({ input, ctx }) => {
|
|
8119
8338
|
const result = orThrow(await handlers.createInvite.execute({
|
|
8120
8339
|
...input,
|
|
8121
8340
|
invitedByPersonId: ctx.viewer.personId
|
|
@@ -8146,7 +8365,7 @@ const accept$1 = (handlers) => personProcedure.input(acceptInviteInputSchema).ou
|
|
|
8146
8365
|
});
|
|
8147
8366
|
return result;
|
|
8148
8367
|
});
|
|
8149
|
-
/** Invitation is the distribution path a link is the alternative to.
|
|
8368
|
+
/** Invitation is the distribution path a link is the alternative to. Recipients may invite onward. */
|
|
8150
8369
|
const createCanvasInviteRouter = (handlers, shouldExposeTokens = false) => trpcRouter({
|
|
8151
8370
|
create: create$1(handlers, shouldExposeTokens),
|
|
8152
8371
|
accept: accept$1(handlers),
|
|
@@ -8732,6 +8951,21 @@ const toAuthorContract = (message, directory) => ({
|
|
|
8732
8951
|
avatarUrl: directory(message.authorPersonId).avatarUrl,
|
|
8733
8952
|
tokenLabel: message.authorTokenLabel
|
|
8734
8953
|
});
|
|
8954
|
+
const reactionsOf = (message, directory) => {
|
|
8955
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
8956
|
+
for (const reaction of message.reactions) {
|
|
8957
|
+
const people = grouped.get(reaction.emoji) ?? [];
|
|
8958
|
+
people.push(reaction.personId);
|
|
8959
|
+
grouped.set(reaction.emoji, people);
|
|
8960
|
+
}
|
|
8961
|
+
return [...grouped].map(([emoji, personIds]) => ({
|
|
8962
|
+
emoji,
|
|
8963
|
+
people: personIds.map((personId) => ({
|
|
8964
|
+
personId,
|
|
8965
|
+
name: directory(personId).displayName
|
|
8966
|
+
}))
|
|
8967
|
+
}));
|
|
8968
|
+
};
|
|
8735
8969
|
const toCommentThreadContract = (view, directory) => {
|
|
8736
8970
|
const [first] = view.messages;
|
|
8737
8971
|
return {
|
|
@@ -8745,7 +8979,12 @@ const toCommentThreadContract = (view, directory) => {
|
|
|
8745
8979
|
body: message.deletedAt === null ? message.body : "(deleted)",
|
|
8746
8980
|
author: toAuthorContract(message, directory),
|
|
8747
8981
|
createdAt: message.createdAt.toISOString(),
|
|
8748
|
-
editedAt: message.editedAt?.toISOString() ?? null
|
|
8982
|
+
editedAt: message.editedAt?.toISOString() ?? null,
|
|
8983
|
+
mentions: message.mentionedPersonIds.map((personId) => ({
|
|
8984
|
+
personId,
|
|
8985
|
+
name: directory(personId).displayName
|
|
8986
|
+
})),
|
|
8987
|
+
reactions: reactionsOf(message, directory)
|
|
8749
8988
|
})),
|
|
8750
8989
|
messageCount: view.thread.messageCount,
|
|
8751
8990
|
hasMoreMessages: view.thread.messageCount > view.messages.length,
|
|
@@ -8808,7 +9047,11 @@ const directoryFor = async (people, views) => {
|
|
|
8808
9047
|
const ids = /* @__PURE__ */ new Set();
|
|
8809
9048
|
for (const view of views) {
|
|
8810
9049
|
if (view.thread.resolvedByPersonId !== null) ids.add(view.thread.resolvedByPersonId);
|
|
8811
|
-
for (const message of view.messages)
|
|
9050
|
+
for (const message of view.messages) {
|
|
9051
|
+
ids.add(message.authorPersonId);
|
|
9052
|
+
for (const personId of message.mentionedPersonIds) ids.add(personId);
|
|
9053
|
+
for (const reaction of message.reactions) ids.add(reaction.personId);
|
|
9054
|
+
}
|
|
8812
9055
|
}
|
|
8813
9056
|
const entries = orThrow(await people.read([...ids]));
|
|
8814
9057
|
const byId = new Map(entries.map((entry) => [entry.personId, {
|
|
@@ -8841,6 +9084,7 @@ const start$1 = (handlers) => canvasCommenterProcedure.input(startCommentInputSc
|
|
|
8841
9084
|
clientThreadId: input.clientThreadId,
|
|
8842
9085
|
anchor: input.anchor,
|
|
8843
9086
|
body: input.body,
|
|
9087
|
+
mentionedPersonIds: input.mentionedPersonIds,
|
|
8844
9088
|
author: authorFrom(ctx.viewer),
|
|
8845
9089
|
mintMembership: ctx.canvasAccess.accessLevel === null
|
|
8846
9090
|
}));
|
|
@@ -8872,10 +9116,15 @@ const createCommentRouter = (handlers) => trpcRouter({
|
|
|
8872
9116
|
list: list$2(handlers),
|
|
8873
9117
|
start: start$1(handlers),
|
|
8874
9118
|
resolve: resolve(handlers),
|
|
9119
|
+
react: canvasCommenterProcedure.input(reactToCommentInputSchema).output(commentThreadSchema).mutation(async ({ input, ctx }) => named(handlers.people, orThrow(await handlers.react.execute({
|
|
9120
|
+
...input,
|
|
9121
|
+
personId: ctx.viewer.personId
|
|
9122
|
+
})))),
|
|
8875
9123
|
reply: canvasCommenterProcedure.input(replyCommentInputSchema).output(commentThreadSchema).mutation(async ({ input, ctx }) => {
|
|
8876
9124
|
const view = orThrow(await handlers.reply.execute({
|
|
8877
9125
|
...input,
|
|
8878
|
-
author: authorFrom(ctx.viewer)
|
|
9126
|
+
author: authorFrom(ctx.viewer),
|
|
9127
|
+
isGuest: ctx.canvasAccess.accessLevel === null
|
|
8879
9128
|
}));
|
|
8880
9129
|
ctx.telemetry.emit("CommentReplied", {
|
|
8881
9130
|
canvasId: input.canvasId,
|
|
@@ -9795,6 +10044,7 @@ const handlers = {
|
|
|
9795
10044
|
reply: unavailable,
|
|
9796
10045
|
edit: unavailable,
|
|
9797
10046
|
move: unavailable,
|
|
10047
|
+
react: unavailable,
|
|
9798
10048
|
resolve: unavailable,
|
|
9799
10049
|
remove: unavailable,
|
|
9800
10050
|
list: unavailable,
|
|
@@ -9940,7 +10190,7 @@ const catalogFor = (source) => {
|
|
|
9940
10190
|
};
|
|
9941
10191
|
const registerUtilityPrograms = (program, input) => {
|
|
9942
10192
|
const screen = createScreenFixtureComposite(input.remote);
|
|
9943
|
-
registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote), input.output);
|
|
10193
|
+
registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
|
|
9944
10194
|
registerCommentProgram(program, input.remote, input.output);
|
|
9945
10195
|
registerDoctorProgram(program, {
|
|
9946
10196
|
version: input.version,
|
|
@@ -9979,7 +10229,7 @@ const createCliProgram = (input) => {
|
|
|
9979
10229
|
router: createRemoteRouterAdapter(source, input.remote),
|
|
9980
10230
|
name: "enhance",
|
|
9981
10231
|
version: input.version,
|
|
9982
|
-
description: "Operate Enhance as the authenticated person
|
|
10232
|
+
description: "Operate Enhance as the authenticated person.",
|
|
9983
10233
|
jsonInput: CLI_ASSEMBLY.jsonInput
|
|
9984
10234
|
});
|
|
9985
10235
|
const runParams = createRunParams(input);
|
|
@@ -9993,7 +10243,7 @@ const createCliProgram = (input) => {
|
|
|
9993
10243
|
mutationKey: input.mutationKey,
|
|
9994
10244
|
output: input.output
|
|
9995
10245
|
});
|
|
9996
|
-
built.description("Operate Enhance as the authenticated person
|
|
10246
|
+
built.description("Operate Enhance as the authenticated person.");
|
|
9997
10247
|
const failureState = input.state;
|
|
9998
10248
|
return {
|
|
9999
10249
|
program: built,
|
|
@@ -10072,6 +10322,7 @@ const createFileCredentialAdapter = (directory) => {
|
|
|
10072
10322
|
const HEALTH_TIMEOUT_MS = 4e3;
|
|
10073
10323
|
const NOT_FOUND_STATUS = 404;
|
|
10074
10324
|
const FORBIDDEN_STATUS = 403;
|
|
10325
|
+
const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
|
|
10075
10326
|
const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
|
|
10076
10327
|
url: `${apiUrl}/trpc`,
|
|
10077
10328
|
headers: {
|
|
@@ -10084,12 +10335,38 @@ const download = async (url) => {
|
|
|
10084
10335
|
if (!response.ok) throw new CliError(response.status === NOT_FOUND_STATUS || response.status === FORBIDDEN_STATUS ? "NOT_FOUND" : "INTERNAL", `Render download answered HTTP ${String(response.status)}.`, "The result may have expired. Request a new render.");
|
|
10085
10336
|
return new Uint8Array(await response.arrayBuffer());
|
|
10086
10337
|
};
|
|
10338
|
+
const authenticationConfig = async (apiUrl) => {
|
|
10339
|
+
const response = await fetch(`${apiUrl}/v1/cli-auth`);
|
|
10340
|
+
if (!response.ok) {
|
|
10341
|
+
if (response.status === NOT_FOUND_STATUS) throw new CliError("BAD_REQUEST", "This Enhance API does not support browser authentication.", "Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.");
|
|
10342
|
+
throw new CliError("INTERNAL", `CLI authentication discovery answered HTTP ${String(response.status)}.`, "Run 'enhance doctor', report the result, and stop.");
|
|
10343
|
+
}
|
|
10344
|
+
return response.json();
|
|
10345
|
+
};
|
|
10346
|
+
const exchangeOauthCode = async (input) => {
|
|
10347
|
+
const response = await fetch(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
|
|
10348
|
+
method: "POST",
|
|
10349
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
10350
|
+
body: new URLSearchParams({
|
|
10351
|
+
grant_type: "authorization_code",
|
|
10352
|
+
client_id: input.clientId,
|
|
10353
|
+
code: input.code,
|
|
10354
|
+
redirect_uri: input.redirectUri,
|
|
10355
|
+
code_verifier: input.verifier
|
|
10356
|
+
})
|
|
10357
|
+
});
|
|
10358
|
+
if (!response.ok) throw new Error(`token exchange answered HTTP ${String(response.status)}`);
|
|
10359
|
+
return oauthTokenResponseSchema.parse(await response.json()).access_token;
|
|
10360
|
+
};
|
|
10087
10361
|
const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
|
|
10088
10362
|
const normalized = apiUrl.replace(/\/$/, "");
|
|
10089
10363
|
return {
|
|
10364
|
+
authenticationConfig: async () => authenticationConfig(normalized),
|
|
10365
|
+
exchangeOauthCode,
|
|
10090
10366
|
query: async (path, input) => clientFor(normalized, await credentials.read()).query(path, input),
|
|
10091
10367
|
queryWithToken: async (path, input, token) => clientFor(normalized, token).query(path, input),
|
|
10092
10368
|
mutate: async (procedure, input) => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input),
|
|
10369
|
+
mutateWithToken: async (procedure, input, token) => clientFor(normalized, token).mutation(procedure, input),
|
|
10093
10370
|
download,
|
|
10094
10371
|
upload: async (input) => {
|
|
10095
10372
|
const isStreaming = !(input.body instanceof Uint8Array);
|
|
@@ -10343,7 +10620,7 @@ const main = async () => {
|
|
|
10343
10620
|
const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
|
|
10344
10621
|
const mutationKey = createMutationKeyAdapter();
|
|
10345
10622
|
const cli = createCliProgram({
|
|
10346
|
-
version: "0.1.
|
|
10623
|
+
version: "0.1.5",
|
|
10347
10624
|
credentials,
|
|
10348
10625
|
remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
|
|
10349
10626
|
mutationKey,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enhance-eng/enhance",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Agent-first command-line interface for Enhance.",
|
|
6
6
|
"keywords": [
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"prepack": "pnpm run build",
|
|
32
32
|
"test": "pnpm run test:e2e",
|
|
33
33
|
"test:e2e": "pnpm run build && node e2e/e2e-runner.ts",
|
|
34
|
+
"test:e2e:browser": "pnpm run build && playwright test",
|
|
34
35
|
"typecheck": "tsc --noEmit"
|
|
35
36
|
},
|
|
36
37
|
"dependencies": {
|
|
@@ -46,6 +47,7 @@
|
|
|
46
47
|
"@enhance3/api": "workspace:*",
|
|
47
48
|
"@enhance3/contract": "workspace:*",
|
|
48
49
|
"@enhance3/tsconfig": "workspace:*",
|
|
50
|
+
"@playwright/test": "^1.62.0",
|
|
49
51
|
"@types/yauzl": "3.4.0",
|
|
50
52
|
"@types/yazl": "3.3.1",
|
|
51
53
|
"@vitest/coverage-v8": "catalog:",
|