Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

auth.ts

331 lines10.7 KB

1import { AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as References from "effect/References";
7import * as Schema from "effect/Schema";
8import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
9​
10import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
11​
12import {
13 formatConnectDeviceList,
14 formatIssuedPairingCredential,
15 formatIssuedSession,
16 formatPairingCredentialList,
17 formatSessionList,
18} from "../cliAuthFormat.ts";
19import * as ServerConfig from "../config.ts";
20import { authScopesFlag } from "./authScopes.ts";
21import {
22 authLocationFlags,
23 type CliAuthLocationFlags,
24 DurationFromString,
25 resolveCliAuthConfig,
26} from "./config.ts";
27​
28const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E>(
29 flags: CliAuthLocationFlags,
30 run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
31 options?: {
32 readonly quietLogs?: boolean;
33 },
34) {
35 const logLevel = yield* GlobalFlag.LogLevel;
36 const config = yield* resolveCliAuthConfig(flags, logLevel, options);
37 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
38 return yield* Effect.gen(function* () {
39 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
40 return yield* run(environmentAuth);
41 }).pipe(
42 Effect.provide(
43 Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
44 Layer.provide(ServerConfig.layer(config)),
45 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
46 ),
47 ),
48 );
49});
50​
51const ttlFlag = Flag.String("ttl").pipe(
52 Flag.withSchema(DurationFromString),
53 Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
54 Flag.optional,
55);
56​
57const jsonFlag = Flag.Boolean("json").pipe(
58 Flag.withDescription("Emit JSON instead of human-readable output."),
59 Flag.withDefault(false),
60);
61​
62const labelFlag = Flag.String("label").pipe(
63 Flag.withDescription("Optional human-readable label."),
64 Flag.optional,
65);
66​
67const subjectFlag = Flag.String("subject").pipe(
68 Flag.withDescription("Optional session subject."),
69 Flag.optional,
70);
71​
72const baseUrlFlag = Flag.String("base-url").pipe(
73 Flag.withSchema(
74 Schema.URLFromString.pipe(
75 Schema.check(
76 Schema.makeFilter((url) => url.protocol === "http:" || url.protocol === "https:", {
77 expected: "an http:// or https:// URL",
78 }),
79 ),
80 ),
81 ),
82 Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
83 Flag.optional,
84);
85​
86const tokenOnlyFlag = Flag.Boolean("token-only").pipe(
87 Flag.withDescription("Print only the issued bearer token."),
88 Flag.withDefault(false),
89);
90​
91const pairingCreateCommand = Command.make("create", {
92 ...authLocationFlags,
93 scopes: authScopesFlag(AuthStandardClientScopes),
94 ttl: ttlFlag,
95 label: labelFlag,
96 baseUrl: baseUrlFlag,
97 json: jsonFlag,
98}).pipe(
99 Command.withDescription("Issue a new client pairing token."),
100 Command.withHandler((flags) =>
101 runWithEnvironmentAuth(
102 flags,
103 (environmentAuth) =>
104 Effect.gen(function* () {
105 const issued = yield* environmentAuth.createPairingLink({
106 scopes: flags.scopes,
107 subject: "one-time-token",
108 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
109 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
110 });
111 const output = formatIssuedPairingCredential(issued, {
112 json: flags.json,
113 ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value.href } : {}),
114 });
115 yield* Console.log(output);
116 }),
117 {
118 quietLogs: flags.json,
119 },
120 ),
121 ),
122);
123​
124const pairingListCommand = Command.make("list", {
125 ...authLocationFlags,
126 json: jsonFlag,
127}).pipe(
128 Command.withDescription("List active client pairing tokens without revealing their secrets."),
129 Command.withHandler((flags) =>
130 runWithEnvironmentAuth(
131 flags,
132 (environmentAuth) =>
133 Effect.gen(function* () {
134 const pairingLinks = yield* environmentAuth.listPairingLinks({
135 excludeSubjects: [EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT],
136 });
137 yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
138 }),
139 {
140 quietLogs: flags.json,
141 },
142 ),
143 ),
144);
145​
146const pairingRevokeCommand = Command.make("revoke", {
147 ...authLocationFlags,
148 id: Argument.String("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
149}).pipe(
150 Command.withDescription("Revoke an active client pairing token."),
151 Command.withHandler((flags) =>
152 runWithEnvironmentAuth(flags, (environmentAuth) =>
153 Effect.gen(function* () {
154 const revoked = yield* environmentAuth.revokePairingLink(flags.id);
155 yield* Console.log(
156 revoked
157 ? `Revoked pairing credential ${flags.id}.\n`
158 : `No active pairing credential found for ${flags.id}.\n`,
159 );
160 }),
161 ),
162 ),
163);
164​
165const pairingCommand = Command.make("pairing").pipe(
166 Command.withDescription("Manage one-time client pairing tokens."),
167 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
168);
169​
170const connectDeviceListCommand = Command.make("list", {
171 ...authLocationFlags,
172 json: jsonFlag,
173}).pipe(
174 Command.withDescription(
175 "List T3 Connect devices waiting for approval and those already trusted.",
176 ),
177 Command.withHandler((flags) =>
178 runWithEnvironmentAuth(
179 flags,
180 (environmentAuth) =>
181 Effect.gen(function* () {
182 const waiting = (yield* environmentAuth.listPairingLinks()).flatMap((link) =>
183 link.connectDeviceRequest ? [link.connectDeviceRequest] : [],
184 );
185 const trusted = yield* environmentAuth.listConnectDevices();
186 yield* Console.log(formatConnectDeviceList({ waiting, trusted }, { json: flags.json }));
187 }),
188 { quietLogs: flags.json },
189 ),
190 ),
191);
192​
193const verificationCodeArgument = Argument.String("code").pipe(
194 Argument.withDescription("The code the device shows, such as `K7QM-2XFD`."),
195);
196​
197const connectDeviceApproveCommand = Command.make("approve", {
198 ...authLocationFlags,
199 code: verificationCodeArgument,
200}).pipe(
201 Command.withDescription("Approve the waiting T3 Connect device that shows this code."),
202 Command.withHandler((flags) =>
203 runWithEnvironmentAuth(flags, (environmentAuth) =>
204 Effect.gen(function* () {
205 const approved = yield* environmentAuth.approveConnectDeviceByCode(flags.code);
206 yield* Console.log(
207 approved
208 ? `Approved ${flags.code}. The device connects on its next try.\n`
209 : `No device waiting for approval shows ${flags.code}.\n`,
210 );
211 }),
212 ),
213 ),
214);
215​
216const connectDeviceRevokeCommand = Command.make("revoke", {
217 ...authLocationFlags,
218 code: verificationCodeArgument,
219}).pipe(
220 Command.withDescription("Stop trusting a T3 Connect device and end its sessions."),
221 Command.withHandler((flags) =>
222 runWithEnvironmentAuth(flags, (environmentAuth) =>
223 Effect.gen(function* () {
224 const outcome = yield* environmentAuth.revokeConnectDeviceByCode(flags.code);
225 yield* Console.log(
226 outcome === "revoked"
227 ? `Revoked ${flags.code}. If approval for new devices is off, it can connect again on its own.\n`
228 : outcome === "ambiguous"
229 ? `More than one trusted device shows ${flags.code}; revoke it from a client.\n`
230 : `No trusted device shows ${flags.code}.\n`,
231 );
232 }),
233 ),
234 ),
235);
236​
237const connectDeviceCommand = Command.make("connect-device").pipe(
238 Command.withDescription("Approve and revoke devices that reach this host through T3 Connect."),
239 Command.withSubcommands([
240 connectDeviceListCommand,
241 connectDeviceApproveCommand,
242 connectDeviceRevokeCommand,
243 ]),
244);
245​
246const sessionIssueCommand = Command.make("issue", {
247 ...authLocationFlags,
248 scopes: authScopesFlag(AuthStandardClientScopes),
249 ttl: ttlFlag,
250 label: labelFlag,
251 subject: subjectFlag,
252 tokenOnly: tokenOnlyFlag,
253 json: jsonFlag,
254}).pipe(
255 Command.withDescription("Issue a scoped bearer access token for headless or remote clients."),
256 Command.withHandler((flags) =>
257 runWithEnvironmentAuth(
258 flags,
259 (environmentAuth) =>
260 Effect.gen(function* () {
261 const issued = yield* environmentAuth.issueSession({
262 scopes: flags.scopes,
263 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
264 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
265 ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
266 });
267 yield* Console.log(
268 formatIssuedSession(issued, {
269 json: flags.json,
270 tokenOnly: flags.tokenOnly,
271 }),
272 );
273 }),
274 {
275 quietLogs: flags.json || flags.tokenOnly,
276 },
277 ),
278 ),
279);
280​
281const sessionListCommand = Command.make("list", {
282 ...authLocationFlags,
283 json: jsonFlag,
284}).pipe(
285 Command.withDescription("List active sessions without revealing bearer tokens."),
286 Command.withHandler((flags) =>
287 runWithEnvironmentAuth(
288 flags,
289 (environmentAuth) =>
290 Effect.gen(function* () {
291 const sessions = yield* environmentAuth.listSessions();
292 yield* Console.log(formatSessionList(sessions, { json: flags.json }));
293 }),
294 {
295 quietLogs: flags.json,
296 },
297 ),
298 ),
299);
300​
301const sessionRevokeCommand = Command.make("revoke", {
302 ...authLocationFlags,
303 sessionId: Argument.String("session-id").pipe(
304 Argument.withDescription("Session id to revoke."),
305 Argument.withSchema(AuthSessionId),
306 ),
307}).pipe(
308 Command.withDescription("Revoke an active session."),
309 Command.withHandler((flags) =>
310 runWithEnvironmentAuth(flags, (environmentAuth) =>
311 Effect.gen(function* () {
312 const revoked = yield* environmentAuth.revokeSession(flags.sessionId);
313 yield* Console.log(
314 revoked
315 ? `Revoked session ${flags.sessionId}.\n`
316 : `No active session found for ${flags.sessionId}.\n`,
317 );
318 }),
319 ),
320 ),
321);
322​
323const sessionCommand = Command.make("session").pipe(
324 Command.withDescription("Manage bearer sessions."),
325 Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
326);
327​
328export const authCommand = Command.make("auth").pipe(
329 Command.withDescription("Manage the local auth control plane for headless deployments."),
330 Command.withSubcommands([pairingCommand, sessionCommand, connectDeviceCommand]),
331);