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