> ## 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

> 面向 Nostr 协议的 Laravel 包。支持密钥管理、事件操作、pool、NIP-05 / NIP-17，并集成 Laravel Notifications。

## 概览

[revolution/laravel-nostr](https://github.com/invokable/laravel-nostr) 是一个让你能在 Laravel 中使用 Nostr 协议的包。它提供密钥生成与转换、事件获取与发布、pool（多 relay）支持、NIP-05 profile、NIP-17 Private Direct Messages，以及与 Laravel Notifications 的集成。

<Info>
  由于 Nostr 规范仍在演进中，该包也在持续开发。通知功能已经可以实际投入使用。
</Info>

## 驱动

该包提供两个驱动。

| 驱动       | 说明                                                                                |
| -------- | --------------------------------------------------------------------------------- |
| `native` | 仅使用 PHP 的实现。使用 [nostr-php](https://github.com/nostrver-se/nostr-php)。目前该驱动已经足够使用。 |
| `node`   | 依赖外部 [WebAPI](https://github.com/kawax/nostr-vercel-api)（Node.js）的实现。             |

<Tip>
  `native` 驱动的独特之处在于其 `WebSocketHttpMixin` 实现。它通过 Laravel 的 HTTP 客户端连接到 WebSocket，收发数据后立即断开。无需持续运行 WebSocket 服务器，任何 Laravel 用户都可以使用。
</Tip>

<Info>
  `native` 驱动不支持 NIP-04。
</Info>

### 配置默认驱动

在 `config/nostr.php` 或 `.env` 中配置。

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

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

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

如果未指定驱动，将使用默认驱动。

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

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

也可以显式指定驱动。

```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();
```

## 安装

<Steps>
  <Step title="安装包">
    ```bash theme={null}
    composer require revolution/laravel-nostr
    ```
  </Step>

  <Step title="发布配置文件">
    ```bash theme={null}
    php artisan vendor:publish --tag=nostr-config
    ```
  </Step>
</Steps>

## 密钥管理

### 生成密钥

```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...',
// ]
```

### 转换密钥

从 nsec 转换。

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

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

从 Secret Key 转换。

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

从 npub 转换（仅公钥）。

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

从 Public Key 转换。

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

## 获取事件

### 获取多个事件

```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' => '...'],
// ]
```

### 获取单个事件

```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: ""}']
```

## 发布事件

### 发布到单个 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');
}
```

### 发布到多个 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 为 array<string, Response>
// ['wss://relay1' => $response, 'wss://relay2' => $response]

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

## Relay 服务器配置

### 使用的 relay 服务器

当仅使用 `Nostr::event()` 时，会使用 `config/nostr.php` 中的第一个 relay。当使用 `Nostr::pool()` 时，配置中的所有 relay 都会作为目标。

### 在运行时更换 relay

```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://'])->...;
```

## NIP-05 profile

```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 仅在 `native` 驱动中受支持。
</Info>

### 发送私信

```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!'
    );
```

### 解密私信

```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

使用 `NostrChannel`，你可以从 Laravel Notifications 向 Nostr 发送消息。

### 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(
            // content 中的 #laravel 用于显示，tags 中的 HashTag 用于协议层面的分类
            content: 'hello #laravel',
            tags: [
                HashTag::make(t: 'laravel'),
            ],
        );
    }
}
```

### 按需通知

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

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

### 与 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 服务器

默认情况下会使用 `config/nostr.php` 中配置的所有 relay。也可以通过 `NostrRoute` 在运行时指定 relay。

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

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

<Info>
  更多最新信息请参见 [GitHub 仓库](https://github.com/invokable/laravel-nostr)。
</Info>


## Related topics

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