-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathauth.ts
More file actions
182 lines (161 loc) · 5.5 KB
/
auth.ts
File metadata and controls
182 lines (161 loc) · 5.5 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Authentication utilities for Anode runtime agents
//
// This module provides utilities for authenticating with the Anode API
// and discovering user identity. These should be used by CLI tools
// before creating runtime agents.
import { logger } from "@runt/lib";
/**
* Options for user identity discovery
*/
export interface DiscoverUserIdentityOptions {
/** Authentication token for API requests */
authToken: string;
/** Sync URL to derive API endpoint from */
syncUrl: string;
/** Skip authentication in test environments */
skipInTests?: boolean;
}
/**
* User information returned from identity discovery
*/
export interface UserInfo {
id: string;
email: string;
name?: string;
}
/**
* Authentication result containing user info and generated client ID
*/
export interface AuthenticationResult {
userId: string;
clientId: string;
userInfo: UserInfo;
}
/**
* Discover authenticated user identity via /api/me endpoint
*
* This should be called before creating runtime agents to get the clientId.
* The clientId is generated using the user ID as a prefix plus a unique identifier,
* following LiveStore best practices where clientId identifies device/app instances.
*
* @param options - Configuration for identity discovery
* @returns Promise resolving to authentication result with userId and generated clientId
* @throws Error if authentication fails
*/
export async function discoverUserIdentity(
options: DiscoverUserIdentityOptions,
): Promise<AuthenticationResult> {
const { authToken, syncUrl, skipInTests = true } = options;
// Skip authentication in test environments if enabled
if (skipInTests) {
const isTestEnvironment = Deno.env.get("DENO_TESTING") === "true" ||
Deno.args.some((arg) => arg.includes("test")) ||
// Detect when running via deno test command
Deno.args.some((arg) => arg.endsWith(".test.ts")) ||
// Detect test files by checking if they end with .test.ts
(typeof Deno !== "undefined" && Deno.mainModule &&
Deno.mainModule.includes(".test.ts")) ||
// Check if auth token looks like a test token
authToken === "test-token";
if (isTestEnvironment) {
logger.debug("Skipping authentication in test environment");
const userId = "test-user-id";
const clientId = `${userId}-${crypto.randomUUID()}`;
return {
userId,
clientId,
userInfo: { id: userId, email: "test@example.com" },
};
}
}
// Convert sync URL to API base URL
const parsedSyncUrl = new URL(syncUrl);
// Convert WebSocket URLs to HTTP URLs
const protocol = parsedSyncUrl.protocol === "wss:" ? "https:" : "http:";
const apiBaseUrl = `${protocol}//${parsedSyncUrl.host}`;
const meEndpoint = `${apiBaseUrl}/api/me`;
try {
const response = await fetch(meEndpoint, {
headers: {
"Authorization": `Bearer ${authToken}`,
"User-Agent": "runt-runtime-agent/1.0",
},
});
if (!response.ok) {
let errorBody = "";
try {
errorBody = await response.text();
} catch (_) {
errorBody = "Unable to read response body";
}
logger.error("Authentication request failed", {
endpoint: meEndpoint,
status: response.status,
statusText: response.statusText,
responseBody: errorBody,
});
throw new Error(
`HTTP ${response.status} ${response.statusText}: ${errorBody}`,
);
}
const userInfo = await response.json() as UserInfo;
if (!userInfo.id) {
logger.error("Invalid user info response", {
endpoint: meEndpoint,
responseBody: JSON.stringify(userInfo),
});
throw new Error("User ID not found in response");
}
// Generate clientId using user ID as prefix plus unique identifier
// This follows LiveStore best practices where clientId identifies device/app instances
const userId = userInfo.id;
const clientId = `${userId}-${crypto.randomUUID()}`;
logger.debug("User identity discovered and clientId generated", {
userId,
clientId,
email: userInfo.email,
name: userInfo.name,
});
return {
userId,
clientId,
userInfo,
};
} catch (error) {
// If we haven't already logged the error above, log it here
if (!(error instanceof Error && error.message.startsWith("HTTP "))) {
logger.error("Network or parsing error during identity discovery", {
endpoint: meEndpoint,
errorMessage: error instanceof Error ? error.message : String(error),
errorType: error instanceof Error
? error.constructor.name
: typeof error,
});
}
// Pretty console output for authentication failure
const hostname = parsedSyncUrl.hostname;
console.log(`\n❌ \x1b[31mAuthentication Failed\x1b[0m`);
console.log(` \x1b[36mEndpoint:\x1b[0m https://${hostname}`);
console.log(
` \x1b[36mError:\x1b[0m ${
error instanceof Error ? error.message : String(error)
}`,
);
console.log(
`\n\x1b[33m💡 Check your RUNT_API_KEY and network connection\x1b[0m\n`,
);
throw new Error(
`Authentication failed: Could not verify identity with ${meEndpoint}. ` +
`Error: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Generate a client ID for runtime agents
*
* @param runtimeId - The runtime ID
* @returns Generated client ID in the format "runtime-{runtimeId}"
*/
export function generateRuntimeClientId(runtimeId: string): string {
return `runtime-${runtimeId}`;
}