@sso-id/cli 0.1.0 → 0.2.1
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.
- package/bin/sso-id.mjs +171 -7
- package/package.json +3 -2
- package/templates/angular-spa/package.json +19 -0
- package/templates/angular-spa/src/app/app.component.ts +63 -0
- package/templates/angular-spa/src/app/app.config.ts +16 -0
- package/templates/angular-spa/src/environments/environment.ts +7 -0
- package/templates/dotnet-api/Program.cs +121 -0
- package/templates/dotnet-api/SsoIdStarter.csproj +12 -0
- package/templates/dotnet-api/appsettings.json +14 -0
- package/templates/express-api/.env.example +12 -0
- package/templates/express-api/README.md +8 -0
- package/templates/express-api/package.json +18 -0
- package/templates/express-api/src/server.mjs +182 -0
- package/templates/go-gin/.env.example +7 -0
- package/templates/go-gin/go.mod +6 -0
- package/templates/go-gin/main.go +112 -0
- package/templates/mobile-react-native/.env.example +5 -0
- package/templates/mobile-react-native/App.tsx +45 -0
- package/templates/mobile-react-native/package.json +11 -0
- package/templates/nextjs/.env.example +19 -0
- package/templates/nextjs/README.md +18 -0
- package/templates/nextjs/next.config.mjs +4 -0
- package/templates/nextjs/package.json +27 -0
- package/templates/nextjs/src/app/api/auth/[...ssoid]/route.ts +10 -0
- package/templates/nextjs/src/app/api/management/[resource]/route.ts +64 -0
- package/templates/nextjs/src/app/api/scim/sync/route.ts +60 -0
- package/templates/nextjs/src/app/api/scim/v2/Groups/[id]/route.ts +58 -0
- package/templates/nextjs/src/app/api/scim/v2/Groups/route.ts +44 -0
- package/templates/nextjs/src/app/api/scim/v2/Users/[id]/route.ts +89 -0
- package/templates/nextjs/src/app/api/scim/v2/Users/route.ts +44 -0
- package/templates/nextjs/src/app/layout.tsx +18 -0
- package/templates/nextjs/src/app/page.tsx +164 -0
- package/templates/nextjs/src/app/providers.tsx +16 -0
- package/templates/nextjs/src/lib/scim-auth.ts +12 -0
- package/templates/nextjs/src/lib/sso.ts +39 -0
- package/templates/nextjs/tsconfig.json +24 -0
- package/templates/php-laravel/.env.example +6 -0
- package/templates/php-laravel/composer.json +9 -0
- package/templates/php-laravel/public/index.php +34 -0
- package/templates/python-fastapi/.env.example +7 -0
- package/templates/python-fastapi/main.py +155 -0
- package/templates/python-fastapi/requirements.txt +6 -0
- package/templates/react-spa/.env.example +5 -0
- package/templates/react-spa/package.json +25 -0
- package/templates/react-spa/src/App.tsx +67 -0
- package/templates/react-spa/src/main.tsx +17 -0
- package/templates/vue-spa/.env.example +5 -0
- package/templates/vue-spa/package.json +20 -0
- package/templates/vue-spa/src/App.vue +57 -0
- package/templates/vue-spa/src/main.ts +14 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { NextResponse } from 'next/server';
|
|
3
|
+
import {
|
|
4
|
+
formatScimListResponse,
|
|
5
|
+
SCIM_CORE_GROUP_SCHEMA,
|
|
6
|
+
type ScimGroupResource,
|
|
7
|
+
} from '@sso-id/node';
|
|
8
|
+
import { requireScimAuth } from '@/lib/scim-auth';
|
|
9
|
+
import { scimStore } from '@/lib/sso';
|
|
10
|
+
|
|
11
|
+
export async function GET(req: Request) {
|
|
12
|
+
const authErr = requireScimAuth(req);
|
|
13
|
+
if (authErr) return authErr;
|
|
14
|
+
|
|
15
|
+
const groups = Array.from(scimStore.groups.values());
|
|
16
|
+
return NextResponse.json(formatScimListResponse(groups));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function POST(req: Request) {
|
|
20
|
+
const authErr = requireScimAuth(req);
|
|
21
|
+
if (authErr) return authErr;
|
|
22
|
+
|
|
23
|
+
const body = (await req.json()) as ScimGroupResource;
|
|
24
|
+
const id = body.id || randomUUID();
|
|
25
|
+
const now = new Date().toISOString();
|
|
26
|
+
const group: ScimGroupResource = {
|
|
27
|
+
...body,
|
|
28
|
+
id,
|
|
29
|
+
schemas: body.schemas?.length ? body.schemas : [SCIM_CORE_GROUP_SCHEMA],
|
|
30
|
+
members: body.members ?? [],
|
|
31
|
+
meta: { resourceType: 'Group', created: now, lastModified: now },
|
|
32
|
+
};
|
|
33
|
+
scimStore.groups.set(id, group);
|
|
34
|
+
scimStore.record({
|
|
35
|
+
direction: 'inbound',
|
|
36
|
+
resourceType: 'Group',
|
|
37
|
+
operation: 'CREATE',
|
|
38
|
+
targetId: id,
|
|
39
|
+
summary: `Synced group ${group.displayName}`,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return NextResponse.json(group, { status: 201 });
|
|
43
|
+
}
|
|
44
|
+
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
import { formatScimError, type ScimUserResource } 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 user = scimStore.users.get(id);
|
|
12
|
+
if (!user) return NextResponse.json(formatScimError('User not found', 404), { status: 404 });
|
|
13
|
+
return NextResponse.json(user);
|
|
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 ScimUserResource;
|
|
22
|
+
const existing = scimStore.users.get(id);
|
|
23
|
+
const updated: ScimUserResource = {
|
|
24
|
+
...body,
|
|
25
|
+
id,
|
|
26
|
+
meta: {
|
|
27
|
+
resourceType: 'User',
|
|
28
|
+
created: existing?.meta?.created ?? new Date().toISOString(),
|
|
29
|
+
lastModified: new Date().toISOString(),
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
scimStore.users.set(id, updated);
|
|
33
|
+
scimStore.record({
|
|
34
|
+
direction: 'inbound',
|
|
35
|
+
resourceType: 'User',
|
|
36
|
+
operation: 'UPDATE',
|
|
37
|
+
targetId: id,
|
|
38
|
+
summary: `Updated user ${updated.userName}`,
|
|
39
|
+
});
|
|
40
|
+
return NextResponse.json(updated);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function PATCH(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
|
+
const existing = scimStore.users.get(id);
|
|
49
|
+
if (!existing) return NextResponse.json(formatScimError('User not found', 404), { status: 404 });
|
|
50
|
+
|
|
51
|
+
const patch = (await req.json()) as {
|
|
52
|
+
Operations?: Array<{ op?: string; path?: string; value?: unknown }>;
|
|
53
|
+
};
|
|
54
|
+
const updated: ScimUserResource = { ...existing };
|
|
55
|
+
for (const op of patch.Operations ?? []) {
|
|
56
|
+
if (op.path === 'active' && typeof op.value === 'boolean') updated.active = op.value;
|
|
57
|
+
if (op.path === 'displayName' && typeof op.value === 'string') updated.displayName = op.value;
|
|
58
|
+
if (!op.path && typeof op.value === 'object' && op.value !== null) {
|
|
59
|
+
Object.assign(updated, op.value);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
updated.meta = { ...existing.meta, lastModified: new Date().toISOString() };
|
|
63
|
+
scimStore.users.set(id, updated);
|
|
64
|
+
scimStore.record({
|
|
65
|
+
direction: 'inbound',
|
|
66
|
+
resourceType: 'User',
|
|
67
|
+
operation: 'PATCH',
|
|
68
|
+
targetId: id,
|
|
69
|
+
summary: `Patched user ${updated.userName} (active=${updated.active})`,
|
|
70
|
+
});
|
|
71
|
+
return NextResponse.json(updated);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function DELETE(req: Request, context: { params: Promise<{ id: string }> }) {
|
|
75
|
+
const authErr = requireScimAuth(req);
|
|
76
|
+
if (authErr) return authErr;
|
|
77
|
+
|
|
78
|
+
const { id } = await context.params;
|
|
79
|
+
scimStore.users.delete(id);
|
|
80
|
+
scimStore.record({
|
|
81
|
+
direction: 'inbound',
|
|
82
|
+
resourceType: 'User',
|
|
83
|
+
operation: 'DELETE',
|
|
84
|
+
targetId: id,
|
|
85
|
+
summary: `Deleted user ${id}`,
|
|
86
|
+
});
|
|
87
|
+
return new NextResponse(null, { status: 204 });
|
|
88
|
+
}
|
|
89
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { NextResponse } from 'next/server';
|
|
3
|
+
import {
|
|
4
|
+
formatScimListResponse,
|
|
5
|
+
SCIM_CORE_USER_SCHEMA,
|
|
6
|
+
type ScimUserResource,
|
|
7
|
+
} from '@sso-id/node';
|
|
8
|
+
import { requireScimAuth } from '@/lib/scim-auth';
|
|
9
|
+
import { scimStore } from '@/lib/sso';
|
|
10
|
+
|
|
11
|
+
export async function GET(req: Request) {
|
|
12
|
+
const authErr = requireScimAuth(req);
|
|
13
|
+
if (authErr) return authErr;
|
|
14
|
+
|
|
15
|
+
const users = Array.from(scimStore.users.values());
|
|
16
|
+
return NextResponse.json(formatScimListResponse(users));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function POST(req: Request) {
|
|
20
|
+
const authErr = requireScimAuth(req);
|
|
21
|
+
if (authErr) return authErr;
|
|
22
|
+
|
|
23
|
+
const body = (await req.json()) as ScimUserResource;
|
|
24
|
+
const id = body.id || randomUUID();
|
|
25
|
+
const now = new Date().toISOString();
|
|
26
|
+
const user: ScimUserResource = {
|
|
27
|
+
...body,
|
|
28
|
+
id,
|
|
29
|
+
schemas: body.schemas?.length ? body.schemas : [SCIM_CORE_USER_SCHEMA],
|
|
30
|
+
active: body.active ?? true,
|
|
31
|
+
meta: { resourceType: 'User', created: now, lastModified: now },
|
|
32
|
+
};
|
|
33
|
+
scimStore.users.set(id, user);
|
|
34
|
+
scimStore.record({
|
|
35
|
+
direction: 'inbound',
|
|
36
|
+
resourceType: 'User',
|
|
37
|
+
operation: 'CREATE',
|
|
38
|
+
targetId: id,
|
|
39
|
+
summary: `Synced user ${user.userName}`,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return NextResponse.json(user, { status: 201 });
|
|
43
|
+
}
|
|
44
|
+
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Metadata } from 'next';
|
|
2
|
+
import { Providers } from './providers';
|
|
3
|
+
|
|
4
|
+
export const metadata: Metadata = {
|
|
5
|
+
title: 'SSO.ID Next.js Starter — Auth, Orgs, OUs, Groups & Real-Time SCIM',
|
|
6
|
+
description: 'Pre-configured SSO.ID starter template with OIDC, Management API, and SCIM 2.0',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
10
|
+
return (
|
|
11
|
+
<html lang="en">
|
|
12
|
+
<body style={{ margin: 0, fontFamily: 'system-ui, -apple-system, sans-serif', background: '#f8fafc', color: '#0f172a' }}>
|
|
13
|
+
<Providers>{children}</Providers>
|
|
14
|
+
</body>
|
|
15
|
+
</html>
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useEffect, useState } from 'react';
|
|
4
|
+
import { useSsoId } from '@sso-id/react';
|
|
5
|
+
import { SignInButton, UserMenu } from '@sso-id/ui';
|
|
6
|
+
|
|
7
|
+
type Tab = 'organizations' | 'organization-units' | 'users' | 'groups' | 'scim';
|
|
8
|
+
|
|
9
|
+
export default function HomePage() {
|
|
10
|
+
const { isAuthenticated, user, isLoading } = useSsoId();
|
|
11
|
+
const [tab, setTab] = useState<Tab>('organizations');
|
|
12
|
+
const [data, setData] = useState<unknown>(null);
|
|
13
|
+
const [scimState, setScimState] = useState<{ users: unknown[]; groups: unknown[]; events: Array<{ id: string; timestamp: string; direction: string; resourceType: string; operation: string; summary: string }> }>({
|
|
14
|
+
users: [],
|
|
15
|
+
groups: [],
|
|
16
|
+
events: [],
|
|
17
|
+
});
|
|
18
|
+
const [name, setName] = useState('');
|
|
19
|
+
const [email, setEmail] = useState('');
|
|
20
|
+
const [orgId, setOrgId] = useState('');
|
|
21
|
+
const [status, setStatus] = useState('');
|
|
22
|
+
|
|
23
|
+
async function loadTab(current: Tab) {
|
|
24
|
+
setStatus('');
|
|
25
|
+
if (current === 'scim') {
|
|
26
|
+
const res = await fetch('/api/scim/sync');
|
|
27
|
+
setScimState(await res.json());
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const res = await fetch(`/api/management/${current}`);
|
|
31
|
+
setData(await res.json());
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
loadTab(tab).catch((err) => setStatus(String(err)));
|
|
36
|
+
}, [tab]);
|
|
37
|
+
|
|
38
|
+
async function handleCreate(e: React.FormEvent) {
|
|
39
|
+
e.preventDefault();
|
|
40
|
+
setStatus('Saving...');
|
|
41
|
+
const payload =
|
|
42
|
+
tab === 'users'
|
|
43
|
+
? { email, userName: email, firstName: name, lastName: 'User' }
|
|
44
|
+
: tab === 'organization-units'
|
|
45
|
+
? { name, organizationId: orgId }
|
|
46
|
+
: { name };
|
|
47
|
+
|
|
48
|
+
const endpoint = tab === 'scim' ? '/api/scim/sync' : `/api/management/${tab}`;
|
|
49
|
+
const body = tab === 'scim' ? { type: 'User', userName: email, displayName: name, email } : payload;
|
|
50
|
+
|
|
51
|
+
const res = await fetch(endpoint, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { 'Content-Type': 'application/json' },
|
|
54
|
+
body: JSON.stringify(body),
|
|
55
|
+
});
|
|
56
|
+
const json = await res.json();
|
|
57
|
+
setStatus(res.ok ? 'Created successfully!' : `Error: ${json.error || res.status}`);
|
|
58
|
+
setName('');
|
|
59
|
+
setEmail('');
|
|
60
|
+
await loadTab(tab);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<main style={{ maxWidth: 1080, margin: '0 auto', padding: '32px 20px' }}>
|
|
65
|
+
<header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid #e2e8f0' }}>
|
|
66
|
+
<div>
|
|
67
|
+
<h1 style={{ margin: 0, fontSize: 22 }}>SSO.ID Starter Workspace (Next.js)</h1>
|
|
68
|
+
<p style={{ margin: '4px 0 0', color: '#475569', fontSize: 14 }}>
|
|
69
|
+
OIDC + PKCE Auth · Organizations & OUs · Users & Groups · Real-Time SCIM 2.0
|
|
70
|
+
</p>
|
|
71
|
+
</div>
|
|
72
|
+
<div>
|
|
73
|
+
{isLoading ? (
|
|
74
|
+
<span>Loading session...</span>
|
|
75
|
+
) : isAuthenticated ? (
|
|
76
|
+
<UserMenu />
|
|
77
|
+
) : (
|
|
78
|
+
<div style={{ display: 'flex', gap: 10 }}>
|
|
79
|
+
<SignInButton />
|
|
80
|
+
<a href="/api/auth/login" style={{ padding: '8px 14px', borderRadius: 8, background: '#0f172a', color: '#fff', textDecoration: 'none', fontSize: 14 }}>
|
|
81
|
+
Server Login
|
|
82
|
+
</a>
|
|
83
|
+
</div>
|
|
84
|
+
)}
|
|
85
|
+
</div>
|
|
86
|
+
</header>
|
|
87
|
+
|
|
88
|
+
{isAuthenticated && user && (
|
|
89
|
+
<div style={{ background: '#ecfdf5', border: '1px solid #a7f3d0', padding: 12, borderRadius: 8, marginBottom: 20, fontSize: 14 }}>
|
|
90
|
+
Signed in as <strong>{String(user.email || user.name || user.sub)}</strong>
|
|
91
|
+
</div>
|
|
92
|
+
)}
|
|
93
|
+
|
|
94
|
+
<nav style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
|
|
95
|
+
{(['organizations', 'organization-units', 'users', 'groups', 'scim'] as Tab[]).map((t) => (
|
|
96
|
+
<button
|
|
97
|
+
key={t}
|
|
98
|
+
onClick={() => setTab(t)}
|
|
99
|
+
style={{
|
|
100
|
+
padding: '8px 16px',
|
|
101
|
+
borderRadius: 8,
|
|
102
|
+
border: '1px solid #cbd5e1',
|
|
103
|
+
background: tab === t ? '#2563eb' : '#fff',
|
|
104
|
+
color: tab === t ? '#fff' : '#0f172a',
|
|
105
|
+
cursor: 'pointer',
|
|
106
|
+
fontWeight: 600,
|
|
107
|
+
}}
|
|
108
|
+
>
|
|
109
|
+
{t === 'scim' ? 'Real-Time SCIM 2.0' : t.replace('-', ' ').toUpperCase()}
|
|
110
|
+
</button>
|
|
111
|
+
))}
|
|
112
|
+
</nav>
|
|
113
|
+
|
|
114
|
+
<section style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 12, padding: 20, marginBottom: 20 }}>
|
|
115
|
+
<h2 style={{ marginTop: 0, fontSize: 18 }}>Create {tab}</h2>
|
|
116
|
+
<form onSubmit={handleCreate} style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
|
|
117
|
+
<input
|
|
118
|
+
value={name}
|
|
119
|
+
onChange={(e) => setName(e.target.value)}
|
|
120
|
+
placeholder={tab === 'users' || tab === 'scim' ? 'Display Name' : 'Name'}
|
|
121
|
+
required
|
|
122
|
+
style={{ padding: '8px 12px', borderRadius: 6, border: '1px solid #cbd5e1', minWidth: 200 }}
|
|
123
|
+
/>
|
|
124
|
+
{(tab === 'users' || tab === 'scim') && (
|
|
125
|
+
<input
|
|
126
|
+
type="email"
|
|
127
|
+
value={email}
|
|
128
|
+
onChange={(e) => setEmail(e.target.value)}
|
|
129
|
+
placeholder="Email address"
|
|
130
|
+
required
|
|
131
|
+
style={{ padding: '8px 12px', borderRadius: 6, border: '1px solid #cbd5e1', minWidth: 220 }}
|
|
132
|
+
/>
|
|
133
|
+
)}
|
|
134
|
+
{tab === 'organization-units' && (
|
|
135
|
+
<input
|
|
136
|
+
value={orgId}
|
|
137
|
+
onChange={(e) => setOrgId(e.target.value)}
|
|
138
|
+
placeholder="Organization ID"
|
|
139
|
+
required
|
|
140
|
+
style={{ padding: '8px 12px', borderRadius: 6, border: '1px solid #cbd5e1', minWidth: 200 }}
|
|
141
|
+
/>
|
|
142
|
+
)}
|
|
143
|
+
<button type="submit" style={{ padding: '8px 16px', borderRadius: 6, border: 'none', background: '#0f172a', color: '#fff', cursor: 'pointer', fontWeight: 600 }}>
|
|
144
|
+
{tab === 'scim' ? 'Push User via SCIM' : 'Create'}
|
|
145
|
+
</button>
|
|
146
|
+
{status && <span style={{ fontSize: 13, color: '#475569' }}>{status}</span>}
|
|
147
|
+
</form>
|
|
148
|
+
</section>
|
|
149
|
+
|
|
150
|
+
<section style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 12, padding: 20 }}>
|
|
151
|
+
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
|
|
152
|
+
<h2 style={{ margin: 0, fontSize: 18 }}>{tab === 'scim' ? 'Live SCIM 2.0 Sync Log & Directory' : `${tab} Directory`}</h2>
|
|
153
|
+
<button onClick={() => loadTab(tab)} style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer' }}>
|
|
154
|
+
Refresh
|
|
155
|
+
</button>
|
|
156
|
+
</div>
|
|
157
|
+
<pre style={{ background: '#0f172a', color: '#e2e8f0', padding: 16, borderRadius: 8, overflowX: 'auto', fontSize: 13 }}>
|
|
158
|
+
{JSON.stringify(tab === 'scim' ? scimState : data, null, 2)}
|
|
159
|
+
</pre>
|
|
160
|
+
</section>
|
|
161
|
+
</main>
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { SsoIdProvider } from '@sso-id/react';
|
|
4
|
+
|
|
5
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
6
|
+
return (
|
|
7
|
+
<SsoIdProvider
|
|
8
|
+
domain={process.env.NEXT_PUBLIC_SSO_ID_DOMAIN || 'acme.sso.id'}
|
|
9
|
+
clientId={process.env.NEXT_PUBLIC_SSO_ID_CLIENT_ID || 'YOUR_CLIENT_ID'}
|
|
10
|
+
redirectUri={process.env.NEXT_PUBLIC_SSO_ID_REDIRECT_URI || 'http://localhost:3000/api/auth/callback'}
|
|
11
|
+
>
|
|
12
|
+
{children}
|
|
13
|
+
</SsoIdProvider>
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
import { formatScimError, verifyScimBearerToken } from '@sso-id/node';
|
|
3
|
+
|
|
4
|
+
export function requireScimAuth(req: Request): NextResponse | null {
|
|
5
|
+
const expected = process.env.SSO_ID_SCIM_BEARER_TOKEN || '';
|
|
6
|
+
const auth = req.headers.get('authorization') ?? undefined;
|
|
7
|
+
if (!verifyScimBearerToken(auth, expected)) {
|
|
8
|
+
return NextResponse.json(formatScimError('Unauthorized SCIM request', 401), { status: 401 });
|
|
9
|
+
}
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ManagementClient, type ScimGroupResource, type ScimUserResource } from '@sso-id/node';
|
|
2
|
+
|
|
3
|
+
export function getManagementClient() {
|
|
4
|
+
return new ManagementClient({
|
|
5
|
+
domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
|
|
6
|
+
clientId: process.env.SSO_ID_M2M_CLIENT_ID || process.env.SSO_ID_CLIENT_ID || '',
|
|
7
|
+
clientSecret: process.env.SSO_ID_M2M_CLIENT_SECRET || process.env.SSO_ID_CLIENT_SECRET || '',
|
|
8
|
+
apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ScimEvent {
|
|
13
|
+
id: string;
|
|
14
|
+
timestamp: string;
|
|
15
|
+
direction: 'inbound' | 'outbound';
|
|
16
|
+
resourceType: 'User' | 'Group';
|
|
17
|
+
operation: 'CREATE' | 'UPDATE' | 'PATCH' | 'DELETE';
|
|
18
|
+
targetId: string;
|
|
19
|
+
summary: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
class ScimRealtimeStore {
|
|
23
|
+
users = new Map<string, ScimUserResource>();
|
|
24
|
+
groups = new Map<string, ScimGroupResource>();
|
|
25
|
+
events: ScimEvent[] = [];
|
|
26
|
+
|
|
27
|
+
record(event: Omit<ScimEvent, 'id' | 'timestamp'>) {
|
|
28
|
+
this.events.unshift({
|
|
29
|
+
...event,
|
|
30
|
+
id: `evt_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
|
|
31
|
+
timestamp: new Date().toISOString(),
|
|
32
|
+
});
|
|
33
|
+
if (this.events.length > 100) this.events.length = 100;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const globalForScim = globalThis as unknown as { __scimStore?: ScimRealtimeStore };
|
|
38
|
+
export const scimStore = globalForScim.__scimStore ?? (globalForScim.__scimStore = new ScimRealtimeStore());
|
|
39
|
+
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"lib": ["dom", "dom.iterable", "esnext"],
|
|
5
|
+
"allowJs": true,
|
|
6
|
+
"skipLibCheck": true,
|
|
7
|
+
"strict": true,
|
|
8
|
+
"noEmit": true,
|
|
9
|
+
"esModuleInterop": true,
|
|
10
|
+
"module": "esnext",
|
|
11
|
+
"moduleResolution": "bundler",
|
|
12
|
+
"resolveJsonModule": true,
|
|
13
|
+
"isolatedModules": true,
|
|
14
|
+
"jsx": "preserve",
|
|
15
|
+
"incremental": true,
|
|
16
|
+
"plugins": [{ "name": "next" }],
|
|
17
|
+
"paths": {
|
|
18
|
+
"@/*": ["./src/*"]
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
|
22
|
+
"exclude": ["node_modules"]
|
|
23
|
+
}
|
|
24
|
+
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
declare(strict_types=1);
|
|
3
|
+
|
|
4
|
+
header('Content-Type: application/scim+json');
|
|
5
|
+
|
|
6
|
+
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
|
7
|
+
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
|
|
8
|
+
$scimToken = getenv('SSO_ID_SCIM_BEARER_TOKEN') ?: '';
|
|
9
|
+
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
|
10
|
+
|
|
11
|
+
if (str_starts_with($path, '/scim/v2')) {
|
|
12
|
+
$provided = str_starts_with($authHeader, 'Bearer ') ? trim(substr($authHeader, 7)) : '';
|
|
13
|
+
if ($scimToken === '' || !hash_equals($scimToken, $provided)) {
|
|
14
|
+
http_response_code(401);
|
|
15
|
+
echo json_encode(['schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'], 'detail' => 'Unauthorized', 'status' => '401']);
|
|
16
|
+
exit;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if ($path === '/scim/v2/Users' && $method === 'GET') {
|
|
20
|
+
echo json_encode(['schemas' => ['urn:ietf:params:scim:api:messages:2.0:ListResponse'], 'totalResults' => 0, 'Resources' => []]);
|
|
21
|
+
exit;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if ($path === '/scim/v2/Users' && $method === 'POST') {
|
|
25
|
+
$payload = json_decode(file_get_contents('php://input') ?: '{}', true) ?? [];
|
|
26
|
+
$payload['id'] = $payload['id'] ?? bin2hex(random_bytes(8));
|
|
27
|
+
http_response_code(201);
|
|
28
|
+
echo json_encode($payload);
|
|
29
|
+
exit;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
echo json_encode(['status' => 'SSO.ID PHP + SCIM 2.0 Starter Ready']);
|
|
34
|
+
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import hmac
|
|
2
|
+
import os
|
|
3
|
+
import uuid
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
|
6
|
+
import httpx
|
|
7
|
+
from dotenv import load_dotenv
|
|
8
|
+
from sso_id.jwt import verify_access_token
|
|
9
|
+
|
|
10
|
+
load_dotenv()
|
|
11
|
+
|
|
12
|
+
app = FastAPI(title="SSO.ID FastAPI + SCIM 2.0 + Management Starter")
|
|
13
|
+
|
|
14
|
+
DOMAIN = os.getenv("SSO_ID_DOMAIN", "acme.sso.id")
|
|
15
|
+
CLIENT_ID = os.getenv("SSO_ID_CLIENT_ID", "")
|
|
16
|
+
CLIENT_SECRET = os.getenv("SSO_ID_CLIENT_SECRET", "")
|
|
17
|
+
API_BASE = os.getenv("SSO_ID_API_BASE_URL", "https://api.sso.id").rstrip("/")
|
|
18
|
+
AUDIENCE = os.getenv("SSO_ID_AUDIENCE") or None
|
|
19
|
+
SCIM_TOKEN = os.getenv("SSO_ID_SCIM_BEARER_TOKEN", "")
|
|
20
|
+
|
|
21
|
+
scim_users: dict[str, dict] = {}
|
|
22
|
+
scim_groups: dict[str, dict] = {}
|
|
23
|
+
scim_events: list[dict] = []
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def require_jwt(authorization: str = Header(default="")):
|
|
27
|
+
if not authorization.startswith("Bearer "):
|
|
28
|
+
raise HTTPException(status_code=401, detail="Missing Bearer token")
|
|
29
|
+
return verify_access_token(authorization[7:], domain=DOMAIN, audience=AUDIENCE)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def require_scim(authorization: str = Header(default="")):
|
|
33
|
+
if not authorization.startswith("Bearer ") or not SCIM_TOKEN:
|
|
34
|
+
raise HTTPException(status_code=401, detail="Unauthorized SCIM request")
|
|
35
|
+
provided = authorization[7:].strip()
|
|
36
|
+
if not hmac.compare_digest(provided, SCIM_TOKEN):
|
|
37
|
+
raise HTTPException(status_code=401, detail="Invalid SCIM bearer token")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def get_m2m_token() -> str:
|
|
41
|
+
async with httpx.AsyncClient() as client:
|
|
42
|
+
res = await client.post(
|
|
43
|
+
f"https://{DOMAIN}/auth/oauth/token",
|
|
44
|
+
data={
|
|
45
|
+
"grant_type": "client_credentials",
|
|
46
|
+
"client_id": CLIENT_ID,
|
|
47
|
+
"client_secret": CLIENT_SECRET,
|
|
48
|
+
},
|
|
49
|
+
)
|
|
50
|
+
res.raise_for_status()
|
|
51
|
+
return res.json()["access_token"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def mgmt_request(method: str, path: str, payload: dict | None = None):
|
|
55
|
+
token = await get_m2m_token()
|
|
56
|
+
async with httpx.AsyncClient() as client:
|
|
57
|
+
res = await client.request(
|
|
58
|
+
method,
|
|
59
|
+
f"{API_BASE}{path}",
|
|
60
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
61
|
+
json=payload,
|
|
62
|
+
)
|
|
63
|
+
res.raise_for_status()
|
|
64
|
+
return res.json() if res.content else {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@app.get("/api/organizations", dependencies=[Depends(require_jwt)])
|
|
68
|
+
async def list_orgs():
|
|
69
|
+
return await mgmt_request("GET", "/api/organizations")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@app.post("/api/organizations", dependencies=[Depends(require_jwt)])
|
|
73
|
+
async def create_org(req: Request):
|
|
74
|
+
return await mgmt_request("POST", "/api/organizations", await req.json())
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@app.get("/api/organization-units", dependencies=[Depends(require_jwt)])
|
|
78
|
+
async def list_ous(organizationId: str | None = None):
|
|
79
|
+
path = f"/api/organization-units/organizationunit/organization/{organizationId}" if organizationId else "/api/organization-units"
|
|
80
|
+
return await mgmt_request("GET", path)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.post("/api/organization-units", dependencies=[Depends(require_jwt)])
|
|
84
|
+
async def create_ou(req: Request):
|
|
85
|
+
return await mgmt_request("POST", "/api/organization-units", await req.json())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@app.get("/api/users", dependencies=[Depends(require_jwt)])
|
|
89
|
+
async def list_users():
|
|
90
|
+
return await mgmt_request("GET", "/api/users")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@app.post("/api/users", dependencies=[Depends(require_jwt)])
|
|
94
|
+
async def create_user(req: Request):
|
|
95
|
+
return await mgmt_request("POST", "/api/users", await req.json())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@app.get("/api/groups", dependencies=[Depends(require_jwt)])
|
|
99
|
+
async def list_groups():
|
|
100
|
+
return await mgmt_request("GET", "/api/groups")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@app.post("/api/groups", dependencies=[Depends(require_jwt)])
|
|
104
|
+
async def create_group(req: Request):
|
|
105
|
+
return await mgmt_request("POST", "/api/groups", await req.json())
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@app.get("/scim/v2/Users", dependencies=[Depends(require_scim)])
|
|
109
|
+
def scim_list_users():
|
|
110
|
+
resources = list(scim_users.values())
|
|
111
|
+
return {
|
|
112
|
+
"schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
|
|
113
|
+
"totalResults": len(resources),
|
|
114
|
+
"startIndex": 1,
|
|
115
|
+
"itemsPerPage": len(resources),
|
|
116
|
+
"Resources": resources,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@app.post("/scim/v2/Users", status_code=201, dependencies=[Depends(require_scim)])
|
|
121
|
+
async def scim_create_user(req: Request):
|
|
122
|
+
body = await req.json()
|
|
123
|
+
uid = body.get("id") or str(uuid.uuid4())
|
|
124
|
+
body["id"] = uid
|
|
125
|
+
scim_users[uid] = body
|
|
126
|
+
scim_events.insert(0, {"type": "User", "op": "CREATE", "id": uid, "at": datetime.now(timezone.utc).isoformat()})
|
|
127
|
+
return body
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@app.get("/scim/v2/Groups", dependencies=[Depends(require_scim)])
|
|
131
|
+
def scim_list_groups():
|
|
132
|
+
resources = list(scim_groups.values())
|
|
133
|
+
return {
|
|
134
|
+
"schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
|
|
135
|
+
"totalResults": len(resources),
|
|
136
|
+
"startIndex": 1,
|
|
137
|
+
"itemsPerPage": len(resources),
|
|
138
|
+
"Resources": resources,
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@app.post("/scim/v2/Groups", status_code=201, dependencies=[Depends(require_scim)])
|
|
143
|
+
async def scim_create_group(req: Request):
|
|
144
|
+
body = await req.json()
|
|
145
|
+
gid = body.get("id") or str(uuid.uuid4())
|
|
146
|
+
body["id"] = gid
|
|
147
|
+
scim_groups[gid] = body
|
|
148
|
+
scim_events.insert(0, {"type": "Group", "op": "CREATE", "id": gid, "at": datetime.now(timezone.utc).isoformat()})
|
|
149
|
+
return body
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@app.get("/api/scim/events", dependencies=[Depends(require_jwt)])
|
|
153
|
+
def get_scim_events():
|
|
154
|
+
return {"users": list(scim_users.values()), "groups": list(scim_groups.values()), "events": scim_events}
|
|
155
|
+
|