> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Nostr

> Pacchetto Laravel per il protocollo Nostr. Gestione delle chiavi, operazioni sugli eventi, supporto per pool, NIP-05 / NIP-17, integrazione con Laravel Notifications.

## Panoramica

[revolution/laravel-nostr](https://github.com/invokable/laravel-nostr) è un pacchetto per utilizzare il protocollo Nostr da Laravel. Fornisce generazione e conversione di chiavi, recupero e pubblicazione di eventi, supporto per pool (più relay), profili NIP-05, Private Direct Messages NIP-17 e integrazione con Laravel Notifications.

<Info>
  Poiché le specifiche di Nostr sono ancora in evoluzione, anche questo pacchetto è in continuo sviluppo. La funzionalità di notifica è già utilizzabile in modo pratico.
</Info>

## Driver

Il pacchetto include due driver.

| Driver   | Descrizione                                                                                                                          |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `native` | Implementazione che funziona solo in PHP. Utilizza [nostr-php](https://github.com/nostrver-se/nostr-php). Attualmente è sufficiente. |
| `node`   | Implementazione che dipende da una [WebAPI](https://github.com/kawax/nostr-vercel-api) esterna (Node.js).                            |

<Tip>
  L'aspetto unico del driver `native` è l'implementazione di `WebSocketHttpMixin`. Si connette a WebSocket con il client HTTP di Laravel, invia e riceve dati e si disconnette immediatamente. Non è necessario mantenere attivo un server WebSocket ed è progettato in modo che qualsiasi utente Laravel possa utilizzarlo.
</Tip>

<Info>
  Il driver `native` non supporta NIP-04.
</Info>

### Impostazione del driver predefinito

Configuralo in `config/nostr.php` o in `.env`.

```php theme={null}
// config/nostr.php

'driver' => env('NOSTR_DRIVER', 'node'),
```

```dotenv theme={null}
NOSTR_DRIVER=native
```

Se non specifichi un driver, viene usato quello predefinito.

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

Nostr::event()->list();
```

Puoi anche specificare il driver esplicitamente.

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

Nostr::driver('node')->event()->list();
Nostr::node()->event()->list();

Nostr::driver('native')->event()->list();
Nostr::native()->event()->list();
```

## Installazione

<Steps>
  <Step title="Installa il pacchetto">
    ```bash theme={null}
    composer require revolution/laravel-nostr
    ```
  </Step>

  <Step title="Pubblica il file di configurazione">
    ```bash theme={null}
    php artisan vendor:publish --tag=nostr-config
    ```
  </Step>
</Steps>

## Gestione delle chiavi

### Genera una chiave

```php theme={null}
use Revolution\Nostr\Facades\Nostr;
use Illuminate\Http\Client\Response;

/** @var Response $response */
$response = Nostr::key()->generate();
$keys = $response->json();
// [
//     'sk'   => 'sk...',
//     'nsec' => 'nsec...',
//     'pk'   => 'pk...',
//     'npub' => 'npub...',
// ]
```

### Converti una chiave

Conversione da nsec.

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$response = Nostr::key()->fromNsec(nsec: 'nsec');
$keys = $response->json();
// ['sk' => '...', 'nsec' => '...', 'pk' => '...', 'npub' => '...']
```

Conversione da Secret Key.

```php theme={null}
$response = Nostr::key()->fromSecretKey(sk: 'sk');
```

Conversione da npub (solo chiave pubblica).

```php theme={null}
$response = Nostr::key()->fromNpub(npub: 'npub');
$keys = $response->json();
// ['pk' => '...', 'npub' => '...']
```

Conversione da Public Key.

```php theme={null}
$response = Nostr::key()->fromPublicKey(pk: 'pk');
```

## Recupero degli eventi

### Recupera più eventi

```php theme={null}
use Illuminate\Http\Client\Response;
use Revolution\Nostr\Facades\Nostr;
use Revolution\Nostr\Filter;
use Revolution\Nostr\Kind;

$filter = Filter::make(
    authors: ['my pk'],
    kinds: [Kind::Text],
    limit: 10,
);

/** @var Response $response */
$response = Nostr::event()->list(filter: $filter);
$events = $response->json('events');
// [
//     ['id' => '...1', 'kind' => 1, 'content' => '...'],
//     ['id' => '...2', 'kind' => 1, 'content' => '...'],
// ]
```

### Recupera un singolo evento

```php theme={null}
use Revolution\Nostr\Facades\Nostr;
use Revolution\Nostr\Filter;
use Revolution\Nostr\Kind;

$filter = Filter::make(
    authors: ['my pk'],
    kinds: [Kind::Metadata],
);

$response = Nostr::event()->get(filter: $filter);
$event = $response->json('event');
// ['id' => '...', 'kind' => 0, 'content' => '{name: ""}']
```

## Pubblicazione di eventi

### Pubblica su un singolo relay

```php theme={null}
use Revolution\Nostr\Facades\Nostr;
use Revolution\Nostr\Event;
use Revolution\Nostr\Kind;

$event = Event::make(
    kind: Kind::Text,
    content: 'hello',
    created_at: now()->timestamp,
    tags: [],
);

$sk = 'my sk';

$response = Nostr::event()->publish(event: $event, sk: $sk);

if ($response->successful()) {
    $event = $response->json('event');
}
```

### Pubblica su più relay (pool)

```php theme={null}
use Revolution\Nostr\Facades\Nostr;
use Revolution\Nostr\Event;
use Revolution\Nostr\Kind;

$event = Event::make(
    kind: Kind::Text,
    content: 'test',
    created_at: now()->timestamp,
    tags: [],
);

$responses = Nostr::pool()->publish(event: $event, sk: 'my sk');
// $responses è un array<string, Response>
// ['wss://relay1' => $response, 'wss://relay2' => $response]

foreach ($responses as $relay => $response) {
    if ($response->failed()) {
        dump($relay . ' : ' . $response->body());
    }
}
```

## Configurazione dei server relay

### Relay utilizzati

Quando utilizzi solo `Nostr::event()`, viene usato il primo relay di `config/nostr.php`. Quando utilizzi `Nostr::pool()`, sono coinvolti tutti i relay presenti nella configurazione.

### Modifica dei relay a runtime

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$response = Nostr::event()->withRelay('wss://')->...;
```

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$response = Nostr::pool()->withRelays(['wss://', 'wss://'])->...;
```

## Profilo NIP-05

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$profile = Nostr::nip05()->profile('user@localhost');
// [
//     'user'   => 'user@localhost',
//     'pubkey' => 'pk',
//     'relays' => [],
// ]
```

## NIP-17 Private Direct Messages

<Info>
  NIP-17 è supportato solo dal driver `native`.
</Info>

### Invia un messaggio privato

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$response = Nostr::driver('native')
    ->nip17()
    ->sendDirectMessage(
        sk: 'sender-secret-key',
        pk: 'receiver-public-key',
        message: 'Hello, this is a private message!'
    );
```

### Decripta un messaggio privato

```php theme={null}
use Revolution\Nostr\Facades\Nostr;

$response = Nostr::driver('native')
    ->nip17()
    ->decryptDirectMessage(
        giftWrap: $receivedGiftWrap,
        sk: 'receiver-secret-key'
    );

$decryptedMessage = $response->json();
```

## Laravel Notifications

Con `NostrChannel` puoi inviare messaggi a Nostr da Laravel Notifications.

### Classe Notification

```php theme={null}
use Illuminate\Notifications\Notification;
use Revolution\Nostr\Notifications\NostrChannel;
use Revolution\Nostr\Notifications\NostrMessage;
use Revolution\Nostr\Tags\HashTag;

class TestNotification extends Notification
{
    public function via(object $notifiable): array
    {
        return [
            'mail',
            NostrChannel::class,
        ];
    }

    public function toNostr(object $notifiable): NostrMessage
    {
        return new NostrMessage(
            // #laravel nel contenuto serve per la visualizzazione, HashTag in tags per la classificazione a livello di protocollo
            content: 'hello #laravel',
            tags: [
                HashTag::make(t: 'laravel'),
            ],
        );
    }
}
```

### Notifica on-demand

```php theme={null}
use Illuminate\Support\Facades\Notification;
use Revolution\Nostr\Notifications\NostrRoute;

Notification::route('nostr', NostrRoute::to(sk: 'sk'))
    ->notify(new TestNotification());
```

### Integrazione con il modello User

```php theme={null}
use Illuminate\Notifications\Notifiable;
use Revolution\Nostr\Notifications\NostrRoute;

class User
{
    use Notifiable;

    public function routeNotificationForNostr($notification): NostrRoute
    {
        return NostrRoute::to(sk: $this->sk, relays: ['wss://']);
    }
}
```

```php theme={null}
$user->notify(new TestNotification());
```

### Relay utilizzati per le notifiche

Per impostazione predefinita vengono utilizzati tutti i relay di `config/nostr.php`. Se specifichi i relay tramite `NostrRoute`, puoi modificarli a runtime.

```php theme={null}
use Revolution\Nostr\Notifications\NostrRoute;

return NostrRoute::to(sk: 'sk', relays: ['wss://', 'wss://']);
```

<Info>
  Per le informazioni più aggiornate consulta il [repository GitHub](https://github.com/invokable/laravel-nostr).
</Info>


## Related topics

- [Laravel Telescope](/it/telescope.md)
- [Laravel Boost](/it/boost.md)
- [Laravel Bluesky](/it/packages/laravel-bluesky/index.md)
- [Laravel Octane](/it/octane.md)
- [VOICEVOX for Laravel](/it/packages/laravel-voicevox/index.md)
