Skip to content

08 Notes

What I find interesting

Posts I saved from X, sorted into pamphlets by subject. My own short notes are below them.

Saved posts
27
Pamphlets
5
Notes
8
Latest
Feb 26, 2026
TIL
6
Tags
20

05 Pamphlets · one per subject

  1. 7 postsAI agents and toolsHow people build with AI agents, and what they learn doing it.
  2. 3 postsWriting and storytellingHow to tell a story, open a post and write so people keep reading.
  3. 5 postsWork and careerDecisions, leverage, job search and interviews.
  4. 3 postsMemory, sleep and learningWhat research says about how the brain remembers, rests and learns.
  5. 9 postsMindset and how to liveShort pieces on attitude, discipline and seeing things clearly.

08 My own notes · newest first · open one to read it

  1. 01TIL: ECPay Webhook Verification on EdgeECPay webhooks need CheckMacValue verification. On Edge Runtime, no crypto.createHash.Tags: tilecpaytaiwanedge

    ECPay webhooks need CheckMacValue verification. On Edge Runtime, no crypto.createHash.

    Web Crypto Version

    async function sha256(message: string): Promise<string> {
      const msgBuffer = new TextEncoder().encode(message);
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }
    
    function generateCheckMac(params: Record<string, string>): Promise<string> {
      const sorted = Object.keys(params)
        .filter(k => k !== 'CheckMacValue')
        .sort()
        .map(k => `${k}=${params[k]}`)
        .join('&');
    
      const raw = `HashKey=${HASH_KEY}&${sorted}&HashIV=${HASH_IV}`;
      const encoded = encodeURIComponent(raw).toLowerCase();
    
      return sha256(encoded).then(hash => hash.toUpperCase());
    }

    Webhook Handler

    export async function POST(request: Request) {
      const formData = await request.formData();
      const params: Record<string, string> = {};
      formData.forEach((value, key) => {
        params[key] = value.toString();
      });
    
      const receivedMac = params.CheckMacValue;
      const expectedMac = await generateCheckMac(params);
    
      if (receivedMac !== expectedMac) {
        console.error('Invalid CheckMacValue', { received: receivedMac, expected: expectedMac });
        return new Response('0|InvalidCheckMac', { status: 400 });
      }
    
      if (params.RtnCode === '1') {
        // Payment successful - add credits
        // CustomField1 = email, CustomField2 = credit amount
        await addCredits(params.CustomField1, parseInt(params.CustomField2));
      }
    
      return new Response('1|OK');
    }

    Idempotency

    ECPay retries if you don’t respond 1|OK. Check if payment already processed:

    const existing = await kvGet(`payment:${params.MerchantTradeNo}`);
    if (existing) {
      return new Response('1|OK'); // Already processed
    }
    
    await addCredits(...);
    await kvPut(`payment:${params.MerchantTradeNo}`, 'processed');
    return new Response('1|OK');

    Gotcha

    URL encoding in CheckMacValue is lowercase. encodeURIComponent(raw).toLowerCase() — the .toLowerCase() is critical.

  2. 02TIL: FFmpeg Fails on AI Videos Without AudioAI-generated videos from photo animation (Veo, BytePlus, Kling) usually have no audio track. FFmpeg commands that assume audio will fail.Tags: tilffmpegvideoai

    AI-generated videos from photo animation (Veo, BytePlus, Kling) usually have no audio track. FFmpeg commands that assume audio will fail.

    The Error

    Stream map '0:a:0' matches no streams.

    Detection

    ffprobe -v error -select_streams a -show_entries stream=codec_type -of csv=p=0 input.mp4

    Returns audio if audio exists, empty if not.

    Fix: Add Silent Audio

    ffmpeg -i input.mp4 \
      -f lavfi -i anullsrc=r=44100:cl=stereo \
      -c:v copy -c:a aac -shortest \
      output.mp4
    • anullsrc generates silence
    • -shortest stops when video ends
    • -c:v copy avoids re-encoding video

    Safety Net: Optional Mapping

    FFmpeg 4.1+ supports optional streams:

    ffmpeg -i input.mp4 -map 0:v:0 -map 0:a:0? output.mp4
    #                                       ^ optional

    The ? makes audio optional. If missing, continues without error.

    TypeScript Pattern

    async function hasAudio(path: string): Promise<boolean> {
      const { stdout } = await exec(
        `ffprobe -v error -select_streams a -show_entries stream=codec_type -of csv=p=0 "${path}"`
      );
      return stdout.trim() === 'audio';
    }
    
    async function ensureAudio(input: string, output: string) {
      if (await hasAudio(input)) {
        await fs.copyFile(input, output);
        return;
      }
    
      const duration = await getDuration(input);
      await exec(`
        ffmpeg -i "${input}" \
          -f lavfi -i anullsrc=r=44100:cl=stereo \
          -c:v copy -c:a aac -shortest -t ${duration} \
          "${output}"
      `);
    }

    Always probe before processing. Never assume AI video has audio.

  3. 03TIL: Cloudflare R2 Video Archival PatternVideos from AI providers expire (usually 24h). Archive them to R2 for permanent storage.Tags: tilcloudflarer2video

    Videos from AI providers expire (usually 24h). Archive them to R2 for permanent storage.

    The Pattern

    // When video generation completes
    async function archiveVideos(jobId: string, cdnUrls: string[]) {
      const r2 = getR2Binding();
    
      for (let i = 0; i < cdnUrls.length; i++) {
        const response = await fetch(cdnUrls[i]);
        const blob = await response.arrayBuffer();
        await r2.put(`videos/${jobId}/${i}.mp4`, blob);
      }
    
      // Update job record with R2 keys instead of CDN URLs
      await kvPut(`job:${jobId}`, JSON.stringify({
        ...job,
        videoUrls: cdnUrls.map((_, i) => `videos/${jobId}/${i}.mp4`)
      }));
    }

    Backward Compatibility

    Old jobs have CDN URLs (start with http). New jobs have R2 keys.

    function getVideoUrl(storedUrl: string, jobId: string, index: number): string {
      if (storedUrl.startsWith('http')) {
        return storedUrl; // Legacy CDN URL
      }
      return `/api/proxy-video?jobId=${jobId}&index=${index}`; // R2 proxy
    }

    Proxy Route

    R2 objects aren’t public by default. Serve via proxy:

    export async function GET(request: Request) {
      const { searchParams } = new URL(request.url);
      const jobId = searchParams.get('jobId');
      const index = searchParams.get('index') || '0';
    
      const r2 = getR2Binding();
      const object = await r2.get(`videos/${jobId}/${index}.mp4`);
    
      if (!object) {
        return new Response('Not found', { status: 404 });
      }
    
      return new Response(object.body, {
        headers: {
          'Content-Type': 'video/mp4',
          'Cache-Control': 'public, max-age=31536000', // 1 year
        }
      });
    }

    Key Insight

    KV records can expire (24h TTL). R2 objects persist forever. Even if job metadata disappears, videos remain accessible if you know the key pattern.

  4. 04Prompting: Be Specific About FormatWhen working with LLMs, always specify the output format explicitly.Tags: aipromptingtil

    When working with LLMs, always specify the output format explicitly.

    Instead of: “Summarize this document”

    Try: “Summarize this document in 3 bullet points, each under 20 words”

    The more specific you are about structure, the more consistent your outputs.

  5. 05TIL: IBKR Flex QueriesInteractive Brokers' Flex Queries are incredibly powerful for automating trade reports. You can pull historical trades, positions, and account data via XML.Tags: tradingibkrtil

    Interactive Brokers’ Flex Queries are incredibly powerful for automating trade reports. You can pull historical trades, positions, and account data via XML.

    Key gotcha: The token expires after 24 hours of inactivity. Build in automatic token refresh if you’re using it for daily automation.

  6. 06Podcast: Naval on WealthRe-listened to the Naval podcast on wealth. The key insight that stuck with me this time:Tags: podcastwealthphilosophy

    Re-listened to the Naval podcast on wealth. The key insight that stuck with me this time:

    “Seek wealth, not money or status. Wealth is having assets that earn while you sleep.”

    This is why I’m focused on building products and systems rather than trading time for money.

  7. 07Cloud Run: Always Use ConcurrencyRookie mistake I made early on: leaving Cloud Run concurrency at 1.Tags: gcpcloud-runtil

    Rookie mistake I made early on: leaving Cloud Run concurrency at 1.

    For most web services, you want concurrency at 80-100. Your Python/Node service can handle multiple concurrent requests — that’s the point of async.

    Low concurrency = more instances = higher costs.

  8. 08Book: Psychology of MoneyFinished Morgan Housel's "Psychology of Money." Best takeaways:Tags: booksinvestingpsychology

    Finished Morgan Housel’s “Psychology of Money.” Best takeaways:

    1. Wealth is what you don’t see (spending less than you earn)
    2. Compounding needs time, so start early and stay in the game
    3. Room for error is the most important thing in any plan

    Simple ideas, but the real challenge is actually living them.