@intelicity/gates-sdk
v0.3.0
Published
Simple SDK for authenticating users with AWS Cognito JWT tokens
Readme
Gates SDK
Node.js SDK for the Gates authentication system (AWS Cognito). It provides JWT verification, group-based and scope-based authorization, admin user management, and framework-agnostic middleware.
Installation
npm install @intelicity/gates-sdkFeatures
- JWT verification for both access tokens and id tokens
- Optional
clientIdvalidation, including multiple accepted client IDs - Group-based access control with Cognito groups
- Scope-based access control for M2M flows
- Framework-agnostic middleware (Fastify, Express, etc.)
- Built-in JWKS caching (1h TTL)
- Admin user management
- Comprehensive error hierarchy
Usage
Token Verification
import { AuthService } from "@intelicity/gates-sdk";
const auth = new AuthService(
"sa-east-1",
"sa-east-1_xxxxxxxxx",
"your-client-id",
);
const user = await auth.verifyToken(accessToken);
// user.user_id, user.groups, user.scopes, user.token_use, user.email?, user.name?Supports both access_token (validates the client_id claim) and id_token (validates the aud claim). The returned GatesUser also exposes scopes, populated from the token scope claim when present.
Middleware
import {
AuthService,
authenticate,
authorize,
authorizeScopes,
extractToken,
handleAuth,
} from "@intelicity/gates-sdk";
const service = new AuthService(region, userPoolId, clientId);
const token = extractToken(req.headers.authorization);
const user = await authenticate(token, service);
authorize(user, ["GAIA", "RECAPE"]);
authorizeScopes(user, "gates/users.read");
req.user = await handleAuth(req.headers.authorization, {
service,
requiredGroups: "GAIA",
requiredScopes: "gates/users.read",
});Error Handling
import {
GatesError,
InvalidTokenError,
TokenExpiredError,
UnauthorizedGroupError,
UnauthorizedScopeError,
} from "@intelicity/gates-sdk";
try {
const user = await auth.verifyToken(token);
} catch (error) {
if (error instanceof TokenExpiredError) {
// error.code === "TOKEN_EXPIRED"
} else if (error instanceof InvalidTokenError) {
// error.code === "INVALID_TOKEN"
} else if (error instanceof UnauthorizedGroupError) {
// error.code === "UNAUTHORIZED_GROUP"
// error.requiredGroups: string[]
} else if (error instanceof UnauthorizedScopeError) {
// error.code === "UNAUTHORIZED_SCOPE"
// error.requiredScopes: string[]
} else if (error instanceof GatesError) {
// error.code, error.message
}
}Admin Service
import { GatesAdminService } from "@intelicity/gates-sdk";
const admin = new GatesAdminService({
baseUrl: "https://abc123.execute-api.sa-east-1.amazonaws.com/prod",
});
const { sub } = await admin.createUser(adminIdToken, {
email: "[email protected]",
name: "New User",
role: "CLIENT_USER",
client: "GAIA",
});
await admin.updateUser(adminIdToken, {
user_id: sub,
clients_to_add: ["RECAPE"],
clients_to_remove: ["INFORMS"],
});API Reference
AuthService
new AuthService(
region: string,
userPoolId: string,
clientId?: string | string[],
)verifyToken(token: string): Promise<GatesUser>
GatesAdminService
new GatesAdminService({ baseUrl: string })createUser(idToken: string, params: CreateUserParams): Promise<CreateUserResponse>updateUser(idToken: string, params: UpdateUserParams): Promise<void>getAllUsers(idToken: string, params: GetAllUsersParams): Promise<GetAllUsersResponse>
Middleware
extractToken(authorizationHeader: string | undefined): stringauthenticate(token: string, service: AuthService): Promise<GatesUser>authorize(user: GatesUser, requiredGroups: string | string[]): voidauthorizeScopes(user: GatesUser, requiredScopes: string | string[]): voidhandleAuth(authorizationHeader: string | undefined, config: AuthHandlerConfig): Promise<GatesUser>
Types
type GatesUser = {
user_id: string;
email?: string;
name?: string;
role?: string;
groups: string[];
scopes: string[];
token_use: "access" | "id";
exp: number;
iat: number;
};
type GatesRole =
| "INTERNAL_ADMIN"
| "INTERNAL_USER"
| "CLIENT_ADMIN"
| "CLIENT_USER";Error Codes
| Code | Class | Description |
| --- | --- | --- |
| TOKEN_EXPIRED | TokenExpiredError | JWT has expired |
| INVALID_TOKEN | InvalidTokenError | Invalid or malformed token |
| MISSING_AUTHORIZATION | MissingAuthorizationError | Authorization header missing |
| UNAUTHORIZED_GROUP | UnauthorizedGroupError | User not in required group |
| UNAUTHORIZED_SCOPE | UnauthorizedScopeError | Token missing required scope |
| API_REQUEST_ERROR | ApiRequestError | Gates API request failed |
| MISSING_PARAMETER | MissingParameterError | Required parameter missing |
| INVALID_PARAMETER | InvalidParameterError | Parameter has invalid value |
Development
npm install
npm run build
npm run typecheck
npm test
npm run test:watchLicense
MIT
