diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index aaf2e9d211896..5700352e0bc00 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -91,6 +91,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 35, name: "GuestLinks" }, { migration_id: 36, name: "OpenLinks" }, { migration_id: 37, name: "PersonNames" }, + { migration_id: 38, name: "OpenLinkJoins" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -132,6 +133,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [35, "GuestLinks"], [36, "OpenLinks"], [37, "PersonNames"], + [38, "OpenLinkJoins"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1380,7 +1382,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, + 36, 37, 38, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index 5148e21470f3c..c5c8b631aa6ad 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -38,6 +38,7 @@ import Migration0034 from "./migrations/034_PeopleAndGrants.ts"; import Migration0035 from "./migrations/035_GuestLinks.ts"; import Migration0036 from "./migrations/036_OpenLinks.ts"; import Migration0037 from "./migrations/037_PersonNames.ts"; +import Migration0038 from "./migrations/038_OpenLinkJoins.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -86,6 +87,7 @@ export const migrationEntries = [ [36, "OpenLinks", Migration0036], // 37 sits in the layer below 36 in the stack that introduced both; ids are never renumbered. [37, "PersonNames", Migration0037], + [38, "OpenLinkJoins", Migration0038], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.test.ts b/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.test.ts new file mode 100644 index 0000000000000..9537f8937e0a2 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.test.ts @@ -0,0 +1,27 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runJ5A2AMigrations } from "../Migrations.ts"; + +it.effect("records each person who joined by an open link as one join of that link", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runJ5A2AMigrations({ toMigrationInclusive: 37 }); + const person = (id: string, link: string | null, at: string) => sql` + INSERT INTO j5_a2a_human_person ( + person_id, is_local_operator, created_at, kind, display_name, joined_open_link_id + ) VALUES (${id}, 0, ${at}, 'guest', ${id}, ${link}) + `; + yield* person("human:named", null, "2026-10-01T00:00:00.000Z"); + yield* person("human:joined", "link-a", "2026-10-02T00:00:00.000Z"); + + yield* runJ5A2AMigrations(); + + assert.deepStrictEqual( + yield* sql`SELECT link_id, person_id, joined_at FROM j5_a2a_open_link_join`, + [{ link_id: "link-a", person_id: "human:joined", joined_at: "2026-10-02T00:00:00.000Z" }], + ); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.ts b/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.ts new file mode 100644 index 0000000000000..29bcc06097c98 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/038_OpenLinkJoins.ts @@ -0,0 +1,31 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Each time a person joins a thread through an open link (#614). A guest already signed in who +// opens a second link joins that link's thread as themselves, so one person can come through +// several links, and each link's list of who came through it, and its cap, count them. +// +// `j5_a2a_human_person.joined_open_link_id` stays: it is the link a person first came to the +// server through, which is what made their name one they gave themselves. The joins recorded +// before this are that link's. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // No foreign key to the link: a link's record may go while the people who joined with it stay. + yield* sql` + CREATE TABLE j5_a2a_open_link_join ( + link_id TEXT NOT NULL, + person_id TEXT NOT NULL, + joined_at TEXT NOT NULL, + PRIMARY KEY (link_id, person_id) + ) + `; + yield* sql` + CREATE INDEX j5_a2a_open_link_join_person_idx ON j5_a2a_open_link_join(person_id) + `; + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + SELECT joined_open_link_id, person_id, created_at FROM j5_a2a_human_person + WHERE joined_open_link_id IS NOT NULL + `; +}); diff --git a/apps/server/src/j5/sharing/GuestProjectIcons.test.ts b/apps/server/src/j5/sharing/GuestProjectIcons.test.ts index ce301910c371a..fdec1bcb71d9c 100644 --- a/apps/server/src/j5/sharing/GuestProjectIcons.test.ts +++ b/apps/server/src/j5/sharing/GuestProjectIcons.test.ts @@ -409,6 +409,10 @@ it.layer(testLayer)("a guest and a project's favicon", (it) => { joined_open_link_id ) VALUES (${`human:icon-full-${index}`}, 0, ${AT}, 'guest', NULL, 1, ${full.linkId}) `; + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${full.linkId}, ${`human:icon-full-${index}`}, ${AT}) + `; } yield* openLinks.revoke(link.linkId); const refusals = []; diff --git a/apps/server/src/j5/sharing/OpenLinkHttp.ts b/apps/server/src/j5/sharing/OpenLinkHttp.ts index f8e841be75d6b..f962edf735a05 100644 --- a/apps/server/src/j5/sharing/OpenLinkHttp.ts +++ b/apps/server/src/j5/sharing/OpenLinkHttp.ts @@ -21,6 +21,10 @@ import { GUEST_SESSION_SUBJECT } from "./PersonAccess.ts"; export const MEMBER_OPENED_OPEN_LINK = "You are already signed in to this server as a member. This link is for guests: send it to them rather than opening it."; +/** What someone joining is told when the name they typed is someone else's, or their own. */ +export const OPEN_LINK_NAME_TAKEN = + "That name is already in use on this server. If it is yours, open this link on the device you joined with, or ask for a link for this device."; + const decodeJoin = Schema.decodeUnknownEffect(SharingJoinRequest); const decodeDescribe = Schema.decodeUnknownEffect(SharingDescribeRequest); @@ -42,12 +46,18 @@ export const openLinkHttpRouteLayer = Layer.unwrap( const openLinks = wired.value; const auth = yield* Effect.serviceOption(EnvironmentAuth.EnvironmentAuth); const environment = yield* Effect.serviceOption(ServerEnvironment.ServerEnvironment); + /** The session a browser's cookie carries, when it carries one that works. */ + const sessionOf = (request: HttpServerRequest.HttpServerRequest) => + Option.isNone(auth) + ? Effect.succeed(null) + : auth.value.authenticateHttpRequest(request).pipe(Effect.orElseSucceed(() => null)); /** * What a link opens, asked before pairing or joining so the page can say what the person is * about to do. It spends and changes nothing. A link that would not work now gets the join * route's one refusal, whatever is wrong with it. A member's browser gets the same answer as - * anyone: it is refused at the next step, where it would pair or join. + * anyone: it is refused at the next step, where it would pair or join. A guest's browser is + * also told whom it can join as. */ const describeRoute = HttpRouter.add( "POST", @@ -60,7 +70,8 @@ export const openLinkHttpRouteLayer = Layer.unwrap( const serverName = Option.isNone(environment) ? "" : (yield* environment.value.getDescriptor).label; - return yield* openLinks.describe(decoded.value.link).pipe( + const session = yield* sessionOf(request); + return yield* openLinks.describe(decoded.value.link, session).pipe( Effect.flatMap((described) => // Each entry by its titles and icon; its project's id stays here. The favicon link // is the one a guest's own client is given once paired (`GuestProjectIcons.ts`): @@ -105,37 +116,40 @@ export const openLinkHttpRouteLayer = Layer.unwrap( const request = yield* HttpServerRequest.HttpServerRequest; // The route asks for no sign-in, but a browser sends its cookie. A member who opens the // link would be recorded as a new guest and then paired as one, so they are told - // instead, and no one is recorded. Anyone else, signed in or not, goes on. - const member = Option.isNone(auth) - ? false - : yield* auth.value.authenticateHttpRequest(request).pipe( - Effect.map((session) => session.subject !== GUEST_SESSION_SUBJECT), - Effect.orElseSucceed(() => false), - ); - if (member) return refusal(409, "signed_in_as_member", MEMBER_OPENED_OPEN_LINK); + // instead, and no one is recorded. A guest may join as themselves. Anyone else, signed + // in or not, gives a name and goes on. + const session = yield* sessionOf(request); + if (session !== null && session.subject !== GUEST_SESSION_SUBJECT) { + return refusal(409, "signed_in_as_member", MEMBER_OPENED_OPEN_LINK); + } const decoded = yield* request.json.pipe(Effect.flatMap(decodeJoin), Effect.option); if (Option.isNone(decoded)) { return refusal( 400, "invalid_request", - "A link is needed, and a name: one line of ordinary characters, up to 80 of them, with no square brackets.", + "A link is needed, and any name given is one line of ordinary characters, up to 80 of them, with no square brackets.", ); } - return yield* openLinks.join(decoded.value).pipe( - Effect.map((link) => - HttpServerResponse.jsonUnsafe({ - credential: link.credential, - expiresAt: link.expiresAt, - }), + const { token, displayName } = decoded.value; + return yield* openLinks.join({ token, displayName, session }).pipe( + Effect.map((joined) => + joined.kind === "new" + ? HttpServerResponse.jsonUnsafe({ + credential: joined.link.credential, + expiresAt: joined.link.expiresAt, + }) + : // Already paired: the browser goes on to the thread it was just given. + HttpServerResponse.jsonUnsafe({ threadId: joined.threadId }), ), Effect.catchTags({ OpenLinkRefusedError: (error) => Effect.succeed(refusal(404, "link_refused", error.message)), OpenLinkNameError: (error) => Effect.succeed(refusal(400, "invalid_request", error.message)), - // Told only to the holder of a link that works, who is about to be let in. - PersonNameTakenError: (error) => - Effect.succeed(refusal(409, "name_taken", error.message)), + // Told only to the holder of a link that works, who is about to be let in. A name is + // no proof of who someone is, so a person on another device is not let in by theirs. + PersonNameTakenError: () => + Effect.succeed(refusal(409, "name_taken", OPEN_LINK_NAME_TAKEN)), }), Effect.catch((cause) => Effect.logError("J5 open link join failed", { cause }).pipe( diff --git a/apps/server/src/j5/sharing/OpenLinks.test.ts b/apps/server/src/j5/sharing/OpenLinks.test.ts index 1e7fdb2c72bef..f686ce3cb6ddf 100644 --- a/apps/server/src/j5/sharing/OpenLinks.test.ts +++ b/apps/server/src/j5/sharing/OpenLinks.test.ts @@ -37,7 +37,7 @@ import { layer as readChangesLayer } from "../a2a/ReadChanges.ts"; import { settledReadRevisions } from "../a2a/test-support/readRevisions.ts"; import * as GuestGate from "./GuestGate.ts"; import * as GuestPairing from "./GuestPairing.ts"; -import { openLinkHttpRouteLayer } from "./OpenLinkHttp.ts"; +import { OPEN_LINK_NAME_TAKEN, openLinkHttpRouteLayer } from "./OpenLinkHttp.ts"; import * as OpenLinks from "./OpenLinks.ts"; import { People } from "./People.ts"; import * as PersonAccess from "./PersonAccess.ts"; @@ -258,6 +258,10 @@ it.layer(testLayer)("joining by an open link", (it) => { joined_open_link_id ) VALUES (${`human:full-${index}`}, 0, ${AT}, 'guest', 'Filler', 1, ${full.linkId}) `; + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${full.linkId}, ${`human:full-${index}`}, ${AT}) + `; } const deleted = yield* make("deleted"); yield* sql` @@ -358,7 +362,8 @@ it.layer(testLayer)("joining by an open link", (it) => { "[Sam", ]) { assert.strictEqual( - (yield* Effect.flip(openLinks.join({ token: good.token, displayName })))._tag, + (yield* Effect.flip(openLinks.join({ token: good.token, displayName, session: null }))) + ._tag, "OpenLinkNameError", ); } @@ -438,6 +443,125 @@ it.layer(testLayer)("joining by an open link", (it) => { }).pipe(Effect.scoped), ); + it.effect("a guest's own browser joins another link's thread as themselves (#614)", () => + Effect.gen(function* () { + const openLinks = yield* OpenLinks.OpenLinks; + const people = yield* People; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const access = yield* PersonAccess.PersonAccess; + const route = yield* joinRoute(); + const first = yield* thread("thread:self-first"); + const second = yield* thread("thread:self-second"); + const third = yield* thread("thread:self-third"); + const firstLink = yield* openLinks.create(first); + const secondLink = yield* openLinks.create(second); + const joinAsSelf = (token: string, cookie?: string) => + route.raw(JSON.stringify({ token }), cookie); + + const joined = yield* route.join(firstLink.token, "Bob Self"); + const paired = yield* auth.createBrowserSession(joined.body.credential!, { + deviceType: "desktop", + }); + const cookie = `${sessions.cookieName}=${paired.sessionToken}`; + const session = yield* auth.authenticateHttpRequest({ + method: "GET", + url: "/ws", + cookies: { [sessions.cookieName]: paired.sessionToken }, + headers: {}, + } as unknown as Parameters[0]); + const bob = (yield* guests).find((person) => person.displayName === "Bob Self")!; + const before = (yield* guests).length; + + // The page is told whom the browser can join as; anyone else's is not. + const described = yield* route.describe(secondLink.token, cookie); + assert.strictEqual((described.body as { joiningAs?: string }).joiningAs, "Bob Self"); + assert.notProperty((yield* route.describe(secondLink.token)).body, "joiningAs"); + + // No name: the guest is given the thread, and nothing is paired or recorded anew. + const added = yield* joinAsSelf(secondLink.token, cookie); + assert.strictEqual(added.status, 200); + assert.strictEqual(added.body.threadId, second); + assert.notProperty(added.body, "credential"); + assert.strictEqual((yield* guests).length, before); + assert.strictEqual(yield* access.threadAccess(session, first), "view"); + assert.strictEqual(yield* access.threadAccess(session, second), "view"); + // Each link counts them once, however often it is opened; their name stays their own word. + assert.strictEqual((yield* joinAsSelf(secondLink.token, cookie)).status, 200); + const joinsOf = (linkId: string) => + openLinks.list.pipe( + Effect.map((links) => links.find((entry) => entry.linkId === linkId)?.joined), + ); + assert.deepStrictEqual(yield* joinsOf(firstLink.linkId), [bob.personId]); + assert.deepStrictEqual(yield* joinsOf(secondLink.linkId), [bob.personId]); + const listed = (yield* guests).find((person) => person.personId === bob.personId)!; + assert.deepStrictEqual( + [listed.joinedOpenLinkId, listed.nameSelfGiven], + [firstLink.linkId, true], + ); + + // A level already held on the thread is kept, and none is carried over from another. + yield* people.rename({ personId: bob.personId, displayName: "Bob Self" }); + yield* people.putGrant({ + personId: bob.personId, + target: { kind: "thread", threadId: third }, + level: "collaborate", + }); + assert.strictEqual( + (yield* joinAsSelf((yield* openLinks.create(third)).token, cookie)).status, + 200, + ); + assert.strictEqual(yield* access.threadAccess(session, third), "collaborate"); + assert.strictEqual(yield* access.threadAccess(session, second), "view"); + + // A browser that is no guest's gives a name; a name someone has is refused with a way on. + const latest = yield* openLinks.create(yield* thread("thread:self-latest")); + assert.strictEqual((yield* joinAsSelf(latest.token)).status, 400); + assert.strictEqual( + (yield* joinAsSelf(latest.token, `${sessions.cookieName}=nope`)).status, + 400, + ); + const taken = yield* route.join(latest.token, "bob self"); + assert.strictEqual(taken.status, 409); + assert.match(taken.body.message!, /open this link on the device you joined with/); + + // A full link still lets in, and offers itself to, a guest it already counts. + const sql = yield* SqlClient.SqlClient; + for (let index = 1; index < OpenLinks.OPEN_LINK_MAX_PEOPLE; index += 1) { + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${secondLink.linkId}, ${`human:self-full-${index}`}, ${AT}) + `; + } + const offered = yield* route.describe(secondLink.token, cookie); + assert.strictEqual((offered.body as { joiningAs?: string }).joiningAs, "Bob Self"); + assert.strictEqual((yield* route.describe(secondLink.token)).status, 404); + assert.strictEqual((yield* joinAsSelf(secondLink.token, cookie)).status, 200); + assert.strictEqual((yield* route.join(secondLink.token, "One Too Many")).status, 404); + + // A guest's session bound to no one is no one: it is offered nothing and gives a name. + const loose = yield* route.join(latest.token, "Loose End"); + const looseSession = yield* auth.createBrowserSession(loose.body.credential!, { + deviceType: "desktop", + }); + const looseCookie = `${sessions.cookieName}=${looseSession.sessionToken}`; + const looseIdentity = yield* auth.authenticateHttpRequest({ + method: "GET", + url: "/ws", + cookies: { [sessions.cookieName]: looseSession.sessionToken }, + headers: {}, + } as unknown as Parameters[0]); + yield* access.unbindSession(looseIdentity.sessionId); + assert.notProperty((yield* route.describe(latest.token, looseCookie)).body, "joiningAs"); + assert.strictEqual((yield* joinAsSelf(latest.token, looseCookie)).status, 400); + + // Removed, they leave every link's list, and free their places on them. + yield* people.removePerson(bob.personId); + assert.deepStrictEqual(yield* joinsOf(firstLink.linkId), []); + assert.notInclude((yield* joinsOf(secondLink.linkId))!, bob.personId); + }).pipe(Effect.scoped), + ); + it.effect("lasts as long as the member chose, and shows on the thread's people", () => Effect.gen(function* () { const openLinks = yield* OpenLinks.OpenLinks; @@ -554,7 +678,7 @@ it.layer(testLayer)("joining by an open link", (it) => { status: 409, body: { error: "name_taken", - message: "That name is already in use on this server. Choose another.", + message: OPEN_LINK_NAME_TAKEN, }, }, displayName, @@ -577,7 +701,7 @@ it.layer(testLayer)("joining by an open link", (it) => { ["Priya", "priya", " PRIYA "], (displayName) => openLinks - .join({ token: link.token, displayName: displayName.trim() }) + .join({ token: link.token, displayName: displayName.trim(), session: null }) .pipe( Effect.as("joined"), Effect.catchTags({ PersonNameTakenError: () => Effect.succeed("taken") }), @@ -630,12 +754,16 @@ it.layer(testLayer)("joining by an open link", (it) => { joined_open_link_id ) VALUES (${`human:places-${index}`}, 0, ${AT}, 'guest', 'Filler', 1, ${link.linkId}) `; + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${link.linkId}, ${`human:places-${index}`}, ${AT}) + `; } const outcomes = yield* Effect.forEach( Array.from({ length: 8 }, (_, index) => `Racer ${index}`), (displayName) => openLinks - .join({ token: link.token, displayName }) + .join({ token: link.token, displayName, session: null }) .pipe( Effect.as("joined"), Effect.catchTags({ OpenLinkRefusedError: () => Effect.succeed("refused") }), @@ -853,6 +981,10 @@ it.layer(testLayer)("asking what a link opens", (it) => { joined_open_link_id ) VALUES (${`human:described-${index}`}, 0, ${AT}, 'guest', 'Filler', 1, ${full.linkId}) `; + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${full.linkId}, ${`human:described-${index}`}, ${AT}) + `; } const deletedThread = yield* thread("thread:undescribed-deleted"); const dead = yield* openLinks.create(deletedThread); @@ -931,10 +1063,16 @@ it.layer(Layer.merge(testLayer, readChangesLayer))( const link = yield* openLinks.create(threadId); assert.isTrue(yield* moved(), "made"); - yield* openLinks.join({ token: link.token, displayName: "Counted joiner" }); + yield* openLinks.join({ + token: link.token, + displayName: "Counted joiner", + session: null, + }); assert.isTrue(yield* moved(), "joined with"); yield* openLinks.list; - yield* Effect.flip(openLinks.join({ token: "no-such-link", displayName: "No one" })); + yield* Effect.flip( + openLinks.join({ token: "no-such-link", displayName: "No one", session: null }), + ); assert.isFalse(yield* moved(), "a read and a refused join"); yield* openLinks.revoke(link.linkId); assert.isTrue(yield* moved(), "revoked"); diff --git a/apps/server/src/j5/sharing/OpenLinks.ts b/apps/server/src/j5/sharing/OpenLinks.ts index 71547d40e1dfa..ef830d96f297e 100644 --- a/apps/server/src/j5/sharing/OpenLinks.ts +++ b/apps/server/src/j5/sharing/OpenLinks.ts @@ -48,6 +48,7 @@ import { * the level the server enforces, so a link that leaks shows the thread and no more than that. * Each person who opens it types a name and becomes a new guest with a View grant on the thread * and an ordinary single-use share link of their own; from there they are a guest like any other. + * A guest already signed in on the browser joins as themselves instead (#614). * Joining needs no sign-in: the token is 32 random bytes, which cannot be guessed, and a link * brings in only so many people. */ @@ -110,6 +111,14 @@ export type LinkDescription = Omit; }; +/** + * What joining did: recorded a new person, whose browser pairs with the share link made for them, + * or gave the link's thread to the guest whose browser it already is. + */ +export type JoinOutcome = + | { readonly kind: "new"; readonly link: SharingLink } + | { readonly kind: "existing"; readonly threadId: ThreadId }; + const decodeChosenIcon = Schema.decodeUnknownOption(Schema.fromJsonString(StoredProjectIcon)); /** The icon a person chose for a project, as it is stored; nothing when none was chosen. */ const chosenIcon = (stored: string | null) => @@ -119,10 +128,12 @@ export interface OpenLinksShape { /** * What a link would open if it were used now, for either kind of link: a named person's share * link or an open link. It reads and changes nothing, however often it is asked. Every link - * that would not work is refused alike, as the join route refuses. + * that would not work is refused alike, as the join route refuses. An open link asked about + * from a guest's own browser also says who that guest is, whom they can join as. */ readonly describe: ( link: string, + session: SessionIdentity | null, ) => Effect.Effect; /** Makes a link for a thread. The token is shown once, here. */ readonly create: ( @@ -150,17 +161,24 @@ export interface OpenLinksShape { /** Every open link, newest first, with the people who joined through it. */ readonly list: Effect.Effect, StorageError>; /** - * What the join route does: records the person under the name they typed, gives them View on - * the link's thread, and makes them a share link of their own to pair their device with. It - * checks everything before it writes, and its writes commit together or not at all. A name - * someone on the server already has is refused, and only after the link has been found good, - * so no one learns whether a name is in use without a link that works. + * What the join route does. With a name, it records a new person under it, gives them View on + * the link's thread, and makes them a share link of their own to pair their device with. A + * name someone on the server already has is refused, and only after the link has been found + * good, so no one learns whether a name is in use without a link that works. + * + * Without a name, it is a guest already signed in on this browser joining as themselves + * (#614): they are given View on the link's thread, unless they already hold a grant on it, and + * nothing is paired. A browser that is no guest's must give a name. + * + * Either way it checks everything before it writes, its writes commit together or not at all, + * and the person is counted among the link's joins. */ readonly join: (input: { readonly token: string; - readonly displayName: string; + readonly displayName: string | undefined; + readonly session: SessionIdentity | null; }) => Effect.Effect< - SharingLink, + JoinOutcome, StorageError | OpenLinkRefusedError | OpenLinkNameError | PersonNameTakenError >; } @@ -204,10 +222,24 @@ const make: Layer.Layer< const joined = (linkId: string) => sql<{ readonly person_id: string }>` - SELECT person_id FROM j5_a2a_human_person - WHERE joined_open_link_id = ${linkId} ORDER BY created_at, person_id + SELECT person_id FROM j5_a2a_open_link_join + WHERE link_id = ${linkId} ORDER BY joined_at, person_id `.pipe(Effect.mapError(storage("read who joined with a link"))); + /** The guest a browser already is, when it is one; a session bound to no one is no one. */ + const guestOf = (session: SessionIdentity | null) => + session === null + ? Effect.succeed(null) + : access + .sessionPerson(session) + .pipe( + Effect.map((person) => + person !== null && person.kind === "guest" && person.personId !== null + ? person + : null, + ), + ); + // Told when a link is made or revoked, which changes what a thread's people answer holds. const linkChanges = yield* Effect.acquireRelease(PubSub.sliding(64), (pubsub) => PubSub.shutdown(pubsub), @@ -328,6 +360,7 @@ const make: Layer.Layer< /** An open link, while it can still be joined with. */ const describeOpenLink = Effect.fn("j5.sharing.openLinks.describeOpenLink")(function* ( token: string, + session: SessionIdentity | null, ) { const nowMs = yield* Clock.currentTimeMillis; const rows = yield* sql` @@ -335,28 +368,29 @@ const make: Layer.Layer< FROM j5_a2a_open_link WHERE token_hash = ${hashToken(token).toString("hex")} `.pipe(Effect.mapError(storage("read an open link"))); const row = rows[0]; - if ( - row === undefined || - row.revoked_at !== null || - Date.parse(row.expires_at) <= nowMs || - (yield* joined(row.link_id)).length >= OPEN_LINK_MAX_PEOPLE - ) { + if (row === undefined || row.revoked_at !== null || Date.parse(row.expires_at) <= nowMs) { return null; } + // A full link still works for a guest it already counts, as joining does. + const joins = yield* joined(row.link_id); + const guest = yield* guestOf(session); + const counted = guest !== null && joins.some((join) => join.person_id === guest.personId); + if (!counted && joins.length >= OPEN_LINK_MAX_PEOPLE) return null; const opens = yield* opened({ kind: "thread", threadId: row.thread_id as ThreadId }, "view"); - return opens.length === 0 - ? null - : ({ - kind: "open", - personName: null, - opens, - expiresAt: DateTime.makeUnsafe(row.expires_at), - } satisfies LinkDescription); + if (opens.length === 0) return null; + return { + kind: "open", + personName: null, + opens, + expiresAt: DateTime.makeUnsafe(row.expires_at), + ...(guest === null || guest.displayName === null ? {} : { joiningAs: guest.displayName }), + } satisfies LinkDescription; }); return OpenLinks.of({ - describe: Effect.fn("j5.sharing.openLinks.describe")(function* (link) { - const described = (yield* describePersonLink(link)) ?? (yield* describeOpenLink(link)); + describe: Effect.fn("j5.sharing.openLinks.describe")(function* (link, session) { + const described = + (yield* describePersonLink(link)) ?? (yield* describeOpenLink(link, session)); if (described === null) return yield* new OpenLinkRefusedError({}); return described; }), @@ -438,8 +472,16 @@ const make: Layer.Layer< ), join: Effect.fn("j5.sharing.openLinks.join")(function* (input) { - // The route's schema says the same; this holds for any other caller. - if (!isPersonName(input.displayName)) return yield* new OpenLinkNameError({}); + // Who is joining: the guest this browser already is, when no name is given, or a new + // person under the name given. The route's schema checks the name too. + const { displayName } = input; + const guest = displayName === undefined ? yield* guestOf(input.session) : null; + const who = + guest ?? + (displayName !== undefined && isPersonName(displayName) + ? { newName: displayName } + : null); + if (who === null) return yield* new OpenLinkNameError({}); const nowMs = yield* Clock.currentTimeMillis; const tokenHash = hashToken(input.token).toString("hex"); const admit = Effect.gen(function* () { @@ -453,25 +495,41 @@ const make: Layer.Layer< WHERE link.token_hash = ${tokenHash} `.pipe(Effect.mapError(storage("read an open link"))); const row = rows[0]; + const joins = row === undefined ? [] : yield* joined(row.link_id); + // A guest already counted among the link's joins takes no further place on it. + const counted = guest !== null && joins.some((join) => join.person_id === guest.personId); if ( row === undefined || row.revoked_at !== null || Date.parse(row.expires_at) <= nowMs || - (yield* joined(row.link_id)).length >= OPEN_LINK_MAX_PEOPLE + (!counted && joins.length >= OPEN_LINK_MAX_PEOPLE) ) { return yield* new OpenLinkRefusedError({}); } - const guest = yield* access.createGuest({ - displayName: input.displayName, - joinedOpenLinkId: row.link_id, - }); - yield* people.putGrant({ - personId: guest.personId, - target: { kind: "thread", threadId: row.thread_id as ThreadId }, - level: "view", - }); + const threadId = row.thread_id as ThreadId; + const target = { kind: "thread", threadId } as const; + const person = + "newName" in who + ? yield* access.createGuest({ + displayName: who.newName, + joinedOpenLinkId: row.link_id, + }) + : who; + const joinedAt = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO j5_a2a_open_link_join (link_id, person_id, joined_at) + VALUES (${row.link_id}, ${person.personId}, ${joinedAt}) + ON CONFLICT (link_id, person_id) DO NOTHING + `.pipe(Effect.mapError(storage("record someone joining"))); + // View, or the level already held on the thread itself, whichever is higher: a guest + // who collaborates on it keeps that. + const held = (yield* access.listGrants(person.personId)).some( + (grant) => grant.target.kind === "thread" && grant.target.threadId === threadId, + ); + if (!held) yield* people.putGrant({ personId: person.personId, target, level: "view" }); + if (guest !== null) return { kind: "existing" as const, threadId }; // Used at once by the browser that asked, so it need not outlive the hour. - return yield* people.createLink(guest.personId, "1h"); + return { kind: "new" as const, link: yield* people.createLink(person.personId, "1h") }; }); return yield* joining .withPermits(1)(sql.withTransaction(admit)) diff --git a/apps/server/src/j5/sharing/PersonAccess.ts b/apps/server/src/j5/sharing/PersonAccess.ts index e48e9f0bb13d5..de10cc9406ff6 100644 --- a/apps/server/src/j5/sharing/PersonAccess.ts +++ b/apps/server/src/j5/sharing/PersonAccess.ts @@ -771,6 +771,8 @@ const make: Layer.Layer yield* sql`DELETE FROM j5_a2a_person_grant WHERE person_id = ${personId}`; yield* sql`DELETE FROM j5_a2a_person_session WHERE person_id = ${personId}`; yield* sql`DELETE FROM j5_a2a_guest_link WHERE person_id = ${personId}`; + // Off every open link's list of who joined, which frees their place on it. + yield* sql`DELETE FROM j5_a2a_open_link_join WHERE person_id = ${personId}`; yield* sql` DELETE FROM j5_a2a_human_person WHERE person_id = ${personId} AND kind = 'guest' `; diff --git a/apps/web/src/j5/sharing/GuestAwarePairingSurface.tsx b/apps/web/src/j5/sharing/GuestAwarePairingSurface.tsx index c1d6014a3860d..c456910c47116 100644 --- a/apps/web/src/j5/sharing/GuestAwarePairingSurface.tsx +++ b/apps/web/src/j5/sharing/GuestAwarePairingSurface.tsx @@ -34,6 +34,7 @@ import { } from "../../environments/primary"; import { APP_DISPLAY_NAME } from "../../branding"; import { projectIconColorClassName } from "../../projectIconColors"; +import { rememberLandingThread } from "./landingThread"; import { pairThroughShareLink } from "./pairedThroughShareLink"; import { NAME_NOT_USABLE } from "./shareLink.logic"; import { @@ -270,22 +271,36 @@ function JoinLinkSurface({ const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); + // A guest already signed in on this browser joins as themselves, unless they say they are not. + const [joiningAs, setJoiningAs] = useState(description.joiningAs ?? null); const join = async () => { const displayName = name.trim(); - if (!isPersonName(displayName)) { + if (joiningAs === null && !isPersonName(displayName)) { setError(NAME_NOT_USABLE); return; } setBusy(true); setError(null); try { - const response = await post(SHARING_JOIN_PATH, { token, displayName }); + const response = await post( + SHARING_JOIN_PATH, + joiningAs === null ? { token, displayName } : { token }, + ); const body = (await response.json().catch(() => null)) as { readonly credential?: unknown; + readonly threadId?: unknown; readonly message?: unknown; } | null; + if (response.ok && typeof body?.threadId === "string") { + // Already paired: the app starts afresh, and the first screen opens the thread just given. + rememberLandingThread(body.threadId); + window.location.replace("/"); + return; + } if (!response.ok || typeof body?.credential !== "string") { + // A browser no longer signed in as that guest gives a name like anyone else. + setJoiningAs(null); setError( typeof body?.message === "string" ? body.message @@ -317,29 +332,55 @@ function JoinLinkSurface({ void join(); }} > -
- - setName(event.currentTarget.value)} - value={name} - /> -
+ {joiningAs === null ? ( +
+ + setName(event.currentTarget.value)} + value={name} + /> +
+ ) : ( +

+ You are signed in here as {joiningAs}. +

+ )} {error === null ? null : ( {error} )} - +
+ + {joiningAs === null ? null : ( + + )} +
This link can be opened by several people. Each one joins on one device, and a member of the diff --git a/apps/web/src/j5/sharing/GuestLanding.tsx b/apps/web/src/j5/sharing/GuestLanding.tsx index cf1fd2dc26c83..4b9e20e8af151 100644 --- a/apps/web/src/j5/sharing/GuestLanding.tsx +++ b/apps/web/src/j5/sharing/GuestLanding.tsx @@ -24,6 +24,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { buildThreadRouteParams } from "../../threadRoutes"; import { j5Sharing } from "./guestAccess"; import { landingFor } from "./joinPage.logic"; +import { forgetLandingThread, landingThread } from "./landingThread"; import { rememberPairedThroughShareLink, wasPairedThroughShareLink, @@ -98,15 +99,23 @@ function GuestHome({ environmentId }: { readonly environmentId: EnvironmentId }) const held = asked && !grants.isPending ? (grants.data?.grants ?? null) : null; const only = held !== null && held.length === 1 ? held[0]!.target : null; const onlyThreadId = only?.kind === "thread" ? only.threadId : null; + // A thread just joined by an open link is opened once the server's list holds it, and not + // before: upstream's thread page leaves an address its list does not hold yet. + const [joinedThreadId] = useState(landingThread); + const joinedThread = useThreadShell( + joinedThreadId === null ? null : scopeThreadRef(environmentId, joinedThreadId), + ); + const openThreadId = joinedThread?.id ?? onlyThreadId; useEffect(() => { - if (onlyThreadId === null) return; + if (openThreadId === null) return; + forgetLandingThread(); void navigate({ to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(environmentId, onlyThreadId)), + params: buildThreadRouteParams(scopeThreadRef(environmentId, openThreadId)), replace: true, }); - }, [environmentId, navigate, onlyThreadId]); + }, [environmentId, navigate, openThreadId]); if (held === null) { return grants.error === null || grants.isPending || !asked ? null : ( @@ -120,7 +129,7 @@ function GuestHome({ environmentId }: { readonly environmentId: EnvironmentId }) ); } - if (onlyThreadId !== null) return null; + if (openThreadId !== null) return null; if (held.length === 0) { return ( diff --git a/apps/web/src/j5/sharing/landingThread.ts b/apps/web/src/j5/sharing/landingThread.ts new file mode 100644 index 0000000000000..d4cf00b495cf1 --- /dev/null +++ b/apps/web/src/j5/sharing/landingThread.ts @@ -0,0 +1,32 @@ +import type { ThreadId } from "@t3tools/contracts"; + +// The thread a guest was just given by joining an open link as themselves (#614). The join page +// cannot open it directly: the app may first draw from a cached thread list that predates the +// grant, and upstream's thread page leaves an address its list does not hold. So the join page +// leaves it here, in the tab's own storage, and the guest's first screen opens it once the +// server's list holds it. +const KEY = "j5:sharing:landing-thread"; + +export function rememberLandingThread(threadId: string): void { + try { + window.sessionStorage.setItem(KEY, threadId); + } catch { + // Storage that cannot be written leaves the guest on their list of what is shared. + } +} + +export function landingThread(): ThreadId | null { + try { + return window.sessionStorage.getItem(KEY) as ThreadId | null; + } catch { + return null; + } +} + +export function forgetLandingThread(): void { + try { + window.sessionStorage.removeItem(KEY); + } catch { + // Nothing was kept. + } +} diff --git a/docs/j5/product/features/shared-server.md b/docs/j5/product/features/shared-server.md index 5b2a92fa7b9ec..745f8789add45 100644 --- a/docs/j5/product/features/shared-server.md +++ b/docs/j5/product/features/shared-server.md @@ -34,7 +34,7 @@ Two constraints are in force on everything built, because retrofitting multiple **What a share promises.** A view grant is a boundary the server enforces: a guest who can view one thread can read nothing else. A collaborate grant is not a boundary. A person who can write to an agent can ask it to read any file, run any command or message any other agent, so the grant shapes what the guest sees and does not contain what they can cause. The product says this in plain words at the moment a share is made, and does not withhold useful things in order to look stricter than it is. -**A share link** is how a new person first connects. There are two kinds, and a member who manages access makes both. A link for a named person pairs one device as that person; a second device takes a second link for the same person. It carries no access of its own: it says who is connecting, and that person's grants say what they reach. **An open link** is made for one thread, and several people can join with it. It gives each person who uses it a View grant on that thread and nothing more. Each of them types a name and becomes a guest of their own; the name is marked as one they gave themselves until a member confirms or changes it, and they are not given Collaborate before then. An open link expires, and a member can revoke it, which stops new people joining and removes no one who already has. Either kind of link travels over the routes by which the server can already be reached; sharing opens no new route to the server. +**A share link** is how a new person first connects. There are two kinds, and a member who manages access makes both. A link for a named person pairs one device as that person; a second device takes a second link for the same person. It carries no access of its own: it says who is connecting, and that person's grants say what they reach. **An open link** is made for one thread, and several people can join with it. It gives each person who uses it a View grant on that thread and nothing more. Each of them types a name and becomes a guest of their own; the name is marked as one they gave themselves until a member confirms or changes it, and they are not given Collaborate before then. A guest already signed in on that device joins as themselves instead. An open link expires, and a member can revoke it, which stops new people joining and removes no one who already has. Either kind of link travels over the routes by which the server can already be reached; sharing opens no new route to the server. **A guest's view** of a server is the threads they were granted, and a project's artifacts when the grant is on the project. The server puts nothing in a guest's inbox or on their Fleet page. A guest cannot use the server's Personas or Playbooks directly, though the agents on the server can. A guest shares nothing onward, and can leave anything they were granted. @@ -86,7 +86,7 @@ Doors deliberately left open and undesigned: addressing a _duty_ rather than a p ### Open links -26. An open link is made for one thread and gives View only. Each person who opens it gives a name and becomes a separate guest with a View grant on that thread; a member raises anyone to Collaborate as they would any guest. +26. An open link is made for one thread and gives View only. Each person who opens it gives a name and becomes a separate guest with a View grant on that thread; a member raises anyone to Collaborate as they would any guest. A guest already signed in on the device they open it with joins as themselves, with no name to give, and keeps any higher level they already hold on that thread; they can still give a name instead, for another person using the same device. 27. A name a person gave themselves is shown as such until a member confirms or changes it, and that person cannot be given Collaborate until then. 28. An open link expires after the time the member chose, seven days unless they say otherwise, and a member can revoke it sooner. Either stops new people joining; people who already joined are removed one at a time. The People page shows who joined through it. @@ -110,3 +110,4 @@ Doors deliberately left open and undesigned: addressing a _duty_ rather than a p - 2026-10-10 — members and guests, grants at two levels, and share links defined; two people in one conversation moved out of the open doors and into [shared conversations](shared-conversations.md) (Jackson; [record](../../worklog/2026-10-09-multi-player-session.md)). AC3 now reads "member" where it read "person"; AC5 onward are new. Upstream's permissions were read at `2625327090`: they are per connection and server-wide, with no roles and nothing scoped to a project or thread, so a grant adds only the scope and keeps upstream's names. - 2026-10-12 — open links added: one view-only link several people can join a thread with, AC26 to AC28, numbered after AC25 so earlier numbers stand (Jackson, 2026-10-11; [#541](https://github.com/Jacksondr5/j5code/issues/541)). - 2026-10-13 — scenario wording: a View guest sees the composer, read-only, with one sentence, not "no composer" (the UI design of 2026-10-12; awaiting Jackson's read; [#535](https://github.com/Jacksondr5/j5code/issues/535)). +- 2026-10-14 — AC26: a guest already signed in on the device joins an open link's thread as themselves, rather than being asked for a name that is then refused as taken ([#614](https://github.com/Jacksondr5/j5code/issues/614)). diff --git a/packages/contracts/src/j5/sharing.ts b/packages/contracts/src/j5/sharing.ts index 30aa391ca0124..1765c2f865fa3 100644 --- a/packages/contracts/src/j5/sharing.ts +++ b/packages/contracts/src/j5/sharing.ts @@ -420,13 +420,21 @@ export const SharingLinkDescription = Schema.Struct({ opens: Schema.Array(SharingLinkOpens), /** When the link stops working if it is not used first. */ expiresAt: Schema.DateTimeUtc, + /** + * For an open link asked about from a guest's own browser: that guest's name. They can join + * as themselves, with no name to give. + */ + joiningAs: Schema.optionalKey(Schema.String), }); export type SharingLinkDescription = typeof SharingLinkDescription.Type; -/** What a person sends to join: the link's token and the name they go by. */ +/** + * What a person sends to join: the link's token and the name they go by. A guest already signed + * in on the browser leaves the name out to join as themselves. + */ export const SharingJoinRequest = Schema.Struct({ token: TrimmedNonEmptyString.check(Schema.isMaxLength(200)), - displayName: SharingPersonName, + displayName: Schema.optionalKey(SharingPersonName), }); export type SharingJoinRequest = typeof SharingJoinRequest.Type;