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

auth.ts

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