Spaces:
Runtime error
Runtime error
File size: 4,311 Bytes
5b12974 | 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 | import { findUserByToken } from "~/models/personal-token.server";
import { oauth2Service } from "~/services/oauth2.server";
// See this for more: https://twitter.com/mattpocockuk/status/1653403198885904387?s=20
export type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
export type ApiAuthenticationResult =
| ApiAuthenticationResultSuccess
| ApiAuthenticationResultFailure;
export type ApiAuthenticationResultSuccess = {
ok: true;
apiKey: string;
type: "PRIVATE" | "OAUTH2";
userId: string;
scopes?: string[];
oneTimeUse?: boolean;
oauth2?: {
clientId: string;
scope: string | null;
};
};
export type ApiAuthenticationResultFailure = {
ok: false;
error: string;
};
/**
* This method is the same as `authenticateApiRequest` but it returns a failure result instead of undefined.
* It should be used from now on to ensure that the API key is always validated and provide a failure result.
*/
export async function authenticateApiRequestWithFailure(
request: Request,
options: { allowPublicKey?: boolean; allowJWT?: boolean } = {},
): Promise<ApiAuthenticationResult> {
const apiKey = getApiKeyFromRequest(request);
if (!apiKey) {
return {
ok: false,
error: "Invalid API Key",
};
}
const authentication = await authenticateApiKeyWithFailure(apiKey, options);
return authentication;
}
/**
* This method is the same as `authenticateApiKey` but it returns a failure result instead of undefined.
* It should be used from now on to ensure that the API key is always validated and provide a failure result.
*/
export async function authenticateApiKeyWithFailure(
apiKey: string,
options: { allowPublicKey?: boolean; allowJWT?: boolean } = {},
): Promise<ApiAuthenticationResult> {
// First try OAuth2 access token
try {
const accessToken = await oauth2Service.validateAccessToken(apiKey);
if (accessToken) {
return {
ok: true,
apiKey,
type: "OAUTH2",
userId: accessToken.user.id,
scopes: accessToken.scope ? accessToken.scope.split(" ") : undefined,
oauth2: {
clientId: accessToken.client.clientId,
scope: accessToken.scope,
},
};
}
} catch (error) {
// If OAuth2 token validation fails, continue to PAT validation
}
// Fall back to PAT authentication
const result = getApiKeyResult(apiKey);
if (!result) {
return {
ok: false,
error: "Invalid API Key",
};
}
switch (result.type) {
case "PRIVATE": {
const user = await findUserByToken(result.apiKey);
if (!user) {
return {
ok: false,
error: "Invalid API Key",
};
}
return {
ok: true,
...result,
userId: user.userId,
};
}
}
}
export function isSecretApiKey(key: string) {
return key.startsWith("rc_");
}
export function getApiKeyFromRequest(request: Request) {
return getApiKeyFromHeader(request.headers.get("Authorization"));
}
export function getApiKeyFromHeader(authorization?: string | null) {
if (typeof authorization !== "string" || !authorization) {
return;
}
const apiKey = authorization.replace(/^Bearer /, "");
return apiKey;
}
export function getApiKeyResult(apiKey: string): {
apiKey: string;
type: "PRIVATE";
} {
return { apiKey, type: "PRIVATE" };
}
/**
* Authenticate OAuth2 requests specifically
* Returns structured result for OAuth endpoints
*/
export async function authenticateOAuthRequest(
request: Request,
scopes?: string[],
): Promise<{
success: boolean;
user?: { id: string };
clientId?: string;
error?: string;
}> {
const apiKey = getApiKeyFromRequest(request);
if (!apiKey) {
return {
success: false,
error: "Missing authorization header",
};
}
// Only allow OAuth2 tokens for OAuth API endpoints
try {
const accessToken = await oauth2Service.validateAccessToken(apiKey, scopes);
if (accessToken) {
return {
success: true,
user: { id: accessToken.user.id },
clientId: accessToken.client.clientId,
};
}
} catch (error) {
return {
success: false,
error: "Invalid or expired access token",
};
}
return {
success: false,
error: "Invalid access token",
};
}
|