Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

codexAuthHandoff.ts

147 lines5.6 KB

1import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { providerAuthReturnUrl } from "./providerAuthReturnUrl.ts";
4​
5export const CodexAuthHandoff = Schema.Struct({
6 authorizationUrl: Schema.String.check(Schema.isMaxLength(16_384)),
7 returnUrl: Schema.String.check(Schema.isMaxLength(4_096)),
8 environmentId: EnvironmentId,
9 instanceId: ProviderInstanceId,
10 flowId: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
11});
12export type CodexAuthHandoff = typeof CodexAuthHandoff.Type;
13const Delivery = Schema.Struct({
14 environmentId: EnvironmentId,
15 instanceId: ProviderInstanceId,
16 flowId: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
17 callbackUrl: Schema.String.check(Schema.isMaxLength(16_384)),
18 returnHash: Schema.String.check(Schema.isMaxLength(128)),
19});
20​
21const encodeHandoff = Schema.encodeSync(Schema.fromJsonString(CodexAuthHandoff));
22const decodeHandoff = Schema.decodeUnknownSync(Schema.fromJsonString(CodexAuthHandoff));
23const encodeDelivery = Schema.encodeSync(Schema.fromJsonString(Delivery));
24const decodeDelivery = Schema.decodeUnknownSync(Schema.fromJsonString(Delivery));
25​
26export function codexAuthorizationRequest(value: string) {
27 const url = new URL(value);
28 if (
29 value.length > 16_384 ||
30 url.origin !== "https://auth.openai.com" ||
31 url.pathname !== "/api/accounts/authorize" ||
32 url.username ||
33 url.password ||
34 url.hash
35 )
36 throw new Error("Invalid ChatGPT sign-in request.");
37 const single = (key: string) => {
38 const values = url.searchParams.getAll(key);
39 if (values.length !== 1 || !values[0]) throw new Error("Invalid ChatGPT sign-in request.");
40 return values[0];
41 };
42 const redirectUri = single("redirect_uri");
43 const redirect = new URL(redirectUri);
44 const state = single("state");
45 if (
46 !/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}\/auth\/callback$/u.test(redirectUri) ||
47 Number(redirect.port) > 65_535 ||
48 !/^[\w-]{16,128}$/u.test(state) ||
49 single("response_type") !== "code" ||
50 single("code_challenge_method") !== "S256" ||
51 !/^[\w-]{43}$/u.test(single("code_challenge")) ||
52 !/^(dynamic_agent_client|oaiapp_[\w-]+)$/u.test(single("client_id"))
53 )
54 throw new Error("Invalid ChatGPT sign-in request.");
55 return { authorizationUrl: url.toString(), redirectUri, state };
57​
58export function codexCallbackUrl(value: string, redirectUri: string, state: string) {
59 const callback = new URL(value);
60 const expected = new URL(redirectUri);
61 const states = callback.searchParams.getAll("state");
62 const codes = callback.searchParams.getAll("code");
63 const errors = callback.searchParams.getAll("error");
64 const clients = callback.searchParams.getAll("client_id");
65 if (
66 value.length > 16_384 ||
67 callback.origin !== expected.origin ||
68 callback.pathname !== expected.pathname ||
69 callback.username ||
70 callback.password ||
71 callback.hash ||
72 states.length !== 1 ||
73 states[0] !== state ||
74 clients.length > 1 ||
75 (clients.length === 1 && !/^oaiapp_[\w-]+$/u.test(clients[0]!)) ||
76 !(
77 (codes.length === 1 && Boolean(codes[0]) && errors.length === 0) ||
78 (errors.length === 1 && Boolean(errors[0]) && codes.length === 0)
79 )
80 )
81 throw new Error("This redirect URL does not belong to the current sign-in.");
82 return callback;
84​
85export function codexAuthHandoffUrl(input: CodexAuthHandoff, development = false) {
86 const url = new URL(`${development ? "t3code-dev" : "t3code"}://auth/codex`);
87 url.searchParams.set("request", encodeHandoff(input));
88 return url.toString();
90​
91export function readCodexAuthHandoff(value: string, development: boolean) {
92 try {
93 const url = new URL(value);
94 if (
95 value.length > 32_768 ||
96 url.protocol !== (development ? "t3code-dev:" : "t3code:") ||
97 url.host !== "auth" ||
98 url.pathname !== "/codex" ||
99 url.username ||
100 url.password ||
101 url.hash ||
102 url.searchParams.getAll("request").length !== 1
103 )
104 return undefined;
105 const input = decodeHandoff(url.searchParams.get("request"));
106 codexAuthorizationRequest(input.authorizationUrl);
107 if (!providerAuthReturnUrl(input.returnUrl)) return undefined;
108 return input;
109 } catch {
110 return undefined;
111 }
113​
114/** Codes travel in a fragment, never in hosted web requests or a token store on the helper. */
115export function codexAuthDeliveryUrl(input: CodexAuthHandoff, callbackUrl: string) {
116 const request = codexAuthorizationRequest(input.authorizationUrl);
117 codexCallbackUrl(callbackUrl, request.redirectUri, request.state);
118 const destination = providerAuthReturnUrl(input.returnUrl);
119 if (!destination) throw new Error("Invalid T3 Code return address.");
120 const url = new URL(destination);
121 const delivery = {
122 environmentId: input.environmentId,
123 instanceId: input.instanceId,
124 flowId: input.flowId,
125 callbackUrl,
126 returnHash: url.hash,
127 };
128 url.hash = `codex-auth=${encodeURIComponent(encodeDelivery(delivery))}`;
129 return url.toString();
131​
132export function readCodexAuthDelivery(value: string) {
133 try {
134 const url = new URL(value);
135 if (!url.hash.startsWith("#codex-auth=") || url.hash.length > 32_768) return undefined;
136 const input = decodeDelivery(decodeURIComponent(url.hash.slice("#codex-auth=".length)));
137 const destination = providerAuthReturnUrl(value);
138 if (!destination) return undefined;
139 const returnUrl = new URL(destination);
140 returnUrl.hash = input.returnHash;
141 const sanitized = providerAuthReturnUrl(returnUrl.toString());
142 if (!sanitized) return undefined;
143 return { ...input, returnUrl: sanitized };
144 } catch {
145 return undefined;
146 }