|
| 1 | +import { AuthAdministrativeScopes, type AuthEnvironmentScope } from "@t3tools/contracts"; |
| 2 | +import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope"; |
| 3 | +import * as Console from "effect/Console"; |
| 4 | +import * as Duration from "effect/Duration"; |
| 5 | +import * as Effect from "effect/Effect"; |
| 6 | +import * as Layer from "effect/Layer"; |
| 7 | +import * as Option from "effect/Option"; |
| 8 | +import * as References from "effect/References"; |
| 9 | +import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; |
| 10 | + |
| 11 | +import * as DeviceAuthorization from "../auth/DeviceAuthorization.fork.ts"; |
| 12 | +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 13 | +import * as ServerConfig from "../config.ts"; |
| 14 | +import { |
| 15 | + authLocationFlags, |
| 16 | + type CliAuthLocationFlags, |
| 17 | + DurationFromString, |
| 18 | + resolveCliAuthConfig, |
| 19 | +} from "./config.ts"; |
| 20 | + |
| 21 | +// The owner's half of the device authorization grant. Nothing here prints a |
| 22 | +// device code or token: the client receives its token by polling directly. |
| 23 | + |
| 24 | +const runWithDeviceAuthorization = <A, E>( |
| 25 | + flags: CliAuthLocationFlags, |
| 26 | + run: (store: DeviceAuthorization.DeviceAuthorizationStore["Service"]) => Effect.Effect<A, E>, |
| 27 | + options?: { readonly quietLogs?: boolean }, |
| 28 | +) => |
| 29 | + Effect.gen(function* () { |
| 30 | + const logLevel = yield* GlobalFlag.LogLevel; |
| 31 | + const config = yield* resolveCliAuthConfig(flags, logLevel); |
| 32 | + return yield* Effect.gen(function* () { |
| 33 | + return yield* run(yield* DeviceAuthorization.DeviceAuthorizationStore); |
| 34 | + }).pipe( |
| 35 | + Effect.provide( |
| 36 | + DeviceAuthorization.layer.pipe( |
| 37 | + Layer.provide(EnvironmentAuth.runtimeLayer), |
| 38 | + Layer.provide(ServerConfig.layer(config)), |
| 39 | + Layer.provide( |
| 40 | + Layer.succeed( |
| 41 | + References.MinimumLogLevel, |
| 42 | + options?.quietLogs ? "Error" : config.logLevel, |
| 43 | + ), |
| 44 | + ), |
| 45 | + ), |
| 46 | + ), |
| 47 | + ); |
| 48 | + }); |
| 49 | + |
| 50 | +const ENVIRONMENT_SCOPES = new Set<AuthEnvironmentScope>(AuthStandardClientScopes); |
| 51 | + |
| 52 | +const jsonFlag = Flag.Boolean("json").pipe( |
| 53 | + Flag.withDescription("Emit JSON instead of human-readable output."), |
| 54 | + Flag.withDefault(false), |
| 55 | +); |
| 56 | + |
| 57 | +const userCodeArgument = Argument.String("user-code").pipe( |
| 58 | + Argument.withDescription("The code the client displays, for example `BCDF-GHJK`."), |
| 59 | +); |
| 60 | + |
| 61 | +// Client fields come from an unauthenticated request, so they print as |
| 62 | +// escaped JSON strings that cannot move the cursor, recolor, or reorder text. |
| 63 | +const quoted = (value: string | null | undefined) => |
| 64 | + value == null ? "-" : DeviceAuthorization.escapeForTerminal(value); |
| 65 | + |
| 66 | +const formatDeviceAuthorizationList = ( |
| 67 | + requests: ReadonlyArray<DeviceAuthorization.DeviceAuthorizationRequest>, |
| 68 | +) => { |
| 69 | + if (requests.length === 0) return "No pending device authorizations.\n"; |
| 70 | + return `${requests |
| 71 | + .map((request) => |
| 72 | + [ |
| 73 | + `${request.userCode} ${request.status} expires ${request.expiresAt}`, |
| 74 | + ` label: ${quoted(request.client.label)}`, |
| 75 | + ` device: ${request.client.deviceType} ${quoted(request.client.os)}`, |
| 76 | + ` ip: ${quoted(request.client.ipAddress)}`, |
| 77 | + ` user agent: ${quoted(request.client.userAgent)}`, |
| 78 | + ` key thumbprint: ${request.proofKeyThumbprint ?? "none (bearer)"}`, |
| 79 | + ` requested scopes: ${request.requestedScopes?.join(" ") ?? "none (standard client scopes)"}`, |
| 80 | + ].join("\n"), |
| 81 | + ) |
| 82 | + .join("\n\n")}\n`; |
| 83 | +}; |
| 84 | + |
| 85 | +const deviceListCommand = Command.make("list", { |
| 86 | + ...authLocationFlags, |
| 87 | + json: jsonFlag, |
| 88 | +}).pipe( |
| 89 | + Command.withDescription("List device authorizations waiting for a decision or a poll."), |
| 90 | + Command.withHandler((flags) => |
| 91 | + runWithDeviceAuthorization( |
| 92 | + flags, |
| 93 | + (store) => |
| 94 | + store |
| 95 | + .listOpen() |
| 96 | + .pipe( |
| 97 | + Effect.flatMap((requests) => |
| 98 | + Console.log( |
| 99 | + flags.json |
| 100 | + ? DeviceAuthorization.escapeForTerminal(requests) |
| 101 | + : formatDeviceAuthorizationList(requests), |
| 102 | + ), |
| 103 | + ), |
| 104 | + ), |
| 105 | + { quietLogs: flags.json }, |
| 106 | + ), |
| 107 | + ), |
| 108 | +); |
| 109 | + |
| 110 | +const deviceApproveCommand = Command.make("approve", { |
| 111 | + ...authLocationFlags, |
| 112 | + userCode: userCodeArgument, |
| 113 | + ttl: Flag.String("ttl").pipe( |
| 114 | + Flag.withSchema(DurationFromString), |
| 115 | + Flag.withDescription("Lifetime of the issued session, for example `7d` or `30d`. Default 30d."), |
| 116 | + Flag.optional, |
| 117 | + ), |
| 118 | + scope: Flag.String("scope").pipe( |
| 119 | + Flag.withDescription( |
| 120 | + "Space-separated scopes to grant. Narrows a request; required to grant more than the standard client scopes to a client that requested none.", |
| 121 | + ), |
| 122 | + Flag.optional, |
| 123 | + ), |
| 124 | + json: jsonFlag, |
| 125 | +}).pipe( |
| 126 | + Command.withDescription( |
| 127 | + "Approve a pending device authorization. The client receives its token on its next poll.", |
| 128 | + ), |
| 129 | + Command.withHandler((flags) => |
| 130 | + runWithDeviceAuthorization( |
| 131 | + flags, |
| 132 | + (store) => |
| 133 | + Effect.gen(function* () { |
| 134 | + const scopes = Option.map(flags.scope, (value) => |
| 135 | + parseAllowedOAuthScope({ value, allowedScopes: ENVIRONMENT_SCOPES }), |
| 136 | + ); |
| 137 | + if (Option.isSome(scopes) && scopes.value === null) { |
| 138 | + return yield* Console.log( |
| 139 | + `Unknown scope. Valid scopes: ${AuthStandardClientScopes.join(" ")}\n`, |
| 140 | + ); |
| 141 | + } |
| 142 | + const approved = yield* store |
| 143 | + .approve({ |
| 144 | + userCode: flags.userCode, |
| 145 | + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), |
| 146 | + ...(Option.isSome(scopes) && scopes.value ? { scopes: scopes.value } : {}), |
| 147 | + }) |
| 148 | + .pipe( |
| 149 | + Effect.catchTag("DeviceAuthorizationScopeError", (error) => |
| 150 | + Console.log( |
| 151 | + `The client did not request that scope. Grantable: ${error.allowedScopes.join(" ")}\n`, |
| 152 | + ).pipe(Effect.as(undefined)), |
| 153 | + ), |
| 154 | + ); |
| 155 | + if (approved === undefined) return; |
| 156 | + if (Option.isNone(approved)) { |
| 157 | + return yield* Console.log( |
| 158 | + `No pending device authorization found for ${flags.userCode}.\n`, |
| 159 | + ); |
| 160 | + } |
| 161 | + const { value } = approved; |
| 162 | + yield* Console.log( |
| 163 | + flags.json |
| 164 | + ? DeviceAuthorization.escapeForTerminal({ |
| 165 | + userCode: value.userCode, |
| 166 | + client: value.client, |
| 167 | + scopes: value.scopes, |
| 168 | + ttlMs: Duration.toMillis(value.ttl), |
| 169 | + proofKeyThumbprint: value.proofKeyThumbprint, |
| 170 | + }) |
| 171 | + : [ |
| 172 | + `Approved ${value.userCode} for ${quoted(value.client.label)}.`, |
| 173 | + `Scopes: ${value.scopes.join(" ")}`, |
| 174 | + `Lifetime: ${Duration.format(value.ttl)} from the client's next poll`, |
| 175 | + `Key thumbprint: ${value.proofKeyThumbprint ?? "none (bearer)"}`, |
| 176 | + "Revoke later with `t3 auth session list` and `t3 auth session revoke <id>`.", |
| 177 | + "", |
| 178 | + ].join("\n"), |
| 179 | + ); |
| 180 | + }), |
| 181 | + { quietLogs: flags.json }, |
| 182 | + ), |
| 183 | + ), |
| 184 | +); |
| 185 | + |
| 186 | +const deviceDenyCommand = Command.make("deny", { |
| 187 | + ...authLocationFlags, |
| 188 | + userCode: userCodeArgument, |
| 189 | +}).pipe( |
| 190 | + Command.withDescription("Deny a device authorization so the client stops polling."), |
| 191 | + Command.withHandler((flags) => |
| 192 | + runWithDeviceAuthorization(flags, (store) => |
| 193 | + store |
| 194 | + .deny(flags.userCode) |
| 195 | + .pipe( |
| 196 | + Effect.flatMap((denied) => |
| 197 | + Console.log( |
| 198 | + denied |
| 199 | + ? `Denied device authorization ${flags.userCode}.\n` |
| 200 | + : `No open device authorization found for ${flags.userCode}.\n`, |
| 201 | + ), |
| 202 | + ), |
| 203 | + ), |
| 204 | + ), |
| 205 | + ), |
| 206 | +); |
| 207 | + |
| 208 | +export const deviceCommand = Command.make("device").pipe( |
| 209 | + Command.withDescription("Approve native clients that start the device authorization grant."), |
| 210 | + Command.withSubcommands([deviceListCommand, deviceApproveCommand, deviceDenyCommand]), |
| 211 | +); |
0 commit comments