Skip to content

Commit cb61cc4

Browse files
igorcostaAutohand Evolve
andcommitted
Use code-only device authorization in current clients
Require schema v2 for new CLI and Blueprint sign-in requests while retaining version-aware polling and cancellation for trusted sessions. Update terminal mocks and protocol documentation for the canonical short-code URL. Co-authored-by: Autohand Evolve <code-noreply@autohand.ai>
1 parent f52ce29 commit cb61cc4

11 files changed

Lines changed: 152 additions & 81 deletions

File tree

‎docs/rpc-protocol.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,9 +149,13 @@ process. Poll returns a closed `pending`, `authorized`, `expired`,
149149
code, raw API body, or credential. `authorized` is returned only after the
150150
existing Autohand config owner persists the credential successfully.
151151

152-
The CLI calls the canonical API routes below. The browser challenge must be
153-
the API-returned `https://autohand.ai/signin` URL with only signed `continue`
154-
and `user_code` parameters.
152+
The CLI calls the canonical API routes below. New API device-auth requests use
153+
schema version 2, whose API-returned browser challenge is exactly
154+
`https://autohand.ai/signin?user_code=XXXX-XXXX`. The CLI also validates and
155+
preserves legacy schema-version-1 challenges containing only signed `continue`
156+
and matching `user_code` parameters so already-issued sessions can drain.
157+
`autohand-cli` remains the wire-protocol client ID; Blueprint is the
158+
presentation client type for this setup flow.
155159

156160
```text
157161
POST https://api.autohand.ai/v1/auth/cli/initiate

‎src/auth/AuthClient.ts‎

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import type {
1717
} from './types.js';
1818

1919
const DEFAULT_TIMEOUT = 10000;
20-
const DEVICE_AUTH_SCHEMA_VERSION = 1 as const;
20+
const DEVICE_AUTH_SCHEMA_VERSION = 2 as const;
2121
const DEVICE_CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
2222
const USER_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/u;
2323
const CREDENTIAL_PATTERN = /^ahc_[A-Za-z0-9_-]{43}$/u;
@@ -171,6 +171,7 @@ function isCanonicalVerificationUrl(
171171
value: string,
172172
userCode: string,
173173
deviceCode: string,
174+
schemaVersion: 1 | 2,
174175
): boolean {
175176
let url: URL;
176177
try {
@@ -180,22 +181,31 @@ function isCanonicalVerificationUrl(
180181
}
181182
const queryEntries = [...url.searchParams.entries()];
182183
const continuation = url.searchParams.get('continue');
184+
const validQuery = schemaVersion === DEVICE_AUTH_SCHEMA_VERSION
185+
? queryEntries.length === 1
186+
&& queryEntries[0]?.[0] === 'user_code'
187+
&& url.searchParams.getAll('user_code').length === 1
188+
&& continuation === null
189+
: queryEntries.length === 2
190+
&& queryEntries.filter(([key]) => key === 'continue').length === 1
191+
&& queryEntries.filter(([key]) => key === 'user_code').length === 1
192+
&& continuation !== null
193+
&& isValidContinuation(continuation);
183194
return url.protocol === 'https:'
184195
&& url.origin === 'https://autohand.ai'
185196
&& url.pathname === '/signin'
186197
&& url.username === ''
187198
&& url.password === ''
188199
&& url.hash === ''
189-
&& queryEntries.length === 2
190-
&& queryEntries.filter(([key]) => key === 'continue').length === 1
191-
&& queryEntries.filter(([key]) => key === 'user_code').length === 1
192-
&& continuation !== null
193-
&& isValidContinuation(continuation)
200+
&& validQuery
194201
&& url.searchParams.get('user_code') === userCode
195202
&& !value.includes(deviceCode);
196203
}
197204

198-
function parseDeviceChallenge(data: unknown): DeviceAuthInitResponse | null {
205+
function parseDeviceChallenge(
206+
data: unknown,
207+
expectedSchemaVersion: 1 | 2,
208+
): DeviceAuthInitResponse | null {
199209
if (!isRecord(data)
200210
|| !hasOnlyKeys(data, [
201211
'success',
@@ -208,7 +218,7 @@ function parseDeviceChallenge(data: unknown): DeviceAuthInitResponse | null {
208218
'interval',
209219
])
210220
|| data.success !== true
211-
|| data.schemaVersion !== DEVICE_AUTH_SCHEMA_VERSION
221+
|| data.schemaVersion !== expectedSchemaVersion
212222
|| typeof data.deviceCode !== 'string'
213223
|| !DEVICE_CODE_PATTERN.test(data.deviceCode)
214224
|| typeof data.userCode !== 'string'
@@ -219,6 +229,7 @@ function parseDeviceChallenge(data: unknown): DeviceAuthInitResponse | null {
219229
data.verificationUriComplete,
220230
data.userCode,
221231
data.deviceCode,
232+
expectedSchemaVersion,
222233
)
223234
|| !Number.isInteger(data.expiresIn)
224235
|| (data.expiresIn as number) < 30
@@ -230,7 +241,7 @@ function parseDeviceChallenge(data: unknown): DeviceAuthInitResponse | null {
230241
}
231242
return {
232243
success: true,
233-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
244+
schemaVersion: expectedSchemaVersion,
234245
deviceCode: data.deviceCode,
235246
userCode: data.userCode,
236247
verificationUri: data.verificationUri,
@@ -265,10 +276,13 @@ function parseAuthUser(value: unknown): AuthUser | null {
265276
};
266277
}
267278

268-
function parsePollResponse(data: unknown): DeviceAuthPollResponse | null {
279+
function parsePollResponse(
280+
data: unknown,
281+
schemaVersion: 1 | 2,
282+
): DeviceAuthPollResponse | null {
269283
if (!isRecord(data)
270284
|| data.success !== true
271-
|| data.schemaVersion !== DEVICE_AUTH_SCHEMA_VERSION
285+
|| data.schemaVersion !== schemaVersion
272286
|| typeof data.status !== 'string') {
273287
return null;
274288
}
@@ -281,7 +295,7 @@ function parsePollResponse(data: unknown): DeviceAuthPollResponse | null {
281295
}
282296
return {
283297
success: true,
284-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
298+
schemaVersion,
285299
status: 'pending',
286300
interval: data.interval as number,
287301
};
@@ -296,7 +310,7 @@ function parsePollResponse(data: unknown): DeviceAuthPollResponse | null {
296310
}
297311
return {
298312
success: true,
299-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
313+
schemaVersion,
300314
status: 'authorized',
301315
token: data.token,
302316
user,
@@ -306,7 +320,7 @@ function parsePollResponse(data: unknown): DeviceAuthPollResponse | null {
306320
if (!hasOnlyKeys(data, ['success', 'schemaVersion', 'status'])) return null;
307321
return {
308322
success: true,
309-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
323+
schemaVersion,
310324
status: data.status,
311325
};
312326
}
@@ -359,7 +373,7 @@ export class AuthClient {
359373
};
360374
}
361375

362-
return parseDeviceChallenge(data) ?? {
376+
return parseDeviceChallenge(data, DEVICE_AUTH_SCHEMA_VERSION) ?? {
363377
success: false,
364378
error: DEVICE_AUTH_ERROR,
365379
};
@@ -375,7 +389,10 @@ export class AuthClient {
375389
/**
376390
* Poll for device authorization status
377391
*/
378-
async pollDeviceAuth(deviceCode: string): Promise<DeviceAuthPollResponse> {
392+
async pollDeviceAuth(
393+
deviceCode: string,
394+
schemaVersion: 1 | 2 = DEVICE_AUTH_SCHEMA_VERSION,
395+
): Promise<DeviceAuthPollResponse> {
379396
const controller = new AbortController();
380397
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
381398

@@ -387,7 +404,7 @@ export class AuthClient {
387404
},
388405
body: JSON.stringify({
389406
deviceCode,
390-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
407+
schemaVersion,
391408
}),
392409
signal: controller.signal,
393410
});
@@ -403,7 +420,7 @@ export class AuthClient {
403420
};
404421
}
405422

406-
return parsePollResponse(data) ?? {
423+
return parsePollResponse(data, schemaVersion) ?? {
407424
success: false,
408425
status: 'pending',
409426
error: DEVICE_AUTH_STATUS_ERROR,
@@ -420,7 +437,10 @@ export class AuthClient {
420437
/**
421438
* Cancel an active device authorization transaction.
422439
*/
423-
async cancelDeviceAuth(deviceCode: string): Promise<DeviceAuthCancelResponse> {
440+
async cancelDeviceAuth(
441+
deviceCode: string,
442+
schemaVersion: 1 | 2 = DEVICE_AUTH_SCHEMA_VERSION,
443+
): Promise<DeviceAuthCancelResponse> {
424444
const controller = new AbortController();
425445
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
426446

@@ -432,7 +452,7 @@ export class AuthClient {
432452
},
433453
body: JSON.stringify({
434454
deviceCode,
435-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
455+
schemaVersion,
436456
}),
437457
signal: controller.signal,
438458
});
@@ -447,13 +467,13 @@ export class AuthClient {
447467
if (!isRecord(data)
448468
|| !hasOnlyKeys(data, ['success', 'schemaVersion', 'status'])
449469
|| data.success !== true
450-
|| data.schemaVersion !== DEVICE_AUTH_SCHEMA_VERSION
470+
|| data.schemaVersion !== schemaVersion
451471
|| data.status !== 'cancelled') {
452472
return { success: false, error: DEVICE_AUTH_STATUS_ERROR };
453473
}
454474
return {
455475
success: true,
456-
schemaVersion: DEVICE_AUTH_SCHEMA_VERSION,
476+
schemaVersion,
457477
status: 'cancelled',
458478
};
459479
} catch (error) {

‎src/auth/types.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export type DeviceAuthClientType =
2424
/** Device authorization initiation response */
2525
export interface DeviceAuthInitResponse {
2626
success: boolean;
27-
schemaVersion?: 1;
27+
schemaVersion?: 1 | 2;
2828
deviceCode?: string;
2929
userCode?: string;
3030
verificationUri?: string;
@@ -37,7 +37,7 @@ export interface DeviceAuthInitResponse {
3737
/** Device authorization poll response */
3838
export interface DeviceAuthPollResponse {
3939
success: boolean;
40-
schemaVersion?: 1;
40+
schemaVersion?: 1 | 2;
4141
status: 'pending' | 'authorized' | 'expired' | 'cancelled';
4242
interval?: number;
4343
token?: string;
@@ -48,7 +48,7 @@ export interface DeviceAuthPollResponse {
4848
/** Device authorization cancellation response */
4949
export interface DeviceAuthCancelResponse {
5050
success: boolean;
51-
schemaVersion?: 1;
51+
schemaVersion?: 1 | 2;
5252
status?: 'cancelled';
5353
error?: string;
5454
}

‎src/commands/login.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,10 @@ export async function login(ctx: LoginContext): Promise<string | null> {
254254

255255
await sleep(pollInterval);
256256

257-
const pollResult = await authClient.pollDeviceAuth(initResult.deviceCode);
257+
const pollResult = await authClient.pollDeviceAuth(
258+
initResult.deviceCode,
259+
initResult.schemaVersion ?? 2,
260+
);
258261

259262
if (pollResult.status === 'authorized' && pollResult.token && pollResult.user) {
260263
// Clear the waiting line

‎src/modes/rpc/blueprintSetup.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,17 @@ type BlueprintSetupTerminalResult = Exclude<
140140

141141
export interface BlueprintDeviceAuthClient {
142142
initiateDeviceAuth(clientType?: DeviceAuthClientType): Promise<DeviceAuthInitResponse>;
143-
pollDeviceAuth(deviceCode: string): Promise<DeviceAuthPollResponse>;
144-
cancelDeviceAuth(deviceCode: string): Promise<{ success: boolean; error?: string }>;
143+
pollDeviceAuth(deviceCode: string, schemaVersion?: 1 | 2): Promise<DeviceAuthPollResponse>;
144+
cancelDeviceAuth(
145+
deviceCode: string,
146+
schemaVersion?: 1 | 2,
147+
): Promise<{ success: boolean; error?: string }>;
145148
}
146149

147150
interface ActiveSetupSession {
148151
kind: 'active';
149152
deviceCode: string;
153+
schemaVersion: 1 | 2;
150154
expiresAtUnixMs: number;
151155
pollAfterMs: number;
152156
nextPollAtUnixMs: number;
@@ -170,6 +174,7 @@ export interface BlueprintSetupSessionManagerOptions {
170174
function validateChallenge(result: DeviceAuthInitResponse): {
171175
deviceCode: string;
172176
userCode: string;
177+
schemaVersion: 1 | 2;
173178
verificationUriComplete: string;
174179
expiresIn: number;
175180
pollAfterMs: number;
@@ -209,15 +214,26 @@ function validateChallenge(result: DeviceAuthInitResponse): {
209214
'Autohand returned an invalid device-authorization challenge.',
210215
);
211216
}
212-
const queryKeys = [...new Set(url.searchParams.keys())].sort();
217+
const queryKeys = [...url.searchParams.keys()];
218+
const schemaVersion = result.schemaVersion ?? (
219+
queryKeys.length === 1 && queryKeys[0] === 'user_code' ? 2 : 1
220+
);
221+
const validQuery = schemaVersion === 2
222+
? queryKeys.length === 1 &&
223+
queryKeys[0] === 'user_code' &&
224+
url.searchParams.getAll('user_code').length === 1
225+
: queryKeys.length === 2 &&
226+
queryKeys.filter(key => key === 'continue').length === 1 &&
227+
queryKeys.filter(key => key === 'user_code').length === 1 &&
228+
Boolean(url.searchParams.get('continue'));
213229
if (url.protocol !== 'https:'
214230
|| url.origin !== 'https://autohand.ai'
215231
|| url.pathname !== '/signin'
216232
|| url.username
217233
|| url.password
218234
|| url.hash
219-
|| queryKeys.join(',') !== 'continue,user_code'
220-
|| !url.searchParams.get('continue')
235+
|| (schemaVersion !== 1 && schemaVersion !== 2)
236+
|| !validQuery
221237
|| url.searchParams.get('user_code') !== result.userCode) {
222238
throw new BlueprintSetupError(
223239
'invalid_challenge',
@@ -228,6 +244,7 @@ function validateChallenge(result: DeviceAuthInitResponse): {
228244
return {
229245
deviceCode: result.deviceCode,
230246
userCode: result.userCode,
247+
schemaVersion,
231248
verificationUriComplete: url.toString(),
232249
expiresIn,
233250
pollAfterMs: interval * 1000,
@@ -352,6 +369,7 @@ export class BlueprintSetupSessionManager {
352369
this.sessions.set(sessionId, {
353370
kind: 'active',
354371
deviceCode: challenge.deviceCode,
372+
schemaVersion: challenge.schemaVersion,
355373
expiresAtUnixMs,
356374
pollAfterMs: challenge.pollAfterMs,
357375
nextPollAtUnixMs: now + challenge.pollAfterMs,
@@ -388,7 +406,10 @@ export class BlueprintSetupSessionManager {
388406
};
389407
}
390408

391-
const apiResult = await this.options.authClient.pollDeviceAuth(session.deviceCode);
409+
const apiResult = await this.options.authClient.pollDeviceAuth(
410+
session.deviceCode,
411+
session.schemaVersion,
412+
);
392413
if (!apiResult.success) return failed('poll_failed');
393414
if (apiResult.status === 'pending') {
394415
session.nextPollAtUnixMs = now + session.pollAfterMs;
@@ -429,7 +450,10 @@ export class BlueprintSetupSessionManager {
429450
if (!session) return failed('protocol_mismatch');
430451
if (session.kind === 'terminal') return session.result;
431452

432-
const result = await this.options.authClient.cancelDeviceAuth(session.deviceCode);
453+
const result = await this.options.authClient.cancelDeviceAuth(
454+
session.deviceCode,
455+
session.schemaVersion,
456+
);
433457
if (!result.success) {
434458
const terminalFailure = failed('cancel_failed');
435459
this.sessions.set(parsed.data.sessionId, { kind: 'terminal', result: terminalFailure });
@@ -444,7 +468,10 @@ export class BlueprintSetupSessionManager {
444468
const cancellations: Promise<unknown>[] = [];
445469
for (const session of this.sessions.values()) {
446470
if (session.kind === 'active') {
447-
cancellations.push(this.options.authClient.cancelDeviceAuth(session.deviceCode));
471+
cancellations.push(this.options.authClient.cancelDeviceAuth(
472+
session.deviceCode,
473+
session.schemaVersion,
474+
));
448475
}
449476
}
450477
this.sessions.clear();

‎src/onboarding/setupWizard.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1163,7 +1163,10 @@ export class SetupWizard {
11631163

11641164
await this.sleep(pollInterval);
11651165

1166-
const pollResult = await authClient.pollDeviceAuth(initResult.deviceCode);
1166+
const pollResult = await authClient.pollDeviceAuth(
1167+
initResult.deviceCode,
1168+
initResult.schemaVersion ?? 2,
1169+
);
11671170

11681171
if (pollResult.status === 'authorized' && pollResult.token && pollResult.user) {
11691172
process.stdout.write('\r' + ' '.repeat(20) + '\r');

0 commit comments

Comments
 (0)