The best way to control Claude Code, Codex and more from any computer or phone

main
ts 328 lines 9.77 KB
Raw
1 /**
2 * Password authentication for the PostgreSQL protocol: MD5 and
3 * SCRAM-SHA-256.
4 *
5 * Message framing lives in `PgProtocol` - SASL payloads travel as opaque
6 * bytes - so this module only computes what goes inside them. Cleartext
7 * authentication needs nothing from here; send the password as a
8 * `PasswordMessage`.
9 *
10 * `SCRAM-SHA-256-PLUS` is not implemented: channel binding needs the TLS
11 * socket, which this codec does not own. Passwords are used as UTF-8 without
12 * SASLprep normalisation, so non-ASCII passwords that require normalisation
13 * are not supported. Server iteration counts above 1,000,000 are rejected
14 * before password derivation.
15 *
16 * @stability unstable
17 * @since 4.0.0
18 */
19 import * as Data from "effect/Data"
20 import * as Base64 from "effect/encoding/Base64"
21 import * as Result from "effect/Result"
22 import { createHash, createHmac, pbkdf2Sync } from "node:crypto"
23
24 /**
25 * Failure returned when an authentication exchange cannot be completed.
26 *
27 * @stability unstable
28 * @category errors
29 * @since 4.0.0
30 */
31 export class AuthError extends Data.TaggedError("PgAuthError")<{
32 readonly message: string
33 }> {}
34
35 const fail = (message: string): never => {
36 throw new AuthError({ message })
37 }
38
39 const result = <A>(evaluate: () => A): Result.Result<A, AuthError> => {
40 try {
41 return Result.succeed(evaluate())
42 } catch (error) {
43 if (error instanceof AuthError) return Result.fail(error)
44 throw error
45 }
46 }
47
48 const textEncoder = new TextEncoder()
49 const textDecoder = new TextDecoder("utf-8", { fatal: true })
50 /** Bounds synchronous PBKDF2 work requested by an untrusted server. */
51 const maxScramIterations = 1_000_000
52
53 const bytesOf = (value: Uint8Array): Uint8Array => Uint8Array.from(value)
54
55 const sha256 = (data: Uint8Array): Uint8Array => bytesOf(createHash("sha256").update(data).digest())
56
57 const hmacSha256 = (key: Uint8Array, data: Uint8Array): Uint8Array =>
58 bytesOf(createHmac("sha256", key).update(data).digest())
59
60 const xor = (left: Uint8Array, right: Uint8Array): Uint8Array => {
61 const result = new Uint8Array(left.length)
62 for (let i = 0; i < left.length; i++) {
63 result[i] = left[i] ^ right[i]
64 }
65 return result
66 }
67
68 const toBase64 = (bytes: Uint8Array): string => Base64.encode(bytes)
69
70 const fromBase64 = (text: string, field: string): Uint8Array => {
71 const decoded = Base64.decode(text)
72 if (Result.isFailure(decoded)) {
73 return fail(`Invalid base64 in SCRAM attribute "${field}"`)
74 }
75 return decoded.success
76 }
77
78 const decodeUtf8 = (bytes: Uint8Array, what: string): string => {
79 try {
80 return textDecoder.decode(bytes)
81 } catch {
82 return fail(`Invalid UTF-8 in ${what}`)
83 }
84 }
85
86 /**
87 * Computes the password string for an `AuthenticationMD5Password` challenge:
88 * `"md5" + md5(md5(password + user) + salt)`. Send the result verbatim as a
89 * `PasswordMessage`.
90 *
91 * @category MD5
92 * @since 4.0.0
93 */
94 const md5PasswordUnsafe = (options: {
95 readonly user: string
96 readonly password: string
97 readonly salt: Uint8Array
98 }): string => {
99 if (options.salt.length !== 4) {
100 return fail(`PostgreSQL MD5 salt must be exactly 4 bytes, received ${options.salt.length}`)
101 }
102 const inner = createHash("md5").update(textEncoder.encode(options.password + options.user)).digest("hex")
103 const outer = createHash("md5").update(textEncoder.encode(inner)).update(options.salt).digest("hex")
104 return `md5${outer}`
105 }
106
107 /**
108 * Computes the legacy PostgreSQL MD5 password response.
109 *
110 * @stability unstable
111 * @category authentication
112 * @since 4.0.0
113 */
114 export const md5Password = (options: {
115 readonly user: string
116 readonly password: string
117 readonly salt: Uint8Array
118 }): Result.Result<string, AuthError> => result(() => md5PasswordUnsafe(options))
119
120 /**
121 * The only SASL mechanism this module implements.
122 *
123 * @stability unstable
124 * @category SCRAM
125 * @since 4.0.0
126 */
127 export const SCRAM_SHA_256 = "SCRAM-SHA-256"
128
129 /**
130 * State after the client's first message, awaiting the server's challenge.
131 *
132 * @stability unstable
133 * @category SCRAM
134 * @since 4.0.0
135 */
136 export interface ScramFirst {
137 readonly _tag: "ScramFirst"
138 readonly password: string
139 readonly clientNonce: string
140 readonly clientFirstMessageBare: string
141 }
142
143 /**
144 * State after the client's final message, awaiting the server signature.
145 *
146 * @stability unstable
147 * @category SCRAM
148 * @since 4.0.0
149 */
150 export interface ScramFinal {
151 readonly _tag: "ScramFinal"
152 readonly serverSignature: Uint8Array
153 }
154
155 /**
156 * The SCRAM exchange state.
157 *
158 * @stability unstable
159 * @category SCRAM
160 * @since 4.0.0
161 */
162 export type ScramState = ScramFirst | ScramFinal
163
164 const GS2_HEADER = "n,,"
165 /** Base64 of the GS2 header, the `c=` attribute value without channel binding. */
166 const CHANNEL_BINDING = "biws"
167
168 const parseAttributes = (message: string): Map<string, string> => {
169 const attributes = new Map<string, string>()
170 for (const part of message.split(",")) {
171 const separator = part.indexOf("=")
172 if (separator < 1) {
173 return fail(`Malformed SCRAM attribute: "${part}"`)
174 }
175 const key = part.slice(0, separator)
176 if (attributes.has(key)) {
177 return fail(`Duplicate SCRAM attribute "${key}"`)
178 }
179 attributes.set(key, part.slice(separator + 1))
180 }
181 return attributes
182 }
183
184 const attribute = (attributes: Map<string, string>, key: string): string =>
185 attributes.get(key) ?? fail(`Missing SCRAM attribute "${key}"`)
186
187 /**
188 * Starts a SCRAM-SHA-256 exchange. The `nonce` must be a fresh, random,
189 * printable ASCII string chosen by the caller; this module never generates
190 * randomness.
191 *
192 * The successful result contains the `initialResponse` bytes for a
193 * `SASLInitialResponse` message with mechanism `SCRAM_SHA_256`.
194 *
195 * @category SCRAM
196 * @since 4.0.0
197 */
198 const scramInitUnsafe = (options: {
199 readonly password: string
200 readonly nonce: string
201 }): { readonly state: ScramFirst; readonly response: Uint8Array } => {
202 if (!/^[\x21-\x2b\x2d-\x7e]+$/.test(options.nonce)) {
203 return fail("SCRAM nonce must contain only printable ASCII characters other than comma")
204 }
205 const clientFirstMessageBare = `n=,r=${options.nonce}`
206 return {
207 state: {
208 _tag: "ScramFirst",
209 password: options.password,
210 clientNonce: options.nonce,
211 clientFirstMessageBare
212 },
213 response: textEncoder.encode(GS2_HEADER + clientFirstMessageBare)
214 }
215 }
216
217 /**
218 * Creates the first SCRAM-SHA-256 client message.
219 *
220 * @stability unstable
221 * @category SCRAM
222 * @since 4.0.0
223 */
224 export const scramInit = (options: {
225 readonly password: string
226 readonly nonce: string
227 }): Result.Result<{ readonly state: ScramFirst; readonly response: Uint8Array }, AuthError> =>
228 result(() => scramInitUnsafe(options))
229
230 /**
231 * Answers an `AuthenticationSASLContinue` challenge.
232 *
233 * The successful result contains the payload bytes for a `SASLResponse`
234 * message.
235 *
236 * @category SCRAM
237 * @since 4.0.0
238 */
239 const scramContinueUnsafe = (
240 state: ScramFirst,
241 challenge: Uint8Array
242 ): { readonly state: ScramFinal; readonly response: Uint8Array } => {
243 const serverFirstMessage = decodeUtf8(challenge, "the SCRAM server-first-message")
244 const attributes = parseAttributes(serverFirstMessage)
245 const nonce = attribute(attributes, "r")
246 if (!nonce.startsWith(state.clientNonce) || nonce.length === state.clientNonce.length) {
247 return fail("SCRAM server nonce does not extend the client nonce")
248 }
249 const saltText = attribute(attributes, "s")
250 if (saltText.length === 0) {
251 return fail("SCRAM salt must not be empty")
252 }
253 const salt = fromBase64(saltText, "s")
254 const iterationText = attribute(attributes, "i")
255 const iterations = Number(iterationText)
256 if (
257 !/^[1-9]\d*$/.test(iterationText) ||
258 !Number.isSafeInteger(iterations) ||
259 iterations > maxScramIterations
260 ) {
261 return fail(`Invalid SCRAM iteration count: ${iterationText}`)
262 }
263
264 const saltedPassword = bytesOf(
265 pbkdf2Sync(textEncoder.encode(state.password), salt, iterations, 32, "sha256")
266 )
267 const clientKey = hmacSha256(saltedPassword, textEncoder.encode("Client Key"))
268 const storedKey = sha256(clientKey)
269 const clientFinalMessageWithoutProof = `c=${CHANNEL_BINDING},r=${nonce}`
270 const authMessage = textEncoder.encode(
271 `${state.clientFirstMessageBare},${serverFirstMessage},${clientFinalMessageWithoutProof}`
272 )
273 const clientProof = xor(clientKey, hmacSha256(storedKey, authMessage))
274 const serverKey = hmacSha256(saltedPassword, textEncoder.encode("Server Key"))
275
276 return {
277 state: {
278 _tag: "ScramFinal",
279 serverSignature: hmacSha256(serverKey, authMessage)
280 },
281 response: textEncoder.encode(`${clientFinalMessageWithoutProof},p=${toBase64(clientProof)}`)
282 }
283 }
284
285 /**
286 * Processes the server's SCRAM challenge and creates the client proof.
287 *
288 * @stability unstable
289 * @category SCRAM
290 * @since 4.0.0
291 */
292 export const scramContinue = (
293 state: ScramFirst,
294 challenge: Uint8Array
295 ): Result.Result<{ readonly state: ScramFinal; readonly response: Uint8Array }, AuthError> =>
296 result(() => scramContinueUnsafe(state, challenge))
297
298 /**
299 * Verifies the server signature carried by `AuthenticationSASLFinal`. Returns
300 * `Result.void` on success and an `AuthError` failure when the server could
301 * not prove that it knows the stored key.
302 *
303 * @category SCRAM
304 * @since 4.0.0
305 */
306 const scramFinishUnsafe = (state: ScramFinal, challenge: Uint8Array): void => {
307 const attributes = parseAttributes(decodeUtf8(challenge, "the SCRAM server-final-message"))
308 const error = attributes.get("e")
309 if (error !== undefined) {
310 fail(`SCRAM authentication failed: ${error}`)
311 }
312 const signature = fromBase64(attribute(attributes, "v"), "v")
313 if (toBase64(state.serverSignature) !== toBase64(signature)) {
314 fail("SCRAM server signature mismatch")
315 }
316 }
317
318 /**
319 * Verifies the server's final SCRAM message.
320 *
321 * @stability unstable
322 * @category SCRAM
323 * @since 4.0.0
324 */
325 export const scramFinish = (
326 state: ScramFinal,
327 challenge: Uint8Array
328 ): Result.Result<void, AuthError> => result(() => scramFinishUnsafe(state, challenge))