@sso-id/node 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2 @@
1
+ export * from './jwt.js';
2
+ export * from './management.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './jwt.js';
2
+ export * from './management.js';
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { type JsonWebKey } from 'node:crypto';
2
+ export interface VerifyTokenOptions {
3
+ /** Tenant domain (e.g. "acme.sso.id" or "https://acme.sso.id") */
4
+ domain: string;
5
+ /** Expected audience (`aud`) claim, optional */
6
+ audience?: string;
7
+ /** Expected issuer (`iss`) claim, defaults to normalized domain */
8
+ issuer?: string;
9
+ /** Clock tolerance in seconds (default: 60) */
10
+ clockToleranceSec?: number;
11
+ /** Optional static JWKS keys for offline/unit-test verification */
12
+ jwksKeys?: JwkKey[];
13
+ }
14
+ export interface JwkKey extends JsonWebKey {
15
+ kid?: string;
16
+ kty: string;
17
+ alg?: string;
18
+ use?: string;
19
+ }
20
+ export interface SsoIdJwtClaims {
21
+ sub: string;
22
+ iss?: string;
23
+ aud?: string | string[];
24
+ exp?: number;
25
+ iat?: number;
26
+ nbf?: number;
27
+ email?: string;
28
+ name?: string;
29
+ org_id?: string;
30
+ roles?: string[];
31
+ permissions?: string[];
32
+ [key: string]: unknown;
33
+ }
34
+ export declare function verifyAccessToken(token: string, options: VerifyTokenOptions): Promise<SsoIdJwtClaims>;
35
+ export declare function requireSsoIdAuth(options: VerifyTokenOptions): (req: {
36
+ headers: Record<string, string | string[] | undefined>;
37
+ ssoIdUser?: SsoIdJwtClaims;
38
+ }, res: {
39
+ status: (code: number) => {
40
+ json: (body: unknown) => void;
41
+ };
42
+ }, next: () => void) => Promise<void>;
package/dist/jwt.js ADDED
@@ -0,0 +1,86 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ const jwksCache = new Map();
3
+ function normalizeDomain(domain) {
4
+ const clean = domain.replace(/\/+$/, '');
5
+ return clean.startsWith('http') ? clean : `https://${clean}`;
6
+ }
7
+ function decodeBase64UrlJson(segment) {
8
+ const json = Buffer.from(segment, 'base64url').toString('utf8');
9
+ return JSON.parse(json);
10
+ }
11
+ async function fetchJwks(baseUrl) {
12
+ const cached = jwksCache.get(baseUrl);
13
+ if (cached && Date.now() < cached.expiresAt) {
14
+ return cached.keys;
15
+ }
16
+ const res = await fetch(`${baseUrl}/auth/.well-known/jwks.json`);
17
+ if (!res.ok) {
18
+ throw new Error(`Failed to fetch SSO.ID JWKS (${res.status})`);
19
+ }
20
+ const body = (await res.json());
21
+ const keys = body.keys ?? [];
22
+ jwksCache.set(baseUrl, { keys, expiresAt: Date.now() + 5 * 60 * 1000 });
23
+ return keys;
24
+ }
25
+ export async function verifyAccessToken(token, options) {
26
+ const parts = token.split('.');
27
+ if (parts.length !== 3) {
28
+ throw new Error('Invalid JWT format');
29
+ }
30
+ const [headerB64, payloadB64, signatureB64] = parts;
31
+ const header = decodeBase64UrlJson(headerB64);
32
+ if (header.alg !== 'RS256') {
33
+ throw new Error(`Unsupported JWT algorithm: ${header.alg ?? 'unknown'}`);
34
+ }
35
+ const claims = decodeBase64UrlJson(payloadB64);
36
+ const baseUrl = normalizeDomain(options.domain);
37
+ const keys = options.jwksKeys ?? (await fetchJwks(baseUrl));
38
+ const matchingKey = (header.kid ? keys.find((k) => k.kid === header.kid) : undefined) ?? keys[0];
39
+ if (!matchingKey) {
40
+ throw new Error('No matching JWK found for token');
41
+ }
42
+ const publicKey = createPublicKey({ key: matchingKey, format: 'jwk' });
43
+ const signingInput = Buffer.from(`${headerB64}.${payloadB64}`, 'utf8');
44
+ const signature = Buffer.from(signatureB64, 'base64url');
45
+ const valid = verify('RSA-SHA256', signingInput, publicKey, signature);
46
+ if (!valid) {
47
+ throw new Error('Invalid JWT signature');
48
+ }
49
+ const nowSec = Math.floor(Date.now() / 1000);
50
+ const tolerance = options.clockToleranceSec ?? 60;
51
+ if (typeof claims.exp === 'number' && nowSec - tolerance >= claims.exp) {
52
+ throw new Error('JWT has expired');
53
+ }
54
+ if (typeof claims.nbf === 'number' && nowSec + tolerance < claims.nbf) {
55
+ throw new Error('JWT is not yet valid');
56
+ }
57
+ const expectedIssuer = options.issuer ?? baseUrl;
58
+ if (expectedIssuer && claims.iss && claims.iss.replace(/\/+$/, '') !== expectedIssuer.replace(/\/+$/, '')) {
59
+ throw new Error(`Invalid issuer: expected ${expectedIssuer}, got ${claims.iss}`);
60
+ }
61
+ if (options.audience) {
62
+ const audList = Array.isArray(claims.aud) ? claims.aud : claims.aud ? [claims.aud] : [];
63
+ if (!audList.includes(options.audience)) {
64
+ throw new Error(`Invalid audience: expected ${options.audience}`);
65
+ }
66
+ }
67
+ return claims;
68
+ }
69
+ export function requireSsoIdAuth(options) {
70
+ return async (req, res, next) => {
71
+ try {
72
+ const raw = req.headers.authorization;
73
+ const header = Array.isArray(raw) ? raw[0] : raw;
74
+ if (!header || !header.startsWith('Bearer ')) {
75
+ res.status(401).json({ error: 'Missing Bearer token' });
76
+ return;
77
+ }
78
+ const token = header.slice('Bearer '.length).trim();
79
+ req.ssoIdUser = await verifyAccessToken(token, options);
80
+ next();
81
+ }
82
+ catch (err) {
83
+ res.status(401).json({ error: err instanceof Error ? err.message : 'Unauthorized' });
84
+ }
85
+ };
86
+ }
@@ -0,0 +1,47 @@
1
+ export interface ManagementClientOptions {
2
+ /** Tenant domain (e.g. "acme.sso.id" or "https://acme.sso.id") */
3
+ domain: string;
4
+ clientId: string;
5
+ clientSecret: string;
6
+ /** Management API base URL (defaults to "https://api.sso.id") */
7
+ apiBaseUrl?: string;
8
+ audience?: string;
9
+ }
10
+ export declare class ManagementClient {
11
+ private readonly authBaseUrl;
12
+ private readonly apiBaseUrl;
13
+ private readonly options;
14
+ private cachedToken;
15
+ constructor(options: ManagementClientOptions);
16
+ private getAccessToken;
17
+ private request;
18
+ readonly users: {
19
+ list: (query?: {
20
+ page?: number;
21
+ pageSize?: number;
22
+ search?: string;
23
+ }) => Promise<unknown>;
24
+ get: (userId: string) => Promise<unknown>;
25
+ create: (data: Record<string, unknown>) => Promise<unknown>;
26
+ update: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
27
+ delete: (userId: string) => Promise<void>;
28
+ };
29
+ readonly roles: {
30
+ list: () => Promise<unknown>;
31
+ create: (data: {
32
+ name: string;
33
+ description?: string;
34
+ }) => Promise<unknown>;
35
+ assignToUser: (userId: string, roleId: string) => Promise<void>;
36
+ };
37
+ readonly organizations: {
38
+ list: () => Promise<unknown>;
39
+ get: (orgId: string) => Promise<unknown>;
40
+ };
41
+ readonly auditLogs: {
42
+ list: (query?: {
43
+ page?: number;
44
+ pageSize?: number;
45
+ }) => Promise<unknown>;
46
+ };
47
+ }
@@ -0,0 +1,94 @@
1
+ export class ManagementClient {
2
+ authBaseUrl;
3
+ apiBaseUrl;
4
+ options;
5
+ cachedToken = null;
6
+ constructor(options) {
7
+ const clean = options.domain.replace(/\/+$/, '');
8
+ this.authBaseUrl = clean.startsWith('http') ? clean : `https://${clean}`;
9
+ this.apiBaseUrl = (options.apiBaseUrl ?? 'https://api.sso.id').replace(/\/+$/, '');
10
+ this.options = options;
11
+ }
12
+ async getAccessToken() {
13
+ if (this.cachedToken && Date.now() < this.cachedToken.expiresAt - 30_000) {
14
+ return this.cachedToken.token;
15
+ }
16
+ const body = new URLSearchParams({
17
+ grant_type: 'client_credentials',
18
+ client_id: this.options.clientId,
19
+ client_secret: this.options.clientSecret,
20
+ ...(this.options.audience ? { audience: this.options.audience } : {}),
21
+ });
22
+ const res = await fetch(`${this.authBaseUrl}/auth/oauth/token`, {
23
+ method: 'POST',
24
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
25
+ body: body.toString(),
26
+ });
27
+ if (!res.ok) {
28
+ const text = await res.text();
29
+ throw new Error(`SSO.ID M2M token request failed (${res.status}): ${text}`);
30
+ }
31
+ const data = (await res.json());
32
+ this.cachedToken = {
33
+ token: data.access_token,
34
+ expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000,
35
+ };
36
+ return this.cachedToken.token;
37
+ }
38
+ async request(method, path, payload) {
39
+ const token = await this.getAccessToken();
40
+ const res = await fetch(`${this.apiBaseUrl}${path}`, {
41
+ method,
42
+ headers: {
43
+ Authorization: `Bearer ${token}`,
44
+ ...(payload !== undefined ? { 'Content-Type': 'application/json' } : {}),
45
+ },
46
+ body: payload !== undefined ? JSON.stringify(payload) : undefined,
47
+ });
48
+ if (!res.ok) {
49
+ const text = await res.text();
50
+ throw new Error(`SSO.ID Management API ${method} ${path} failed (${res.status}): ${text}`);
51
+ }
52
+ if (res.status === 204) {
53
+ return undefined;
54
+ }
55
+ return (await res.json());
56
+ }
57
+ users = {
58
+ list: (query) => {
59
+ const params = new URLSearchParams();
60
+ if (query?.page)
61
+ params.set('page', String(query.page));
62
+ if (query?.pageSize)
63
+ params.set('pageSize', String(query.pageSize));
64
+ if (query?.search)
65
+ params.set('search', query.search);
66
+ const qs = params.toString();
67
+ return this.request('GET', `/api/v1/users${qs ? `?${qs}` : ''}`);
68
+ },
69
+ get: (userId) => this.request('GET', `/api/v1/users/${encodeURIComponent(userId)}`),
70
+ create: (data) => this.request('POST', '/api/v1/users', data),
71
+ update: (userId, data) => this.request('PUT', `/api/v1/users/${encodeURIComponent(userId)}`, data),
72
+ delete: (userId) => this.request('DELETE', `/api/v1/users/${encodeURIComponent(userId)}`),
73
+ };
74
+ roles = {
75
+ list: () => this.request('GET', '/api/v1/roles'),
76
+ create: (data) => this.request('POST', '/api/v1/roles', data),
77
+ assignToUser: (userId, roleId) => this.request('POST', `/api/v1/users/${encodeURIComponent(userId)}/roles`, { roleId }),
78
+ };
79
+ organizations = {
80
+ list: () => this.request('GET', '/api/v1/organizations'),
81
+ get: (orgId) => this.request('GET', `/api/v1/organizations/${encodeURIComponent(orgId)}`),
82
+ };
83
+ auditLogs = {
84
+ list: (query) => {
85
+ const params = new URLSearchParams();
86
+ if (query?.page)
87
+ params.set('page', String(query.page));
88
+ if (query?.pageSize)
89
+ params.set('pageSize', String(query.pageSize));
90
+ const qs = params.toString();
91
+ return this.request('GET', `/api/v1/audit-logs${qs ? `?${qs}` : ''}`);
92
+ },
93
+ };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@sso-id/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Official SSO.ID Node.js SDK (RS256 JWKS JWT verification, Express/Fastify middleware, Management API client)",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "test": "node --test tests/*.test.mjs"
12
+ },
13
+ "keywords": [
14
+ "sso.id",
15
+ "node",
16
+ "jwt",
17
+ "jwks",
18
+ "oauth2",
19
+ "oidc",
20
+ "management-api"
21
+ ],
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": ">=18.0.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^20.11.0",
28
+ "typescript": "^5.4.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ]
36
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.