Published on

El Hechizo de La puerta mágica - Interview challenge solution

Authors

TLDR:

  • Call the door API at specific minute intervals (:00, :01, :02, :03, :04)
  • Collect the gryffindor cookies
  • Decode the base64 message with "revelio"
  • Script

This challenge belongs to a series of programming challenges published by AltScore. You can see the complete list here. This is the eighth challenge.

Problem Statement

El Hechizo de La puerta mágica

Contexto:

En la vasta biblioteca de Altwarts, los antiguos fundadores escondieron un conocimiento arcano, protegido por un hechizo poderoso conocido como “El Encantamiento de la Puerta Mágica”. Para desentrañar este conocimiento, debes resolver el acertijo que dejaron atrás. Cada pista te llevará más cerca de la solución final, pero ten cuidado, pues solo los magos más astutos serán capaces de encontrar el camino.

Primera pista: El Reloj de los Segundos

En la Torre del Reloj de Altwarts, el tiempo es tu mayor aliado y tu peor enemigo. Cada segundo marca el paso de una clave que abre una puerta. Elige el momento correcto, y la llave será tuya. Pero recuerda, solo en el primer segundo puedes encontrar la llave de la primera puerta.

Segunda pista: Acción y reacción, las puertas traen revelación

En el aula de Encantamientos, el profesor Flitwick guarda un pergamino antiguo que habla de palabras ocultas, no en los hechizos mismos, sino en las consecuencias de su lanzamiento. Cada acción mágica genera una reacción, y en esa reacción yacen los secretos que buscan los magos astutos. Solo aquellos que observan más allá de lo evidente, que desentrañan los hilos invisibles que conectan causa y efecto, podrán descifrar el verdadero mensaje.

Tercera pista:

En el Gran Comedor, N puertas mágicas están alineadas, cada una desbloqueada solo por una palabra. Un hechizo pronunciado mal te perderá, pero el correcto te guiará. Solo avanzando en orden y en el momento adecuado, alcanzarás tu objetivo.

Cuarta pista:

Cada puerta te llevará a la siguiente, pero la respuesta no se encuentra al final, sino que el camino mismo es la clave. Recuerda usar el hechizo Revelio para ver lo que está oculto.

Recursos:

  • API para intentar abrir una puerta: [POST] /v1/s1/e8/actions/door (No siempre recibirás un status 200, pero los errores te dan pistas).
  • Envía tu respuesta aquí: [POST] /v1/s1/e8/solution
  • Consulta la Documentación para más detalles.

¡Prepárate a demostrar a Altwarts que tienes la magia! 🚀

Solution

Step 1: Discover the timing pattern

When testing the door endpoint in the Swagger UI, I noticed something interesting:

# Response at :00 (seconds = 00)
{
  "response": "¡Bienvenido al desafío de Altwarts! Tienes suerte, aquí está la primera pista."
}

# Response at :01
{
  "response": "Correcto, pero aún tienes un camino por recorrer."
}

# Response at :02, :03
{
  "response": "Correcto, pero aún tienes un camino por recorrer."
}

# Response at :04
{
  "response": "Has llegado al final. Recuerda usar el hechizo 'revelio' para descubrir el mensaje oculto."
}

The pattern became clear: you need to call the door at specific minutes, when the seconds are :00.

Each successful call sets a gryffindor cookie that contains part of the message!

Step 2: Collect the cookies

I wrote a script to automate the cookie collection:

const API_KEY = 'API-KEY'
const URL = 'https://makers-challenge.altscore.ai/v1/s1/e8/actions/door'

async function makeRequest(currentCookie = '') {
  try {
    const headers = {
      accept: 'application/json',
      'API-KEY': API_KEY,
    }

    if (currentCookie) {
      headers.Cookie = `gryffindor=${currentCookie}`
    }

    const response = await fetch(URL, {
      method: 'POST',
      headers,
      body: '',
    })

    console.log('\nCurrent cookie:', currentCookie)

    // Check if we've reached the end
    const data = await response.text()
    if (data.includes('Has llegado al final')) {
      return { finished: true }
    }

    // Extract new cookie from Set-Cookie header
    const setCookieHeader = response.headers.get('set-cookie')
    let newCookie = ''

    if (setCookieHeader) {
      const match = setCookieHeader.match(/gryffindor=["]*([^";]*)["]*/)
      if (match) {
        newCookie = match[1]
      }
    }

    console.log('New cookie:', newCookie)

    if (newCookie) {
      console.log('Got new cookie value:', newCookie)
      return { finished: false, newCookie }
    }

    return { finished: true }
  } catch (error) {
    console.error('Error making request:', error.message)
    return { finished: true }
  }
}

async function collectCookies() {
  console.log('Collecting cookies...')
  let currentCookie = ''
  let cookieValues = []
  let finished = false

  while (!finished) {
    const result = await makeRequest(currentCookie)

    if (result.finished) {
      finished = true
    } else if (result.newCookie) {
      currentCookie = result.newCookie
      cookieValues.push(result.newCookie)
    }

    await new Promise((resolve) => setTimeout(resolve, 1000))
  }

  const cookieString = cookieValues.join(' ')
  console.log('All cookie values:', cookieString)

  console.log('Decoding message...')
  try {
    const decodedMessage = Buffer.from(cookieString, 'base64').toString('utf-8')
    console.log('Decoded message:', decodedMessage)
  } catch (error) {
    console.error('Error decoding message:', error.message)
  }
}

collectCookies()

The key insight is:

  1. Each request returns a new cookie value
  2. You must send the previous cookie to get the next one
  3. The cookie values are base64-encoded fragments
  4. When concatenated and decoded, they reveal the secret message

Step 3: Apply the "revelio" spell

The message says to use "revelio" to decode. In this case, it means Base64 decoding:

const cookieString = 'SGVsbG8g... V29ybGQh' // collected cookie values
const decodedMessage = Buffer.from(cookieString, 'base64').toString('utf-8')
console.log(decodedMessage) // The secret message!

Step 4: Submit the answer

After decoding the message, submit it to the solution endpoint:

curl -X 'POST' \
  'https://makers-challenge.altscore.ai/v1/s1/e8/solution' \
  -H 'accept: application/json' \
  -H 'API-KEY: API-KEY' \
  -H 'Content-Type: application/json' \
  -d '{
  "secret_message": "THE_DECODED_MESSAGE_HERE"
}'

And the response is:

{
  "result": "correct"
}

Key learnings

  1. Cookie chaining - Each cookie value depends on the previous one, like a linked list
  2. Timing matters - The door only responds correctly at specific times (every minute on the minute)
  3. Base64 encoding - "revelio" is a hint to decode/reveal the hidden message

TADA! 🎉