[nextjs]SNS Server-14(myapp24)

👉🏻 myapp24에서는 Announce (Boost) 를 구현합니다.
myapp24 implements Announce (Boost).

👉🏻 부스트는 다른 사람이 쓴 글을 내 팔로워에게 알리는 기능입니다.
Boost is a feature that shares posts written by others with your followers.

👉🏻 내가 쓴 글은 부스트를 할 수 없습니다.
I cannot boost the posts I have written.

📁 전체 프로젝트 구조 / Overall Project Structure

myapp24/  
├── app/  (Next.js App Router)
│   ├── .well-known/webfinger/route.ts  -> webfinger
│   ├── api/follow/route.ts    -> Follow API(temporary)
│   ├── api/announce/route.ts  -> Boost(Announcement)
│   ├── api/like/route.ts.     -> Like API
│   ├── api/posts/route.ts     -> Writing API
│   ├── api/timeline/route.ts  -> Timeline API
│   ├── users/[username]/
│   │   ├── statuses/[id]/route.ts -> Indivisual Post
│   │   ├── route.ts               -> Acotr Information
│   │   ├── followers/route.ts     -> Followers List
│   │   ├── following/route.ts     -> Following List
│   │   ├── inbox/route.ts         -> Inbox
│   │   └── outbox/route.ts        -> outbox
│   ├── usersui/[username]/page.tsx  -> Timeline UI
│   ├── layout.tsx, page.tsx, globals.css
│   └── favicon.ico
├── lib/
│   ├── ap.ts                  -> Follow Accept
│   └── db.ts                  -> DB connection
├── data/
│   └── keys/                  -> private.pem, public.pem
├── data.sqlite                -> Database
├── Caddyfile                  -> https 
└── package.json

📁 프로젝트 시작(myapp24)
Project Start (myapp24)

npx create-next-app@latest

📁 SQLite설치 / Installing SQLite

cd ~/myapp24
npm install better-sqlite3
npm install -D @types/better-sqlite3

📁 DDNS,https설정 / DDNS,https settings

📁 도메인허용, @userid 사용하기
Allowing domains, using @userid

— next.config.ts

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* allow domain*/
  allowedDevOrigins: ['aloy-horizon.duckdns.org', '*.duckdns.org'],

  /* host.domain.org/@userid */
  async rewrites() {
    return [
      {
        source: '/@:username',
        destination: '/usersui/:username',
      },
    ]
  }
};


export default nextConfig;

📁 테이블 추가 / Add Table

CREATE TABLE IF NOT EXISTS announces (
  id TEXT PRIMARY KEY, 
  username TEXT, 
  object TEXT, 
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_announces_obj_user ON announces(object, username);
CREATE INDEX IF NOT EXISTS idx_announces_username ON announces(username);

📁 라우트추가 / Add route

✔️ myapp24/app/api/announce/route.ts 생성

// myapp24/app/api/announce/route.ts
// myapp24 ✅

import { NextRequest, NextResponse } from 'next/server';
import db from '@/lib/db';
import { signedFetch, getActorData, sendAnnounce, sendUndoAnnounce } from '@/lib/ap';
const DOMAIN = process.env.DOMAIN || 'aloy-horizon.duckdns.org'; 

export async function POST(req: NextRequest) {
  try {
    const { username, target } = await req.json();
    if (!username || !target) {
      return NextResponse.json({ ok: false, error: 'username and target required' }, { status: 400 });
    }

    if (target.startsWith(`https://${DOMAIN}/users/${username}`)) {
      return NextResponse.json({ ok: false, error: 'cannot boost own post' }, { status: 400 });
    }

    let apObjectId: string = target;
    let inbox: string;

    try {
      const postRes = await signedFetch(target, username);
      if (postRes.ok) {
        const postData = await postRes.json();
        apObjectId = postData.id || target;
        const attributedTo = postData.attributedTo || postData.actor;
        const actorUrl = typeof attributedTo === 'string' ? attributedTo : attributedTo?.id;
        if (!actorUrl) throw new Error('no actor');
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      } else {
        const url = new URL(target);
        const parts = url.pathname.split('/');
        const usersIdx = parts.indexOf('users');
        if (usersIdx === -1) throw new Error('invalid target');
        const actorUrl = `${url.origin}${parts.slice(0, usersIdx + 2).join('/')}`;
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      }
    } catch (e) {
      return NextResponse.json({ ok: false, error: 'invalid target post id' }, { status: 400 });
    }

    const existing = db.prepare('SELECT id FROM announces WHERE object = ? AND username = ?').get(apObjectId, username) as any;
    if (existing) {
      return NextResponse.json({ ok: true, alreadyAnnounced: true, id: existing.id });
    }

    const result = await sendAnnounce(inbox, apObjectId, username);

    if (result.ok) {
      db.prepare('INSERT INTO announces (id, username, object) VALUES (?, ?, ?)').run(result.announceDoc.id, username, apObjectId);
    }

    return NextResponse.json({ ok: true, result });

  } catch (e: any) {
    console.error('[Announce POST]', e);
    return NextResponse.json({ ok: false, error: e.message }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { username, target } = await req.json();
    if (!username || !target) {
      return NextResponse.json({ ok: false, error: 'username and target required' }, { status: 400 });
    }

    let apObjectId: string = target;
    let inbox: string;

    try {
      const postRes = await signedFetch(target, username);
      if (postRes.ok) {
        const postData = await postRes.json();
        apObjectId = postData.id || target;
        const attributedTo = postData.attributedTo || postData.actor;
        const actorUrl = typeof attributedTo === 'string' ? attributedTo : attributedTo?.id;
        if (!actorUrl) throw new Error('no actor');
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      } else {
        const url = new URL(target);
        const parts = url.pathname.split('/');
        const usersIdx = parts.indexOf('users');
        if (usersIdx === -1) throw new Error('invalid target');
        const actorUrl = `${url.origin}${parts.slice(0, usersIdx + 2).join('/')}`;
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      }
    } catch (e) {
      return NextResponse.json({ ok: false, error: 'invalid target post id' }, { status: 400 });
    }

    const row = db.prepare('SELECT id FROM announces WHERE object = ? AND username = ?').get(apObjectId, username) as any;
    if (!row) {
      return NextResponse.json({ ok: true, alreadyUnAnnounced: true });
    }

    const result = await sendUndoAnnounce(inbox, row.id, apObjectId, username);
    db.prepare('DELETE FROM announces WHERE id = ?').run(row.id);

    return NextResponse.json({ ok: true, result });

  } catch (e: any) {
    console.error('[Announce DELETE]', e);
    return NextResponse.json({ ok: false, error: e.message }, { status: 500 });
  }
}

📁 코드 수정 / Code Modification

✔️myapp24/lib/db.ts

db.exec(`
  -- myapp24 ✅  Boost(Announcement)
  CREATE TABLE IF NOT EXISTS announces (
    id TEXT PRIMARY KEY, 
    username TEXT, 
    object TEXT, 
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`);
db.exec(`
... ...
  -- myapp24 ✅
  CREATE INDEX IF NOT EXISTS idx_announces_obj_user ON announces(object, username);
  CREATE INDEX IF NOT EXISTS idx_announces_username ON announces(username);
`);

✔️myapp24/lib/ap.ts

... ...

// getActorData아래에 코드 추가하기
// Add code below getActorData

// ✅ myapp24 - Send Announce(Boost) 
export async function sendAnnounce(toInbox: string, targetPostId: string, username: string) {
  const actorId = `https://${DOMAIN}/users/${username}`;
  const announceId = `${actorId}/announces/${crypto.randomUUID()}`;

  const doc = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    id: announceId,
    type: 'Announce',
    actor: actorId,
    object: targetPostId,
    published: new Date().toISOString(),
    to: ['https://www.w3.org/ns/activitystreams#Public'],
    cc: [`${actorId}/followers`, `${actorId}`],
  };

  const body = JSON.stringify(doc);
  const url = new URL(toInbox);
  const digest = `SHA-256=${crypto.createHash('sha256').update(body).digest('base64')}`;
  const date = new Date().toUTCString();
  const signingString = `(request-target): post ${url.pathname}\nhost: ${url.host}\ndate: ${date}\ndigest: ${digest}`;
  const signer = crypto.createSign('sha256');
  signer.update(signingString);
  const signature = signer.sign(PRIVATE_KEY, 'base64');
  const keyId = `${actorId}#main-key`;
  const sigHeader = `keyId="${keyId}",headers="(request-target) host date digest",signature="${signature}"`;

  console.log(`🔁 [${username}] Announce 전송 -> ${toInbox} (${targetPostId})`);

  const res = await fetch(toInbox, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/activity+json',
      'Date': date,
      'Digest': digest,
      'Signature': sigHeader,
      'Host': url.host
    },
    body
  });

  const text = await res.text();
  console.log(`📬 Announce 결과: ${res.status}`, text);
  return { ok: res.ok, status: res.status, text, announceDoc: doc };
}

// ✅ myapp24 - Undo Announce
export async function sendUndoAnnounce(toInbox: string, announceId: string, targetPostId: string, username: string) {
  const actorId = `https://${DOMAIN}/users/${username}`;
  const undoId = `${actorId}#undo/${crypto.randomUUID()}`;

  const undoDoc = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    id: undoId,
    type: 'Undo',
    actor: actorId,
    published: new Date().toISOString(),
    to: ['https://www.w3.org/ns/activitystreams#Public'],
    cc: [`${actorId}/followers`],
    object: {
      id: announceId,
      type: 'Announce',
      actor: actorId,
      object: targetPostId,
      published: new Date().toISOString(),
      to: ['https://www.w3.org/ns/activitystreams#Public'],
      cc: [`${actorId}/followers`],
    }
  };

  const body = JSON.stringify(undoDoc);
  const url = new URL(toInbox);
  const digest = `SHA-256=${crypto.createHash('sha256').update(body).digest('base64')}`;
  const date = new Date().toUTCString();
  const signingString = `(request-target): post ${url.pathname}\nhost: ${url.host}\ndate: ${date}\ndigest: ${digest}`;
  const signer = crypto.createSign('sha256');
  signer.update(signingString);
  const signature = signer.sign(PRIVATE_KEY, 'base64');
  const keyId = `${actorId}#main-key`;
  const sigHeader = `keyId="${keyId}",headers="(request-target) host date digest",signature="${signature}"`;

  console.log(`↩ [${username}] Undo Announce 전송 -> ${toInbox}`);

  const res = await fetch(toInbox, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/activity+json',
      'Date': date,
      'Digest': digest,
      'Signature': sigHeader,
      'Host': url.host
    },
    body
  });

  const text = await res.text();
  console.log(`📬 Undo Announce 결과: ${res.status}`, text);
  return { ok: res.ok, status: res.status, text, undoDoc };
}

📁 테스트 / Test

✔️ POST,DELETE 메소드 라우트
POST and DELETE method routes

# -- freelifemakers.com(gotosocial) --
# 부스트 / Boost

curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'


# 부스트 취소 / Cancle Boost

curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'

# -- mastodon server ---
# 부스트 / Boost

curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089028658055432"}'

# 부스트 취소 / Cancle Boost

curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089028658055432"}'

# 내 글 부스트 시도 -> 400 에러 나야 정상
# Attempting to boost my post -> A 400 error is the expected result.

curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://aloy-horizon.duckdns.org/users/user1/statuses/e6c99652-572f-491a-9e61-05e67b0d58fc"}'

✔️ GTS Server

# GTS Boost

myapp24 % curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'

{"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","announceDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/announces/66cb2e85-0bd0-4e6c-856a-d77070cc3807","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG","published":"2026-08-27T00:50:15.162Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers","https://aloy-horizon.duckdns.org/users/user1"]}}}%                                                              
gimdaegyeong@gimdaegyeong-ui-MacBookAir myapp24 %   

# GTS Boost Cancle  

myapp24 % curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'

{"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","undoDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1#undo/34cb45a0-c1f1-4bcb-bb64-2cb9a0aba982","type":"Undo","actor":"https://aloy-horizon.duckdns.org/users/user1","published":"2026-08-27T00:53:42.406Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers"],"object":{"id":"https://aloy-horizon.duckdns.org/users/user1/announces/66cb2e85-0bd0-4e6c-856a-d77070cc3807","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG","published":"2026-08-27T00:53:42.406Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers"]}}}}%   
GTS Boost

✔️ Mastodon Server

— 게시물 주소 / Post address

https://mastodon.social/@mcnees/117089028658055432

# Boost

myapp24 % curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089028658055432"}'

{"ok":true,"result":{"ok":true,"status":202,"text":"","announceDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/announces/827c782f-9422-43d4-bc14-0fed1cf648b6","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/mcnees/statuses/117089028658055432","published":"2026-08-27T00:58:19.780Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers","https://aloy-horizon.duckdns.org/users/user1"]}}}%                                                                                                 
gimdaegyeong@gimdaegyeong-ui-MacBookAir myapp24 % 

# Cancle Boost

myapp24 % curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089028658055432"}'
{"ok":true,"result":{"ok":true,"status":202,"text":"","undoDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1#undo/3c643e41-dcb6-4e5c-ae6c-21c0ab5820b3","type":"Undo","actor":"https://aloy-horizon.duckdns.org/users/user1","published":"2026-08-27T00:59:54.564Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers"],"object":{"id":"https://aloy-horizon.duckdns.org/users/user1/announces/827c782f-9422-43d4-bc14-0fed1cf648b6","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/mcnees/statuses/117089028658055432","published":"2026-08-27T00:59:54.564Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers"]}}}}%                                                                                                                                                         
Mastodon Boost

✔️ 내 글 부스트 차단확인 / Check if my post is blocked from the Boost feature

myapp24 % curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://aloy-horizon.duckdns.org/users/user1/statuses/e6c99652-572f-491a-9e61-05e67b0d58fc"}'

{"ok":false,"error":"cannot boost own post"}%                                                                                                                           

📁 지금까지 작업한 내용과 라우트 입니다.
Here is the work done so far and the routes.

✔️ 브라우저에서 테스트 할 수 있는 라우트
Routes that can be tested in a browser

# 1. WebFinger
https://aloy-horizon.duckdns.org/.well-known/webfinger?resource=acct:user1@aloy-horizon.duckdns.org

# 2. Actor (프로필 / Profile)
https://aloy-horizon.duckdns.org/users/user1

# 3. Followers (남이 나 팔로우 / Someone follows me)
https://aloy-horizon.duckdns.org/users/user1/followers

# 4. Following (내가 남을 팔로우 / I follow others)
https://aloy-horizon.duckdns.org/users/user1/following

# 5. Outbox (내 글 목록 / My post list)
https://aloy-horizon.duckdns.org/users/user1/outbox

# 6. 타임라인 / Timeline

# - 타임라인UI / Timeline UI
https://aloy-horizon.duckdns.org/usersui/user1
# or
https://aloy-horizon.duckdns.org/@user1

# - 타임라인API / Timeline API
https://aloy-horizon.duckdns.org/api/timeline?username=user1

# 7. 개별 글(글 상세) / indivisual posts(Post Details)[posts, inbox_posts]
https://aloy-horizon.duckdns.org/users/user1/statuses/[ID]

# ex)
# posts table
https://aloy-horizon.duckdns.org/users/user1/statuses/e6c99652-572f-491a-9e61-05e67b0d58fc

# inbox_posts table
https://aloy-horizon.duckdns.org/users/user1/statuses/01M0P8VYEQTFW28N97W6MG8PY5

✔️ 터미널에서만 테스트 가능한 라우트
Routes that can only be tested in the terminal

# 팔로우 (following 1로 증가)
# Follow (following increased to 1)

curl -X POST https://aloy-horizon.duckdns.org/api/follow \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","target":"https://freelifemakers.com/users/user1"}'

# 언팔로우 (following 0으로 감소)
# Unfollow (following count reduced to 0)

curl -X DELETE https://aloy-horizon.duckdns.org/api/follow \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","target":"https://freelifemakers.com/users/user1"}'

# 글 쓰기 (outbox 7로 증가 + 팔로워들에게 배달)
# Writing a post (added to outbox 7 + delivered to followers)

curl -X POST https://aloy-horizon.duckdns.org/api/posts \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","content":"Hello Fediverse! #test"}'

# 좋아요 실행 / Likes
curl -X POST https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}'

# 좋아요 취소하기 / Undo Likes
curl -X DELETE https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@Gargron/114559081070832514"}'

# 부스트 실행 / Boost
curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'

# 부스트 취소 / Cancle Boost
curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/@user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG"}'

요한복음 8장 32절 / John 8:32

“그리고 너희는 진리를 알게 될 것이며, 진리가 너희를 자유롭게 할 것이다.”

“Then you will know the truth ,and the truth will set you free”

Leave a Reply