-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice_flow.js
More file actions
103 lines (87 loc) · 3.3 KB
/
Copy pathdevice_flow.js
File metadata and controls
103 lines (87 loc) · 3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Hardware claims are in the access token JWT (RFC 9068), not the id_token.
function decodeAccessToken(token) {
return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
}
const VOUCH_ISSUER = process.env.VOUCH_ISSUER || 'https://us.vouch.sh';
const CLIENT_ID = process.env.VOUCH_CLIENT_ID;
if (!CLIENT_ID) {
console.error('Error: VOUCH_CLIENT_ID environment variable is required');
process.exit(1);
}
async function fetchUserInfo(accessToken) {
const response = await fetch(`${VOUCH_ISSUER}/oauth/userinfo`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!response.ok) {
throw new Error(`UserInfo request failed: ${response.status}`);
}
return response.json();
}
async function deviceFlow() {
// Step 1: Request device code
const deviceResponse = await fetch(`${VOUCH_ISSUER}/oauth/device`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: CLIENT_ID,
scope: 'openid email',
}),
});
if (!deviceResponse.ok) {
throw new Error(`Device request failed: ${deviceResponse.status}`);
}
const deviceData = await deviceResponse.json();
// Step 2: Display instructions to user
console.log(`\nTo sign in, visit: ${deviceData.verification_uri}`);
console.log(`Enter code: ${deviceData.user_code}\n`);
// Step 3: Poll for token
let interval = (deviceData.interval || 5) * 1000;
while (true) {
await new Promise((resolve) => setTimeout(resolve, interval));
const tokenResponse = await fetch(`${VOUCH_ISSUER}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
device_code: deviceData.device_code,
client_id: CLIENT_ID,
}),
});
if (tokenResponse.ok) {
const tokens = await tokenResponse.json();
console.log('Authenticated!');
console.log(`Access token: ${tokens.access_token.slice(0, 20)}...`);
// Step 4: Fetch user info and decode hardware claims from access token
const userInfo = await fetchUserInfo(tokens.access_token);
const atClaims = decodeAccessToken(tokens.access_token);
console.log(`Email: ${userInfo.email || 'N/A'}`);
console.log(`Hardware verified: ${atClaims.hardware_verified || false}`);
if (atClaims.hardware_aaguid) {
console.log(`Hardware AAGUID: ${atClaims.hardware_aaguid}`);
}
// Step 5: Demonstrate post-auth API call with the access token
console.log('\n--- Post-auth API call ---');
const userInfo2 = await fetchUserInfo(tokens.access_token);
console.log(`Second userinfo call succeeded: ${userInfo2.email}`);
return;
}
const { error } = await tokenResponse.json();
switch (error) {
case 'authorization_pending':
continue;
case 'slow_down':
interval += 5000;
continue;
case 'expired_token':
throw new Error('Device code expired. Please try again.');
case 'access_denied':
throw new Error('Access denied by user.');
default:
throw new Error(`Unexpected error: ${error}`);
}
}
}
deviceFlow().catch((err) => {
console.error(`Error: ${err.message}`);
process.exit(1);
});