# Development Notes - Core Bootstrap Package

## 🎯 Goal

Create an npm package that verifies if a developer's device is authorized to work on a project by checking their MAC address and access expiration date against a Firestore database.

## 💡 What We Built

A verification system that:
- Reads developer ID from a local allowlist file
- Gets current device MAC address
- Sends both to an API for verification
- Checks if MAC address matches and access hasn't expired
- Allows or denies access based on verification

## 🔧 Problems Faced & Solutions

### Problem 1: Where to Store the Allowlist File?

**Issue:** Developers need a file with their ID, but where should it be stored? In project folder? Different for each project?

**What we considered:**
- Inside project folder - But then it gets committed to git
- In home directory - Clean, separate from projects
- Custom location - Too complicated for developers

**Solution:**
- Default location: `~/.dev-allowlist/developer-allowlist.json`
- Lives in user's home directory
- Same file works for all projects from same team
- Can use custom path with `--allowlist` flag if needed

**Result:** Simple, clean, and works perfectly.

---

### Problem 2: How to Pass API URL?

**Issue:** Different teams will have different API URLs. How should developers configure it?

**What we tried:**
1. Hard-code in package - No, not flexible
2. Store in allowlist file - Makes file more complex
3. Command line flag every time - Annoying to type

**Solution:**
- Use environment variable `DEV_VERIFY_API_URL`
- Developers set it once in their shell profile
- Can override with `--api` flag if needed
- Works automatically after initial setup

**Result:** Set once, works forever.

---

### Problem 3: Making HTTP Requests Without Dependencies

**Issue:** Need to make POST requests to API, but don't want to add heavy dependencies like axios.

**What we did:**
- Used Node.js built-in `http` and `https` modules
- Wrote custom promise wrapper for HTTP requests
- Auto-detect http vs https from URL
- Zero external dependencies

**Result:** Lightweight package with native Node.js only.

---

### Problem 4: Handling Different Date Formats

**Issue:** Team lead wanted to use simple string dates like "12/17/2025" in Firestore instead of timestamps.

**Initial problem:** API expected Firestore Timestamp objects.

**What we did:**
- Updated API to detect if `expiresAt` is a Timestamp or string
- Added conversion logic:
  ```javascript
  if (typeof expiresAt.toDate === 'function') {
    // It's a Firestore Timestamp
    expirationDate = expiresAt.toDate();
  } else if (typeof expiresAt === 'string') {
    // It's a string date
    expirationDate = new Date(expiresAt);
  }
  ```
- Set string dates to end of day (23:59:59) for fairness

**Result:** Now supports Timestamps, string dates, AND duration days.

---

### Problem 5: Error Messages Not Clear

**Issue:** When verification failed, developers didn't know WHY - was it expired? Wrong MAC? Wrong ID?

**Initial messages:** Generic "Access denied" for everything.

**What we did:**
- Added specific messages for each failure reason:
  - MAC address mismatch → "Device not authorized"
  - Access expired → "Access expired on [date]"
  - Developer not found → "Developer not found"
  - API error → Shows error details
- Different icons for different situations (⏱️ for expired, ❌ for denied)
- Show expiration date when access is still valid

**Result:** Developers know exactly what's wrong and what to do.

---

### Problem 6: Testing the Complete Flow

**Issue:** Need to test the whole system without deploying API to production.

**What we did:**
1. Created `example-api.js` with full implementation
2. Can run locally with `node example-api.js`
3. Set `DEV_VERIFY_API_URL=http://localhost:3000/verify-device`
4. Test everything end-to-end locally

**Result:** Easy to test before deploying.

---

## 📝 Key Learnings

1. **Environment variables are great for configuration** - Set once, use everywhere
2. **Clear error messages are critical** - Users need to know what went wrong
3. **Support multiple formats** - Timestamps AND strings makes it flexible
4. **Default paths should be simple** - `~/.dev-allowlist` is easy to remember
5. **Zero dependencies when possible** - Keeps package lightweight and fast
6. **Provide example implementations** - Helps teams deploy quickly

---

## 🚀 How It Works

```
Developer runs: npx @anisrh/core-bootstrap
     ↓
Read ~/.dev-allowlist/developer-allowlist.json
     ↓
Get developer ID: "dev-12345"
     ↓
Get current device MAC address
     ↓
POST to API: {developerId, deviceFingerprint}
     ↓
API queries Firestore: dev_device_fingerprints/dev-12345
     ↓
API checks:
  1. Does MAC address match? ✓
  2. Is access expired? ✓
     ↓
API responds: {allowed: true/false, message: "..."}
     ↓
CLI shows result to developer
     ↓
Exit 0 (success) or Exit 1 (failed)
```

---

## 📦 Files Created

- `index.js` - Core verification logic
- `cli.js` - Command-line interface
- `core-bootstrap.cmd` - Windows wrapper
- `example-api.js` - Sample API implementation (Express + Vercel)
- `package.json` - Package configuration
- `README.md` - User documentation
- `FIRESTORE_SETUP.md` - Database setup guide

---

## ✅ Final Result

A complete verification system that:
- ✅ Verifies device MAC address
- ✅ Checks access expiration dates
- ✅ Supports multiple date formats (Timestamp, string, duration days)
- ✅ Clear error messages for each failure type
- ✅ Works with any API (Vercel, Express, Cloud Functions, etc.)
- ✅ Zero external dependencies
- ✅ Easy to use with npx
- ✅ Includes example API implementation

---

## 🔄 Version History

- **1.0.0** - Initial release with full verification system

---

## 🔐 Security Features

1. **MAC Address Verification** - Device-based auth
2. **Expiration Checking** - Time-based access control
3. **Firestore Backend** - Centralized access management
4. **Real-time Verification** - Checks on every run
5. **Easy Revocation** - Update Firestore to revoke access
6. **Audit Trail** - `lastVerified` field tracks usage

---

## 💭 Future Improvements

Ideas for next version:
- Add offline grace period (allow X hours without verification)
- Support multiple MAC addresses per developer (desktop + laptop)
- Add webhook notifications when access expires
- Support for team/group access controls
- Add device name/description field in Firestore
- Dashboard for team leads to manage access
- Automatic email reminders before expiration
- Support for IP address verification as fallback

---

## 🤝 How API Works

### What API Receives:
```json
{
  "developerId": "dev-12345",
  "deviceFingerprint": "88:F4:DA:62:51:F1"
}
```

### What API Does:
1. Get document from Firestore: `dev_device_fingerprints/dev-12345`
2. Compare `deviceFingerprint` with stored `device_fingerprint`
3. Check if `expiresAt` has passed
4. Update `lastVerified` timestamp
5. Return allowed/denied response

### What API Returns:
```json
{
  "allowed": true/false,
  "message": "Reason for result",
  "expiresAt": "2025-12-17T23:59:59.999Z",
  "expiredAt": "2025-12-17T23:59:59.999Z" (if expired)
}
```

---

## 🌐 Deployment Options

The example API can be deployed to:

1. **Vercel** - Serverless function (recommended for simplicity)
2. **Netlify Functions** - Similar to Vercel
3. **Google Cloud Functions** - Good if already using GCP
4. **AWS Lambda** - Good if already using AWS
5. **Express.js Server** - Traditional server approach
6. **Cloud Run** - Containerized deployment

All examples provided in `example-api.js`.

---

**Built with security and developer experience in mind** 🔒
