# Auth Session Module

The `auth_session` module automatically detects authenticated user session data on the page and collects it as signals for analytics.

## Collected Signals

The module collects the following signals:

- **`u_auth_email`**: User email address (hashed for privacy)
- **`u_auth_id`**: User ID (unencrypted)
- **`u_auth_uuid`**: User UUID (unencrypted)
- **`u_auth_roles`**: User roles as comma-separated string (unencrypted)

## Data Sources

The module searches for authentication data in three locations, with the following priority:

### 1. localStorage - `boldUserProfile` (Priority 1)

The module first checks localStorage for a key named `boldUserProfile` containing user profile data.

**Expected format:**
```json
{
  "id": 275285,
  "medielogin_id": "605664fe-774a-4fda-b998-7555df7d4844",
  "name": null,
  "email": "user@example.com",
  "username": "bold 275285",
  "signature": null,
  "roles": ["registered", "forum_user"],
  "relevance": [],
  "fetched_at": "2025-10-31 02:45:59",
  "created_at": "2025-10-22 04:55:08",
  "token_version": "v3"
}
```

### 2. Holdet.dk API (Priority 2, only on www.holdet.dk)

When the script is running on `www.holdet.dk` domain, the module will attempt to fetch user session data from the Holdet.dk authentication API.

**API Endpoint:** `https://www.holdet.dk/api/auth/session`

**Expected response format:**
```json
{
  "user": {
    "name": "User Name",
    "email": "user@example.com",
    "image": null,
    "id": "2474593",
    "subsiteId": 6,
    "hasPamAccount": true,
    "roles": ["user"]
  },
  "expires": "2025-11-30T09:08:57.519Z"
}
```

**Features:**
- Only activated when `window.location.hostname === 'www.holdet.dk'`
- Sends credentials (cookies) with the request for authentication
- Fails silently if the API is unreachable or returns an error
- Extracts: `email`, `id`, and `roles` from the response

### 3. SvelteKit Inline Script (Fallback)

If localStorage data is not found and Holdet.dk API is not available (or not on www.holdet.dk domain), the module searches for SvelteKit initialization scripts in the page that contain user data.

The module looks for:
- Inline `<script>` tags containing `kit.start()` calls
- User data passed in the `data` array to `kit.start()`
- A pre-captured data object stored in `window.__samhub_sveltekit_data`

**Example SvelteKit pattern:**
```javascript
Promise.all([import("./app.js")]).then(([kit, app]) => {
  kit.start(app, element, {
    node_ids: [0, 7, 27],
    data: [{
      type: "data",
      data: {
        user: {
          email: "user@example.com",
          sub: "auth0|605664fe-774a-4fda-b998-7555df7d4844",
          // ... other user properties
        }
      }
    }]
  });
});
```

## Usage

The module is automatically loaded when included in the IdGraph modules configuration:

```typescript
const idGraph = new IdGraph('my-container', {
  modules: ['auth_session'], // Include the auth_session module
  // ... other options
});
```

Or it's included by default when no modules are specified:

```typescript
const idGraph = new IdGraph('my-container', {
  // auth_session is loaded by default along with other modules
});
```

## Privacy Considerations

- **Email addresses are hashed** using SHA-256 with a salt before being sent to the analytics endpoint
- **User IDs, UUIDs, and roles are NOT hashed** and sent as plain text
- The module fails silently if data cannot be found or parsed

## Data Extraction Details

### localStorage Extraction
- Reads the `boldUserProfile` key from localStorage
- Parses the JSON data
- Extracts: `id`, `medielogin_id`, `email`, and `roles` fields

### Holdet.dk API Extraction
- Checks if current hostname is `www.holdet.dk`
- Sends GET request to `https://www.holdet.dk/api/auth/session` with credentials
- Parses JSON response
- Extracts: `user.id`, `user.email`, and `user.roles` fields
- Does not provide UUID (not available in Holdet.dk response)

### SvelteKit Extraction
- Searches all inline script tags for `kit.start()` patterns
- Uses regex to extract user object from the script content
- Extracts `email` and `sub` (UUID) from the user object
- The `sub` field format is typically `"auth0|{uuid}"`, the module extracts the UUID portion

## Troubleshooting

If signals are not being collected:

1. **Check localStorage**: Open browser DevTools → Application → Local Storage and verify `boldUserProfile` exists
2. **Check Holdet.dk API** (if on www.holdet.dk):
   - Open DevTools → Network tab
   - Look for a request to `https://www.holdet.dk/api/auth/session`
   - Verify the response contains user data
   - Check if you're logged in (API requires authentication)
3. **Check script tags**: Use DevTools → Elements to search for inline scripts with `kit.start`
4. **Enable debug mode**: Set `debug: true` in IdGraph options to see console logs
5. **Verify data format**: Ensure the data matches the expected JSON structure

## Example

```typescript
// Initialize IdGraph with debug enabled
const idGraph = new IdGraph('my-container', {
  debug: true,
  modules: ['auth_session']
});

// After initialization, if user data is present, you'll see debug logs like:
// "Samhub -> IdGraph Module loaded: auth_session"

// Check collected signals
console.log(idGraph.getSignals());
// Output might include:
// [
//   { name: "u_auth_email", value: "<hashed-email>", hashed: true },
//   { name: "u_auth_id", value: "275285", hashed: false },
//   { name: "u_auth_uuid", value: "605664fe-774a-4fda-b998-7555df7d4844", hashed: false },
//   { name: "u_auth_roles", value: "registered,forum_user", hashed: false }
// ]
```
