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

auth.ts

249 lines7.7 KB

1import {
2 AuthAdministrativeScopes,
3 AuthSessionId,
4 AuthStandardClientScopes,
5} from "@t3tools/contracts";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as References from "effect/References";
11import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
12​
13import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
14​
15import {
16 formatIssuedPairingCredential,
17 formatIssuedSession,
18 formatPairingCredentialList,
19 formatSessionList,
20} from "../cliAuthFormat.ts";
21import * as ServerConfig from "../config.ts";
22import { authScopesFlag } from "./authScopes.ts";
23import {
24 authLocationFlags,
25 type CliAuthLocationFlags,
26 DurationFromString,
27 resolveCliAuthConfig,
28} from "./config.ts";
29​
30const runWithEnvironmentAuth = <A, E>(
31 flags: CliAuthLocationFlags,
32 run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
33 options?: {
34 readonly quietLogs?: boolean;
35 },
36) =>
37 Effect.gen(function* () {
38 const logLevel = yield* GlobalFlag.LogLevel;
39 const config = yield* resolveCliAuthConfig(flags, logLevel);
40 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
41 return yield* Effect.gen(function* () {
42 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
43 return yield* run(environmentAuth);
44 }).pipe(
45 Effect.provide(
46 Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
47 Layer.provide(ServerConfig.layer(config)),
48 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
49 ),
50 ),
51 );
52 });
53​
54const ttlFlag = Flag.String("ttl").pipe(
55 Flag.withSchema(DurationFromString),
56 Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
57 Flag.optional,
58);
59​
60const jsonFlag = Flag.Boolean("json").pipe(
61 Flag.withDescription("Emit JSON instead of human-readable output."),
62 Flag.withDefault(false),
63);
64​
65const labelFlag = Flag.String("label").pipe(
66 Flag.withDescription("Optional human-readable label."),
67 Flag.optional,
68);
69​
70const subjectFlag = Flag.String("subject").pipe(
71 Flag.withDescription("Optional session subject."),
72 Flag.optional,
73);
74​
75const baseUrlFlag = Flag.String("base-url").pipe(
76 Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
77 Flag.optional,
78);
79​
80const tokenOnlyFlag = Flag.Boolean("token-only").pipe(
81 Flag.withDescription("Print only the issued bearer token."),
82 Flag.withDefault(false),
83);
84​
85const pairingCreateCommand = Command.make("create", {
86 ...authLocationFlags,
87 scopes: authScopesFlag(AuthStandardClientScopes),
88 ttl: ttlFlag,
89 label: labelFlag,
90 baseUrl: baseUrlFlag,
91 json: jsonFlag,
92}).pipe(
93 Command.withDescription("Issue a new client pairing token."),
94 Command.withHandler((flags) =>
95 runWithEnvironmentAuth(
96 flags,
97 (environmentAuth) =>
98 Effect.gen(function* () {
99 const issued = yield* environmentAuth.createPairingLink({
100 scopes: flags.scopes,
101 subject: "one-time-token",
102 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
103 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
104 });
105 const output = formatIssuedPairingCredential(issued, {
106 json: flags.json,
107 ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
108 });
109 yield* Console.log(output);
110 }),
111 {
112 quietLogs: flags.json,
113 },
114 ),
115 ),
116);
117​
118const pairingListCommand = Command.make("list", {
119 ...authLocationFlags,
120 json: jsonFlag,
121}).pipe(
122 Command.withDescription("List active client pairing tokens without revealing their secrets."),
123 Command.withHandler((flags) =>
124 runWithEnvironmentAuth(
125 flags,
126 (environmentAuth) =>
127 Effect.gen(function* () {
128 const pairingLinks = yield* environmentAuth.listPairingLinks({
129 excludeSubjects: [EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT],
130 });
131 yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
132 }),
133 {
134 quietLogs: flags.json,
135 },
136 ),
137 ),
138);
139​
140const pairingRevokeCommand = Command.make("revoke", {
141 ...authLocationFlags,
142 id: Argument.String("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
143}).pipe(
144 Command.withDescription("Revoke an active client pairing token."),
145 Command.withHandler((flags) =>
146 runWithEnvironmentAuth(flags, (environmentAuth) =>
147 Effect.gen(function* () {
148 const revoked = yield* environmentAuth.revokePairingLink(flags.id);
149 yield* Console.log(
150 revoked
151 ? `Revoked pairing credential ${flags.id}.\n`
152 : `No active pairing credential found for ${flags.id}.\n`,
153 );
154 }),
155 ),
156 ),
157);
158​
159const pairingCommand = Command.make("pairing").pipe(
160 Command.withDescription("Manage one-time client pairing tokens."),
161 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
162);
163​
164const sessionIssueCommand = Command.make("issue", {
165 ...authLocationFlags,
166 scopes: authScopesFlag(AuthAdministrativeScopes),
167 ttl: ttlFlag,
168 label: labelFlag,
169 subject: subjectFlag,
170 tokenOnly: tokenOnlyFlag,
171 json: jsonFlag,
172}).pipe(
173 Command.withDescription("Issue a scoped bearer access token for headless or remote clients."),
174 Command.withHandler((flags) =>
175 runWithEnvironmentAuth(
176 flags,
177 (environmentAuth) =>
178 Effect.gen(function* () {
179 const issued = yield* environmentAuth.issueSession({
180 scopes: flags.scopes,
181 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
182 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
183 ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
184 });
185 yield* Console.log(
186 formatIssuedSession(issued, {
187 json: flags.json,
188 tokenOnly: flags.tokenOnly,
189 }),
190 );
191 }),
192 {
193 quietLogs: flags.json || flags.tokenOnly,
194 },
195 ),
196 ),
197);
198​
199const sessionListCommand = Command.make("list", {
200 ...authLocationFlags,
201 json: jsonFlag,
202}).pipe(
203 Command.withDescription("List active sessions without revealing bearer tokens."),
204 Command.withHandler((flags) =>
205 runWithEnvironmentAuth(
206 flags,
207 (environmentAuth) =>
208 Effect.gen(function* () {
209 const sessions = yield* environmentAuth.listSessions();
210 yield* Console.log(formatSessionList(sessions, { json: flags.json }));
211 }),
212 {
213 quietLogs: flags.json,
214 },
215 ),
216 ),
217);
218​
219const sessionRevokeCommand = Command.make("revoke", {
220 ...authLocationFlags,
221 sessionId: Argument.String("session-id").pipe(
222 Argument.withDescription("Session id to revoke."),
223 Argument.withSchema(AuthSessionId),
224 ),
225}).pipe(
226 Command.withDescription("Revoke an active session."),
227 Command.withHandler((flags) =>
228 runWithEnvironmentAuth(flags, (environmentAuth) =>
229 Effect.gen(function* () {
230 const revoked = yield* environmentAuth.revokeSession(flags.sessionId);
231 yield* Console.log(
232 revoked
233 ? `Revoked session ${flags.sessionId}.\n`
234 : `No active session found for ${flags.sessionId}.\n`,
235 );
236 }),
237 ),
238 ),
239);
240​
241const sessionCommand = Command.make("session").pipe(
242 Command.withDescription("Manage bearer sessions."),
243 Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
244);
245​
246export const authCommand = Command.make("auth").pipe(
247 Command.withDescription("Manage the local auth control plane for headless deployments."),
248 Command.withSubcommands([pairingCommand, sessionCommand]),
249);