cedros-login-server 0.0.24

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Downloadable skills bundle endpoint
//!
//! - /.well-known/skills.zip - ZIP bundle containing all skills for local installation
//!
//! Compatible with Claude Code (SKILL.md format) and OpenAI Codex skill folders.

use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use std::io::{Cursor, Write};
use std::sync::Arc;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;

use crate::callback::AuthCallback;
use crate::services::EmailService;
use crate::AppState;

/// GET /.well-known/skills.zip - Downloadable skills bundle
///
/// Returns a ZIP file containing all skills in a format compatible with
/// Claude Code and OpenAI Codex local skill installation.
///
/// Structure:
/// ```text
/// skills/
/// ├── auth/
/// │   └── SKILL.md
/// ├── profile/
/// │   └── SKILL.md
/// ├── orgs/
/// │   └── SKILL.md
/// ├── mfa/
/// │   └── SKILL.md
/// ├── wallet/
/// │   └── SKILL.md
/// └── admin/
///     └── SKILL.md
/// ```
pub async fn skills_bundle_zip<C: AuthCallback + 'static, E: EmailService + 'static>(
    State(state): State<Arc<AppState<C, E>>>,
) -> Response {
    let base = get_base_path(&state);

    // Create ZIP in memory
    let mut buffer = Cursor::new(Vec::new());
    {
        let mut zip = ZipWriter::new(&mut buffer);
        let options = SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .unix_permissions(0o644);

        // Generate and add each skill file
        let skills = generate_skill_contents(&base);
        for (skill_id, content) in skills {
            let path = format!("skills/{}/SKILL.md", skill_id);
            if let Err(e) = zip.start_file(&path, options) {
                tracing::error!("Failed to create zip entry {}: {}", path, e);
                return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create bundle")
                    .into_response();
            }
            if let Err(e) = zip.write_all(content.as_bytes()) {
                tracing::error!("Failed to write zip content for {}: {}", path, e);
                return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create bundle")
                    .into_response();
            }
        }

        // Add a README at the root
        let readme = generate_readme(&base);
        if let Err(e) = zip.start_file("skills/README.md", options) {
            tracing::error!("Failed to create README entry: {}", e);
            return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create bundle").into_response();
        }
        if let Err(e) = zip.write_all(readme.as_bytes()) {
            tracing::error!("Failed to write README: {}", e);
            return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create bundle").into_response();
        }

        if let Err(e) = zip.finish() {
            tracing::error!("Failed to finalize zip: {}", e);
            return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create bundle").into_response();
        }
    }

    let bytes = buffer.into_inner();

    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "application/zip"),
            (
                header::CONTENT_DISPOSITION,
                "attachment; filename=\"skills.zip\"",
            ),
        ],
        bytes,
    )
        .into_response()
}

/// Generate README for the bundle
fn generate_readme(base: &str) -> String {
    format!(
        r#"# Cedros Login Skills Bundle

This bundle contains skills for the Cedros Login authentication service.

## Installation

### Claude Code
Copy the skill folders to your Claude Code skills directory:
```bash
unzip skills.zip -d ~/.claude/skills/cedros-login/
```

### OpenAI Codex
Copy to your Codex skills directory:
```bash
unzip skills.zip -d ~/.codex/skills/cedros-login/
```

## Available Skills

| Skill | Description |
|-------|-------------|
| auth | User registration, login, sessions, API keys |
| profile | User profile and settings management |
| orgs | Team and organization management |
| mfa | Multi-factor authentication setup |
| wallet | Embedded Solana wallet operations |
| admin | System administration (requires admin role) |

## API Base URL

All endpoints are relative to: `{base}`

## Online Documentation

- Full API: {base}/openapi.json
- Agent Guide: {base}/agent.md
- Skill Index: {base}/skill.md

## Authentication

The fastest way to authenticate as an agent:

1. `POST {base}/solana/challenge` with `{{"publicKey": "<your-pubkey>"}}`
2. Sign the returned nonce with your private key
3. `POST {base}/solana` with `{{"publicKey": "...", "signature": "..."}}`
4. Use returned API key: `Authorization: Bearer ck_xxx`
"#,
        base = base
    )
}

/// Generate content for all skills
fn generate_skill_contents(base: &str) -> Vec<(&'static str, String)> {
    vec![
        ("auth", generate_auth_skill(base)),
        ("profile", generate_profile_skill(base)),
        ("orgs", generate_orgs_skill(base)),
        ("mfa", generate_mfa_skill(base)),
        ("wallet", generate_wallet_skill(base)),
        ("admin", generate_admin_skill(base)),
    ]
}

fn generate_auth_skill(base: &str) -> String {
    format!(
        r#"---
skill: auth
name: Authentication
version: "1.0.0"
description: User registration, login, sessions, and API key management
apiBase: "{base}"
requiresAuth: false
---

# Authentication Skill

Handles user registration, login, session management, and API key operations.

## Solana Wallet Auth (Recommended for Agents)

### Step 1: Request Challenge
```
POST {base}/solana/challenge
Content-Type: application/json

{{"publicKey": "YourBase58SolanaPublicKey"}}
```

Response:
```json
{{"nonce": "Sign this message: cedros-auth-abc123...", "expiresAt": "2024-..."}}
```

### Step 2: Submit Signed Challenge
```
POST {base}/solana
Content-Type: application/json

{{
  "publicKey": "YourBase58SolanaPublicKey",
  "signature": "Base58SignatureOfNonce"
}}
```

Response:
```json
{{
  "user": {{"id": "uuid", "walletAddress": "..."}},
  "tokens": {{"accessToken": "...", "refreshToken": "..."}},
  "apiKey": "ck_live_abc123...",
  "isNewUser": true
}}
```

## Email/Password Auth

### Register
```
POST {base}/register
Content-Type: application/json

{{"email": "user@example.com", "password": "SecurePassword123!", "name": "User Name"}}
```

### Login
```
POST {base}/login
Content-Type: application/json

{{"email": "user@example.com", "password": "..."}}
```

## Session Management

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/sessions | List active sessions |
| DELETE | {base}/sessions | Revoke all sessions |
| POST | {base}/logout | Logout current session |
| POST | {base}/logout-all | Logout all sessions |

## API Key Management

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/user/api-key | Get current API key |
| POST | {base}/user/api-key/regenerate | Regenerate API key |
"#,
        base = base
    )
}

fn generate_profile_skill(base: &str) -> String {
    format!(
        r#"---
skill: profile
name: Profile
version: "1.0.0"
description: User profile and settings management
apiBase: "{base}"
requiresAuth: true
---

# Profile Skill

Manage user profile information and account settings.

## Get Current User
```
GET {base}/user
Authorization: Bearer <api-key>
```

Response:
```json
{{
  "id": "uuid",
  "email": "user@example.com",
  "name": "User Name",
  "walletAddress": "...",
  "mfaEnabled": false,
  "createdAt": "2024-..."
}}
```

## Update Profile
```
PATCH {base}/me
Authorization: Bearer <api-key>
Content-Type: application/json

{{"name": "New Name"}}
```

## Change Password
```
POST {base}/change-password
Authorization: Bearer <api-key>
Content-Type: application/json

{{"currentPassword": "...", "newPassword": "..."}}
```

## Endpoints Summary

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/user | Get current user |
| PATCH | {base}/me | Update profile |
| POST | {base}/change-password | Change password |
"#,
        base = base
    )
}

fn generate_orgs_skill(base: &str) -> String {
    format!(
        r#"---
skill: orgs
name: Organizations
version: "1.0.0"
description: Team and organization management with RBAC
apiBase: "{base}"
requiresAuth: true
---

# Organizations Skill

Create and manage organizations, members, invites, and roles.

## List Organizations
```
GET {base}/orgs
Authorization: Bearer <api-key>
```

## Create Organization
```
POST {base}/orgs
Authorization: Bearer <api-key>
Content-Type: application/json

{{"name": "My Organization", "slug": "my-org"}}
```

## Get Organization
```
GET {base}/orgs/{{id}}
Authorization: Bearer <api-key>
```

## Member Management

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/orgs/{{id}}/members | List members |
| PATCH | {base}/orgs/{{id}}/members/{{userId}} | Update member role |
| DELETE | {base}/orgs/{{id}}/members/{{userId}} | Remove member |

## Invites

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/orgs/{{id}}/invites | List pending invites |
| POST | {base}/orgs/{{id}}/invites | Create invite |
| POST | {base}/invites/{{token}}/accept | Accept invite |
| DELETE | {base}/orgs/{{id}}/invites/{{id}} | Cancel invite |

## Roles

Built-in roles: `owner`, `admin`, `member`, `viewer`

Custom roles can be created via the RBAC endpoints.
"#,
        base = base
    )
}

fn generate_mfa_skill(base: &str) -> String {
    format!(
        r#"---
skill: mfa
name: MFA
version: "1.0.0"
description: Multi-factor authentication setup and verification
apiBase: "{base}"
requiresAuth: true
---

# MFA Skill

Setup and manage multi-factor authentication using TOTP.

## Check MFA Status
```
GET {base}/mfa/status
Authorization: Bearer <api-key>
```

Response:
```json
{{"enabled": false, "backupCodesRemaining": 0}}
```

## Setup MFA

### Step 1: Start Setup
```
POST {base}/mfa/setup
Authorization: Bearer <api-key>
```

Response:
```json
{{
  "secret": "BASE32SECRET",
  "qrCodeUrl": "otpauth://totp/...",
  "backupCodes": ["code1", "code2", ...]
}}
```

### Step 2: Enable MFA
```
POST {base}/mfa/enable
Authorization: Bearer <api-key>
Content-Type: application/json

{{"code": "123456"}}
```

## Disable MFA
```
POST {base}/mfa/disable
Authorization: Bearer <api-key>
Content-Type: application/json

{{"code": "123456"}}
```

## Verify MFA (during login)
```
POST {base}/mfa/verify
Content-Type: application/json

{{"mfaToken": "...", "code": "123456"}}
```

## Endpoints Summary

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/mfa/status | Get MFA status |
| POST | {base}/mfa/setup | Start MFA setup |
| POST | {base}/mfa/enable | Enable MFA |
| POST | {base}/mfa/disable | Disable MFA |
| POST | {base}/mfa/verify | Verify MFA code |
"#,
        base = base
    )
}

fn generate_wallet_skill(base: &str) -> String {
    format!(
        r#"---
skill: wallet
name: Wallet
version: "1.0.0"
description: Embedded Solana wallet operations
apiBase: "{base}"
requiresAuth: true
---

# Wallet Skill

Manage embedded Solana wallet for transaction signing.

## Get Wallet Status
```
GET {base}/wallet/status
Authorization: Bearer <api-key>
```

Response:
```json
{{
  "enrolled": true,
  "publicKey": "SolanaPublicKey...",
  "locked": true
}}
```

## Enroll Wallet
```
POST {base}/wallet/enroll
Authorization: Bearer <api-key>
Content-Type: application/json

{{"userSecret": "user-chosen-passphrase"}}
```

## Unlock Wallet
```
POST {base}/wallet/unlock
Authorization: Bearer <api-key>
Content-Type: application/json

{{"userSecret": "user-chosen-passphrase"}}
```

## Sign Transaction
```
POST {base}/wallet/sign
Authorization: Bearer <api-key>
Content-Type: application/json

{{
  "transaction": "base64-encoded-transaction",
  "userSecret": "user-chosen-passphrase"
}}
```

Response:
```json
{{"signature": "base58-signature"}}
```

## Endpoints Summary

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/wallet/status | Get wallet status |
| GET | {base}/wallet/material | Get wallet material |
| POST | {base}/wallet/enroll | Enroll new wallet |
| POST | {base}/wallet/unlock | Unlock wallet |
| POST | {base}/wallet/sign | Sign transaction |
"#,
        base = base
    )
}

fn generate_admin_skill(base: &str) -> String {
    format!(
        r#"---
skill: admin
name: Admin
version: "1.0.0"
description: System administration and user management
apiBase: "{base}"
requiresAuth: true
requiresAdmin: true
---

# Admin Skill

System administration operations. Requires admin role.

## User Management

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/admin/users | List all users (paginated) |
| GET | {base}/admin/users/stats | Get user statistics |
| GET | {base}/admin/users/{{id}} | Get user details |
| PATCH | {base}/admin/users/{{id}} | Update user |
| DELETE | {base}/admin/users/{{id}} | Delete user |
| POST | {base}/admin/users/{{id}}/system-admin | Set system admin status |

## System Settings

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/admin/settings | List all settings |
| PUT | {base}/admin/settings | Update settings |

## Audit Logs

| Method | Path | Description |
|--------|------|-------------|
| GET | {base}/admin/audit-logs | Get system audit logs |
| GET | {base}/admin/orgs/{{id}}/audit-logs | Get org audit logs |

## Example: List Users
```
GET {base}/admin/users?page=1&limit=20
Authorization: Bearer <admin-api-key>
```

Response:
```json
{{
  "users": [...],
  "total": 150,
  "page": 1,
  "limit": 20
}}
```

## Full Admin Reference

See {base}/llms-admin.txt for complete admin documentation.
"#,
        base = base
    )
}

fn get_base_path<C: AuthCallback, E: EmailService>(state: &AppState<C, E>) -> String {
    let base_path = state.config.server.auth_base_path.trim_end_matches('/');
    if base_path.is_empty() {
        String::new()
    } else {
        base_path.to_string()
    }
}