feat(tailscale): your own devices find and connect to your boxes with no pairing code #26757
Opent3dotgg(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/26757/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/client-runtime/src/connection/model.ts line 193OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -167,2 +173,21 @@167173 export type ConnectionAttemptStage = "preparing" | "opening" | "synchronizing";168174175+/**176+ * What the latest attempt saw on one route: the host answered there, did not177+ * answer the reachability check, or the connection over it failed.178+ */179+export type ConnectionRouteOutcome = {180+ readonly routeId: string;181+ readonly kind: ConnectionRouteKind;182+ readonly address: string | null;183+} & (184+ | { readonly result: "answered" | "silent" }185+ | { readonly result: "failed"; readonly error: ConnectionAttemptError }186+);187+188+/** A route that gave no sign the host is there, as opposed to one that answered and refused. */189+export function routeDidNotAnswer(outcome: ConnectionRouteOutcome): boolean {190+ return (191+ outcome.result === "silent" ||192+ (outcome.result === "failed" &&193+ outcome.error._tag === "ConnectionTransientError" &&apps/server/src/startupAccess.ts line 184OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -99,3 +181,4 @@99181 const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>100182 privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []),101183 );184+ if (tailscaleOnly) {packages/client-runtime/src/connection/onboarding.ts lines 253 to 253OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -189,4 +234,20 @@189234 ? yield* credentials.get(entry.target.connectionId)190235 : Option.none();236+ // A Tailscale session is pinned to where it signed in, so a new address signs in again.237+ const signInBaseUrl = Option.exists(credential, isTailnetCredential)238+ ? tailnetSignInBaseUrl(input.httpBaseUrl)239+ : null;240+ const savedHttpBaseUrl = entry === undefined ? null : routeHttpBaseUrl(entry);241+ const signedIn =242+ signInBaseUrl === null ||243+ savedHttpBaseUrl === null ||244+ sameAddress(signInBaseUrl, savedHttpBaseUrl)245+ ? Option.none<TailnetConnectionRegistration>()246+ : yield* prepareTailnetRegistration({247+ httpBaseUrl: signInBaseUrl,248+ expectedEnvironmentId: input.environmentId,249+ joinsRoutes: true,250+ });191251 const registration = yield* prepareBearerConnectionUpdate({192- input,252+ input: Option.match(signedIn, {253+ onNone: () => input,packages/tailscale/src/tailscale.ts line 1125OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -453,0 +814,21 @@814+ });815+});816+817+/**818+ * Points the Serve port at this server unless another live server holds it.819+ * A root that already points here, or at a stopped loopback server, is replaced.820+ */821+export const claimTailscaleServe = Effect.fn("tailscale.claimTailscaleServe")(function* (822+ input: TailscaleServeTarget,823+) {824+ const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;825+ const holder = tailscaleServePortHolder(yield* readTailscaleServeConfig, servePort);826+ if (827+ holder._tag === "other" ||828+ (holder._tag === "proxy" &&829+ holder.target !== serveProxyTarget(input) &&830+ (yield* proxyTargetIsLive(holder.target)))831+ ) {832+ return yield* new TailscaleServeOccupiedError({ servePort });833+ }834+ yield* ensureTailscaleServe(input);
- apps/mobile/src/features/connection/tailnetDiscovery.ts lines 58 to 61OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +41,21 @@41+ for (const conflict of conflicts) {42+ const key = `${conflict.label}@${conflict.address}`;43+ if (warned.has(key)) continue;44+ warned.add(key);45+ Dialog.alert(46+ `${conflict.label} answered at a new address`,47+ `${conflict.address} is not one of its saved routes, so it was not added. Make sure that address is really this machine.`,48+ );49+ }50+ };51+52+ const update = (force: boolean) => {53+ if (!isAppActive() || !appAtomRegistry.get(environmentCatalog.catalogValueAtom).isReady) return;54+ const connected = [...appAtomRegistry.get(environmentPresentations.presentationsAtom)]55+ .filter(([, presentation]) => presentation.connection.phase === "connected")56+ .map(([id]) => id)57+ .join(",");58+ const changed = connected !== connectedKey;59+ connectedKey = connected;60+ if (connected === "" || (!force && !changed)) return;61+ if (Date.now() - lastRunAt < DISCOVERY_MIN_GAP_MS) return;apps/server/src/startupAccess.ts lines 184 to 190OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -99,3 +181,10 @@99181 const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>100182 privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []),101183 );184+ if (tailscaleOnly) {185+ const tailnet = interfaceEntries.find(186+ (entry) =>187+ !entry.internal && isIpv4Family(entry.family) && isTailnetIpv4Address(entry.address),188+ );189+ return tailnet?.address ?? "localhost";190+ }apps/server/src/ws.ts line 1902OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1795,3 +1811,4 @@17951811 }),17961812 newProjectsRoot: managedFolders.namedProjectsRoot,17971813 ...(lastEventLoopStall === undefined ? {} : { lastEventLoopStall }),1814+ ...(tailscale === undefined ? {} : { tailscale }),
- apps/server/src/cli/up.ts line 52OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+ reason: Schema.String,33+ cause: Schema.optional(Schema.Defect()),34+}) {35+ override get message(): string {36+ return this.reason;37+ }38+}39+40+const SERVICE_ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/u;41+42+/**43+ * Sets or removes (`undefined`) entries in a `service.env` file and keeps44+ * every other line, including comments, as the user wrote it.45+ */46+export const upsertServiceEnv = (47+ contents: string,48+ entries: Readonly<Record<string, string | undefined>>,49+): string => {50+ const written = new Set<string>();51+ const lines = contents.split("\n").flatMap((line) => {52+ const key = SERVICE_ENV_KEY.exec(line)?.[1];apps/server/src/ws.ts line 366OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -348,3 +362,5 @@348362 const next = { ...rest, ...event.editorConfig };349363 return [next, [{ version: 1, type: "snapshot", config: next }]];350364 }365+ case "tailscaleRead": {366+ if (tailscaleFacts(event.tailscale) === tailscaleFacts(current.tailscale)) {packages/client-runtime/src/connection/onboarding.ts line 311OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -198,0 +289,21 @@289+ }290+ const connectionId = `tailnet:${descriptor.environmentId}:${new URL(input.httpBaseUrl).origin}`;291+ const route = {292+ target: new BearerConnectionTarget({293+ environmentId: descriptor.environmentId,294+ label: descriptor.label,295+ connectionId,296+ }),297+ profile: new BearerConnectionProfile({298+ connectionId,299+ environmentId: descriptor.environmentId,300+ label: descriptor.label,301+ httpBaseUrl: input.httpBaseUrl,302+ wsBaseUrl: deriveWsBaseUrl(input.httpBaseUrl),303+ authorization: "tailnet",304+ network: "tailscale",305+ }),306+ };307+ if (input.joinsRoutes !== true) {308+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;309+ yield* registry.assertKnownAddress({ ...route, profile: Option.some(route.profile) });
- apps/server/src/cli/up.ts lines 196 to 197OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +177,21 @@177+const TAGGING_TIP = [178+ "Tip: this box is not tagged. If agents run here, tag it so they",179+ "cannot sign in to your other machines. Add to your ACL:",180+ ' "tagOwners": { "tag:server": ["autogroup:admin"] }',181+ "then run: sudo tailscale set --advertise-tags=tag:server",182+].join("\n");183+184+/**185+ * Discovery probes only the default port, so `t3 up` pins it rather than let186+ * the server fall back to the next free one. A port the user set is kept.187+ */188+export const upPortCheck = (input: {189+ readonly configuredPort: string | undefined;190+ readonly defaultPortFree: boolean;191+ /** The live server this T3 home already runs, if any. */192+ readonly running: { readonly port: number; readonly serviceManaged: boolean } | null;193+}): "ok" | "taken" | "custom" | "manual" => {194+ // The service cannot take this home over from a server started by hand.195+ if (input.running !== null && !input.running.serviceManaged) return "manual";196+ if (input.configuredPort !== undefined) {197+ return Number(input.configuredPort) === ServerConfig.DEFAULT_PORT ? "ok" : "custom";apps/web/src/components/desktop/TailnetDiscoveryCoordinator.tsx line 31OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+const DISCOVERY_MIN_GAP_MS = 30_000;12+13+/**14+ * Adds the T3 Code machines on this desktop's tailnet that offer Tailscale15+ * sign-in, from its own peer list and from each connected machine, and says so.16+ */17+export function TailnetDiscoveryCoordinator() {18+ const registry = useContext(RegistryContext);19+ const discover = useAtomCommand(discoverTailnetMachines, { reportFailure: false });20+ // Each conflict is worth one warning per app run, not one every few minutes.21+ const warned = useRef(new Set<string>());22+ const lastRunAt = useRef(0);23+ const trailing = useRef<ReturnType<typeof setTimeout>>(undefined);24+25+ const run = useEffectEvent(async () => {26+ const bridge = window.desktopBridge;27+ if (!bridge) return;28+ // A machine that connects inside the gap is covered once the gap ends.29+ const wait = lastRunAt.current + DISCOVERY_MIN_GAP_MS - Date.now();30+ if (wait > 0) {31+ trailing.current ??= setTimeout(() => {
- packages/client-runtime/src/connection/diagnosis.ts line 512OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -290,3 +502,11 @@290502 if (located === null) return null;291503 const host = input.hostLabel;292504 const failure = input.state.lastFailure;505+ // A direct route that did not answer, where every Tailscale route also failed.506+ // A refusal from an earlier attempt says nothing once this device is offline.507+ const refusal = located.hop === "server" ? failure?.tailnetRefusal : undefined;508+ const tailnetRoutes =509+ located.hop === "server" &&510+ located.cause === null &&511+ refusal === undefined &&512+ failure?._tag === "ConnectionTransientError"
- packages/contracts/src/server.ts lines 690 to 695OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -608,0 +669,21 @@669+ return `Tailscale is not installed on ${host}`;670+ case "not_running":671+ return `Tailscale is not running on ${host}`;672+ case "needs_login":673+ return `Tailscale on ${host} is signed out`;674+ case "needs_machine_approval":675+ return `Tailscale on ${host} is waiting for approval`;676+ case "stopped":677+ return `Tailscale is off on ${host}`;678+ case "starting":679+ return `Tailscale on ${host} is starting`;680+ case "unreadable":681+ return `T3 Code could not read the Tailscale status on ${host}`;682+ case "key_expired":683+ return `The Tailscale node key on ${host} has expired`;684+ case "key_expiring": {685+ const expiresAt = keyExpiry === null ? Number.NaN : Date.parse(keyExpiry);686+ return Number.isNaN(expiresAt)687+ ? `The Tailscale node key on ${host} expires soon`688+ : `The Tailscale node key on ${host} expires in ${formatRoughDuration(expiresAt - now)}`;689+ }
- packages/client-runtime/src/connection/diagnosis.ts lines 456 to 456OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -281,0 +436,21 @@436+ return [peer.online ? "online" : "offline", detail].filter(Boolean).join(", ");437+}438+439+interface TailnetVerdict {440+ readonly headline: string;441+ readonly steps: ReadonlyArray<string>;442+}443+444+/** Why every Tailscale route failed: this device, then the host's report, then the peer list. */445+function tailnetVerdict(446+ input: ConnectionDiagnosisInput,447+ routes: ReadonlyArray<ConnectionRouteOutcome>,448+ now: number,449+): TailnetVerdict {450+ const host = input.hostLabel;451+ const local = input.localTailscale;452+ const awake = `Make sure ${host} is awake and T3 Code is running on it.`;453+ if (localTailscaleDown(local?.state)) {454+ return {455+ headline: tailscaleIssueHeadline("this device", { cause: local.state, fix: "" }, null, now),456+ steps: ["Turn on Tailscale on this device and sign in. T3 Code reconnects on its own."],
- apps/server/src/cli/up.ts line 366OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -153,0 +346,21 @@346+ readonly running: { readonly port: number; readonly serviceManaged: boolean } | null;347+}): "ok" | "taken" | "custom" | "manual" => {348+ // The service cannot take this home over from a server started by hand.349+ if (input.running !== null && !input.running.serviceManaged) return "manual";350+ const port =351+ input.configuredPort === undefined ? ServerConfig.DEFAULT_PORT : Number(input.configuredPort);352+ if (!input.portFree && input.running?.port !== port) return "taken";353+ return port === ServerConfig.DEFAULT_PORT ? "ok" : "custom";354+};355+356+/** The `service.env` entries Tailscale sign-in needs, after checking the port and owner. */357+const tailscaleEntries = Effect.fn("cli.up.tailscale_entries")(function* (358+ tailscale: { readonly status: TailscaleStatus },359+ flags: { readonly owner: Option.Option<string>; readonly tailscaleServe: Option.Option<boolean> },360+ requireGrant: boolean,361+) {362+ const config = yield* ServerConfig.ServerConfig;363+ const { entries, path: serviceEnvPath } = yield* CliService.readServiceEnv(config.baseDir);364+ const tagged = tailscale.status.selfTags.length > 0;365+ // With grants required, the policy names who gets in, so the box needs no owner.366+ const owner = requireGrant ? null : yield* resolveOwner(tailscale.status, flags.owner);apps/server/src/cli/up.ts line 563OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -202,9 +549,15 @@202549 if (!routes.connect && current.connect) {203550 yield* disconnectCloud({ clearAuthorization: false });204551 }205- yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });552+ // Settings land before the service starts, so it never runs with sign-in half set up.553+ yield* CliService.writeServiceEnv(config.baseDir, {554+ T3CODE_LAN: String(routes.lan),555+ ...(signIn?.entries ?? (current.tailscale ? { T3CODE_TAILSCALE_SIGN_IN: undefined } : {})),556+ });206557 if (before.host !== undefined) {207558 yield* Console.warn(208- `service.env sets T3CODE_HOST=${before.host}, which decides where T3 Code listens. Remove it to use the local network choice.`,559+ `service.env sets T3CODE_HOST=${before.host}, which decides where T3 Code listens. Remove it to use these choices.`,209560 );210561 }562+ const after = yield* readSetup();563+ const changed =apps/server/src/cli/up.ts line 569OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -205,11 +552,18 @@205- yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });552+ // Settings land before the service starts, so it never runs with sign-in half set up.553+ yield* CliService.writeServiceEnv(config.baseDir, {554+ T3CODE_LAN: String(routes.lan),555+ ...(signIn?.entries ?? (current.tailscale ? { T3CODE_TAILSCALE_SIGN_IN: undefined } : {})),556+ });206557 if (before.host !== undefined) {207558 yield* Console.warn(208- `service.env sets T3CODE_HOST=${before.host}, which decides where T3 Code listens. Remove it to use the local network choice.`,559+ `service.env sets T3CODE_HOST=${before.host}, which decides where T3 Code listens. Remove it to use these choices.`,209560 );210561 }562+ const after = yield* readSetup();563+ const changed =564+ !sameSettings(before.settings, after.settings) || (routes.connect && !current.connect);211565212566 const printServeCommand = Effect.fn(function* (reason: string) {213567 const serve = yield* resolveCliCommand("serve");214568 yield* Console.log(215- `${reason} Run this and keep the terminal open:\n ${serve}${routes.lan ? " --lan" : ""}\n`,569+ `${reason} Run this and keep the terminal open:\n ${serve}${routes.lan ? " --lan" : ""}${
- apps/server/src/cli/up.ts line 276OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -154,0 +256,21 @@256+const resolveOwner = Effect.fn("cli.up.resolveOwner")(function* (257+ status: TailscaleStatus,258+ ownerLogin: Option.Option<string>,259+) {260+ if (status.selfTags.length === 0) {261+ if (status.selfUserId === null) {262+ return yield* upError("Tailscale did not report this host's user.");263+ }264+ const own: Owner = { userId: status.selfUserId, login: loginOf(status, status.selfUserId) };265+ if (Option.isSome(ownerLogin)) {266+ const requested = yield* ownerForLogin(status, ownerLogin.value);267+ if (requested.userId !== own.userId) {268+ return yield* upError(269+ `This host is not tagged, so its owner is its own Tailscale user (${own.login ?? own.userId}). Drop --owner, or tag the host first.`,270+ );271+ }272+ }273+ return own;274+ }275+ if (Option.isSome(ownerLogin)) return yield* ownerForLogin(status, ownerLogin.value);276+ if (!interactiveTerminal()) {
- apps/server/src/cli/up.ts line 393OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -174,0 +373,21 @@373+ const port =374+ input.configuredPort === undefined ? ServerConfig.DEFAULT_PORT : Number(input.configuredPort);375+ if (!input.portFree && input.running?.port !== port) return "taken";376+ return port === ServerConfig.DEFAULT_PORT ? "ok" : "custom";377+};378+379+/** The `service.env` entries Tailscale sign-in needs, after checking the port and owner. */380+const tailscaleEntries = Effect.fn("cli.up.tailscale_entries")(function* (381+ tailscale: { readonly status: TailscaleStatus },382+ flags: {383+ readonly owner: Option.Option<string>;384+ readonly tailscaleServe: Option.Option<boolean>;385+ readonly yes: boolean;386+ },387+ requireGrant: boolean,388+) {389+ const config = yield* ServerConfig.ServerConfig;390+ const { entries, path: serviceEnvPath } = yield* CliService.readServiceEnv(config.baseDir);391+ const tagged = tailscale.status.selfTags.length > 0;392+ // With grants required, the policy names who gets in, so the box needs no owner.393+ const owner = requireGrant
- packages/client-runtime/src/authorization/tailnet.ts lines 97 to 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ ...(input.clientMetadata === undefined ? {} : { clientMetadata: input.clientMetadata }),81+ }).pipe(Effect.mapError((error) => mapRemoteEnvironmentError(error)));82+ const issuedAt = yield* Clock.currentTimeMillis;83+ return new TailnetConnectionCredential({84+ signInBaseUrl: input.httpBaseUrl,85+ accessToken: access.access_token,86+ expiresAtEpochMs: issuedAt + access.expires_in * 1_000,87+ dpopThumbprint: thumbprint,88+ });89+ },90+);91+92+/**93+ * Tailscale sessions keyed by credential id. A session renews by signing in94+ * again at its pinned address, before expiry or after a rejection, so every95+ * host check runs again. Concurrent callers share one sign-in.96+ */97+export const makeTailnetSessions = (input: {98+ readonly credentials: ConnectionCredentialStore.ConnectionCredentialStore["Service"];99+ readonly signer: ManagedRelayDpopSigner["Service"];100+ readonly httpClient: HttpClient.HttpClient;packages/client-runtime/src/authorization/tailnet.ts lines 28 to 29OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +9,21 @@9+10+import { TailnetConnectionCredential } from "../connection/catalog.ts";11+import type * as ConnectionCredentialStore from "../connection/credentialStore.ts";12+import { credentialMissingError, mapRemoteEnvironmentError } from "../connection/errors.ts";13+import {14+ ConnectionBlockedError,15+ DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,16+ type ConnectionAttemptError,17+} from "../connection/model.ts";18+import { tailnetRefusalError } from "../connection/tailnet.ts";19+import { environmentEndpointUrl } from "../environment/endpoint.ts";20+import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";21+import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiGroupClient } from "../rpc/http.ts";22+import { exchangeRemoteDpopAccessToken } from "./remote.ts";23+24+const TAILNET_SIGN_IN_TIMEOUT_MS = 10_000;25+26+const isTailnetCredential = Schema.is(TailnetConnectionCredential);27+28+const proofError = () =>29+ new ConnectionBlockedError({
- packages/client-runtime/src/connection/diagnosis.test.ts lines 235 to 238OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -128,0 +215,21 @@215+ );216+ });217+218+ it("names the check a host's Tailscale sign-in refused instead of guessing", () => {219+ const refused = (reason: "blocked" | "rate_limited") => {220+ const error = tailnetRefusalError(reason);221+ return diagnose({ ...backoff(error), routes: [{ ...TAILNET_FAILED, error }] }, "direct");222+ };223+ expect(refused("blocked")).toMatchObject({224+ headline: "Mac mini blocked this device",225+ steps: [226+ "On another device connected to Mac mini, open Settings > Environments and unblock this device.",227+ "Or run `t3 pair` on Mac mini, pair this device with the code, then unblock it.",228+ ],229+ moreInfoUrl: expect.stringMatching(/#tailscale-troubleshooting$/),230+ });231+ expect(refused("blocked")?.facts).toContainEqual(["Cause", "blocked"]);232+ // Add forms show the error itself, so it reads as a sentence.233+ expect(tailnetRefusalError("routes_for_others").message).toBe(234+ "This device is a subnet router, so it cannot sign in. Traffic it forwards could arrive as this device, so no grant lets it in. Stop advertising routes on it. Or pair this device with a code instead.",235+ );
- apps/server/src/cli/up.ts line 568OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +548,21 @@548+ const offered = [549+ ...(tailscale.ok ? ["--tailscale"] : []),550+ ...(before.connect === null ? [] : ["--connect"]),551+ "--lan",552+ ];553+ return yield* upError(554+ `No terminal. Choose access with ${offered.join(", ")}, or use --yes for the default. See \`t3 up --help\`.`,555+ );556+ }557+ // Nothing to run in the background, but a route left on still gets turned off.558+ if (!before.service.installed && !routes.connect && !routes.lan && !routes.tailscale) {559+ if (current.connect || before.connectRevoked) {560+ yield* disconnectCloud({ clearAuthorization: false });561+ }562+ yield* CliService.writeServiceEnv(config.baseDir, {563+ ...(current.lan ? { T3CODE_LAN: "false" } : {}),564+ ...(current.tailscale ? { T3CODE_TAILSCALE_SIGN_IN: undefined } : {}),565+ });566+ return yield* Console.log(formatNextSteps(routes));567+ }568+ if (routes.tailscale && !tailscale.ok) {apps/server/src/cli/up.ts line 601OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +581,21 @@581+ const planned = Object.fromEntries(582+ Object.entries({ ...before.entries, ...writes }).flatMap(([key, value]) =>583+ value === undefined ? [] : [[key, value] as const],584+ ),585+ );586+ const { installedVersion } = before.service;587+ const newer =588+ installedVersion !== undefined &&589+ compareExactServiceVersions(installedVersion, packageJson.version) > 0;590+ // A running service reads these settings only at start. Asked before anything591+ // changes, so a declined restart leaves service.env matching what it runs.592+ // A stopped service of this version is not current, so reconcile starts it;593+ // a newer one is left alone and needs this restart to start.594+ const stopped = before.service.problems?.includes("service-stopped") === true;595+ const restart =596+ before.service.installed &&597+ (before.service.current || newer) &&598+ (!sameSettings(before.settings, serviceSettings(planned, true)) ||599+ (routes.connect && !current.connect) ||600+ stopped);601+ if (restart && interactive && !stopped) {apps/server/src/cli/up.ts line 579OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +559,21 @@559+ if (current.connect || before.connectRevoked) {560+ yield* disconnectCloud({ clearAuthorization: false });561+ }562+ yield* CliService.writeServiceEnv(config.baseDir, {563+ ...(current.lan ? { T3CODE_LAN: "false" } : {}),564+ ...(current.tailscale ? { T3CODE_TAILSCALE_SIGN_IN: undefined } : {}),565+ });566+ return yield* Console.log(formatNextSteps(routes));567+ }568+ if (routes.tailscale && !tailscale.ok) {569+ return yield* upError(`${tailscale.reason} Then run t3 up again.`);570+ }571+572+ const requireGrant = flags.requireGrant || before.requireGrant;573+ const signIn =574+ routes.tailscale && tailscale.ok575+ ? yield* tailscaleEntries(tailscale, flags, requireGrant)576+ : null;577+ const writes: Readonly<Record<string, string | undefined>> = {578+ T3CODE_LAN: String(routes.lan),579+ ...(signIn?.entries ?? (current.tailscale ? { T3CODE_TAILSCALE_SIGN_IN: undefined } : {})),
- apps/server/src/cli/up.ts lines 701 to 703OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -313,10 +685,19 @@313685 yield* Console.warn(314- `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,686+ `T3CODE_HOST=${before.host} in service.env overrides the network choices. Remove it to apply them.`,315687 );316688 }317689318690 const printServeCommand = Effect.fn(function* (reason: string) {691+ // The same settings the service would read from service.env.319692 const { command } = yield* resolveHostCliCommand("serve", [320693 ...Option.match(flags.baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),321- // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.694+ // Explicit either way, so settings in the shell cannot override the choices.322695 routes.lan ? "--lan" : "--no-lan",696+ routes.tailscale ? "--tailscale-sign-in" : "--no-tailscale-sign-in",697+ ...(planned.T3CODE_PORT === undefined ? [] : ["--port", planned.T3CODE_PORT]),698+ ...(routes.tailscale && planned.T3CODE_TAILSCALE_OWNER !== undefined699+ ? ["--tailscale-owner", planned.T3CODE_TAILSCALE_OWNER]700+ : []),701+ ...(routes.tailscale && parseBoolean(planned.T3CODE_TAILSCALE_SERVE) === true702+ ? ["--tailscale-serve"]703+ : []),
- apps/server/src/auth/TailnetSignIn.ts lines 880 to 890OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +639,21 @@639+ )(function* (stableNodeId) {640+ return yield* blocks641+ .unblock({ stableNodeId })642+ .pipe(Effect.mapError(accessError("Could not unblock the device.")));643+ });644+645+ if (config.tailscaleSignInEnabled === true) {646+ yield* recheckSessions.pipe(647+ Effect.repeat(Schedule.spaced(RECHECK_INTERVAL)),648+ Effect.forkScoped,649+ );650+ } else {651+ // Turning sign-in off ends Tailscale sessions now, not when they expire.652+ const signedIn = new Map(653+ (yield* sessions.listActive())654+ .filter((session) => session.subject.startsWith(TAILNET_SUBJECT_PREFIX))655+ .map((session) => [656+ session.subject.slice(TAILNET_SUBJECT_PREFIX.length),657+ session.client.label ?? null,658+ ]),659+ );
- apps/server/src/cli/up.ts lines 624 to 628OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -237,8 +595,18 @@237- });595+ const offered = [596+ ...(tailscale.ok ? ["--tailscale"] : []),597+ ...(before.connect === null ? [] : ["--connect"]),598+ "--lan",599+ ];600+ return yield* upError(601+ `No terminal. Choose access with ${offered.join(", ")}, or use --yes for the default. See \`t3 up --help\`.`,602+ );238603 }239604 // Nothing to run in the background, but a route left on still gets turned off.240- if (!before.service.installed && !routes.connect && !routes.lan) {605+ if (!before.service.installed && !routes.connect && !routes.lan && !routes.tailscale) {241606 if (current.connect || before.connectRevoked) {242607 yield* disconnectCloud({ clearAuthorization: false });243608 }244- if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });609+ yield* CliService.writeServiceEnv(config.baseDir, {610+ ...(current.lan ? { T3CODE_LAN: "false" } : {}),611+ ...(current.tailscale ? TAILSCALE_OFF : {}),612+ });
- apps/server/src/tailscaleServe.ts line 120OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +100,21 @@100+ logContext,101+ ),102+ ),103+ Effect.catch((cause) =>104+ Effect.logWarning("Failed to disable Tailscale Serve", {105+ cause,106+ ...logContext,107+ }),108+ ),109+ )110+ : Effect.void,111+ ),112+ ),113+ );114+115+ let lastFailure: string | undefined;116+ // The daemon applies the mapping before the CLI exits, so an interrupt117+ // between the two would leave it behind with nothing to remove it.118+ // Shutdown waits for the commands' own timeouts instead.119+ const attempt = claimTailscaleServe(target).pipe(120+ Effect.tap(() => Ref.set(configured, true)),
t3dotgg(GitHub profile, opens in a new tab) closed this
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XS
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed