cedros-login-server 0.0.19

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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
//! Composable content generators for AI discovery
//!
//! This module exports functions that generate AI discovery content without
//! being tied to HTTP handlers. This allows consuming applications to:
//!
//! 1. Use the default handlers for standalone deployment
//! 2. Compose unified discovery from multiple packages (e.g., cedros-login + cedros-pay)
//!
//! # Example: Composing unified discovery
//!
//! ```text
//! use cedros_login::ai_discovery::{ContentConfig, get_skills, get_llms_content};
//! use cedros_pay::ai_discovery as pay_discovery;
//!
//! // Get skills from both packages
//! let login_config = ContentConfig::new("/auth");
//! let pay_config = pay_discovery::ContentConfig::new("/pay");
//!
//! let mut all_skills = get_skills(&login_config);
//! all_skills.extend(pay_discovery::get_skills(&pay_config));
//!
//! // Generate unified llms.txt
//! let unified_llms = format!(
//!     "# Cedros Platform\n\n{}\n\n{}",
//!     get_llms_section(&login_config),
//!     pay_discovery::get_llms_section(&pay_config),
//! );
//! ```

use super::types::*;

/// Configuration for content generation
#[derive(Debug, Clone)]
pub struct ContentConfig {
    /// Base path for all endpoints (e.g., "" for root, "/auth" for mounted)
    pub base_path: String,
    /// Service name
    pub name: String,
    /// Service version
    pub version: String,
    /// Service description
    pub description: String,
    /// Homepage URL (optional)
    pub homepage: Option<String>,
}

impl ContentConfig {
    /// Create a new content config with the given base path
    pub fn new(base_path: &str) -> Self {
        Self {
            base_path: base_path.to_string(),
            name: "cedros-login".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: "Authentication and authorization API for apps and AI agents".to_string(),
            homepage: None,
        }
    }

    /// Create config with custom name and description
    pub fn with_details(base_path: &str, name: &str, description: &str) -> Self {
        Self {
            base_path: base_path.to_string(),
            name: name.to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: description.to_string(),
            homepage: None,
        }
    }

    /// Set homepage URL
    pub fn with_homepage(mut self, url: &str) -> Self {
        self.homepage = Some(url.to_string());
        self
    }

    /// Get full path for an endpoint
    pub fn path(&self, endpoint: &str) -> String {
        format!("{}{}", self.base_path, endpoint)
    }
}

impl Default for ContentConfig {
    fn default() -> Self {
        Self::new("")
    }
}

// ============================================================================
// Skill Definitions
// ============================================================================

/// Get all skill references for cedros-login
pub fn get_skill_references(config: &ContentConfig) -> Vec<SkillReference> {
    vec![
        SkillReference {
            id: "auth".to_string(),
            name: "Authentication".to_string(),
            path: config.path("/skills/auth.md"),
            description: "User registration, login, sessions, and API key management".to_string(),
            requires_auth: Some(false),
            requires_admin: None,
        },
        SkillReference {
            id: "profile".to_string(),
            name: "Profile".to_string(),
            path: config.path("/skills/profile.md"),
            description: "User profile management and settings".to_string(),
            requires_auth: Some(true),
            requires_admin: None,
        },
        SkillReference {
            id: "orgs".to_string(),
            name: "Organizations".to_string(),
            path: config.path("/skills/orgs.md"),
            description: "Organization management, members, invites, and RBAC".to_string(),
            requires_auth: Some(true),
            requires_admin: None,
        },
        SkillReference {
            id: "mfa".to_string(),
            name: "MFA".to_string(),
            path: config.path("/skills/mfa.md"),
            description: "Multi-factor authentication setup and management".to_string(),
            requires_auth: Some(true),
            requires_admin: None,
        },
        SkillReference {
            id: "wallet".to_string(),
            name: "Wallet".to_string(),
            path: config.path("/skills/wallet.md"),
            description: "Embedded Solana wallet operations".to_string(),
            requires_auth: Some(true),
            requires_admin: None,
        },
        SkillReference {
            id: "admin".to_string(),
            name: "Admin".to_string(),
            path: config.path("/skills/admin.md"),
            description: "System administration and user management".to_string(),
            requires_auth: Some(true),
            requires_admin: Some(true),
        },
    ]
}

/// Get skill capabilities for cedros-login
pub fn get_skill_capabilities() -> SkillCapabilities {
    SkillCapabilities {
        user_auth: true,
        admin_auth: true,
        organizations: true,
        embedded_wallet: true,
        mfa: true,
        rbac: true,
        api_keys: true,
    }
}

/// Get authentication info for cedros-login
pub fn get_skill_auth() -> SkillAuth {
    SkillAuth {
        methods: vec![
            "solana-wallet".to_string(),
            "email-password".to_string(),
            "passkey".to_string(),
            "oauth".to_string(),
            "api-key".to_string(),
        ],
        recommended: "solana-wallet".to_string(),
        api_key_prefix: "ck_".to_string(),
        header: "Authorization".to_string(),
    }
}

/// Get rate limits for cedros-login
pub fn get_rate_limits() -> RateLimits {
    RateLimits {
        auth_endpoints: "10 req/min per IP".to_string(),
        api_endpoints: "100 req/min per key".to_string(),
        admin_endpoints: "30 req/min per key".to_string(),
    }
}

/// Get complete skill metadata for cedros-login
pub fn get_skill_metadata(config: &ContentConfig) -> SkillMetadata {
    SkillMetadata {
        name: config.name.clone(),
        version: config.version.clone(),
        description: config.description.clone(),
        homepage: config.homepage.clone(),
        api_base: config.base_path.clone(),
        category: "authentication".to_string(),
        capabilities: get_skill_capabilities(),
        skills: get_skill_references(config),
        authentication: get_skill_auth(),
        rate_limits: get_rate_limits(),
        downloadable_bundles: Some(DownloadableBundles {
            claude_code: config.path("/.well-known/skills.zip"),
            codex: config.path("/.well-known/skills.zip"),
        }),
    }
}

// ============================================================================
// Discovery Index
// ============================================================================

/// Get AI discovery index for cedros-login
pub fn get_discovery_index(config: &ContentConfig) -> AiDiscoveryIndex {
    AiDiscoveryIndex {
        version: "1.0.0".to_string(),
        name: config.name.clone(),
        description: config.description.clone(),
        endpoints: DiscoveryEndpoints {
            llms_txt: config.path("/llms.txt"),
            llms_full_txt: config.path("/llms-full.txt"),
            llms_admin_txt: Some(config.path("/llms-admin.txt")),
            skill_index_markdown: config.path("/skill.md"),
            skill_index_json: config.path("/skill.json"),
            agent_guide: config.path("/agent.md"),
            openapi: config.path("/openapi.json"),
            a2a_agent_card: config.path("/.well-known/agent.json"),
            ai_plugin: config.path("/.well-known/ai-plugin.json"),
            mcp: config.path("/.well-known/mcp"),
            health: config.path("/heartbeat.json"),
            auth_discovery: config.path("/discovery"),
            skills_bundle: Some(config.path("/.well-known/skills.zip")),
        },
        skills: Some(
            get_skill_references(config)
                .into_iter()
                .map(|s| SkillPointer {
                    id: s.id,
                    name: s.name,
                    path: s.path,
                })
                .collect(),
        ),
    }
}

// ============================================================================
// Text Content Generators
// ============================================================================

/// Generate llms.txt content
pub fn generate_llms_txt(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"# Cedros Login

> Authentication and authorization API for apps and AI agents. Supports Solana wallet auth (recommended for agents), email/password, OAuth, passkeys, MFA, organizations with RBAC, and embedded Solana wallet operations.

Cedros Login provides identity and access management with first-class support for AI agents. Agents can authenticate using Solana wallet signatures without requiring email verification, receiving an API key for subsequent requests.

## Quick Start

1. Generate Ed25519 keypair (Solana format)
2. `POST {base}/solana/challenge` with `{{"publicKey": "<base58-pubkey>"}}`
3. Sign the returned nonce with your private key
4. `POST {base}/solana` with `{{"publicKey": "...", "signature": "<base58-sig>"}}`
5. Use returned API key: `Authorization: Bearer ck_xxx`

## Docs

- [{base}/agent.md]({base}/agent.md): Agent integration guide with code examples in Python, JavaScript, and Rust
- [{base}/llms-full.txt]({base}/llms-full.txt): Complete API documentation
- [{base}/llms-admin.txt]({base}/llms-admin.txt): Admin operations reference

## Skills

- [{base}/skills/auth.md]({base}/skills/auth.md): Authentication, sessions, API keys
- [{base}/skills/profile.md]({base}/skills/profile.md): User profile management
- [{base}/skills/orgs.md]({base}/skills/orgs.md): Organizations, members, invites, RBAC
- [{base}/skills/mfa.md]({base}/skills/mfa.md): Multi-factor authentication setup
- [{base}/skills/wallet.md]({base}/skills/wallet.md): Embedded Solana wallet operations
- [{base}/skills/admin.md]({base}/skills/admin.md): System administration (requires admin role)

## API

- [{base}/openapi.json]({base}/openapi.json): Full OpenAPI 3.0 specification
- [{base}/discovery]({base}/discovery): Machine-readable auth configuration
- [{base}/skill.json]({base}/skill.json): Machine-readable skill metadata

## Optional

- [{base}/heartbeat.json]({base}/heartbeat.json): Health check endpoint
- [{base}/.well-known/ai-discovery.json]({base}/.well-known/ai-discovery.json): Discovery index (links to all endpoints)
- [{base}/.well-known/agent.json]({base}/.well-known/agent.json): Google A2A Agent Card
- [{base}/.well-known/mcp]({base}/.well-known/mcp): MCP server discovery
"#,
        base = base
    )
}

/// Generate ai.txt content
pub fn generate_ai_txt(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"# AI Access Policy
# This file signals permissions for AI crawlers and agents.
# See: https://ai-txt.org (emerging standard)

# Policy: Allow all AI access
User-agent: *
Allow: /

# AI Discovery Entry Point
# Start here to discover all available endpoints and capabilities
AI-Discovery: {base}/.well-known/ai-discovery.json

# Quick Links for AI Systems
LLMs-Txt: {base}/llms.txt
LLMs-Full: {base}/llms-full.txt
OpenAPI: {base}/openapi.json
Skills: {base}/skill.json
Agent-Guide: {base}/agent.md

# Authentication
# This service supports AI agent authentication via Solana wallet signatures.
# No email verification required for agents.
# See: {base}/agent.md

# Rate Limits
# Auth endpoints: 10 req/min per IP
# API endpoints: 100 req/min per key
# Admin endpoints: 30 req/min per key

# Contact
# For API access issues, see the documentation at {base}/llms.txt
"#,
        base = base
    )
}

/// Generate skill.md content (YAML frontmatter + markdown)
pub fn generate_skill_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    let skills = get_skill_references(config);

    let skills_yaml: Vec<String> = skills
        .iter()
        .map(|s| {
            let mut yaml = format!(
                "  - id: {}\n    path: {}\n    requiresAuth: {}",
                s.id,
                s.path,
                s.requires_auth.unwrap_or(false)
            );
            if let Some(true) = s.requires_admin {
                yaml.push_str("\n    requiresAdmin: true");
            }
            yaml
        })
        .collect();

    let skills_table: Vec<String> = skills
        .iter()
        .map(|s| {
            let auth = if s.requires_admin == Some(true) {
                "Yes (Admin)"
            } else if s.requires_auth == Some(true) {
                "Yes"
            } else {
                "No"
            };
            format!(
                "| [{}]({}) | {} | {} |",
                s.name, s.path, s.description, auth
            )
        })
        .collect();

    format!(
        r#"---
name: cedros-login
version: "{version}"
description: Authentication and authorization API for apps and AI agents
category: authentication
apiBase: "{base}"
capabilities:
  userAuth: true
  adminAuth: true
  organizations: true
  embeddedWallet: true
  mfa: true
  rbac: true
  apiKeys: true
authentication:
  methods: [solana-wallet, email-password, passkey, oauth, api-key]
  recommended: solana-wallet
  apiKeyPrefix: "ck_"
  header: "Authorization: Bearer <api-key>"
rateLimits:
  auth: "10 req/min per IP"
  api: "100 req/min per key"
  admin: "30 req/min per key"
skills:
{skills_yaml}
---

# Cedros Login Skills

Authentication and authorization API for apps and AI agents. Supports Solana wallet auth (recommended for agents), email/password, OAuth, passkeys, MFA, organizations with RBAC, and embedded Solana wallet operations.

## Available Skills

| Skill | Description | Auth Required |
|-------|-------------|---------------|
{skills_table}

## Quick Start for Agents

1. Generate Ed25519 keypair (Solana format)
2. Request challenge: `POST {base}/solana/challenge` with `{{"publicKey": "<base58>"}}`
3. Sign the nonce with your private key
4. Authenticate: `POST {base}/solana` with `{{"publicKey": "...", "signature": "..."}}`
5. Use API key: `Authorization: Bearer ck_xxx`

## Discovery Endpoints

| Endpoint | Format | Purpose |
|----------|--------|---------|
| {base}/llms.txt | text | Brief API summary |
| {base}/llms-full.txt | text | Complete documentation |
| {base}/llms-admin.txt | text | Admin operations |
| {base}/skill.json | JSON | Machine-readable skill metadata |
| {base}/agent.md | markdown | Integration guide with code |
| {base}/openapi.json | JSON | Full OpenAPI specification |
| {base}/discovery | JSON | Auth configuration |

## Authentication Methods

### Solana Wallet (Recommended for Agents)

No email verification required. Sign a challenge with your Ed25519 key to get an API key.

### API Key

After initial authentication, use your API key for all requests:
```
Authorization: Bearer ck_xxx
```

### Email/Password

Traditional auth with optional email verification.

## Rate Limits

| Category | Limit |
|----------|-------|
| Auth endpoints | 10 req/min per IP |
| API endpoints | 100 req/min per key |
| Admin endpoints | 30 req/min per key |

## Error Format

```json
{{
  "code": "ERROR_CODE",
  "message": "Human-readable description",
  "details": {{}}
}}
```
"#,
        version = config.version,
        base = base,
        skills_yaml = skills_yaml.join("\n"),
        skills_table = skills_table.join("\n"),
    )
}

// ============================================================================
// Manifest Generators
// ============================================================================

/// Generate OpenAI plugin manifest
pub fn get_ai_plugin_manifest(config: &ContentConfig) -> AiPluginManifest {
    AiPluginManifest {
        schema_version: "v1".to_string(),
        name_for_human: "Cedros Login".to_string(),
        name_for_model: "cedros_login".to_string(),
        description_for_human: "Authentication and identity management for apps and AI agents"
            .to_string(),
        description_for_model: format!(
            "Cedros Login API for authentication. Supports Solana wallet auth (recommended), \
            email/password, passkeys, OAuth, MFA, organizations with RBAC, and embedded wallets. \
            Agents should use Solana wallet auth: POST {}/solana/challenge then POST {}/solana.",
            config.base_path, config.base_path
        ),
        auth: AiPluginAuth {
            auth_type: "bearer".to_string(),
            instructions: Some(format!(
                "Authenticate via Solana wallet signature to get an API key. \
                See {}/agent.md for complete guide.",
                config.base_path
            )),
        },
        api: AiPluginApi {
            api_type: "openapi".to_string(),
            url: config.path("/openapi.json"),
        },
        logo_url: None,
        contact_email: None,
        legal_info_url: None,
    }
}

/// Generate A2A Agent Card
pub fn get_agent_card(config: &ContentConfig) -> AgentCard {
    let skills = get_skill_references(config);

    AgentCard {
        name: "Cedros Login".to_string(),
        description: config.description.clone(),
        url: config.base_path.clone(),
        version: config.version.clone(),
        capabilities: AgentCapabilities {
            streaming: false,
            push_notifications: false,
            state_management: true,
        },
        authentication: AgentAuthentication {
            schemes: vec![
                AuthScheme {
                    scheme: "bearer".to_string(),
                    description: "API key authentication (recommended for agents)".to_string(),
                    instructions_url: Some(config.path("/agent.md")),
                    token_url: None,
                    authorization_url: None,
                },
                AuthScheme {
                    scheme: "oauth2".to_string(),
                    description: "OAuth 2.0 with JWT tokens".to_string(),
                    instructions_url: Some(config.path("/skills/auth.md")),
                    token_url: Some(config.path("/login")),
                    authorization_url: Some(config.path("/oauth/authorize")),
                },
            ],
            scopes: Some(vec![
                AuthScope {
                    name: "user:read".to_string(),
                    description: "Read user profile and settings".to_string(),
                },
                AuthScope {
                    name: "user:write".to_string(),
                    description: "Modify user profile and settings".to_string(),
                },
                AuthScope {
                    name: "org:read".to_string(),
                    description: "Read organization data".to_string(),
                },
                AuthScope {
                    name: "org:write".to_string(),
                    description: "Manage organization members and settings".to_string(),
                },
                AuthScope {
                    name: "wallet:read".to_string(),
                    description: "Read wallet balance and history".to_string(),
                },
                AuthScope {
                    name: "wallet:sign".to_string(),
                    description: "Sign transactions with embedded wallet".to_string(),
                },
                AuthScope {
                    name: "admin:read".to_string(),
                    description: "Read admin data (requires admin role)".to_string(),
                },
                AuthScope {
                    name: "admin:write".to_string(),
                    description: "Perform admin operations (requires admin role)".to_string(),
                },
            ]),
        },
        skills: skills
            .into_iter()
            .map(|s| {
                let scopes = match s.id.as_str() {
                    "auth" => vec!["user:read".to_string(), "user:write".to_string()],
                    "profile" => vec!["user:read".to_string(), "user:write".to_string()],
                    "orgs" => vec!["org:read".to_string(), "org:write".to_string()],
                    "wallet" => vec!["wallet:read".to_string(), "wallet:sign".to_string()],
                    "admin" => vec!["admin:read".to_string(), "admin:write".to_string()],
                    _ => vec!["user:read".to_string()],
                };
                AgentSkill {
                    id: s.id.clone(),
                    name: s.name,
                    description: s.description,
                    input_modes: vec!["application/json".to_string()],
                    output_modes: vec!["application/json".to_string()],
                    documentation_url: Some(s.path),
                    openapi_tag: Some(s.id.to_uppercase()),
                    required_scopes: Some(scopes),
                }
            })
            .collect(),
        documentation_url: Some(config.path("/llms-full.txt")),
        provider: Some(AgentProvider {
            name: "Cedros".to_string(),
            url: config.homepage.clone(),
        }),
    }
}

/// Generate MCP discovery info
pub fn get_mcp_discovery(config: &ContentConfig) -> McpDiscovery {
    McpDiscovery {
        name: config.name.clone(),
        version: config.version.clone(),
        protocol_version: "2024-11-05".to_string(),
        description: config.description.clone(),
        capabilities: McpCapabilities {
            tools: true,
            resources: true,
            prompts: false,
            sampling: false,
        },
        tools: vec![
            McpTool {
                name: "authenticate".to_string(),
                description: "Authenticate with Solana wallet signature".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "publicKey": {
                            "type": "string",
                            "description": "Base58-encoded Solana public key"
                        },
                        "signature": {
                            "type": "string",
                            "description": "Base58-encoded signature of the challenge nonce"
                        }
                    },
                    "required": ["publicKey", "signature"]
                }),
            },
            McpTool {
                name: "get_user".to_string(),
                description: "Get current user profile".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {}
                }),
            },
            McpTool {
                name: "list_orgs".to_string(),
                description: "List organizations the user belongs to".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {}
                }),
            },
        ],
        authentication: McpAuth {
            required: true,
            schemes: vec!["bearer".to_string()],
            instructions: format!(
                "Authenticate via Solana wallet signature. See {}/agent.md",
                config.base_path
            ),
        },
    }
}

// ============================================================================
// Individual Skill Content
// ============================================================================

/// Skill file content for auth.md
pub fn generate_skill_auth_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: auth
name: Authentication
version: "{version}"
description: User registration, login, sessions, and API key management
apiBase: "{base}"
requiresAuth: false
---

# Authentication Skill

User registration, login, session management, and API key operations.

## Solana Wallet Auth (Recommended for Agents)

### Step 1: Get Challenge

```
POST {base}/solana/challenge
Content-Type: application/json

{{"publicKey": "<base58-encoded-public-key>"}}
```

Response:
```json
{{"nonce": "<challenge-string-to-sign>", "expiresAt": "2024-01-01T00:00:00Z"}}
```

### Step 2: Authenticate

```
POST {base}/solana
Content-Type: application/json

{{
  "publicKey": "<base58-encoded-public-key>",
  "signature": "<base58-encoded-signature-of-nonce>"
}}
```

Response:
```json
{{
  "user": {{"id": "uuid", "walletAddress": "..."}},
  "apiKey": "ck_xxx"
}}
```

## Email/Password Auth

### Register

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

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

### Login

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

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

## API Keys

### Get Current API Key (Legacy)

```
GET {base}/user/api-key
Authorization: Bearer <jwt-or-api-key>
```

### Regenerate API Key (Legacy)

```
POST {base}/user/api-key/regenerate
Authorization: Bearer <jwt-or-api-key>
```

### List All API Keys

```
GET {base}/user/api-keys
Authorization: Bearer <jwt-or-api-key>
```

Response:
```json
{{"keys": [{{"id": "uuid", "keyPrefix": "ck_xxxx", "label": "default", "createdAt": "...", "lastUsedAt": "..."}}]}}
```

### Create API Key

```
POST {base}/user/api-keys
Authorization: Bearer <jwt-or-api-key>
Content-Type: application/json

{{"label": "bot-alpha"}}
```

### Delete API Key

```
DELETE {base}/user/api-keys/{{key_id}}
Authorization: Bearer <jwt-or-api-key>
```

## Sessions

### Logout Current Session

```
POST {base}/logout
Authorization: Bearer <jwt-or-api-key>
```

### Logout All Sessions

```
POST {base}/logout-all
Authorization: Bearer <jwt-or-api-key>
```

## Error Codes

| Code | Description |
|------|-------------|
| INVALID_CREDENTIALS | Email/password incorrect |
| INVALID_SIGNATURE | Wallet signature verification failed |
| NONCE_EXPIRED | Challenge nonce has expired |
| EMAIL_NOT_VERIFIED | Email verification required |
| RATE_LIMITED | Too many auth attempts |
"#,
        version = config.version,
        base = base
    )
}

/// Skill file content for profile.md
pub fn generate_skill_profile_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: profile
name: Profile
version: "{version}"
description: User profile management and settings
apiBase: "{base}"
requiresAuth: true
---

# Profile Skill

Manage user profile information and settings.

## Get Current User

```
GET {base}/user
Authorization: Bearer <api-key>
```

Response:
```json
{{
  "id": "uuid",
  "email": "user@example.com",
  "name": "User Name",
  "walletAddress": "base58...",
  "emailVerified": true,
  "mfaEnabled": false,
  "createdAt": "2024-01-01T00:00:00Z"
}}
```

## Update Profile

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

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

## Email Verification

### Send Verification Email

```
POST {base}/send-verification
Authorization: Bearer <api-key>
```

### Verify Email

```
POST {base}/verify-email
Content-Type: application/json

{{"token": "<verification-token>"}}
```

## Error Codes

| Code | Description |
|------|-------------|
| UNAUTHORIZED | Not authenticated |
| INVALID_TOKEN | Verification token invalid or expired |
"#,
        version = config.version,
        base = base
    )
}

/// Skill file content for orgs.md
pub fn generate_skill_orgs_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: orgs
name: Organizations
version: "{version}"
description: Organization management, members, invites, and RBAC
apiBase: "{base}"
requiresAuth: true
---

# Organizations Skill

Create and manage organizations with role-based access control.

## List My Organizations

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

## Create Organization

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

{{"name": "My Organization"}}
```

## Get Organization

```
GET {base}/orgs/{{org_id}}
Authorization: Bearer <api-key>
```

## Members

### List Members

```
GET {base}/orgs/{{org_id}}/members
Authorization: Bearer <api-key>
```

### Update Member Role

```
PATCH {base}/orgs/{{org_id}}/members/{{user_id}}
Authorization: Bearer <api-key>
Content-Type: application/json

{{"role": "admin"}}
```

Roles: `owner`, `admin`, `member`, `viewer`

### Remove Member

```
DELETE {base}/orgs/{{org_id}}/members/{{user_id}}
Authorization: Bearer <api-key>
```

## Invites

### Create Invite (Email)

```
POST {base}/orgs/{{org_id}}/invites
Authorization: Bearer <api-key>
Content-Type: application/json

{{"email": "newuser@example.com", "role": "member"}}
```

### Create Invite (Wallet)

```
POST {base}/orgs/{{org_id}}/invites
Authorization: Bearer <api-key>
Content-Type: application/json

{{"walletAddress": "base58...", "role": "member"}}
```

### List Pending Invites

```
GET {base}/orgs/{{org_id}}/invites
Authorization: Bearer <api-key>
```

### Accept Invite

```
POST {base}/invites/accept
Authorization: Bearer <api-key>
Content-Type: application/json

{{"token": "<invite-token>"}}
```

## Error Codes

| Code | Description |
|------|-------------|
| FORBIDDEN | Insufficient permissions |
| NOT_FOUND | Organization not found |
| ALREADY_MEMBER | User already in organization |
| INVITE_EXPIRED | Invite has expired |
"#,
        version = config.version,
        base = base
    )
}

/// Skill file content for mfa.md
pub fn generate_skill_mfa_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: mfa
name: MFA
version: "{version}"
description: Multi-factor authentication setup and management
apiBase: "{base}"
requiresAuth: true
---

# MFA Skill

Set up and manage multi-factor authentication.

## TOTP (Authenticator App)

### Begin Setup

```
POST {base}/mfa/totp/setup
Authorization: Bearer <api-key>
```

Response includes QR code URL and secret for authenticator apps.

### Verify Setup

```
POST {base}/mfa/totp/verify
Authorization: Bearer <api-key>
Content-Type: application/json

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

### Disable TOTP

```
DELETE {base}/mfa/totp
Authorization: Bearer <api-key>
Content-Type: application/json

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

## WebAuthn (Passkeys)

### Register Passkey

```
POST {base}/webauthn/register/begin
Authorization: Bearer <api-key>
```

```
POST {base}/webauthn/register/finish
Authorization: Bearer <api-key>
Content-Type: application/json

{{...webauthn-response...}}
```

### List Passkeys

```
GET {base}/webauthn/credentials
Authorization: Bearer <api-key>
```

## Error Codes

| Code | Description |
|------|-------------|
| INVALID_CODE | TOTP code incorrect |
| MFA_ALREADY_ENABLED | MFA already set up |
| MFA_REQUIRED | Operation requires MFA verification |
"#,
        version = config.version,
        base = base
    )
}

/// Skill file content for wallet.md
pub fn generate_skill_wallet_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: wallet
name: Wallet
version: "{version}"
description: Embedded Solana wallet operations
apiBase: "{base}"
requiresAuth: true
---

# Wallet Skill

Manage embedded Solana wallets with secure key sharding.

## Check Wallet Status

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

Response:
```json
{{
  "hasWallet": true,
  "publicKey": "base58...",
  "authMethod": "passkey"
}}
```

## Enroll Wallet

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

{{
  "authMethod": "passkey",
  "prfSalt": "<base64-salt>",
  "encryptedShareA": "<base64-encrypted>",
  "encryptedShareB": "<base64-encrypted>",
  "walletPubkey": "base58..."
}}
```

Auth methods: `passkey`, `pin`, `password`, `api_key`

When authenticated via API key, use `"authMethod": "api_key"` to encrypt Share A with the API key itself. This enables fully headless signing — no separate credential needed.

## Sign Transaction

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

{{
  "transaction": "<base64-serialized-tx>",
  "shareA": "<decrypted-share-a>"
}}
```

Response:
```json
{{
  "signature": "base58...",
  "signedTransaction": "<base64-signed-tx>"
}}
```

## Get Balance

```
GET {base}/wallet/balance
Authorization: Bearer <api-key>
```

## List Wallets

```
GET {base}/wallet/list
Authorization: Bearer <api-key>
```

Response:
```json
{{
  "wallets": [
    {{"id": "uuid", "walletPubkey": "base58...", "authMethod": "passkey", "apiKeyLabel": null, "isDefault": true, "createdAt": "..."}},
    {{"id": "uuid", "walletPubkey": "base58...", "authMethod": "api_key", "apiKeyLabel": "bot-alpha", "isDefault": false, "createdAt": "..."}}
  ]
}}
```

## Rotate Wallet

Replaces the current wallet with a new keypair. **Irreversible** — funds at old address are NOT migrated.

```
POST {base}/wallet/rotate
Authorization: Bearer <api-key>
Content-Type: application/json

{{
  "authMethod": "passkey",
  "walletPubkey": "new-base58...",
  "encryptedShareA": "<base64>",
  "encryptedShareB": "<base64>"
}}
```

## Multi-Wallet Support

Each user can have:
- **One default wallet** (enrolled via JWT auth)
- **One wallet per API key** (enrolled via API key auth)

Wallet selection is automatic: API key auth uses the key-linked wallet, JWT auth uses the default wallet.

## Error Codes

| Code | Description |
|------|-------------|
| NO_WALLET | User has no enrolled wallet |
| INVALID_SHARE | Share decryption/verification failed |
| SIGNING_FAILED | Transaction signing failed |
"#,
        version = config.version,
        base = base
    )
}

/// Skill file content for admin.md
pub fn generate_skill_admin_md(config: &ContentConfig) -> String {
    let base = &config.base_path;
    format!(
        r#"---
skill: admin
name: Admin
version: "{version}"
description: System administration and user management
apiBase: "{base}"
requiresAuth: true
requiresAdmin: true
---

# Admin Skill

Administrative operations requiring elevated permissions.

## User Management

### List Users (Org Admin)

```
GET {base}/orgs/{{org_id}}/members?page=1&limit=20
Authorization: Bearer <api-key>
```

### Update User Role

```
PATCH {base}/orgs/{{org_id}}/members/{{user_id}}
Authorization: Bearer <api-key>
Content-Type: application/json

{{"role": "admin"}}
```

### Remove User

```
DELETE {base}/orgs/{{org_id}}/members/{{user_id}}
Authorization: Bearer <api-key>
```

## Organization Settings

### Get Settings

```
GET {base}/orgs/{{org_id}}/settings
Authorization: Bearer <api-key>
```

### Update Settings

```
PUT {base}/orgs/{{org_id}}/settings
Authorization: Bearer <api-key>
Content-Type: application/json

{{...settings...}}
```

## Audit Logs

### Query Audit Events

```
GET {base}/orgs/{{org_id}}/audit?event_type=login&limit=100
Authorization: Bearer <api-key>
```

## Error Codes

| Code | Description |
|------|-------------|
| FORBIDDEN | Requires admin role |
| CANNOT_DEMOTE_OWNER | Cannot change owner's role |
| LAST_OWNER | Cannot remove last owner |
"#,
        version = config.version,
        base = base
    )
}