本文へ移動
cccskills
無料GitHub で公開

nostr-replaceable-event-mutation-overwrite

Fix silent data loss when mutating Nostr replaceable events (Kind 0 profile, Kind 3 contact/follow list, Kind 10002 relay list, etc.) in client apps. Use when: (1) Following someone wipes the user's entire follow list, (2) Updating profile metadata loses existing fields, (3) Fresh browser session or mobile login causes data loss on first action, (4) Replaceable event mutation uses stale or null cached state. Root cause: Nostr replaceable events are full-replace (no partial update), so publishing based on stale/unloaded cache overwrites the canonical version. Applies to any Nostr client using React, Flutter, or similar reactive frameworks where query state may not be loaded when a mutation fires.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md7.5 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Nostr Replaceable Event Mutation Overwrite

Problem

Nostr replaceable events (Kind 0, 3, 10002, etc.) use a full-replace model: publishing a new event completely replaces the previous one. If a client publishes a mutation based on stale, incomplete, or null cached state, it silently overwrites the canonical version on relays, causing data loss. The most common case is follow list (Kind 3) wipes when a user follows someone before the client has loaded their existing contact list.

Context / Trigger Conditions

  • User reports "I followed someone and lost all my other follows"
  • Follow/unfollow action on a fresh browser session or mobile login
  • Profile update loses existing metadata fields
  • Relay list update drops existing relays
  • Any mutation on a replaceable event where the UI passes cached state to the mutation function
  • React Query / TanStack Query data is undefined when mutation fires (query still loading)
  • The mutation function accepts the current event as a parameter from the UI layer

Solution

1. Always Fetch Fresh State Inside the Mutation

Never rely solely on the UI's cached/query state. Fetch the latest version of the replaceable event directly from the relay inside the mutation function, before publishing:

// BAD: Relies on UI cache which may be null/stale
mutationFn: async ({ targetPubkey, currentContactList }) => {
  const currentTags = currentContactList?.tags || []; // null -> [] -> data loss!
  // ... publish with only the new follow
}

// GOOD: Fetches fresh from relay before mutating
mutationFn: async ({ targetPubkey, currentContactList }) => {
  let bestContactList = currentContactList;

  try {
    const relayEvents = await nostr.query([
      { kinds: [3], authors: [userPubkey], limit: 1 },
    ], { signal: AbortSignal.timeout(5000) });

    const relayContactList = relayEvents
      .sort((a, b) => b.created_at - a.created_at)[0] || null;

    if (relayContactList) {
      // NIP-01 already fixes which copy of a replaceable event wins:
      // the higher created_at, and on an exact tie the lower event id.
      // Never compare tag counts — a shorter list is what a legitimate
      // unfollow produces.
      const passed = currentContactList;
      const isNewer =
        !passed ||
        relayContactList.created_at > passed.created_at ||
        (relayContactList.created_at === passed.created_at &&
          relayContactList.id < passed.id);
      if (isNewer) {
        bestContactList = relayContactList;
      }
    }
  } catch {
    // The read failed. It cannot be told apart from "the relay holds
    // nothing", so refuse to publish rather than replacing from a guess.
    throw new Error('Could not confirm the current list. Please try again.');
  }

  if (!bestContactList) {
    throw new Error('Could not load existing data. Please try again.');
  }

  // Now mutate bestContactList...
}

2. Newest Wins, Per NIP-01

Order the relay's version against the cached one by created_at, and on an exact tie by the lower event id. That is the rule relays themselves apply, so it is the only choice that converges.

Do not compare tag counts. "Use whichever has MORE data" looks safe and is not: the newer, authoritative list is shorter whenever the user removed someone, so preferring the longer copy silently resurrects every unfollow, unmuted account, or deleted relay — and republishes it. The heuristic cannot tell "this copy is stale" from "the user removed something", because those two produce the identical shape.

A source that carries no timestamp at all — a bare cached array, a derived REST index — has unknowable freshness, not old freshness. It may seed an empty state, but it must lose to any copy that can name a created_at.

Worked example, including the persistence migration that gives the local cache a timestamp to be ordered by: divinevideo/divine-mobile#8266.

3. Refuse to Publish on Total Failure

If neither the relay fetch nor the UI cache provides data, throw an error instead of publishing an empty/minimal replaceable event. A user-friendly error message is always better than silent data loss.

4. Apply to Both Directions

Apply this pattern to ALL mutation directions (follow AND unfollow, add AND remove relay, update AND clear profile fields). The unfollow path is just as dangerous as follow.

Verification

Cold-start overwrite:

  1. Open the app in a private/incognito browser window
  2. Log in with an account that has multiple follows
  3. Navigate to a profile and tap Follow IMMEDIATELY (before the page fully loads)
  4. Check that the follow count increased by 1 (not reset to 1)

Cross-device removal — the case a tag-count heuristic passes and still corrupts:

  1. On a second client, unfollow two of several accounts
  2. Cold-start the first client and confirm the removals are still gone
  3. Follow one new account there, then read the relay's kind 3 back and confirm the two removed accounts did not reappear in its p tags

Example

// Real-world fix from divine-web useFollowUser hook
export function useFollowUser() {
  const { nostr } = useNostr();

  return useMutation({
    mutationFn: async ({ targetPubkey, currentContactList }) => {
      // Step 1: Fetch fresh from relay
      let bestContactList = currentContactList;
      try {
        const events = await nostr.query([
          { kinds: [3], authors: [user.pubkey], limit: 1 }
        ], { signal: AbortSignal.timeout(5000) });
        const relayList = events.sort((a, b) => b.created_at - a.created_at)[0];
        if (relayList) {
          const relayFollows = relayList.tags.filter(t => t[0] === 'p').length;
          const cachedFollows = currentContactList?.tags.filter(t => t[0] === 'p').length ?? 0;
          if (relayFollows >= cachedFollows) bestContactList = relayList;
        }
      } catch { /* fall back to cached */ }

      // Step 2: Refuse if no data
      if (!bestContactList) throw new Error('Could not load follow list');

      // Step 3: Mutate safely
      const tags = [...bestContactList.tags, ['p', targetPubkey]];
      return publishEvent({ kind: 3, tags, content: bestContactList.content });
    }
  });
}

Notes

  • This pattern applies to ALL Nostr replaceable event kinds: Kind 0 (profile), Kind 3 (contacts), Kind 10002 (relay list), Kind 10000 (mute list), Kind 30000+ (addressable)
  • The race condition is most common on mobile browsers where network is slower and users tap quickly
  • Safety check dialogs (like "are you sure?") don't help because they check the same stale cache - the fix must be inside the mutation itself
  • The 5-second timeout on the relay fetch is a reasonable balance between safety and UX
  • Consider also disabling the mutation button while the initial query is loading, as a belt-and-suspenders approach

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

divinevideo のスキルをすべて見る

このスキルの問題を報告する