@ciscode/authentication-kit 1.0.33

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,38 @@
1
+ name: CD - Release
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+
7
+ permissions:
8
+ contents: write
9
+ issues: write
10
+ pull-requests: write
11
+
12
+ jobs:
13
+ release:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Checkout
17
+ uses: actions/checkout@v4
18
+ with:
19
+ fetch-depth: 0
20
+
21
+ - name: Use Node.js
22
+ uses: actions/setup-node@v4
23
+ with:
24
+ node-version: 22
25
+ cache: npm
26
+ registry-url: https://registry.npmjs.org/
27
+
28
+ - name: Install dependencies
29
+ run: npm ci
30
+
31
+ - name: Build library
32
+ run: npm run build:lib
33
+
34
+ - name: Release
35
+ env:
36
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
37
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
38
+ run: npm run release
@@ -0,0 +1,38 @@
1
+ # Code of Conduct
2
+
3
+ This project adheres to the Contributor Covenant Code of Conduct.
4
+
5
+ ---
6
+
7
+ ## Our Pledge
8
+
9
+ We pledge to make participation in this project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity.
10
+
11
+ ---
12
+
13
+ ## Our Standards
14
+
15
+ Examples of behavior that contributes to a positive environment include:
16
+ - Being respectful and inclusive
17
+ - Giving and accepting constructive feedback
18
+ - Focusing on what is best for the community
19
+
20
+ Examples of unacceptable behavior include:
21
+ - Harassment or discriminatory language
22
+ - Personal attacks or trolling
23
+ - Publishing private information without consent
24
+
25
+ ---
26
+
27
+ ## Enforcement
28
+
29
+ Project maintainers are responsible for clarifying and enforcing standards of acceptable behavior.
30
+
31
+ Instances of abusive behavior may be reported to the maintainers through private communication channels.
32
+
33
+ ---
34
+
35
+ ## Attribution
36
+
37
+ This Code of Conduct is adapted from the Contributor Covenant
38
+ version 2.1 — https://www.contributor-covenant.org/
@@ -0,0 +1,40 @@
1
+ # Contributing
2
+
3
+ Thank you for your interest in contributing to this project.
4
+
5
+ Contributions of all kinds are welcome, including bug reports, feature requests, documentation improvements, and code contributions.
6
+
7
+ ---
8
+
9
+ ## How to Contribute
10
+
11
+ 1. Fork the repository
12
+ 2. Create a new branch from `main`
13
+ 3. Make your changes
14
+ 4. Add or update tests where applicable
15
+ 5. Ensure existing tests pass
16
+ 6. Open a pull request with a clear description
17
+
18
+ ---
19
+
20
+ ## Guidelines
21
+
22
+ - Keep changes focused and minimal
23
+ - Follow existing code style and conventions
24
+ - Avoid breaking backward compatibility when possible
25
+ - Write clear commit messages
26
+ - Do not include secrets, credentials, or tokens
27
+
28
+ ---
29
+
30
+ ## Reporting Bugs
31
+
32
+ When reporting bugs, please include:
33
+ - A clear description of the issue
34
+ - Steps to reproduce
35
+ - Expected vs actual behavior
36
+ - Relevant logs or error messages (redacted if needed)
37
+
38
+ ---
39
+
40
+ By contributing, you agree that your contributions will be licensed under the same license as the project.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ciscode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ Auth Service (Express · JWT · Multi‑Tenant · RBAC)
2
+ Internal package — private to the company.
3
+ This package is not published on npmjs. Install it only from the company’s Azure Artifacts feed using a project or user-level .npmrc.
4
+
5
+ Authentication & authorization service for Node/Express apps.
6
+ Provides local email/password auth with lockout, JWT access tokens + refresh, tenant scoping, RBAC, and optional Microsoft Entra (Azure AD) OAuth.
7
+
8
+ Features
9
+ Local auth (email/password) with account lockout policy.
10
+ JWT access tokens (Bearer) and refresh endpoint (cookie or body).
11
+ Multi-tenant scope on requests.
12
+ RBAC (roles → permission strings).
13
+ Microsoft Entra (Azure AD) OAuth (optional).
14
+ MongoDB/Mongoose models.
15
+ Routes are mounted under:
16
+
17
+ /api/auth (auth, password reset)
18
+ /api/users (user admin)
19
+ /api/auth/roles and /api/auth/permissions (RBAC)
20
+ Installation (Azure Artifacts only)
21
+ 1) Configure .npmrc
22
+ Do not commit real tokens. Prefer ~/.npmrc or generate .npmrc in CI using secrets.
23
+
24
+ For developers (user-level ~/.npmrc):
25
+
26
+ registry=https://registry.npmjs.org/
27
+
28
+ # Route @ciscodeapps scope to the private feed
29
+ @ciscodeapps:registry=https://pkgs.dev.azure.com/CISCODEAPPS/Templates/_packaging/testfeed/npm/registry/
30
+
31
+ //pkgs.dev.azure.com/CISCODEAPPS/Templates/_packaging/testfeed/npm/registry/:_authToken=${AZURE_ARTIFACTS_PAT}
32
+ always-auth=true
33
+ Set the token as an environment variable before installing:
34
+
35
+ export AZURE_ARTIFACTS_PAT="<your PAT with Packaging:Read>"
36
+ You can also use the username/_password form:
37
+
38
+ //pkgs.dev.azure.com/...:username=AzureDevOps
39
+ //pkgs.dev.azure.com/...:_password=${BASE64_PAT}
40
+ //pkgs.dev.azure.com/...:email=not-used@localhost
41
+ where BASE64_PAT=$(printf %s "$AZURE_ARTIFACTS_PAT" | base64).
42
+
43
+ 2) Install the package
44
+ npm i @ciscodeapps/auth-service
45
+ 3) Required environment variables (host app)
46
+ Create a .env in the host project:
47
+
48
+ # Server
49
+ PORT=3000
50
+ NODE_ENV=development
51
+ BASE_URL=http://localhost:3000
52
+
53
+ # Database (the service connects to this on startup)
54
+ MONGO_URI_T=mongodb://127.0.0.1:27017/auth_service
55
+
56
+ # JWT
57
+ JWT_SECRET=change_me
58
+ JWT_ACCESS_TOKEN_EXPIRES_IN=15m
59
+ JWT_REFRESH_SECRET=change_me_too
60
+ JWT_REFRESH_TOKEN_EXPIRES_IN=7d
61
+
62
+ # Lockout policy
63
+ MAX_FAILED_LOGIN_ATTEMPTS=5
64
+ ACCOUNT_LOCK_TIME_MINUTES=15
65
+
66
+ # (Optional) Microsoft Entra ID (Azure AD)
67
+ MICROSOFT_TENANT=organizations
68
+ MICROSOFT_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
69
+ MICROSOFT_CLIENT_SECRET=your-secret
70
+ MICROSOFT_CALLBACK_URL=${BASE_URL}/api/auth/microsoft/callback
71
+ Use inside an existing Express app
72
+ Your package exports an Express app that already parses JSON, connects to Mongo, and mounts its routes. Just mount it:
73
+
74
+ // server.js (host app)
75
+ require('dotenv').config();
76
+ const express = require('express');
77
+ const authApp = require('@ciscodeapps/auth-service');
78
+
79
+ const app = express();
80
+ app.use(authApp); // exposes /api/auth, /api/users, /api/auth/roles, /api/auth/permissions
81
+
82
+ app.get('/health', (_, res) => res.json({ ok: true }));
83
+ app.listen(process.env.PORT || 3000, () =>
84
+ console.log('Host app on', process.env.PORT || 3000)
85
+ );
86
+ Prefer mounting the service. If you need to run it standalone, you can also start this package directly (it calls connectDB() on import).
87
+
88
+ What’s included (routes & behavior)
89
+ Auth
90
+ POST /api/auth/register – Create a user (email/password).
91
+ POST /api/auth/login – Local login. On success, returns accessToken and may set a refreshToken httpOnly cookie.
92
+ POST /api/auth/verify-otp – If OTP/step-up is enabled, verifies the code and completes login.
93
+ POST /api/auth/refresh-token – New access token from a valid refresh token (cookie or body).
94
+ POST /api/auth/request-password-reset – Sends a reset token (e.g., by email).
95
+ PATCH /api/auth/reset-password – Consumes the reset token and sets a new password.
96
+ GET /api/auth/microsoft → GET /api/auth/microsoft/callback – Optional Microsoft Entra OAuth; issues first-party tokens.
97
+ Users
98
+ GET /api/users – List users (tenant-scoped, paginated).
99
+ POST /api/users – Create a user (requires permission).
100
+ Additional CRUD endpoints as exposed by controllers.
101
+ Roles & Permissions
102
+ GET/POST /api/auth/roles – Manage roles (name, tenantId, permissions: string[]).
103
+ GET /api/auth/permissions – List permission strings and metadata.
104
+ Protecting your own routes (host app)
105
+ const authenticate = require('@ciscodeapps/auth-service/src/middleware/authenticate'); // JWT
106
+ const { hasPermission } = require('@ciscodeapps/auth-service/src/middleware/rbac.middleware'); // RBAC
107
+
108
+ app.get('/reports',
109
+ authenticate,
110
+ hasPermission('reports:read'),
111
+ (req, res) => res.json({ ok: true })
112
+ );
113
+ Tenant scope comes from the JWT payload (e.g., tenantId) and is used inside controllers/guards to filter queries.
114
+
115
+ Quick start (smoke tests)
116
+ Start your host app:
117
+
118
+ node server.js
119
+ Register & Login
120
+
121
+ curl -X POST http://localhost:3000/api/auth/register \
122
+ -H 'Content-Type: application/json' \
123
+ -d '{"email":"a@b.com","password":"Secret123!","tenantId":"t-001","name":"Alice"}'
124
+
125
+ curl -X POST http://localhost:3000/api/auth/login \
126
+ -H 'Content-Type: application/json' \
127
+ -d '{"email":"a@b.com","password":"Secret123!","tenantId":"t-001"}'
128
+ # => { "accessToken": "...", "refreshToken": "..." }
129
+ Call a protected route
130
+
131
+ ACCESS=<paste_access_token_here>
132
+ curl http://localhost:3000/api/users -H "Authorization: Bearer $ACCESS"
133
+ Refresh token
134
+
135
+ curl -X POST http://localhost:3000/api/auth/refresh-token \
136
+ -H 'Content-Type: application/json' \
137
+ -d '{"refreshToken":"<paste_refresh_token_here>"}'
138
+ # => { "accessToken": "..." }
139
+ Microsoft OAuth (optional) - Visit: http://localhost:3000/api/auth/microsoft → complete sign-in.
140
+ - Callback: ${BASE_URL}/api/auth/microsoft/callback returns tokens (and may set the refresh cookie).
141
+
142
+ CI/CD (Azure Pipelines)
143
+ # azure-pipelines.yml (snippet)
144
+ - task: npmAuthenticate@0
145
+ inputs:
146
+ workingFile: .npmrc # optional; the task wires npm auth for subsequent steps
147
+
148
+ - script: npm ci
149
+ displayName: Install deps
150
+ (For GitHub Actions, write a ~/.npmrc with the token from secrets.AZURE_ARTIFACTS_PAT before npm ci.)
151
+
152
+ Security notes
153
+ Never commit real PATs. Use env vars or CI secrets.
154
+ Run behind HTTPS. Rotate JWT & refresh secrets periodically.
155
+ Limit login attempts; log auth events for auditing.
156
+ License
157
+ Internal — Company proprietary.
package/SECURITY ADDED
@@ -0,0 +1,31 @@
1
+ # Security Policy
2
+
3
+ Security is taken seriously in this project.
4
+
5
+ If you discover a security vulnerability, please **do not open a public issue**.
6
+
7
+ ---
8
+
9
+ ## Reporting a Vulnerability
10
+
11
+ Please report security issues privately by contacting the maintainers using one of the following methods:
12
+
13
+ - Email the address listed in the repository’s contact or maintainer information
14
+ - Use private disclosure channels if available on the hosting platform
15
+
16
+ When reporting, please include:
17
+ - A description of the vulnerability
18
+ - Steps to reproduce
19
+ - Potential impact
20
+ - Any suggested mitigations (if known)
21
+
22
+ ---
23
+
24
+ ## Security Best Practices
25
+
26
+ - Never commit secrets or credentials
27
+ - Use strong, rotated secrets for JWT signing
28
+ - Run services behind HTTPS
29
+ - Apply rate limiting and monitoring in production environments
30
+
31
+ We appreciate responsible disclosure and will work to address issues promptly.
@@ -0,0 +1,100 @@
1
+ trigger:
2
+ - main
3
+
4
+ pool:
5
+ vmImage: 'ubuntu-latest'
6
+
7
+ variables:
8
+ - group: BE # AZURE_ARTIFACTS_PAT lives here; add NPM_TOKEN and (optionally) GH_PAT as secrets
9
+
10
+ # Optional toggles (default = behave exactly like your old pipeline: publish only to Azure Artifacts)
11
+ parameters:
12
+ - name: pushToGitHub
13
+ type: boolean
14
+ default: false
15
+ - name: publishToNpm
16
+ type: boolean
17
+ default: false
18
+ - name: packagePath
19
+ type: string
20
+ default: 'modules/login'
21
+
22
+ steps:
23
+ # Allows pushing back to GitHub if pushToGitHub=true (we'll still use GH_PAT if provided)
24
+ - checkout: self
25
+ persistCredentials: true
26
+ displayName: 'Checkout (allows push when enabled)'
27
+
28
+ # 1) Use Node.js (unchanged)
29
+ - task: NodeTool@0
30
+ inputs:
31
+ versionSpec: '20.x'
32
+ displayName: 'Use Node.js'
33
+
34
+ # 2) Authenticate with Azure Artifacts (unchanged)
35
+ - script: |
36
+ echo "Setting up npm authentication for Azure Artifacts..."
37
+ echo "//pkgs.dev.azure.com/CISCODEAPPS/Templates/_packaging/testfeed/npm/registry/:_authToken=$(AZURE_ARTIFACTS_PAT)" > ~/.npmrc
38
+ npm set registry "https://pkgs.dev.azure.com/CISCODEAPPS/Templates/_packaging/testfeed/npm/registry/"
39
+ displayName: 'Authenticate with Azure Artifacts'
40
+
41
+ # 3) Bump + publish to Azure Artifacts (mandatory)
42
+ - script: |
43
+ set -e
44
+ echo "Bumping package version before publishing login..."
45
+ cd ${{ parameters.packagePath }}
46
+ npm version patch --no-git-tag-version
47
+
48
+ # capture for optional steps
49
+ NEW_VERSION=$(node -p "require('./package.json').version")
50
+ PKG_NAME=$(node -p "require('./package.json').name")
51
+ echo "Decided version: ${NEW_VERSION} for ${PKG_NAME}"
52
+ echo "##vso[task.setvariable variable=NEW_VERSION]$NEW_VERSION"
53
+ echo "##vso[task.setvariable variable=PKG_NAME]$PKG_NAME"
54
+
55
+ # sanity: see what will be published
56
+ npm pack --dry-run
57
+
58
+ # publish to Azure Artifacts (mandatory)
59
+ npm publish --registry=https://pkgs.dev.azure.com/CISCODEAPPS/Templates/_packaging/testfeed/npm/registry/
60
+ displayName: 'Publish authentication module (Azure Artifacts - mandatory)'
61
+
62
+ # OPTIONAL: push the version bump back to GitHub
63
+ - ${{ if eq(parameters.pushToGitHub, true) }}:
64
+ - script: |
65
+ set -e
66
+ cd ${{ parameters.packagePath }}
67
+
68
+ # bot identity for the commit
69
+ git config user.name "azure-pipelines[bot]"
70
+ git config user.email "azure-pipelines-bot@example.local"
71
+
72
+ # If a GitHub PAT is provided, use it to ensure push works (esp. with GitHub App connections)
73
+ if [ -n "$(GH_PAT)" ]; then
74
+ echo "Using GH_PAT to authenticate push..."
75
+ git remote set-url origin "https://x-access-token:$(GH_PAT)@github.com/CISCODE-MA/auth_package"
76
+ fi
77
+
78
+ git add package.json package-lock.json || true
79
+ git commit -m "chore(login): bump $(PKG_NAME) to v$(NEW_VERSION) [skip ci]" || echo "No changes to commit"
80
+ git push origin HEAD:$(Build.SourceBranchName)
81
+ displayName: 'Push version bump to GitHub (optional)'
82
+
83
+ # OPTIONAL: publish same version to npm public (with pre-check)
84
+ - ${{ if eq(parameters.publishToNpm, true) }}:
85
+ - script: |
86
+ set -e
87
+ echo "Switching npm auth to npm public..."
88
+ rm -f ~/.npmrc || true
89
+ echo "//registry.npmjs.org/:_authToken=$(NPM_TOKEN)" > ~/.npmrc
90
+ npm set registry "https://registry.npmjs.org/"
91
+
92
+ cd ${{ parameters.packagePath }}
93
+
94
+ # Skip if the exact version already exists on npm
95
+ if npm view "$(PKG_NAME)@$(NEW_VERSION)" version >/dev/null 2>&1; then
96
+ echo "$(PKG_NAME)@$(NEW_VERSION) already exists on npm; skipping publish."
97
+ else
98
+ npm publish --access public
99
+ fi
100
+ displayName: 'Publish to npm public (optional)'
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@ciscode/authentication-kit",
3
+ "publishConfig": { "access": "public"},
4
+ "version": "1.0.33",
5
+ "description": "A login library with local login, Microsoft Entra ID authentication, password reset, and roles/permissions for multi-tenant applications.",
6
+ "main": "src/index.js",
7
+ "scripts": {
8
+ "start": "node src/index.js",
9
+ "test": "echo \"No tests defined\" && exit 0"
10
+ },
11
+ "keywords": [
12
+ "login",
13
+ "authentication",
14
+ "microsoft-oauth",
15
+ "password-reset",
16
+ "roles",
17
+ "permissions",
18
+ "multi-tenant"
19
+ ],
20
+ "author": "Ciscode",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "bcryptjs": "^2.4.3",
24
+ "crypto": "^1.0.1",
25
+ "dotenv": "^16.0.3",
26
+ "express": "^4.18.2",
27
+ "jsonwebtoken": "^9.0.0",
28
+ "mongoose": "^7.0.0",
29
+ "mongoose-paginate-v2": "^1.7.1",
30
+ "nodemailer": "^6.9.1",
31
+ "passport": "^0.6.0",
32
+ "passport-azure-ad-oauth2": "^0.0.4",
33
+ "passport-local": "^1.0.0"
34
+ }
35
+ }
@@ -0,0 +1,21 @@
1
+ const mongoose = require('mongoose');
2
+ require('dotenv').config();
3
+
4
+ // Optionally, set strictQuery per Mongoose recommendations
5
+ mongoose.set('strictQuery', false);
6
+
7
+ const connectDB = async () => {
8
+ try {
9
+ const mongoURI = process.env.MONGO_URI_T;
10
+ if (!mongoURI) {
11
+ throw new Error('MONGO_URI is not defined in the environment variables.');
12
+ }
13
+ await mongoose.connect(mongoURI);
14
+ console.log("MongoDB Connected...");
15
+ } catch (error) {
16
+ console.error("MongoDB Connection Error:", error);
17
+ process.exit(1);
18
+ }
19
+ };
20
+
21
+ module.exports = connectDB;