@sso-id/cli 0.0.0-stage → 0.2.0

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.
Files changed (51) hide show
  1. package/bin/sso-id.mjs +181 -0
  2. package/package.json +28 -4
  3. package/templates/angular-spa/package.json +19 -0
  4. package/templates/angular-spa/src/app/app.component.ts +63 -0
  5. package/templates/angular-spa/src/app/app.config.ts +16 -0
  6. package/templates/angular-spa/src/environments/environment.ts +7 -0
  7. package/templates/dotnet-api/Program.cs +121 -0
  8. package/templates/dotnet-api/SsoIdStarter.csproj +12 -0
  9. package/templates/dotnet-api/appsettings.json +14 -0
  10. package/templates/express-api/.env.example +12 -0
  11. package/templates/express-api/README.md +8 -0
  12. package/templates/express-api/package.json +18 -0
  13. package/templates/express-api/src/server.mjs +182 -0
  14. package/templates/go-gin/.env.example +7 -0
  15. package/templates/go-gin/go.mod +6 -0
  16. package/templates/go-gin/main.go +112 -0
  17. package/templates/mobile-react-native/.env.example +5 -0
  18. package/templates/mobile-react-native/App.tsx +45 -0
  19. package/templates/mobile-react-native/package.json +11 -0
  20. package/templates/nextjs/.env.example +19 -0
  21. package/templates/nextjs/README.md +18 -0
  22. package/templates/nextjs/next.config.mjs +4 -0
  23. package/templates/nextjs/package.json +27 -0
  24. package/templates/nextjs/src/app/api/auth/[...ssoid]/route.ts +10 -0
  25. package/templates/nextjs/src/app/api/management/[resource]/route.ts +64 -0
  26. package/templates/nextjs/src/app/api/scim/sync/route.ts +60 -0
  27. package/templates/nextjs/src/app/api/scim/v2/Groups/[id]/route.ts +58 -0
  28. package/templates/nextjs/src/app/api/scim/v2/Groups/route.ts +44 -0
  29. package/templates/nextjs/src/app/api/scim/v2/Users/[id]/route.ts +89 -0
  30. package/templates/nextjs/src/app/api/scim/v2/Users/route.ts +44 -0
  31. package/templates/nextjs/src/app/layout.tsx +18 -0
  32. package/templates/nextjs/src/app/page.tsx +164 -0
  33. package/templates/nextjs/src/app/providers.tsx +16 -0
  34. package/templates/nextjs/src/lib/scim-auth.ts +12 -0
  35. package/templates/nextjs/src/lib/sso.ts +39 -0
  36. package/templates/nextjs/tsconfig.json +24 -0
  37. package/templates/php-laravel/.env.example +6 -0
  38. package/templates/php-laravel/composer.json +9 -0
  39. package/templates/php-laravel/public/index.php +34 -0
  40. package/templates/python-fastapi/.env.example +7 -0
  41. package/templates/python-fastapi/main.py +155 -0
  42. package/templates/python-fastapi/requirements.txt +6 -0
  43. package/templates/react-spa/.env.example +5 -0
  44. package/templates/react-spa/package.json +25 -0
  45. package/templates/react-spa/src/App.tsx +67 -0
  46. package/templates/react-spa/src/main.tsx +17 -0
  47. package/templates/vue-spa/.env.example +5 -0
  48. package/templates/vue-spa/package.json +20 -0
  49. package/templates/vue-spa/src/App.vue +57 -0
  50. package/templates/vue-spa/src/main.ts +14 -0
  51. package/README.md +0 -3
@@ -0,0 +1,182 @@
1
+ import 'dotenv/config';
2
+ import { randomUUID } from 'node:crypto';
3
+ import express from 'express';
4
+ import cors from 'cors';
5
+ import { auth, requiresAuth } from '@sso-id/express';
6
+ import {
7
+ ManagementClient,
8
+ verifyAccessToken,
9
+ verifyScimBearerToken,
10
+ formatScimListResponse,
11
+ formatScimError,
12
+ SCIM_CORE_USER_SCHEMA,
13
+ SCIM_CORE_GROUP_SCHEMA,
14
+ } from '@sso-id/node';
15
+
16
+ const app = express();
17
+ app.use(cors({ origin: process.env.CORS_ORIGIN || true, credentials: true }));
18
+ app.use(express.json({ type: ['application/json', 'application/scim+json'] }));
19
+
20
+ const mgmt = new ManagementClient({
21
+ domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
22
+ clientId: process.env.SSO_ID_CLIENT_ID || '',
23
+ clientSecret: process.env.SSO_ID_CLIENT_SECRET || '',
24
+ apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
25
+ audience: process.env.SSO_ID_AUDIENCE || undefined,
26
+ });
27
+
28
+ // 1. OIDC Session Auth (@sso-id/express)
29
+ app.use(
30
+ auth({
31
+ domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
32
+ clientId: process.env.SSO_ID_CLIENT_ID || '',
33
+ clientSecret: process.env.SSO_ID_CLIENT_SECRET || '',
34
+ baseURL: process.env.SSO_ID_BASE_URL || 'http://localhost:4000',
35
+ secret: process.env.SSO_ID_SESSION_SECRET || 'dev-secret-change-me',
36
+ }),
37
+ );
38
+
39
+ // Bearer JWT guard for SPA / Mobile callers
40
+ async function requireBearerOrSession(req, res, next) {
41
+ if (req.oidc?.isAuthenticated()) return next();
42
+ const header = req.headers.authorization || '';
43
+ const token = header.startsWith('Bearer ') ? header.slice(7) : '';
44
+ if (!token) return res.status(401).json({ error: 'Unauthorized' });
45
+ try {
46
+ req.user = await verifyAccessToken(token, {
47
+ domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
48
+ audience: process.env.SSO_ID_AUDIENCE || undefined,
49
+ });
50
+ return next();
51
+ } catch (err) {
52
+ return res.status(401).json({ error: err.message });
53
+ }
54
+ }
55
+
56
+ app.get('/api/me', requiresAuth(), (req, res) => {
57
+ res.json({ user: req.oidc.user });
58
+ });
59
+
60
+ // 2. Organizations, OUs, Users, Groups (Management API)
61
+ app.get('/api/organizations', requireBearerOrSession, async (_req, res) => {
62
+ res.json(await mgmt.organizations.list());
63
+ });
64
+ app.post('/api/organizations', requireBearerOrSession, async (req, res) => {
65
+ res.status(201).json(await mgmt.organizations.create(req.body));
66
+ });
67
+
68
+ app.get('/api/organization-units', requireBearerOrSession, async (req, res) => {
69
+ const orgId = req.query.organizationId;
70
+ res.json(orgId ? await mgmt.organizationUnits.listByOrganization(String(orgId)) : await mgmt.organizationUnits.list());
71
+ });
72
+ app.post('/api/organization-units', requireBearerOrSession, async (req, res) => {
73
+ res.status(201).json(await mgmt.organizationUnits.create(req.body));
74
+ });
75
+
76
+ app.get('/api/users', requireBearerOrSession, async (_req, res) => {
77
+ res.json(await mgmt.users.list({ page: 1, pageSize: 50 }));
78
+ });
79
+ app.post('/api/users', requireBearerOrSession, async (req, res) => {
80
+ res.status(201).json(await mgmt.users.create(req.body));
81
+ });
82
+
83
+ app.get('/api/groups', requireBearerOrSession, async (_req, res) => {
84
+ res.json(await mgmt.groups.list());
85
+ });
86
+ app.post('/api/groups', requireBearerOrSession, async (req, res) => {
87
+ res.status(201).json(await mgmt.groups.create(req.body));
88
+ });
89
+
90
+ // 3. Real-Time SCIM 2.0 Provisioning Endpoints
91
+ const scimUsers = new Map();
92
+ const scimGroups = new Map();
93
+ const scimEvents = [];
94
+
95
+ function requireScimAuth(req, res, next) {
96
+ if (!verifyScimBearerToken(req.headers.authorization, process.env.SSO_ID_SCIM_BEARER_TOKEN || '')) {
97
+ return res.status(401).json(formatScimError('Unauthorized SCIM request', 401));
98
+ }
99
+ return next();
100
+ }
101
+
102
+ app.get('/scim/v2/Users', requireScimAuth, (_req, res) => {
103
+ res.json(formatScimListResponse(Array.from(scimUsers.values())));
104
+ });
105
+
106
+ app.post('/scim/v2/Users', requireScimAuth, (req, res) => {
107
+ const id = req.body.id || randomUUID();
108
+ const user = {
109
+ schemas: [SCIM_CORE_USER_SCHEMA],
110
+ active: true,
111
+ ...req.body,
112
+ id,
113
+ meta: { resourceType: 'User', lastModified: new Date().toISOString() },
114
+ };
115
+ scimUsers.set(id, user);
116
+ scimEvents.unshift({ type: 'User', op: 'CREATE', id, userName: user.userName, at: new Date().toISOString() });
117
+ res.status(201).json(user);
118
+ });
119
+
120
+ app.put('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
121
+ const user = { ...req.body, id: req.params.id, meta: { resourceType: 'User', lastModified: new Date().toISOString() } };
122
+ scimUsers.set(req.params.id, user);
123
+ scimEvents.unshift({ type: 'User', op: 'UPDATE', id: req.params.id, at: new Date().toISOString() });
124
+ res.json(user);
125
+ });
126
+
127
+ app.patch('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
128
+ const existing = scimUsers.get(req.params.id);
129
+ if (!existing) return res.status(404).json(formatScimError('User not found', 404));
130
+ for (const op of req.body.Operations || []) {
131
+ if (op.path === 'active') existing.active = Boolean(op.value);
132
+ if (!op.path && typeof op.value === 'object') Object.assign(existing, op.value);
133
+ }
134
+ scimEvents.unshift({ type: 'User', op: 'PATCH', id: req.params.id, at: new Date().toISOString() });
135
+ res.json(existing);
136
+ });
137
+
138
+ app.delete('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
139
+ scimUsers.delete(req.params.id);
140
+ scimEvents.unshift({ type: 'User', op: 'DELETE', id: req.params.id, at: new Date().toISOString() });
141
+ res.status(204).end();
142
+ });
143
+
144
+ app.get('/scim/v2/Groups', requireScimAuth, (_req, res) => {
145
+ res.json(formatScimListResponse(Array.from(scimGroups.values())));
146
+ });
147
+
148
+ app.post('/scim/v2/Groups', requireScimAuth, (req, res) => {
149
+ const id = req.body.id || randomUUID();
150
+ const group = {
151
+ schemas: [SCIM_CORE_GROUP_SCHEMA],
152
+ members: [],
153
+ ...req.body,
154
+ id,
155
+ meta: { resourceType: 'Group', lastModified: new Date().toISOString() },
156
+ };
157
+ scimGroups.set(id, group);
158
+ scimEvents.unshift({ type: 'Group', op: 'CREATE', id, displayName: group.displayName, at: new Date().toISOString() });
159
+ res.status(201).json(group);
160
+ });
161
+
162
+ app.get('/api/scim/events', requireBearerOrSession, (_req, res) => {
163
+ res.json({ users: Array.from(scimUsers.values()), groups: Array.from(scimGroups.values()), events: scimEvents });
164
+ });
165
+
166
+ app.post('/api/scim/push-user', requireBearerOrSession, async (req, res) => {
167
+ const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
168
+ const created = await scim.createUser({
169
+ schemas: [SCIM_CORE_USER_SCHEMA],
170
+ userName: req.body.userName || req.body.email,
171
+ displayName: req.body.displayName,
172
+ emails: req.body.email ? [{ value: req.body.email, primary: true }] : [],
173
+ active: true,
174
+ });
175
+ res.status(201).json(created);
176
+ });
177
+
178
+ const port = Number(process.env.PORT || 4000);
179
+ app.listen(port, () => {
180
+ console.log(`SSO.ID Express + SCIM + Management API listening on http://localhost:${port}`);
181
+ });
182
+
@@ -0,0 +1,7 @@
1
+ PORT=8080
2
+ SSO_ID_DOMAIN=acme.sso.id
3
+ SSO_ID_CLIENT_ID=YOUR_M2M_CLIENT_ID
4
+ SSO_ID_CLIENT_SECRET=YOUR_M2M_CLIENT_SECRET
5
+ SSO_ID_API_BASE_URL=https://api.sso.id
6
+ SSO_ID_SCIM_BEARER_TOKEN=REPLACE_WITH_STRONG_SCIM_TOKEN
7
+
@@ -0,0 +1,6 @@
1
+ module ssoid-go-starter
2
+
3
+ go 1.22
4
+
5
+ require github.com/sso-id/sso-id-go v0.1.0
6
+
@@ -0,0 +1,112 @@
1
+ package main
2
+
3
+ import (
4
+ "crypto/subtle"
5
+ "encoding/json"
6
+ "log"
7
+ "net/http"
8
+ "os"
9
+ "strings"
10
+ "sync"
11
+ )
12
+
13
+ func main() {
14
+ scimToken := os.Getenv("SSO_ID_SCIM_BEARER_TOKEN")
15
+ var mu sync.RWMutex
16
+ scimUsers := map[string]map[string]any{}
17
+ scimGroups := map[string]map[string]any{}
18
+
19
+ validScim := func(r *http.Request) bool {
20
+ h := r.Header.Get("Authorization")
21
+ if !strings.HasPrefix(h, "Bearer ") || scimToken == "" {
22
+ return false
23
+ }
24
+ provided := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
25
+ return subtle.ConstantTimeCompare([]byte(provided), []byte(scimToken)) == 1
26
+ }
27
+
28
+ mux := http.NewServeMux()
29
+ mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
30
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
31
+ })
32
+
33
+ mux.HandleFunc("/scim/v2/Users", func(w http.ResponseWriter, r *http.Request) {
34
+ if !validScim(r) {
35
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
36
+ return
37
+ }
38
+ w.Header().Set("Content-Type", "application/scim+json")
39
+ if r.Method == http.MethodGet {
40
+ mu.RLock()
41
+ list := make([]map[string]any, 0, len(scimUsers))
42
+ for _, u := range scimUsers {
43
+ list = append(list, u)
44
+ }
45
+ mu.RUnlock()
46
+ _ = json.NewEncoder(w).Encode(map[string]any{
47
+ "schemas": []string{"urn:ietf:params:scim:api:messages:2.0:ListResponse"},
48
+ "totalResults": len(list),
49
+ "Resources": list,
50
+ })
51
+ return
52
+ }
53
+ if r.Method == http.MethodPost {
54
+ var body map[string]any
55
+ _ = json.NewDecoder(r.Body).Decode(&body)
56
+ id, _ := body["id"].(string)
57
+ if id == "" {
58
+ id = "usr_" + strings.ReplaceAll(r.RemoteAddr, ":", "_")
59
+ body["id"] = id
60
+ }
61
+ mu.Lock()
62
+ scimUsers[id] = body
63
+ mu.Unlock()
64
+ w.WriteHeader(http.StatusCreated)
65
+ _ = json.NewEncoder(w).Encode(body)
66
+ }
67
+ })
68
+
69
+ mux.HandleFunc("/scim/v2/Groups", func(w http.ResponseWriter, r *http.Request) {
70
+ if !validScim(r) {
71
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
72
+ return
73
+ }
74
+ w.Header().Set("Content-Type", "application/scim+json")
75
+ if r.Method == http.MethodGet {
76
+ mu.RLock()
77
+ list := make([]map[string]any, 0, len(scimGroups))
78
+ for _, g := range scimGroups {
79
+ list = append(list, g)
80
+ }
81
+ mu.RUnlock()
82
+ _ = json.NewEncoder(w).Encode(map[string]any{
83
+ "schemas": []string{"urn:ietf:params:scim:api:messages:2.0:ListResponse"},
84
+ "totalResults": len(list),
85
+ "Resources": list,
86
+ })
87
+ return
88
+ }
89
+ if r.Method == http.MethodPost {
90
+ var body map[string]any
91
+ _ = json.NewDecoder(r.Body).Decode(&body)
92
+ id, _ := body["id"].(string)
93
+ if id == "" {
94
+ id = "grp_default"
95
+ body["id"] = id
96
+ }
97
+ mu.Lock()
98
+ scimGroups[id] = body
99
+ mu.Unlock()
100
+ w.WriteHeader(http.StatusCreated)
101
+ _ = json.NewEncoder(w).Encode(body)
102
+ }
103
+ })
104
+
105
+ port := os.Getenv("PORT")
106
+ if port == "" {
107
+ port = "8080"
108
+ }
109
+ log.Printf("SSO.ID Go + SCIM starter listening on :%s", port)
110
+ log.Fatal(http.ListenAndServe(":"+port, mux))
111
+ }
112
+
@@ -0,0 +1,5 @@
1
+ SSO_ID_DOMAIN=acme.sso.id
2
+ SSO_ID_CLIENT_ID=YOUR_MOBILE_CLIENT_ID
3
+ SSO_ID_REDIRECT_URI=com.acme.app://callback
4
+ API_BASE_URL=http://localhost:4000
5
+
@@ -0,0 +1,45 @@
1
+ import React, { useState } from 'react';
2
+ import { Button, SafeAreaView, ScrollView, Text, View } from 'react-native';
3
+ import { SsoIdMobileClient } from '@sso-id/react-native';
4
+
5
+ const sso = new SsoIdMobileClient({
6
+ domain: 'acme.sso.id',
7
+ clientId: 'YOUR_MOBILE_CLIENT_ID',
8
+ redirectUri: 'com.acme.app://callback',
9
+ });
10
+
11
+ export default function App() {
12
+ const [status, setStatus] = useState('Not signed in');
13
+ const [orgs, setOrgs] = useState<unknown>(null);
14
+
15
+ async function loadOrgs(accessToken: string) {
16
+ const res = await fetch('http://localhost:4000/api/organizations', {
17
+ headers: { Authorization: `Bearer ${accessToken}` },
18
+ });
19
+ setOrgs(await res.json());
20
+ }
21
+
22
+ return (
23
+ <SafeAreaView style={{ flex: 1, padding: 20 }}>
24
+ <ScrollView>
25
+ <Text style={{ fontSize: 20, fontWeight: '700', marginBottom: 12 }}>SSO.ID React Native Starter</Text>
26
+ <Text style={{ marginBottom: 12 }}>{status}</Text>
27
+ <View style={{ gap: 10 }}>
28
+ <Button
29
+ title="Build OIDC + PKCE Authorize URL"
30
+ onPress={async () => {
31
+ const { url } = await sso.buildAuthorizeUrl();
32
+ setStatus(`Authorize URL ready: ${url}`);
33
+ }}
34
+ />
35
+ <Button
36
+ title="Fetch Organizations (via Companion API)"
37
+ onPress={() => loadOrgs('YOUR_ACCESS_TOKEN').catch((e) => setStatus(String(e)))}
38
+ />
39
+ </View>
40
+ {orgs && <Text style={{ marginTop: 16, fontFamily: 'monospace' }}>{JSON.stringify(orgs, null, 2)}</Text>}
41
+ </ScrollView>
42
+ </SafeAreaView>
43
+ );
44
+ }
45
+
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "sso-id-react-native-template",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@sso-id/react-native": "^0.1.0",
7
+ "react": "^18.3.1",
8
+ "react-native": "^0.75.0"
9
+ }
10
+ }
11
+
@@ -0,0 +1,19 @@
1
+ # SSO.ID OIDC / OAuth 2.0 + PKCE (Frontend & Route Handler)
2
+ NEXT_PUBLIC_SSO_ID_DOMAIN=acme.sso.id
3
+ NEXT_PUBLIC_SSO_ID_CLIENT_ID=YOUR_SPA_OR_WEB_CLIENT_ID
4
+ NEXT_PUBLIC_SSO_ID_REDIRECT_URI=http://localhost:3000/api/auth/callback
5
+
6
+ SSO_ID_DOMAIN=acme.sso.id
7
+ SSO_ID_CLIENT_ID=YOUR_WEB_CLIENT_ID
8
+ SSO_ID_CLIENT_SECRET=YOUR_WEB_CLIENT_SECRET
9
+ SSO_ID_REDIRECT_URI=http://localhost:3000/api/auth/callback
10
+
11
+ # SSO.ID Machine-to-Machine (Management API for Orgs, OUs, Users, Groups)
12
+ SSO_ID_M2M_CLIENT_ID=YOUR_M2M_CLIENT_ID
13
+ SSO_ID_M2M_CLIENT_SECRET=YOUR_M2M_CLIENT_SECRET
14
+ SSO_ID_API_BASE_URL=https://api.sso.id
15
+
16
+ # Real-Time SCIM 2.0 Provisioning
17
+ SSO_ID_SCIM_BEARER_TOKEN=REPLACE_WITH_STRONG_SCIM_TOKEN
18
+ SSO_ID_SCIM_CONNECTION_ID=
19
+
@@ -0,0 +1,18 @@
1
+ # SSO.ID Next.js Starter Template
2
+
3
+ Pre-configured Next.js App Router template using `@sso-id/nextjs`, `@sso-id/react`, `@sso-id/ui`, and `@sso-id/node`.
4
+
5
+ ## Included Capabilities
6
+ - **OIDC + PKCE Authentication** (`/api/auth/login`, `/api/auth/callback`, `<SignInButton />`, `<UserMenu />`)
7
+ - **Organizations, Organization Units, Users & Groups** (`/api/management/[resource]`)
8
+ - **Real-Time SCIM 2.0 Provisioning** (`/api/scim/v2/Users`, `/api/scim/v2/Groups`, and `/api/scim/sync`)
9
+
10
+ ## Quick Start
11
+ ```bash
12
+ cp .env.example .env
13
+ npm install
14
+ npm run dev
15
+ ```
16
+
17
+ Point your SSO.ID SCIM outbound connection to `https://<your-domain>/api/scim/v2` with `Authorization: Bearer <SSO_ID_SCIM_BEARER_TOKEN>` for real-time user and group sync.
18
+
@@ -0,0 +1,4 @@
1
+ /** @type {import('next').NextConfig} */
2
+ const nextConfig = {};
3
+ export default nextConfig;
4
+
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "sso-id-nextjs-template",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "next dev",
7
+ "build": "next build",
8
+ "start": "next start",
9
+ "typecheck": "tsc --noEmit"
10
+ },
11
+ "dependencies": {
12
+ "@sso-id/nextjs": "^0.1.0",
13
+ "@sso-id/node": "^0.2.0",
14
+ "@sso-id/react": "^0.1.0",
15
+ "@sso-id/ui": "^0.1.0",
16
+ "next": "^15.0.0",
17
+ "react": "^18.3.1",
18
+ "react-dom": "^18.3.1"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^22.0.0",
22
+ "@types/react": "^18.3.0",
23
+ "@types/react-dom": "^18.3.0",
24
+ "typescript": "^5.6.0"
25
+ }
26
+ }
27
+
@@ -0,0 +1,10 @@
1
+ import { createSsoIdRouteHandler } from '@sso-id/nextjs';
2
+
3
+ export const GET = createSsoIdRouteHandler({
4
+ domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
5
+ clientId: process.env.SSO_ID_CLIENT_ID || '',
6
+ clientSecret: process.env.SSO_ID_CLIENT_SECRET || '',
7
+ baseURL: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
8
+ secret: process.env.SSO_ID_SESSION_SECRET || 'dev-session-secret-change-in-production',
9
+ });
10
+
@@ -0,0 +1,64 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { getManagementClient } from '@/lib/sso';
3
+
4
+ type Resource = 'organizations' | 'organization-units' | 'users' | 'groups';
5
+
6
+ export async function GET(
7
+ req: Request,
8
+ context: { params: Promise<{ resource: string }> },
9
+ ) {
10
+ const { resource } = await context.params;
11
+ const mgmt = getManagementClient();
12
+ const url = new URL(req.url);
13
+
14
+ try {
15
+ switch (resource as Resource) {
16
+ case 'organizations':
17
+ return NextResponse.json(await mgmt.organizations.list());
18
+ case 'organization-units': {
19
+ const orgId = url.searchParams.get('organizationId');
20
+ const data = orgId
21
+ ? await mgmt.organizationUnits.listByOrganization(orgId)
22
+ : await mgmt.organizationUnits.list();
23
+ return NextResponse.json(data);
24
+ }
25
+ case 'users':
26
+ return NextResponse.json(await mgmt.users.list({ page: 1, pageSize: 50 }));
27
+ case 'groups':
28
+ return NextResponse.json(await mgmt.groups.list());
29
+ default:
30
+ return NextResponse.json({ error: `Unknown resource: ${resource}` }, { status: 404 });
31
+ }
32
+ } catch (err) {
33
+ const message = err instanceof Error ? err.message : 'Management API error';
34
+ return NextResponse.json({ error: message }, { status: 500 });
35
+ }
36
+ }
37
+
38
+ export async function POST(
39
+ req: Request,
40
+ context: { params: Promise<{ resource: string }> },
41
+ ) {
42
+ const { resource } = await context.params;
43
+ const body = (await req.json()) as Record<string, unknown>;
44
+ const mgmt = getManagementClient();
45
+
46
+ try {
47
+ switch (resource as Resource) {
48
+ case 'organizations':
49
+ return NextResponse.json(await mgmt.organizations.create(body), { status: 201 });
50
+ case 'organization-units':
51
+ return NextResponse.json(await mgmt.organizationUnits.create(body), { status: 201 });
52
+ case 'users':
53
+ return NextResponse.json(await mgmt.users.create(body), { status: 201 });
54
+ case 'groups':
55
+ return NextResponse.json(await mgmt.groups.create(body), { status: 201 });
56
+ default:
57
+ return NextResponse.json({ error: `Unknown resource: ${resource}` }, { status: 404 });
58
+ }
59
+ } catch (err) {
60
+ const message = err instanceof Error ? err.message : 'Management API error';
61
+ return NextResponse.json({ error: message }, { status: 500 });
62
+ }
63
+ }
64
+
@@ -0,0 +1,60 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { SCIM_CORE_GROUP_SCHEMA, SCIM_CORE_USER_SCHEMA } from '@sso-id/node';
3
+ import { getManagementClient, scimStore } from '@/lib/sso';
4
+
5
+ export async function GET() {
6
+ return NextResponse.json({
7
+ users: Array.from(scimStore.users.values()),
8
+ groups: Array.from(scimStore.groups.values()),
9
+ events: scimStore.events,
10
+ });
11
+ }
12
+
13
+ export async function POST(req: Request) {
14
+ const body = (await req.json()) as {
15
+ type: 'User' | 'Group';
16
+ userName?: string;
17
+ displayName?: string;
18
+ email?: string;
19
+ };
20
+ const mgmt = getManagementClient();
21
+ const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
22
+
23
+ try {
24
+ if (body.type === 'User') {
25
+ const created = await scim.createUser({
26
+ schemas: [SCIM_CORE_USER_SCHEMA],
27
+ userName: body.userName || body.email || '',
28
+ displayName: body.displayName || body.userName || '',
29
+ emails: body.email ? [{ value: body.email, primary: true }] : [],
30
+ active: true,
31
+ });
32
+ scimStore.record({
33
+ direction: 'outbound',
34
+ resourceType: 'User',
35
+ operation: 'CREATE',
36
+ targetId: created.id || body.userName || '',
37
+ summary: `Pushed user ${created.userName} to SSO.ID SCIM v2`,
38
+ });
39
+ return NextResponse.json(created, { status: 201 });
40
+ }
41
+
42
+ const created = await scim.createGroup({
43
+ schemas: [SCIM_CORE_GROUP_SCHEMA],
44
+ displayName: body.displayName || 'New Group',
45
+ members: [],
46
+ });
47
+ scimStore.record({
48
+ direction: 'outbound',
49
+ resourceType: 'Group',
50
+ operation: 'CREATE',
51
+ targetId: created.id || '',
52
+ summary: `Pushed group ${created.displayName} to SSO.ID SCIM v2`,
53
+ });
54
+ return NextResponse.json(created, { status: 201 });
55
+ } catch (err) {
56
+ const message = err instanceof Error ? err.message : 'SCIM sync error';
57
+ return NextResponse.json({ error: message }, { status: 500 });
58
+ }
59
+ }
60
+
@@ -0,0 +1,58 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { formatScimError, type ScimGroupResource } from '@sso-id/node';
3
+ import { requireScimAuth } from '@/lib/scim-auth';
4
+ import { scimStore } from '@/lib/sso';
5
+
6
+ export async function GET(req: Request, context: { params: Promise<{ id: string }> }) {
7
+ const authErr = requireScimAuth(req);
8
+ if (authErr) return authErr;
9
+
10
+ const { id } = await context.params;
11
+ const group = scimStore.groups.get(id);
12
+ if (!group) return NextResponse.json(formatScimError('Group not found', 404), { status: 404 });
13
+ return NextResponse.json(group);
14
+ }
15
+
16
+ export async function PUT(req: Request, context: { params: Promise<{ id: string }> }) {
17
+ const authErr = requireScimAuth(req);
18
+ if (authErr) return authErr;
19
+
20
+ const { id } = await context.params;
21
+ const body = (await req.json()) as ScimGroupResource;
22
+ const existing = scimStore.groups.get(id);
23
+ const updated: ScimGroupResource = {
24
+ ...body,
25
+ id,
26
+ meta: {
27
+ resourceType: 'Group',
28
+ created: existing?.meta?.created ?? new Date().toISOString(),
29
+ lastModified: new Date().toISOString(),
30
+ },
31
+ };
32
+ scimStore.groups.set(id, updated);
33
+ scimStore.record({
34
+ direction: 'inbound',
35
+ resourceType: 'Group',
36
+ operation: 'UPDATE',
37
+ targetId: id,
38
+ summary: `Updated group ${updated.displayName}`,
39
+ });
40
+ return NextResponse.json(updated);
41
+ }
42
+
43
+ export async function DELETE(req: Request, context: { params: Promise<{ id: string }> }) {
44
+ const authErr = requireScimAuth(req);
45
+ if (authErr) return authErr;
46
+
47
+ const { id } = await context.params;
48
+ scimStore.groups.delete(id);
49
+ scimStore.record({
50
+ direction: 'inbound',
51
+ resourceType: 'Group',
52
+ operation: 'DELETE',
53
+ targetId: id,
54
+ summary: `Deleted group ${id}`,
55
+ });
56
+ return new NextResponse(null, { status: 204 });
57
+ }
58
+