MCPcopy Create free account
hub / github.com/Effect-TS/effect / scramContinueUnsafe

Function scramContinueUnsafe

packages/sql/pg/src/PgAuth.ts:253–309  ·  view source on GitHub ↗
(
  state: ScramFirst,
  challenge: Uint8Array,
  cached?: ScramSaltedPassword | undefined
)

Source from the content-addressed store, hash-verified

251 * @since 4.0.0
252 */
253const scramContinueUnsafe = (
254 state: ScramFirst,
255 challenge: Uint8Array,
256 cached?: ScramSaltedPassword | undefined
257): {
258 readonly state: ScramFinal
259 readonly response: Uint8Array
260 readonly saltedPassword: ScramSaltedPassword
261} => {
262 const serverFirstMessage = decodeUtf8(challenge, "the SCRAM server-first-message")
263 const attributes = parseAttributes(serverFirstMessage)
264 const nonce = attribute(attributes, "r")
265 if (!nonce.startsWith(state.clientNonce) || nonce.length === state.clientNonce.length) {
266 return fail("SCRAM server nonce does not extend the client nonce")
267 }
268 const saltText = attribute(attributes, "s")
269 if (saltText.length === 0) {
270 return fail("SCRAM salt must not be empty")
271 }
272 const salt = fromBase64(saltText, "s")
273 const iterationText = attribute(attributes, "i")
274 const iterations = Number(iterationText)
275 if (
276 !/^[1-9]\d*$/.test(iterationText) ||
277 !Number.isSafeInteger(iterations) ||
278 iterations > maxScramIterations
279 ) {
280 return fail(`Invalid SCRAM iteration count: ${iterationText}`)
281 }
282
283 const saltedPassword: ScramSaltedPassword = cached !== undefined &&
284 cached.salt === saltText &&
285 cached.iterations === iterations
286 ? cached
287 : {
288 salt: saltText,
289 iterations,
290 bytes: bytesOf(pbkdf2Sync(textEncoder.encode(state.password), salt, iterations, 32, "sha256"))
291 }
292 const clientKey = hmacSha256(saltedPassword.bytes, textEncoder.encode("Client Key"))
293 const storedKey = sha256(clientKey)
294 const clientFinalMessageWithoutProof = `c=${CHANNEL_BINDING},r=${nonce}`
295 const authMessage = textEncoder.encode(
296 `${state.clientFirstMessageBare},${serverFirstMessage},${clientFinalMessageWithoutProof}`
297 )
298 const clientProof = xor(clientKey, hmacSha256(storedKey, authMessage))
299 const serverKey = hmacSha256(saltedPassword.bytes, textEncoder.encode("Server Key"))
300
301 return {
302 state: {
303 _tag: "ScramFinal",
304 serverSignature: hmacSha256(serverKey, authMessage)
305 },
306 response: textEncoder.encode(`${clientFinalMessageWithoutProof},p=${toBase64(clientProof)}`),
307 saltedPassword
308 }
309}
310

Callers 1

scramContinueFunction · 0.85

Calls 12

fromBase64Function · 0.85
hmacSha256Function · 0.85
xorFunction · 0.85
encodeMethod · 0.80
decodeUtf8Function · 0.70
parseAttributesFunction · 0.70
attributeFunction · 0.70
failFunction · 0.70
bytesOfFunction · 0.70
sha256Function · 0.70
toBase64Function · 0.70
NumberFunction · 0.50

Tested by

no test coverage detected