Skip to content

Commit 739aad2

Browse files
donjor-agent[bot]donjor
authored andcommitted
feat(server): owner-approved device authorization for native clients (#1483)
## Problem A headless native client has no way to get a token without a person copying it through chat or a browser. The existing routes need a pairing credential first, and handing that over is the same copy-paste problem. ## Change Adds an RFC 8628-style device grant, approved by the owner on the host. 1. Client: `POST /oauth/device_authorization` 2. Owner: `t3 auth device list` 3. Owner: `t3 auth device approve <user-code>` 4. Client: polls `POST /oauth/device_token` | Aspect | Rule | | --- | --- | | Approval | Host CLI only; no HTTP route can approve | | Device code | SHA-256 digest at rest; single use | | Key binding | DPoP at start binds the request and the session | | Scopes | Requested, else standard; `--scope` narrows only | | Lifetime | `--ttl`, default 30 days; renew with a new grant | | Revocation | `t3 auth session revoke <id>` | | Browsers | Refused when `Origin` or `Sec-Fetch-Site` is present; Node `fetch` passes | | Abuse cap | 20 open requests, admitted atomically; 10-minute expiry | | Replay | Each poll needs a later proof `iat` | | Unauth state | Only the capped table; no replay markers | | Labels | Control and format characters refused | | CLI display | Client fields print as escaped JSON | Existing scope checks are unchanged: the result is an ordinary `SessionStore` session. The table lands through `ForkSchema.ts`, under a new `device-auth` domain. ### Client protocol ```text POST /oauth/device_authorization (form) client_label required, max 120, no control chars client_os optional, same rules scope optional, space-separated DPoP header optional, binds the key → {device_code, user_code: "XXXX-XXXX", expires_in: 600, interval: 5} POST /oauth/device_token (form, + DPoP proof when bound) grant_type=urn:ietf:params:oauth:grant-type:device_code device_code each poll: fresh proof, iat later than the last → 400 authorization_pending | slow_down | access_denied | expired_token | invalid_grant | invalid_dpop_proof → 200 {access_token, token_type: "DPoP"|"Bearer", expires_in, scope} ``` ## Scope and approval Requested by the owner to connect a key-bound native client without passing a secret through any channel. Merging deploys nothing: production use needs the fork build on the host and an owner approval per client. ## Verification | Check | Result | | --- | --- | | `vp run typecheck` in `apps/server` | exit 0 | | `vp test run` device, CLI, persistence | 82 passed | | Concurrent starts on the old cap | 40 admitted; now 20 | | Flood test on the old routes | 80 markers; now 0 | | `vp run knip:check` | exit 0 | | `vp run fork:ci` | exit 0 | | Security review | no high; three medium fixed | | Live server or real client | not checked | <details> <summary>Known limits</summary> | Limit | Detail | | --- | --- | | Cap exhaustion | Anyone reaching the endpoint can fill the 20 slots; only this flow blocks | | Label | Client-controlled; the owner checks IP and thumbprint before approving | | Open sockets | Revoke blocks new requests and upgrades; an open WebSocket keeps its upgrade scopes until it closes | | Lifetime | 30-day DPoP default exceeds the 1-hour `/oauth/token` exchange on purpose: this grant is the durable path | </details> 🤖 claude-opus-5-5 via Claude Code in T3 Code ## Fork trailers Squashes: - 24b215d feat(server): owner-approved device authorization for native clients (#1483) (#1483) - f0f426e fixup! feat(server): owner-approved device authorization for native clients (#1483) (#1483) - ace227b feat(server): owner-approved device authorization for native clients (#1483) (#1483) - f925704 fixup! feat(server): owner-approved device authorization for native clients (#1483) (#1483) Fork-Domain: device-auth Fork-Tier: core Co-authored-by: donjor <[email protected]>
1 parent eb1bf01 commit 739aad2

9 files changed

Lines changed: 1334 additions & 1 deletion

File tree

‎.github/pull_request_template.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ the change. Upload evidence to GitHub and embed or link it here. Never commit PR
5050
backend-attach
5151
browser-bookmarks
5252
custom-agents
53+
device-auth
5354
distribution
5455
fork-meta
5556
github-issues

‎apps/server/src/auth/DeviceAuthorization.fork.test.ts‎

Lines changed: 483 additions & 0 deletions
Large diffs are not rendered by default.

‎apps/server/src/auth/DeviceAuthorization.fork.ts‎

Lines changed: 575 additions & 0 deletions
Large diffs are not rendered by default.

‎apps/server/src/cli/auth.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as References from "effect/References";
77
import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
88

99
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
10+
import { deviceCommand } from "./authDevice.fork.ts"; // fork-hook: device-auth/cli-device-import
1011

1112
import {
1213
formatIssuedPairingCredential,
@@ -240,5 +241,5 @@ const sessionCommand = Command.make("session").pipe(
240241

241242
export const authCommand = Command.make("auth").pipe(
242243
Command.withDescription("Manage the local auth control plane for headless deployments."),
243-
Command.withSubcommands([pairingCommand, sessionCommand]),
244+
Command.withSubcommands([pairingCommand, sessionCommand, deviceCommand]), // fork-hook: device-auth/cli-device-command
244245
);
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
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+
);

‎apps/server/src/persistence/ForkSchema.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,24 @@ const FORK_TABLES = [
3838
)`,
3939
`CREATE INDEX IF NOT EXISTS idx_projection_thread_issues_issue
4040
ON projection_thread_issues(host, repository, number)`,
41+
// Owner-approved native client requests for the device-auth domain. Only a
42+
// digest of the device code is stored; rows prune once expired.
43+
`CREATE TABLE IF NOT EXISTS auth_device_authorizations (
44+
device_code_hash TEXT PRIMARY KEY,
45+
user_code TEXT NOT NULL UNIQUE,
46+
status TEXT NOT NULL,
47+
client_json TEXT NOT NULL,
48+
requested_scopes TEXT,
49+
proof_key_thumbprint TEXT,
50+
created_at TEXT NOT NULL,
51+
expires_at TEXT NOT NULL,
52+
last_polled_at TEXT,
53+
last_proof_iat INTEGER,
54+
granted_scopes TEXT,
55+
granted_ttl_ms INTEGER,
56+
decided_at TEXT,
57+
session_id TEXT
58+
)`,
4159
] as const;
4260

4361
/**

‎apps/server/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";
9696
import * as Keybindings from "./keybindings.ts";
9797
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
9898
import * as ServerOwnership from "./serverOwnership.ts";
99+
import * as DeviceAuthorizationRoutes from "./auth/DeviceAuthorization.fork.ts"; // fork-hook: device-auth/server-routes-import
99100
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
100101
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
101102
import * as ServerSettings from "./serverSettings.ts";
@@ -766,6 +767,7 @@ const layerMakeRoutes = Layer.mergeAll(
766767
ServerBrowserStream.routeLayer,
767768
ServerHttp.layerStaticAndDevRoute,
768769
Ws.layer,
770+
DeviceAuthorizationRoutes.routeLayer, // fork-hook: device-auth/server-routes
769771
),
770772
McpHttpServer.layer.pipe(
771773
Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),

‎docs/fork/internals/fork-delta.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ A per-file diff says nothing about seam growth until `git cat-file -e origin/mai
157157
| [backend-attach](#backend-attach) | Active | core | Upstream ships desktop attach |
158158
| [github-issues](#github-issues) | Active | core, bugfix | Upstream ships multi-environment Issues |
159159
| [custom-agents](#custom-agents) | Active | core | Upstream main-thread agent selection |
160+
| [device-auth](#device-auth) | Active | core | Upstream ships native client approval |
160161
| [markdown-editing](#markdown-editing) | Active | core | Upstream ships rich Markdown editing |
161162
| [workspace-files](#workspace-files) | Active | core | Upstream supports linked artifacts |
162163
| [fork-meta](#fork-meta) | Active | core, qol, bugfix | Never; it documents the fork |
@@ -431,6 +432,46 @@ Retired with the fork.
431432
| `pnpm-lock.yaml`, `third-party-licenses.config.json` | Other shared paths |
432433
| `.agents/skills/test-t3-*/**`, `apps/desktop/src/app/DesktopAppIdentity.ts`, `apps/desktop/src/app/DesktopClerk.test.ts`, `apps/desktop/src/app/DesktopConfig.ts`, `apps/desktop/src/ipc/methods/preview*.ts`, `apps/desktop/src/preview/Manager.fork.test.ts`, `apps/desktop/src/window/*.ts`, `apps/*/vite.config.ts`, `apps/web/src/browser/devAppPreviewHandoff.ts`, `apps/web/src/components/ChatView.tsx`, `apps/web/src/hooks/useThreadActions.ts`, `apps/web/src/state/shell.ts`, `apps/web/src/state/windowProjectBootstrap.fork.ts`, `apps/web/src/state/githubIssues.ts`, `apps/web/src/lucideOptimizer.test.ts`, `scripts/lib/dev-app*.ts`, `t3.json` | `dev:app` test surfaces |
433434

435+
## device-auth
436+
437+
### Need
438+
439+
- **Client:** a headless native client needs a token
440+
- **Gap:** upstream hands tokens out by copy-paste
441+
- **Rule:** the token never passes through a person
442+
443+
### Shape
444+
445+
An RFC 8628-style device grant, approved by the owner on the host.
446+
447+
1. Client: `POST /oauth/device_authorization`, optional DPoP proof
448+
2. Owner: `t3 auth device list`, then `approve <user-code>`
449+
3. Client: polls `POST /oauth/device_token`, receives the token
450+
451+
| Aspect | Rule |
452+
| ----------- | ------------------------------------------------------------------------ |
453+
| Approval | Host CLI only; no HTTP route can approve |
454+
| Storage | `auth_device_authorizations` through `ForkSchema.ts` |
455+
| Device code | Stored as a SHA-256 digest; single use |
456+
| Key | A DPoP start binds the request and the session to that key |
457+
| Scopes | Requested, else standard; owner `--scope` narrows only |
458+
| Browsers | Refused: CORS answers every origin, and no credential gates these routes |
459+
| Lifetime | `--ttl`, default 30 days; renewal is a new grant |
460+
| Revocation | The issued session, through `t3 auth session revoke` |
461+
| Abuse cap | 20 open requests; 10-minute expiry |
462+
463+
### Retirement condition
464+
465+
A tagged upstream release ships owner-approved native client authorization.
466+
467+
### Rebase scan
468+
469+
| Path | Why it matters |
470+
| ------------------------------------------------------------------------------------------------------- | --------------------------- |
471+
| `apps/server/src/auth/DeviceAuthorization.fork.ts`, `apps/server/src/cli/authDevice.fork.ts` | Fork-owned grant and CLI |
472+
| `apps/server/src/server.ts`, `apps/server/src/cli/auth.ts`, `apps/server/src/persistence/ForkSchema.ts` | Route, command, table hooks |
473+
| `apps/server/src/auth/SessionStore.ts`, `apps/server/src/auth/dpop.ts` | Reused issue and proof APIs |
474+
434475
## distribution
435476

436477
### Need

‎scripts/lib/fork-trailers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ export const FORK_DOMAINS = [
33
"backend-attach",
44
"browser-bookmarks",
55
"custom-agents",
6+
"device-auth",
67
"distribution",
78
"fork-meta",
89
"github-issues",

0 commit comments

Comments
 (0)