# dblurt Security Architecture

> Strategic security model for `@beblurt/dblurt`.
>
> This document defines security boundaries and decision principles. It is not a vulnerability fix plan and it is not a promise that every risk is handled inside the SDK.

## Document status

Status: accepted security architecture baseline for maintainer review and future hardening milestones.

Scope:

- SDK security responsibilities.
- Application versus SDK responsibilities.
- Trust model for Layer 1 RPC, Nexus Layer 2 RPC and browser/backend runtimes.
- Cryptographic compatibility constraints.
- Classification of known security findings.
- Roadmap for future specialized audits.

Non-goals:

- No runtime implementation change in this document.
- No npm publication decision.
- No claim that dblurt has completed a formal cryptographic audit.
- No claim that public RPC or Nexus data is trusted consensus data.

## Security objective

`@beblurt/dblurt` should be a reusable infrastructure SDK that lets applications interact with Blurt safely enough to build production systems, while making its trust boundaries explicit.

The SDK should protect against mistakes inside the SDK boundary and provide safe defaults where doing so preserves compatibility. It must not pretend to solve security problems that belong to applications, wallets, infrastructure operators or the Blurt protocol itself.

## System context

```text
Applications / wallets / bots / MCP servers / CLIs / frontends
        │
        │ use SDK APIs, provide keys and RPC endpoints
        ▼
@beblurt/dblurt
        │
        ├── local key parsing, signing, memo helpers, serializers
        ├── JSON-RPC request construction, timeout/failover behavior
        ├── Layer 1 helper APIs
        └── Nexus/Bridge helper APIs
        │
        ├── Blurt Layer 1 RPC exposed by blurtd
        └── Nexus Layer 2 indexed/social/query RPC
        │
        ▼
Blurt blockchain and indexing infrastructure
```

Layer 1 RPC is the source of consensus truth. Nexus is an indexed/query/social layer built from Layer 1 data. dblurt may talk to both, but security-sensitive state must not treat Nexus as replacing Layer 1.

## Security boundaries

### Inside the SDK boundary

The SDK owns:

- deterministic construction and serialization of supported operations;
- local transaction digest/signature generation;
- public/private key parsing and validation behavior;
- memo encode/decode compatibility helpers;
- JSON-RPC request shape;
- response/error handling policy;
- timeout and failover behavior;
- browser bundle/package artifact integrity from source;
- accurate documentation of SDK behavior and limits.

### Outside the SDK boundary

Applications own:

- account authorization decisions;
- key custody, wallet UX and user consent;
- endpoint allowlisting and network egress policy;
- determining whether an operation is safe for a user to sign;
- validating business rules and user intent;
- protecting browser apps from XSS and malicious dependencies;
- deciding whether to trust Nexus-derived social/indexed data;
- monitoring production RPC nodes and availability.

Infrastructure and protocol layers own:

- blurtd consensus validation;
- block production and finality;
- public RPC node correctness and availability;
- Nexus indexing correctness and freshness;
- legacy memo format constraints.

## Trust model

### Private keys

Private keys are never expected to leave the application runtime through dblurt. The SDK can parse, hold and use keys, but it cannot guarantee safe key custody once the application passes key material into process memory or browser memory.

Security expectation:

- SDK APIs must not log full private keys by default.
- Documentation and examples must not hard-code private keys.
- Browser signing must be treated as high risk unless mediated by a wallet or equivalent user-controlled signing flow.

### RPC endpoints

RPC endpoints are untrusted network services unless the application has explicitly chosen and secured them.

Security expectation:

- The SDK should not silently upgrade untrusted data to trusted state.
- Applications should prefer HTTPS and trusted endpoint lists.
- Server-side applications must not pass user-controlled RPC URLs into `Client` without allowlisting and egress controls.

### Layer 1

Layer 1 RPC responses can still be wrong if served by a malicious or faulty endpoint. Consensus truth comes from the blockchain, not from a single HTTP response.

Security expectation:

- The SDK should construct requests correctly and reject malformed responses where practical.
- Applications should use multiple trusted endpoints or independent verification for high-value decisions.

### Nexus Layer 2

Nexus data is an indexed/query view. It is useful for social and application discovery, but it is not the canonical consensus source.

Security expectation:

- Nexus helpers should be documented as Layer 2 helpers.
- Security-sensitive actions should validate relevant Layer 1 state where appropriate.

### Browser runtime

The browser runtime is hostile compared with a controlled backend: XSS, extensions, CDN compromise, script injection and user-device malware can all expose keys.

Security expectation:

- Browser examples should be read-only by default.
- Browser signing examples require explicit warnings.
- CDN usage should prefer pinned versions and, when possible, Subresource Integrity or self-hosting.

## Threat model

### Assets to protect

- User private keys.
- Signed transaction integrity.
- Transaction amount precision.
- User intent and authority selection.
- Memo plaintext confidentiality and integrity expectations.
- Application availability under RPC failure.
- Package consumers from supply-chain compromise.

### Threat actors

- Malicious public RPC operator.
- Network attacker/MITM when HTTP or compromised TLS trust is used.
- Malicious or compromised Nexus/indexing endpoint.
- Attacker controlling application input such as RPC URL, operation payload, memo ciphertext or asset string.
- Browser XSS attacker.
- npm/package supply-chain attacker.
- Honest application developer misunderstanding SDK boundaries.

### Representative attack paths

- User-controlled RPC URL in a backend produces SSRF.
- Malicious RPC returns manipulated head block data during transaction preparation, causing invalid/expired or confusing broadcast behavior.
- Malicious RPC returns malformed JSON-RPC response shape to confuse application error handling.
- Large asset string loses precision before signing.
- Modified encrypted memo ciphertext decrypts to altered plaintext because legacy memo encryption is unauthenticated.
- Browser app exposes raw WIF through XSS or dependency compromise.
- Build-time dependency compromise alters generated `dist/` or `lib/` artifacts.

## Cryptographic responsibilities

### What dblurt must do

- Serialize transactions exactly according to Blurt expectations.
- Compute transaction digests using the correct chain id.
- Sign digests locally with secp256k1 keys.
- Parse public/private keys consistently with Blurt formats.
- Preserve legacy memo compatibility when using the existing `#...` encrypted memo format.
- Avoid implying that memo keys are transaction authorities.

### What dblurt should not claim

- That JavaScript private-key operations are side-channel hardened.
- That password-derived keys from `fromLogin` are protected by a modern KDF.
- That legacy encrypted memos provide modern authenticated encryption.
- That browser signing is safe merely because the SDK works in browsers.

### Protocol compatibility constraints

Some weaknesses are inherited from protocol or legacy ecosystem compatibility. Those should be made explicit rather than hidden.

Examples:

- Password-to-key derivation via `username + role + password` and single SHA-256 is legacy-compatible, not a general password KDF.
- Existing encrypted memo format is legacy-compatible and uses AES-CBC without a modern authentication tag.
- Signature canonicality and verification policy may need to match consensus/client compatibility rather than modern application-auth defaults.

## Transaction signing and broadcasting architecture

The signing path should be understood as two separate phases:

```text
prepare transaction from RPC-derived chain properties
        │
sign exact transaction locally
        │
broadcast signed transaction
        │
interpret result or ambiguous network failure
```

Security implications:

- `prepareTransaction()` depends on RPC data such as head block number, head block id and time.
- A malicious RPC cannot forge a signature but can influence expiration/reference data and user-visible state.
- Broadcast retries must be handled differently from read-only calls because an ambiguous timeout may mean the transaction was accepted, rejected or still propagating.
- Applications should keep and surface the local transaction id when broadcast status is ambiguous.

## Package and build trust

The published npm package is part of the security boundary for consumers.

Current intended package contents:

```text
README.md
LICENSE
package.json
lib/
dist/
guide/
```

Repository-only artifacts such as tests, examples, AI context, architecture notes and docs-check tooling are not currently part of the npm payload.

Security expectations:

- Generated `lib/` and `dist/` should be reproducible from source during release validation.
- Runtime dependency vulnerability scans should pass before publication.
- Dev dependency issues should be tracked separately from runtime consumer risk.
- Source maps should be an explicit release decision, not accidental cargo.

## Classification of current findings

| Finding | Classification | Security architecture decision |
| --- | --- | --- |
| Asset amount precision loss through JavaScript `number` | Implementation bug with transaction-integrity impact | SDK responsibility; should be fixed before a security-branded release. |
| `cryptoUtils.isWif()` false-negative for valid WIF | Implementation bug | SDK responsibility; fix with tests. |
| Legacy encrypted memo malleability / no ciphertext authentication | Accepted protocol/legacy limitation unless a new format is introduced | Do not silently change existing format; document limitation and consider versioned authenticated format later. |
| Memo nonce based on time/counter and `Math.random` seed | Architectural weakness in legacy memo helper | Improve uniqueness if compatible; document nonce uniqueness requirements. |
| `PrivateKey.fromLogin()` weak KDF | Accepted legacy compatibility API | Keep for compatibility; document as legacy, not a modern KDF. |
| `PublicKey.verify(..., { strict: false })` | Compatibility decision requiring confirmation | Preserve if chain compatibility requires it; expose/document strict app-auth behavior only by design. |
| Arbitrary RPC endpoint URLs / SSRF in backend apps | Application concern with optional SDK guardrail opportunity | Applications must allowlist; SDK may later expose endpoint validation hooks. |
| No HTTPS enforcement | Operational recommendation / compatibility decision | Recommend HTTPS; do not break local tests/private deployments without strict opt-in. |
| Broadcast hang/retry ambiguity | Architectural weakness in transport policy | SDK responsibility to define clearer broadcast semantics. |
| Minimal JSON-RPC response validation | Defense-in-depth implementation weakness | SDK should validate response shape before error/result handling. |
| Constant JSON-RPC id `0` | Intentional legacy behavior with weak diagnostics | Not urgent for one-request-per-call, but future transports should use unique ids. |
| Browser signing risk | Application/runtime concern | Docs must warn; SDK cannot make arbitrary browser key custody safe. |
| CDN script without SRI | Operational recommendation | Prefer self-hosting or SRI where feasible. |
| Runtime dependency audit clean | Current positive evidence | Preserve with CI. |
| Dev dependency low vulnerabilities / install script | Build supply-chain risk | Track separately; not a runtime consumer vulnerability by itself. |
| Runtime caret dependency ranges | Supply-chain policy decision | Consider tighter ranges for crypto-critical packages. |

## Security invariants for future changes

Future changes should preserve these invariants:

1. Private keys are never sent to RPC by SDK code.
2. Layer 1 remains the canonical source of blockchain truth.
3. Nexus helper APIs are labeled and treated as Layer 2/indexed views.
4. Browser examples remain read-only unless explicitly marked as signing examples with warnings.
5. Side-effectful broadcast examples name the required authority and irreversible effects.
6. Generated artifacts are not manually edited.
7. The npm package payload remains intentional and reviewed.
8. Any new crypto format must be versioned and compatibility-scoped.
9. Any retry policy for broadcast must preserve the distinction between safe read retries and ambiguous transaction submission.
10. Asset serialization must be exact before signing.

## Security review process

Recommended recurring review gates:

### Per change

- `npm run lint`
- `npm run typecheck`
- `npm test`
- `npm run docs:check` when docs/examples/API documentation changed
- targeted tests for crypto, serializer, transport or package changes

### Before npm publication

- clean git status;
- build from source;
- compare generated artifacts policy;
- runtime dependency audit;
- package dry-run review;
- clean consumer smoke for CommonJS, TypeScript and browser bundle;
- no hard-coded secrets in examples/docs;
- review of generated `dist/` and source-map decision.

### Periodic specialized audits

- Cryptography audit: signing, memo compatibility, WIF, nonce, side-channel assumptions.
- Transport audit: JSON-RPC validation, timeout/failover, broadcast ambiguity, SSRF guidance.
- Supply-chain audit: dependencies, provenance, generated artifacts, npm package payload.
- Browser audit: CDN use, CSP/SRI, wallet integration, XSS/key-custody guidance.
- Fuzz/property tests: asset parser, serializers, memo decoder, RPC response parser.

## Roadmap

### Security milestone 1: correctness before claims

- Fix exact asset serialization.
- Fix WIF validation.
- Add negative tests for malformed RPC responses and memo ciphertext.
- Clarify broadcast timeout/retry semantics.

### Security milestone 2: compatibility-aware cryptography

- Decide whether legacy memo limitations are documentation-only or require a new authenticated format.
- Confirm signature strictness requirements.
- Add cross-client fixtures against known Blurt-compatible implementations.

### Security milestone 3: production hardening

- Add optional endpoint validation/strict transport configuration.
- Add dependency/security audit CI.
- Define release provenance policy.
- Decide whether source maps ship in npm/browser CDN artifacts.

## Summary

dblurt should be secure by being explicit: exact in transaction construction, conservative in signing, honest about legacy protocol limitations, clear about RPC trust, and strict about package/release hygiene.

The SDK should fix bugs inside its boundary, document accepted protocol constraints, and avoid absorbing application-layer responsibilities that would turn it into a wallet, firewall, indexer or framework.
