@icarusmx/creta 1.5.14 → 1.5.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ # API Changes for Poetic Authentication
2
+
3
+ ## Endpoint to Modify
4
+
5
+ **Location:** `icarus.mx/api/creta/testeo`
6
+
7
+ This endpoint needs to be created/modified to handle the poetic key-value authentication pattern.
8
+
9
+ ---
10
+
11
+ ## Required Behavior
12
+
13
+ ### Request
14
+ ```bash
15
+ curl -H "Authorization: Bearer es un secreto" https://icarus.mx/api/creta/testeo
16
+ ```
17
+
18
+ ### Response
19
+ ```json
20
+ {
21
+ "message": "que a tu mirada y la mía la separa el abismo"
22
+ }
23
+ ```
24
+
25
+ Or as plain text:
26
+ ```
27
+ que a tu mirada y la mía la separa el abismo
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Implementation (SvelteKit Example)
33
+
34
+ If the API is SvelteKit-based, create:
35
+
36
+ **File:** `src/routes/api/creta/testeo/+server.js`
37
+
38
+ ```javascript
39
+ // src/routes/api/creta/testeo/+server.js
40
+
41
+ export async function GET({ request }) {
42
+ // Extract Authorization header
43
+ const authHeader = request.headers.get('Authorization');
44
+
45
+ // Check for the poetic key
46
+ if (authHeader === 'Bearer es un secreto') {
47
+ return new Response(
48
+ JSON.stringify({
49
+ message: "que a tu mirada y la mía la separa el abismo"
50
+ }),
51
+ {
52
+ status: 200,
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ 'Access-Control-Allow-Origin': '*'
56
+ }
57
+ }
58
+ );
59
+ }
60
+
61
+ // Unauthorized response
62
+ return new Response(
63
+ JSON.stringify({
64
+ error: "Unauthorized",
65
+ hint: "¿Conoces el secreto?"
66
+ }),
67
+ {
68
+ status: 401,
69
+ headers: {
70
+ 'Content-Type': 'application/json'
71
+ }
72
+ }
73
+ );
74
+ }
75
+
76
+ // Handle OPTIONS for CORS
77
+ export async function OPTIONS() {
78
+ return new Response(null, {
79
+ status: 204,
80
+ headers: {
81
+ 'Access-Control-Allow-Origin': '*',
82
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
83
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type'
84
+ }
85
+ });
86
+ }
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Implementation (Express.js Example)
92
+
93
+ If using Express.js:
94
+
95
+ ```javascript
96
+ // routes/api/creta.js
97
+
98
+ router.get('/testeo', (req, res) => {
99
+ const authHeader = req.headers.authorization;
100
+
101
+ if (authHeader === 'Bearer es un secreto') {
102
+ return res.json({
103
+ message: "que a tu mirada y la mía la separa el abismo"
104
+ });
105
+ }
106
+
107
+ return res.status(401).json({
108
+ error: "Unauthorized",
109
+ hint: "¿Conoces el secreto?"
110
+ });
111
+ });
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Testing the Endpoint
117
+
118
+ ### Using curl
119
+ ```bash
120
+ # Unauthorized (no key)
121
+ curl https://icarus.mx/api/creta/testeo
122
+
123
+ # Authorized (correct key)
124
+ curl -H "Authorization: Bearer es un secreto" https://icarus.mx/api/creta/testeo
125
+ ```
126
+
127
+ ### Using lz function
128
+ ```bash
129
+ # Without key
130
+ lz icarus.mx/api/creta/testeo
131
+
132
+ # With key
133
+ export key="es un secreto"
134
+ lz icarus.mx/api/creta/testeo
135
+ ```
136
+
137
+ ### Expected Outputs
138
+
139
+ **Without key (401):**
140
+ ```json
141
+ {
142
+ "error": "Unauthorized",
143
+ "hint": "¿Conoces el secreto?"
144
+ }
145
+ ```
146
+
147
+ **With correct key (200):**
148
+ ```json
149
+ {
150
+ "message": "que a tu mirada y la mía la separa el abismo"
151
+ }
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Poetic Context
157
+
158
+ This authentication pattern is inspired by romantic poetry - a playful way to teach API authentication concepts:
159
+
160
+ - **Key:** "es un secreto" (it's a secret)
161
+ - **Response:** "que a tu mirada y la mía la separa el abismo" (that separates your gaze and mine, the abyss)
162
+
163
+ It makes learning authentication memorable and culturally relevant for Spanish-speaking students.
164
+
165
+ ---
166
+
167
+ ## Security Note
168
+
169
+ **⚠️ This is for educational purposes only!**
170
+
171
+ In production:
172
+ - Never use predictable keys like "es un secreto"
173
+ - Use proper JWT tokens or API keys with sufficient entropy
174
+ - Implement rate limiting
175
+ - Use HTTPS (already doing this)
176
+ - Hash/encrypt sensitive data
177
+ - Implement token expiration
178
+
179
+ This endpoint is designed to teach the **concept** of Bearer token authentication in a memorable, culturally resonant way.
180
+
181
+ ---
182
+
183
+ ## Next Steps
184
+
185
+ 1. Deploy the endpoint to `icarus.mx/api/creta/testeo`
186
+ 2. Test with curl
187
+ 3. Test with `lz` function
188
+ 4. Update exercise documentation with live endpoint
189
+ 5. Consider adding to curl-and-pipes lesson (06-curl-and-pipes.md)
190
+
191
+ ---
192
+
193
+ **Reference:** This endpoint supports the `lz` shell function taught in exercise 13-shell-aliases.md
@@ -0,0 +1,114 @@
1
+ # Creta - Utilities for Exercises
2
+
3
+ This directory contains ready-to-use shell functions and utilities that students can copy and use while learning with Creta.
4
+
5
+ ## Available Utilities
6
+
7
+ ### lz-functions.sh
8
+
9
+ **Purpose:** API querying made simple with automatic API key management
10
+
11
+ **What it provides:**
12
+ - `lz [url]` - HTTP GET requests with automatic authentication
13
+ - `headers [url]` - View HTTP headers
14
+ - `post [url] [json]` - POST requests with JSON
15
+ - `switch_key [env]` - Switch between dev/staging/prod keys
16
+ - `show_key` - View current API key status (masked)
17
+ - `lz_help` - Quick reference
18
+
19
+ **Installation:**
20
+
21
+ ```bash
22
+ # Option 1: Copy to home directory
23
+ cp lib/exercises/utils/lz-functions.sh ~/.lz-functions.sh
24
+
25
+ # Add to ~/.zshrc
26
+ echo "source ~/.lz-functions.sh" >> ~/.zshrc
27
+
28
+ # Reload
29
+ source ~/.zshrc
30
+ ```
31
+
32
+ **Usage:**
33
+
34
+ ```bash
35
+ # Basic request
36
+ lz icarus.mx
37
+
38
+ # With authentication
39
+ export key="sk_test_your_api_key"
40
+ lz icarus.mx/api/endpoint
41
+
42
+ # POST with JSON
43
+ post icarus.mx/api/users '{"name":"Memo"}'
44
+
45
+ # View headers
46
+ headers icarus.mx/api/health
47
+
48
+ # Switch environments
49
+ switch_key dev
50
+ switch_key prod
51
+ switch_key clear # Remove key
52
+
53
+ # Check current key
54
+ show_key
55
+ ```
56
+
57
+ **Security Best Practices:**
58
+
59
+ 1. Never put API keys directly in `~/.zshrc`
60
+ 2. Create `~/.api_keys` with restrictive permissions:
61
+ ```bash
62
+ touch ~/.api_keys
63
+ chmod 600 ~/.api_keys
64
+ ```
65
+ 3. Add your keys to `~/.api_keys`:
66
+ ```bash
67
+ export key="your_api_key_here"
68
+ ```
69
+ 4. Source it from `~/.zshrc`:
70
+ ```bash
71
+ if [ -f ~/.api_keys ]; then
72
+ source ~/.api_keys
73
+ fi
74
+ ```
75
+ 5. Use `unset key` when done with sensitive APIs
76
+
77
+ **Related Lessons:**
78
+ - Exercise 13: Shell Functions - API Querying Simplificado
79
+ - Exercise 06: Curl y pipes
80
+
81
+ ---
82
+
83
+ ## Adding New Utilities
84
+
85
+ When creating new utilities for exercises:
86
+
87
+ 1. Create a descriptive filename (e.g., `git-helpers.sh`)
88
+ 2. Add comprehensive comments explaining:
89
+ - What it does
90
+ - How to install it
91
+ - How to use it
92
+ - Examples
93
+ 3. Update this README with the new utility
94
+ 4. Reference it from the relevant exercise
95
+
96
+ ## Philosophy
97
+
98
+ These utilities are **learning tools**, not production code:
99
+ - Simple over clever
100
+ - Well-commented
101
+ - Easy to understand
102
+ - Ready to copy-paste
103
+ - Safe defaults
104
+
105
+ Students should be able to:
106
+ 1. Copy the file
107
+ 2. Understand what it does
108
+ 3. Customize it for their needs
109
+ 4. Learn from the code
110
+
111
+ ---
112
+
113
+ **Maintained by:** Icarus Software School
114
+ **License:** MIT (educational use)
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env zsh
2
+
3
+ # ==============================================================================
4
+ # lz - API Querying Simplificado con manejo automático de API keys
5
+ # ==============================================================================
6
+ #
7
+ # Instalación:
8
+ # 1. Copia este archivo a ~/.lz-functions.sh
9
+ # 2. Agrega a tu ~/.zshrc:
10
+ # source ~/.lz-functions.sh
11
+ # 3. Recarga: source ~/.zshrc
12
+ #
13
+ # Uso básico:
14
+ # lz icarus.mx # Request normal
15
+ # export key="es un secreto" # Define API key (poético)
16
+ # lz icarus.mx/api/creta/testeo # Request con autenticación automática
17
+ # unset key # Elimina la key (seguridad)
18
+ #
19
+ # ==============================================================================
20
+
21
+ # ------------------------------------------------------------------------------
22
+ # lz() - Función principal para hacer requests HTTP
23
+ # ------------------------------------------------------------------------------
24
+ # Detecta automáticamente si la variable $key está definida y agrega el header
25
+ # de autorización. Acepta URLs con o sin protocolo (agrega https:// si falta).
26
+ #
27
+ # Ejemplos:
28
+ # lz icarus.mx
29
+ # lz icarus.mx/api/endpoint
30
+ # lz https://api.ejemplo.com/data
31
+ # ------------------------------------------------------------------------------
32
+ lz() {
33
+ local url="$1"
34
+
35
+ # Validar que se pasó una URL
36
+ if [ -z "$url" ]; then
37
+ echo "❌ Uso: lz [url]"
38
+ echo "Ejemplo: lz icarus.mx/api/endpoint"
39
+ return 1
40
+ fi
41
+
42
+ # Si la URL no tiene protocolo, agregar https://
43
+ if [[ ! "$url" =~ ^https?:// ]]; then
44
+ url="https://$url"
45
+ fi
46
+
47
+ # Si hay API key exportada, incluirla en el header
48
+ if [ -n "$key" ]; then
49
+ echo "🔑 Request con autenticación a: $url"
50
+ curl -H "Authorization: Bearer $key" "$url"
51
+ else
52
+ echo "🌐 Request sin autenticación a: $url"
53
+ curl "$url"
54
+ fi
55
+ }
56
+
57
+ # ------------------------------------------------------------------------------
58
+ # headers() - Ver solo los headers de un endpoint
59
+ # ------------------------------------------------------------------------------
60
+ # Wrapper de lz con flag -I para ver headers HTTP
61
+ #
62
+ # Ejemplos:
63
+ # headers icarus.mx
64
+ # headers api.ejemplo.com/health
65
+ # ------------------------------------------------------------------------------
66
+ headers() {
67
+ local url="$1"
68
+
69
+ if [ -z "$url" ]; then
70
+ echo "❌ Uso: headers [url]"
71
+ return 1
72
+ fi
73
+
74
+ # Agregar https:// si falta
75
+ if [[ ! "$url" =~ ^https?:// ]]; then
76
+ url="https://$url"
77
+ fi
78
+
79
+ if [ -n "$key" ]; then
80
+ curl -I -H "Authorization: Bearer $key" "$url"
81
+ else
82
+ curl -I "$url"
83
+ fi
84
+ }
85
+
86
+ # ------------------------------------------------------------------------------
87
+ # post() - Hacer POST request con JSON
88
+ # ------------------------------------------------------------------------------
89
+ # Envía datos JSON a un endpoint. Incluye API key automáticamente si existe.
90
+ #
91
+ # Ejemplos:
92
+ # post icarus.mx/api/users '{"name":"Guillermo"}'
93
+ # export key="es un secreto"
94
+ # post icarus.mx/api/creta/testeo '{"message":"hola"}'
95
+ # ------------------------------------------------------------------------------
96
+ post() {
97
+ local url="$1"
98
+ local data="$2"
99
+
100
+ if [ -z "$url" ] || [ -z "$data" ]; then
101
+ echo "❌ Uso: post [url] [json]"
102
+ echo "Ejemplo: post icarus.mx/api/users '{\"name\":\"Memo\"}'"
103
+ return 1
104
+ fi
105
+
106
+ # Agregar https:// si falta
107
+ if [[ ! "$url" =~ ^https?:// ]]; then
108
+ url="https://$url"
109
+ fi
110
+
111
+ if [ -n "$key" ]; then
112
+ echo "🔑 POST con autenticación a: $url"
113
+ curl -X POST \
114
+ -H "Authorization: Bearer $key" \
115
+ -H "Content-Type: application/json" \
116
+ -d "$data" \
117
+ "$url"
118
+ else
119
+ echo "🌐 POST sin autenticación a: $url"
120
+ curl -X POST \
121
+ -H "Content-Type: application/json" \
122
+ -d "$data" \
123
+ "$url"
124
+ fi
125
+ }
126
+
127
+ # ------------------------------------------------------------------------------
128
+ # switch_key() - Cambiar entre diferentes API keys
129
+ # ------------------------------------------------------------------------------
130
+ # Útil cuando trabajas con múltiples ambientes (dev, staging, prod).
131
+ # Personaliza los casos según tus necesidades.
132
+ #
133
+ # Ejemplos:
134
+ # switch_key dev
135
+ # switch_key prod
136
+ # switch_key staging
137
+ # ------------------------------------------------------------------------------
138
+ switch_key() {
139
+ case "$1" in
140
+ dev)
141
+ export key="sk_test_desarrollo_placeholder"
142
+ echo "✅ API key: desarrollo"
143
+ ;;
144
+ staging)
145
+ export key="sk_test_staging_placeholder"
146
+ echo "✅ API key: staging"
147
+ ;;
148
+ prod)
149
+ export key="sk_live_produccion_placeholder"
150
+ echo "⚠️ API key: producción (¡cuidado!)"
151
+ ;;
152
+ clear)
153
+ unset key
154
+ echo "🧹 API key eliminada"
155
+ ;;
156
+ *)
157
+ echo "❌ Uso: switch_key [dev|staging|prod|clear]"
158
+ return 1
159
+ ;;
160
+ esac
161
+ }
162
+
163
+ # ------------------------------------------------------------------------------
164
+ # show_key() - Mostrar el estado actual de la API key
165
+ # ------------------------------------------------------------------------------
166
+ # Útil para verificar qué key está activa sin exponer su valor completo.
167
+ #
168
+ # Ejemplos:
169
+ # show_key
170
+ # ------------------------------------------------------------------------------
171
+ show_key() {
172
+ if [ -n "$key" ]; then
173
+ # Mostrar solo los primeros 10 caracteres (seguridad)
174
+ local masked_key="${key:0:10}***"
175
+ echo "🔑 API key activa: $masked_key"
176
+ else
177
+ echo "❌ No hay API key definida"
178
+ echo "💡 Define una con: export key=\"tu_api_key\""
179
+ fi
180
+ }
181
+
182
+ # ------------------------------------------------------------------------------
183
+ # lz_help() - Ayuda rápida
184
+ # ------------------------------------------------------------------------------
185
+ lz_help() {
186
+ cat << 'EOF'
187
+ ╔══════════════════════════════════════════════════════════════╗
188
+ ║ lz - API Querying Simplificado ║
189
+ ╚══════════════════════════════════════════════════════════════╝
190
+
191
+ 📚 Funciones disponibles:
192
+
193
+ lz [url] Request GET con autenticación automática
194
+ headers [url] Ver solo headers HTTP
195
+ post [url] [json] POST request con JSON
196
+ switch_key [env] Cambiar entre dev/staging/prod/clear
197
+ show_key Ver estado de la API key actual
198
+
199
+ 🔐 Gestión de API keys:
200
+
201
+ export key="sk_..." Define API key para la sesión
202
+ unset key Elimina API key (seguridad)
203
+ switch_key dev Cambia a ambiente de desarrollo
204
+ switch_key clear Elimina la key actual
205
+
206
+ 💡 Ejemplos:
207
+
208
+ # Request normal
209
+ lz icarus.mx
210
+
211
+ # Request con autenticación (poético)
212
+ export key="es un secreto"
213
+ lz icarus.mx/api/creta/testeo
214
+ # Responde: "que a tu mirada y la mía la separa el abismo"
215
+
216
+ # Ver headers
217
+ headers icarus.mx/api/health
218
+
219
+ # POST con JSON
220
+ post icarus.mx/api/users '{"name":"Guillermo"}'
221
+
222
+ # Combinar con jq para parsear JSON
223
+ lz icarus.mx/api/data | jq '.results'
224
+
225
+ 🔒 Seguridad:
226
+
227
+ ❌ NUNCA pongas keys en ~/.zshrc directamente
228
+ ✅ Usa ~/.api_keys con permisos 600
229
+ ✅ Agrega a ~/.zshrc: source ~/.api_keys
230
+ ✅ Usa unset key al terminar
231
+
232
+ 📖 Más info: creta help lz
233
+
234
+ EOF
235
+ }
236
+
237
+ # ------------------------------------------------------------------------------
238
+ # Mensaje de bienvenida (opcional - comenta si no lo quieres)
239
+ # ------------------------------------------------------------------------------
240
+ # echo "✅ lz functions cargadas. Usa 'lz_help' para ayuda."