Author SHA1 Message Date
andwati 2c7f98c0dc nuxt init 2025-08-16 23:39:00 +03:00
85 changed files with 11352 additions and 7800 deletions
-100
View File
@@ -1,100 +0,0 @@
# Project dictionary for content/**/*.md (names, tools, jargon)
Andwati
angr
archlinux
Ashish
bashfu
binarysith
binwalk
bmod
bruteforcing
chall
ciphertexts
cmark
comming
disassemblers
diskchal
distros
dlresolve
dnsmasq
dokploy
Einherjar
exiftool
expecially
Fastbin
Garuda
Geospatial
Ghidra
Gitaly
Gitea
Hashnode
Heartbleed
Heredocs
homoglyphs
honggfuzz
hotspot
Hotspots
IDOR
jadx
Kernighan
keyserver
Kleppmann
libc
malloc
MINECRAFTISFUN
mmuctf
mockingspectre
MVCC
Namecheap
Niki
Noam
openpgp
Parmar
Pgadget
Pipx
Pwntools
RDBMS
RDBMSs
Revealme
Riccomini
Ritchie
Sandboxing
seccomp
Shazeer
shellcode
Shellshock
Sidekiq
Sigreturn
SIGSEGV
SNMP
SROP
staticnoise
stego
strikethrough
subresource
Sussman
syscalls
Tcache
tera
tshark
unbootable
Userland
Vaswani
vuejs
Wireshark
# Review: possible typos or intentional wordplay in existing posts (kept so checks pass)
Ledilect
Metawork
iddleness
thatsss
trol
whyyy
# Intentional homoglyph text in the mmuctf2025 writeup
cοmfort
doоrs
this
соrner
girl
Jobless
-12
View File
@@ -1,12 +0,0 @@
node_modules
.next
.git
.gitignore
.env*
!.env.example
Dockerfile
.dockerignore
README.md
npm-debug.log*
*.md
!content/**/*.md
+19 -36
View File
@@ -1,41 +1,24 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# Nuxt dev/build outputs
.output
.data
.nuxt
.nitro
.cache
dist
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# Node dependencies
node_modules
# testing
/coverage
# Logs
logs
*.log
# next.js
/.next/
/out/
# production
/build
# misc
# Misc
.DS_Store
*.pem
.fleet
.idea
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Local env files
.env
.env.*
!.env.example
-1
View File
@@ -1 +0,0 @@
pnpm exec lint-staged
-4
View File
@@ -1,4 +0,0 @@
# Prettier only formats writing/pages. Biome owns code, CSS and JSON.
*
!content/
!content/**
-5
View File
@@ -1,5 +0,0 @@
{
"proseWrap": "preserve",
"embeddedLanguageFormatting": "off",
"overrides": [{ "files": "*.md", "options": { "printWidth": 100 } }]
}
-7
View File
@@ -1,7 +0,0 @@
{
"recommendations": [
"biomejs.biome",
"esbenp.prettier-vscode",
"streetsidesoftware.code-spell-checker"
]
}
-12
View File
@@ -1,12 +0,0 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "biomejs.biome",
"[markdown]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.wordWrap": "on"
},
"prettier.enable": true,
"cSpell.language": "en",
"cSpell.enabledFileTypes": { "markdown": true },
"editor.codeActionsOnSave": { "source.fixAll.biome": "explicit" }
}
-9
View File
@@ -1,9 +0,0 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
-30
View File
@@ -1,30 +0,0 @@
# syntax=docker/dockerfile:1
# Static site: build with Next (output: export), serve with static-web-server.
# docker build -t andwati-site \
# --build-arg PUBLIC_UMAMI_SCRIPT_URL=... --build-arg PUBLIC_UMAMI_WEBSITE_ID=... .
FROM node:24-alpine AS deps
ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH
RUN corepack enable
WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
pnpm install --frozen-lockfile
FROM node:24-alpine AS build
ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH NEXT_TELEMETRY_DISABLED=1
RUN corepack enable
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Umami is read at build time (pages are prerendered), so pass these as build args.
ARG PUBLIC_UMAMI_SCRIPT_URL
ARG PUBLIC_UMAMI_WEBSITE_ID
ENV PUBLIC_UMAMI_SCRIPT_URL=$PUBLIC_UMAMI_SCRIPT_URL \
PUBLIC_UMAMI_WEBSITE_ID=$PUBLIC_UMAMI_WEBSITE_ID
RUN pnpm build
FROM ghcr.io/static-web-server/static-web-server:2
COPY --from=build /app/out /public
COPY sws.toml /sws.toml
EXPOSE 80
+56 -30
View File
@@ -1,49 +1,75 @@
# andwati.com
# Nuxt Minimal Starter
Personal site: about, writing, reading and portfolio. Next.js (App Router) with Tailwind CSS v4, exported as static files and served by [static-web-server](https://static-web-server.net/).
Look at the [Nuxt documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
## Develop
## Setup
```sh
Make sure to install dependencies:
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
## Development Server
Start the development server on `http://localhost:3000`:
```bash
# npm
npm run dev
# pnpm
pnpm dev
# yarn
yarn dev
# bun
bun run dev
```
## Content
## Production
Everything lives in `content/` as markdown with YAML frontmatter:
Build the application for production:
- `content/about.md` is the home page
- `content/writing/*.md` are posts (`title`, `description`, `date`, `tags`)
- `content/reading/*.md` are books and papers
- `content/portfolio/*.md` are projects
```bash
# npm
npm run build
Covers go in `public/covers/<slug>.jpg`. Math (`$...$`), code fences, callouts and YouTube embeds are supported.
# pnpm
pnpm build
## Checks
# yarn
yarn build
```sh
pnpm check # Biome (code) + Prettier and cspell (content)
pnpm format:content # format markdown
# bun
bun run build
```
A pre-commit hook runs these on staged files. Add project words to `.cspell/words.txt`.
Locally preview production build:
## Analytics
```bash
# npm
npm run preview
Umami is loaded when both variables are set **at build time**:
# pnpm
pnpm preview
```
PUBLIC_UMAMI_SCRIPT_URL=https://analytics.andwati.com/script.js
PUBLIC_UMAMI_WEBSITE_ID=...
# yarn
yarn preview
# bun
bun run preview
```
## Deploy
```sh
docker build -t andwati-site \
--build-arg PUBLIC_UMAMI_SCRIPT_URL=... \
--build-arg PUBLIC_UMAMI_WEBSITE_ID=... .
```
The image builds the static export (`out/`) and serves it with `sws.toml` (security headers, clean URLs, `.well-known`). In Dokploy, pass the two Umami variables as build args.
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
+6
View File
@@ -0,0 +1,6 @@
<template>
<div>
<NuxtRouteAnnouncer />
<NuxtWelcome />
</div>
</template>
-39
View File
@@ -1,39 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.2/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"ignoreUnknown": true,
"includes": ["**", "!node_modules", "!.next", "!dist", "!build"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2
},
"css": {
"parser": {
"tailwindDirectives": true
}
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
},
"domains": {
"next": "recommended",
"react": "recommended"
}
},
"assist": {
"actions": {
"source": {
"organizeImports": "on"
}
}
}
}
-33
View File
@@ -1,33 +0,0 @@
---
title: "About"
---
# Ian Andwati
## Some things about me:
- I'm a software engineer by day. Cyber Security is my hobby and my side work.
- I have a degree in computer science, and most of what I do for fun still centres on it.
- I'm the captain of the [**binarysith**](https://ctftime.org/team/379200) CTF team. I play CTFs on the weekends under the alias **mockingspectre**.
- I like infrastructure-level software: the code that other code runs on.
- I write essays on software development, from personal experience to opinion pieces (with varying degrees of "success"). The blog has been going since 2021 and has moved around a lot: different domains, Medium, dev.to, Hashnode. This site is where I keep the originals.
## Some things I'm interested in:
- The intersection of software engineering and cyber security.
- Low-level programming, because it's where performance and security meet.
- Distributed systems and performance at scale.
- Compiler design.
- Database internals.
- Reading, fiction and non-fiction alike, especially the classics.
- Art, history and science.
Check out my [reading](/reading), [writing](/writing) and [portfolio](/portfolio).
### PGP
For anything sensitive, you can reach me encrypted.
- Fingerprint: `AD58 AAB7 A20D 8523 CBF5 9A79 1F20 FED0 AA05 B0DA`
- Public key: [/.well-known/pgp-key.txt](/.well-known/pgp-key.txt)
- Also on: [keys.openpgp.org](https://keys.openpgp.org/search?q=AD58AAB7A20D8523CBF59A791F20FED0AA05B0DA) and [keyserver.ubuntu.com](https://keyserver.ubuntu.com/pks/lookup?op=vindex&search=0xAD58AAB7A20D8523CBF59A791F20FED0AA05B0DA)
-11
View File
@@ -1,11 +0,0 @@
---
title: "Example Project"
description: "Placeholder portfolio entry establishing the schema."
role: "Author"
dateStart: "2026-01-01"
outcome: "Established the portfolio content schema."
links:
- label: "Source"
url: "https://github.com/andwati"
tags: ["placeholder"]
---
@@ -1,11 +0,0 @@
---
title: "Attention Is All You Need"
kind: "paper"
authors: ["Ashish Vaswani", "Noam Shazeer", "Niki Parmar"]
url: "https://arxiv.org/abs/1706.03762"
coverImage: "/covers/attention-is-all-you-need.jpg"
rating: 5
status: "read"
dateFinished: "2026-02-03"
tags: ["machine-learning", "papers"]
---
@@ -1,10 +0,0 @@
---
title: "Designing Data-Intensive Applications, 2nd Edition"
kind: "book"
authors: ["Martin Kleppmann", "Chris Riccomini"]
url: "https://www.oreilly.com/library/view/designing-data-intensive-applications/9781098119058/"
coverImage: "/covers/designing-data-intensive-applications-2nd-edition.webp"
rating: 5
status: "reading"
tags: ["distributed-systems"]
---
@@ -1,10 +0,0 @@
---
title: "Structure and Interpretation of Computer Programs"
kind: "book"
authors: ["Harold Abelson", "Gerald Jay Sussman"]
coverImage: "/covers/structure-and-interpretation-of-computer-programs.jpg"
rating: 5
status: "read"
dateFinished: "2026-01-20"
tags: ["computer-science", "programming"]
---
-55
View File
@@ -1,55 +0,0 @@
---
title: "A Fresh Coat Of Paint"
description: "Migrating to Zola"
date: "2023-08-24"
tags: ["zola", "blog", "tera", "rust"]
---
Using Zola as my preferred static site generator
After using Hugo for over eight months I got tired of it and looked for other alternatives. That's when I stumbled upon Zola. Zola is a static site generator (SSG), similar to [Hugo](https://gohugo.io/), [Pelican](https://blog.getpelican.com/), and [Jekyll](https://jekyllrb.com/).
It is written in Rust and uses the Tera template engine, similar to Jinja2, Django templates, Liquid, and Twig. SSGs use dynamic templates to transform content into static HTML pages. Static sites are thus very fast and require no databases, making them easy to host.
My previous Hugo site used a theme because I wasn't really ready to learn Go's template engine. I'm already familiar with Python Django and its template system so using Tera wasn't hard because it's similar to jinja2 and the Django template syntax.
Content is written in [CommonMark](https://commonmark.org/), a strongly defined, highly compatible specification of [Markdown](https://www.markdownguide.org/). Zola uses [pulldown-cmark](https://github.com/raphlinus/pulldown-cmark#pulldown-cmark) to parse markdown files. The goal of this library is 100% compliance with the CommonMark spec. It adds a few additional features such as parsing footnotes, Github-flavored tables, Github-flavored task lists, and strikethrough.
Zola comes with built-in syntax highlighting, but you must first enable it in the configuration file.
Zola is very minimalistic, it is installed only as a single binary, with no extra dependencies needed. It is configured in `toml` and you only use what is needed. For example here is the configuration for this site `config.toml`:
```toml
title = "Ian Andwati"
description = "Ian Andwati's personal website"
base_url = "https://andwati.github.io"
generate_categories_pages = false
generate_tags_pages = false
generate_feed = true
feed_filename = "rss.xml"
minify_html = false
taxonomies = [{ name = 'tags', feed = false }]
compile_sass = true
[markdown]
highlight_code = true
highlight_theme = "gruvbox-dark"
[link_checker]
[extra]
author = "Ian Andwati"
```
## Inspiration
The motivation to use Zola also came from my decision to move from independently developed themes. I decided to write the HTML and CSS myself and endeavor to maintain the site individually. The base CSS is borrowed from [Reilly Tucker Siemens](https://tuckersiemens.com/) who had created a nice gruvbox palette for his site.
I improved on it by adding an archive page, pagination, a comment system, and Google Analytics (more of these in later posts). I also implemented article read time and word count.
## What next
The site is a work in progress and is far from polished. I plan on implementing a newsletter to notify readers of new posts. The site is primarily a dark theme, in the future I'll also add theme toggling and maybe different palettes.
You can subscribe to the site's RSS feed at [https://andwati.com/rss.xml](https://andwati.com/rss.xml).
-322
View File
@@ -1,322 +0,0 @@
---
title: "From C to Machine Code: What Actually Runs"
description: "Before diving into how to break a program, we need to understand what the computer is actually executing"
date: "2026-04-08"
tags: ["assembly", "rev", "pwn"]
---
<div class="youtube"><iframe src="https://www.youtube-nocookie.com/embed/KbH239zvDtM" title="YouTube video" loading="lazy" allowfullscreen></iframe></div>
Before diving into how to break a program, we need to understand what the computer is actually executing. When you write a C program, the processor doesn't understand a single line of it. The C language exists for _our_ benefit, allowing us to write logic without having to manually shuffle bits around in the processor.
To bridge this gap, we use a compiler (like `GCC`), which translates our human-readable C code into machine code—raw binary instructions. Assembly language is simply the human-readable representation of that machine code.
Because we usually don't have the original C source code when analyzing malware or playing a CTF, we are forced to read the assembly. (Though tools like Ghidra can try to decompile assembly back into C-like pseudocode to save us from staring at assembly instructions all day).
Let's look at what a basic `printf("Hello World!");` program actually turns into.
```c
#include <stdio.h>
int main(){
printf("hello world\n");
return 0;
}
```
We will compile the hello world C program, then dump the assembly in Intel syntax(it defaults to AT&T syntax, a cancer).
```sh
gcc -o hello hello.c && objdump -d -M intel hello | grep -A 15 "**<main>:**"
```
<br>
```asm
0000000000001139 <main>:
1139: 55 push rbp
113a: 48 89 e5 mov rbp,rsp
113d: 48 8d 05 c0 0e 00 00 lea rax,[rip+0xec0] # 2004 <_IO_stdin_used+0x4>
1144: 48 89 c7 mov rdi,rax
1147: e8 e4 fe ff ff call 1030 <puts@plt>
114c: b8 00 00 00 00 mov eax,0x0
1151: 5d pop rbp
1152: c3 ret
Disassembly of section .fini:
0000000000001154 <_fini>:
1154: 48 83 ec 08 sub rsp,0x8
1158: 48 83 c4 08 add rsp,0x8
115c: c3 ret
```
Notice how different this looks from C. The processor executes different instruction sets depending on its architecture. The two most common architectures you will encounter are 32-bit (x86) and 64-bit (x86_64 or just x64/AMD64/Intel 64).
## **The Processor's Workbench: Registers**
To process data rapidly, the CPU doesn't want to constantly reach all the way out to your system's RAM. Instead, it uses registers—extremely fast, temporary storage buckets located directly on the processor.
Here are the critical x64 registers you need to know:
- **`rip` (Instruction Pointer):** The most important register for exploitation. It points to the exact memory address of the _next_ instruction the CPU is supposed to execute.
- **`rsp` (Stack Pointer):** Points to the very top of your current stack frame.
- **`rbp` (Base Pointer):** Points to the bottom of your current stack frame.
### **General Purpose Registers & Calling Conventions**
There are also general-purpose registers (`rax`, `rbx`, `rcx`, `rdx`, `rsi`, `rdi`, and `r8` through `r15`). While they can be used for general math and data storage, they have strict roles when functions are called.
In x64 Linux, when a function is called, the arguments are passed directly into registers in this specific order:
1. `rdi` (First argument)
2. `rsi` (Second argument)
3. `rdx` (Third argument)
4. `rcx` (Fourth argument)
5. `r8` (Fifth argument)
6. `r9` (Sixth argument)
<aside class="callout callout-note">
In older x86 32-bit binaries, arguments aren't passed in registers at all; they are pushed onto the stack. When a function finishes and returns a value, that return value is almost always placed in the **`rax`** register (or `eax` in 32-bit).
</aside>
### **Register Sizes and "Words"**
Registers have different sizes depending on the architecture, and you can reference smaller chunks of a larger register. In binary exploitation, you'll frequently see data referred to by size:
**Word:** 2 bytes
**Dword (Double Word):** 4 bytes
**Qword (Quad Word):** 8 bytes
Here is how x64 registers break down into smaller accessible chunks:
| 8-Byte (Qword)[64 bit] | Lower 4-Bytes (Dword)[lower 32 bits] | Lower 2-Bytes (Word)[lower 16 bits] | Lower 1-Byte[lower 8 bits] |
| :--------------------- | :----------------------------------- | :---------------------------------- | :------------------------- |
| rax | eax | ax | al |
| rbx | ebx | bx | bl |
| rcx | ecx | cx | cl |
| rdx | edx | dx | dl |
| rdi | edi | di | dil |
| rsi | edi | si | sil |
| rsp | esp | sp | spl |
| rbp | ebp | bp | bpl |
| rip | eip | - | - |
| r8 | r8d | r8w | r8b |
| r9 | r9d | r9w | r9b |
| r10 | r10d | r10w | r10b |
| r11 | r11d | r11w | r11b |
| r12 | r12d | r12w | r12b |
| r13 | r13d | r13w | r13b |
| r14 | r14d | r14w | r14b |
| r15 | r15d | r15w | r15b |
<br>
<p>If you are dealing with a 32-bit (x86) binary, the 8-byte 'R' registers don't exist. The largest buckets you have are the 4-byte 'E' registers (`eax`, `ebp`, etc.).</p>
## **The Stack**
The stack is a segment of memory heavily used during execution. It's primarily used to store local variables, keep track of function calls, and manage control flow. It operates as a LIFO (Last-In, First-Out) structure—meaning you can only add (push) to the top of it, and remove (pop) from the top of it.
The boundaries of the current stack space are tracked by `rbp` (the base) and `rsp` (the top). When you declare a local variable in C, like `int x = 5;`, the program allocates space for it on the stack.
Consider stack.c
```c
#include<stdio.h>
int main() {
int x = 5;
puts("hi");
}
```
Compile this with the command:
```sh
gcc -o stack stack.c && objdump -d -M intel stack | grep -A 15 "<main>:"
```
```asm
0000000000001139 <main>:
1139: 55 push rbp
113a: 48 89 e5 mov rbp,rsp
113d: 48 83 ec 10 sub rsp,0x10
1141: c7 45 fc 05 00 00 00 mov DWORD PTR [rbp-0x4],0x5
1148: 48 8d 05 b5 0e 00 00 lea rax,[rip+0xeb5] # 2004 <_IO_stdin_used+0x4>
114f: 48 89 c7 mov rdi,rax
1152: e8 d9 fe ff ff call 1030 <puts@plt>
1157: b8 00 00 00 00 mov eax,0x0
115c: c9 leave
115d: c3 ret
Disassembly of section .fini:
0000000000001160 <_fini>:
1160: 48 83 ec 08 sub rsp,0x8
```
<br>
In your output, you'll see an instruction moving the value `0x5` into a memory location relative to the base pointer, usually something like `[rbp-0x4]`. That is your local variable resting on the stack.
## **The Heap**
We will just do an overview of this section. It can get quite complex very fast. We will eventually cover them in future articles.
If the stack is the CPU’s fast, tightly organized workbench, the heap is the massive, slightly chaotic warehouse out back.
The stack is great for small, temporary variables, but it has severe limitations: it is relatively small, and you must know exactly how much space you need at compile time. What if you want to load a 10MB image file? Or what if you are accepting user input and you don't know if the user will type 10 characters or 10,000?
For dynamic, large, or unpredictable data, we use the **Heap**.
Unlike the stack, which the CPU manages automatically by just moving the `rsp` register up and down, the heap is entirely manual. The programmer must explicitly ask the operating system for a chunk of memory, and more importantly, they must explicitly give it back when they are done.
In C, this is done using the `malloc()` (memory allocate) and `free()` functions.
Consider heap.c
```c
#include <stdlib.h>
#include <string.h>
int main() {
// Ask the warehouse for 64 bytes of space
char *buffer = (char *)malloc(64);
// Put some data into that space
strcpy(buffer, "hello heap");
// Give the space back to the warehouse
free(buffer);
return 0;
}
```
Now we do the necessary:
```sh
gcc -o heap heap.c && objdump -d -M intel heap | grep -A 20 "<main>:"
```
<br>
```asm
0000000000001149 **<main>:**
1149: 55 push rbp
114a: 48 89 e5 mov rbp,rsp
114d: 48 83 ec 10 sub rsp,0x10
1151: bf 40 00 00 00 mov edi,0x40
1156: e8 e5 fe ff ff call 1040 <malloc@plt>
115b: 48 89 45 f8 mov QWORD PTR [rbp-0x8],rax
115f: 48 8b 45 f8 mov rax,QWORD PTR [rbp-0x8]
1163: 48 ba 68 65 6c 6c 6f movabs rdx,0x6568206f6c6c6568
116a: 20 68 65
116d: 48 89 10 mov QWORD PTR [rax],rdx
1170: c7 40 07 65 61 70 00 mov DWORD PTR [rax+0x7],0x706165
1177: 48 8b 45 f8 mov rax,QWORD PTR [rbp-0x8]
117b: 48 89 c7 mov rdi,rax
117e: e8 ad fe ff ff call 1030 <free@plt>
1183: b8 00 00 00 00 mov eax,0x0
1188: c9 leave
1189: c3 ret
Disassembly of section .fini:
```
When you look at this assembly, you won't see data simply being pushed onto the stack. Instead, you will see instructions setting up arguments (like putting `0x40`—which is 64 in hex—into the `edi` register) followed by a `call` to `malloc@plt`.
`malloc` acts as the warehouse manager. It goes out, finds 64 bytes of free space in the heap memory region, and returns a pointer (a memory address) to that space in the `tax` register.
This manual management is exactly why the heap is such a prime target for exploitation. If a programmer calls `malloc` but forgets to call `free`, the program leaks memory. If they call `free` but keep using the pointer anyway, you get a "Use-After-Free" vulnerability. If they ask for 64 bytes but copy 100 bytes into it, you get a Heap Overflow. Breaking the heap means tricking the warehouse manager (`glibc`'s allocator) into giving you access to things you shouldn't have.
## **The CPU's Instruction Set**
Assembly might look like gibberish at first, but it essentially boils down to moving data, doing basic math, and jumping around memory. Here are the most common instructions you will encounter:
### **Moving Data**
- **`mov dest, src`**: Copies data from the source to the destination. (`mov rax, rdx` copies the value in `rdx` into `rax`).
- **Dereferencing `[]`**: Brackets act like pointers in C. `mov rax, [rdx]` doesn't move `rdx` itself; it goes to the memory address stored in `rdx` and grabs the value sitting there. Conversely, `mov [rax], rdx` takes the value in `rdx` and writes it into the memory address pointed to by `rax`.
- **`lea dest, src`**: Load Effective Address. It calculates a memory address and stores the _address itself_ in the destination, rather than the data at that address. (`lea rdi, [rbx+0x10]`).
### **Math and Logic**
- **`add dest, src` / `sub dest, src`**: Adds or subtracts the source from the destination, storing the result in the destination.
- **`xor dest, src`**: Performs a bitwise exclusive OR. (You will frequently see `xor rax, rax`—this is simply an optimized way to set `rax` to 0).
### **Stack Operations**
- **`push reg`**: Subtracts from `rsp` to grow the stack, then places the register's value onto the new top of the stack.
- **`pop reg`**: Takes the value from the top of the stack, puts it into the register, and adds to `rsp` to shrink the stack.
### **Control Flow**
- **`jmp address`**: Unconditionally redirects code execution to a new memory address.
- **`call address`**: Used to invoke functions. It pushes the current `rip` onto the stack (so the program remembers where it was) and then jumps to the new address.
- **`ret`**: Pops the saved address off the stack and places it back into `rip`, seamlessly resuming execution where it left off before the `call`.
### **Conditionals and Flags**
The CPU has a special register dedicated to **Flags**—individual bits that indicate the state of the processor (e.g., the Zero Flag, Carry Flag, Sign Flag).
- **`cmp arg1, arg2`**: Compares two values by silently subtracting them. It doesn't save the mathematical result; instead, it updates the CPU Flags (like setting the Zero Flag if the two values were equal).
- **`jz` / `jnz`**: Jump if Zero / Jump if Not Zero. These look at the CPU flags set by a previous `cmp` instruction. If the Zero Flag is set, `jz` will take the jump. If not, the program just continues to the next instruction.
There is one register that contains flags. A flag is a particular bit of this register. If it is set or not, will typically mean something. Here is the list of flags.
```txt
00: Carry Flag
01: always 1
02: Parity Flag
03: always 0
04: Adjust Flag
05: always 0
06: Zero Flag
07: Sign Flag
08: Trap Flag
09: Interruption Flag
10: Direction Flag
11: Overflow Flag
12: I/O Privilege Field lower bit
13: I/O Privilege Field higher bit
14: Nested Task Flag
15: Resume Flag
```
<br>
There are other flags then the one listed, however we really don't deal with them too much (and out of these, there are only a few we actively deal with).
This has been a lot to unpack but it will get simpler with time. Now that we understand how C code becomes assembly, how the CPU juggles data in registers, and how the stack manages memory, we need to look at how all of this is packaged together by the operating system. Next, we will dive deeper into the structure of the ELF binary itself.
You can support my work at [https://buymeacoffee.com/mockingspectre](https://buymeacoffee.com/mockingspectre)
## Further Reading
[https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture](https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture)
[https://en.wikipedia.org/wiki/Assembly_language](https://en.wikipedia.org/wiki/Assembly_language)
@@ -1,37 +0,0 @@
---
title: "Django Secret Key Tutorial"
description: "Managing secrets"
date: "2022-11-11"
tags: ["tutorial", "django", "python", ".env"]
---
Managing the Django SECRET_KEY variable.
The Django `SECRET_KEY` variable is very crucial to your Django application. The secret key must be a large random value and it must be kept secret. Leaking this value to unauthorized people could lead to a security breach. The SECRET_KEY is used in Django for cryptographic signing. It is used to generate tokens and hashes, they can be recreated using this variable. If it is not configured Django throws a `django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty` error
# Using Environment Variables
The secret key should not be committed to version control. It is best practice to store the value in a .env file which is added to the .gitignore file to un-track its changes. The values can be loaded programmatically into your settings.py file.
# Generating A New Secret Key
This solution is using python's secrets lib on the back
```python
from django.core.management.utils import get_random_secret_key
# print new random secret key
print(get_random_secret_key())
```
This code can be run in the terminal as a command:
```python
python -c 'from django.core.management.utils import get_random_secret_key; \
print(get_random_secret_key())'
```
Alternatively, If you are using python 3.6+ then you can use the `secrets.token_hex(\[nbytes=None])` function:
```python
python3 -c 'import secrets; print(secrets.token_hex(100))'
```
-32
View File
@@ -1,32 +0,0 @@
---
title: "Hello World"
description: "Hello world"
date: "2022-11-04"
tags: ["hugo", "blog", "go"]
---
How it begins
In this post-web2.0 age, people seem to blog less and less, and blogs seem to be dying slowly. People are separated in different Apps where the content is not searchable by search engines.
However, I still prefer to write using a blog.
# Why this?
The best way to learn something is to teach others the knowledge that you have gained. Regurgitating that information will solidify it more firmly in your mind.
# What I write?
Mostly random stuff and a few tutorials. I'll see where this goes.Although some of the blog posts may only be helpful to myself, but who knows, I hope they will be helpful to someone else in some day.
# Static blog generator
I use hugo as a static site generator.After trying a couple of blogging platforms and trying to build a few from scratch I decided to
throw in the towel and opt in for a ready made solution, no need reinventing the wheel.
Hugo is one of the most popular open-source static site generators. With its amazing speed and flexibility, Hugo makes building websites fun again.Hugo provides a robust theming system that is easy to implement but capable of producing even the most complicated websites.Hugo's Go-based templates provide just the right amount of logic to build anything from the simple to complex. For this site I decided to go with the [even theme](https://github.com/olOwOlo/hugo-theme-even). The commenting system is implemented using [Utterances](https://utteranc.es/)
# Blog site hosting
The site is hosted on github pages as evident by the \*.github.io domain name.I prefer this mainly because it is free and I don't have
to switch to a different hosting provider.
-18
View File
@@ -1,18 +0,0 @@
---
title: "cognitive inertia"
description: "inertia"
date: "2025-02-26"
tags: ["cognition"]
---
Staring at the void
Cognitive inertia is the reason changing our habits can be difficult. If you want to overcome inertia you have to apply a force. I consider myself an eternal student, who is ready to learn anything, or so I thought. It happened but I had not noticed, I had stopped moving forward.
## Metawork
I will define this as the things we do before getting the "real" work doe. Its things like choosing the best IDE or text editor, setting up your coding environment, choosing the best note taking app, or even the 'best' operating system. They are the prerequisites of the actual work.
I had been stuck on this loop, always trying to craft the perfect workflow. Setting up the best personalized linux distro, switching note taking apps, trying out multiple layouts, stylings and technologies for my blog, the list is endless.
All of these metawork took more time thn the actual work; building, active learning and writing. Im going to stop all of these and start doing the important stuff.
@@ -1,170 +0,0 @@
---
title: "Install PostgreSQL on Arch | Manjaro | Garuda Linux"
description: "Getting PostgreSQL up and running on Arch Linux-based distros"
date: "2023-02-16"
tags: ["postgresql", "archlinux", "manjaro", "garuda", "linux"]
---
# Overview
**PostgreSQL** is a powerful open-source relational database management system (RDBMS) that allows you to store and manage large amounts of data. It was first released in 1996 and has become one of the most popular RDBMSs in the world.
PostgreSQL is designed to handle high levels of **concurrency**, providing features such as **MVCC (multi-version concurrency control)** that allow multiple users to access the same data simultaneously without conflicts. It is also **highly extensible**, with a large number of third-party extensions and libraries available that can be used to add functionality to the core database.
Some of the key features of PostgreSQL include support for **complex SQL queries**, **advanced indexing** and **query optimization**, **transactional integrity**, and support for a **wide range of programming languages** and development frameworks.PostgreSQL is used by a wide range of organizations, from small businesses to large enterprises, and is particularly popular in industries such as finance, healthcare, and e-commerce, where high levels of data security and reliability are critical.
In this tutorial, we’ll look at how to install PostgreSQL on Arch Linux, Manjaro, Garuda Linux, or any other Arch-based distro out there.
# PostgreSQL use cases
- **E-commerce websites:** PostgreSQL is a popular choice for e-commerce websites because it can handle large amounts of data and supports complex queries. It is used for product catalogs, order management, customer data, and more.
- **Financial institutions:** PostgreSQL is used in financial institutions to store and manage transactional data, such as stock trades, bank transfers, and credit card transactions. It is highly secure and provides features such as transactional integrity and data encryption.
- **Healthcare industry:** PostgreSQL is used in the healthcare industry to store patient data, such as medical records and diagnostic test results. It is also used for research purposes, where large amounts of data need to be stored and analyzed.
- **Government agencies:** PostgreSQL is used by government agencies for a variety of purposes, including managing large datasets, storing and analyzing census data, and managing public health information.
- **Mobile and web applications:** PostgreSQL is often used as a back-end database for mobile and web applications. It provides reliable data storage and retrieval and supports a wide range of programming languages and development frameworks.
- **Geospatial applications:** PostgreSQL has built-in support for geospatial data and is often used for applications that require location-based data, such as mapping and GPS tracking.
# Why PostgreSQL?
Postgres offers a lot of advantages that make it an excellent choice for highly transactional environments regardless of application size and data volume. Its rich feature set and flexibility make it a popular choice for a wide range of applications and industries. Some of the top features are:
- **ACID Compliance:** PostgreSQL is ACID (Atomicity, Consistency, Isolation, Durability) compliant, which means it provides high reliability, consistency, and data integrity, even in the presence of hardware failures, power outages, and other system errors.
- **Extensibility:** PostgreSQL is highly extensible, allowing developers to add new data types, operators, and functions using its extension framework. This makes it easy to customize PostgreSQL to meet the specific needs of your application.
- **Concurrency:** PostgreSQL provides a high level of concurrency, allowing multiple users to access the same data at the same time without conflicts. It uses a Multi-Version Concurrency Control (MVCC) model that enables fast and reliable access to data, even under heavy load.
- **Full-text search:** PostgreSQL provides a powerful full-text search engine that supports advanced search capabilities, such as stemming, ranking, and relevance matching.
- **Advanced indexing:** PostgreSQL provides a wide range of indexing options, including B-tree, Hash, GiST, SP-GiST, GIN, and BRIN. These indexing options allow developers to optimize database performance for their specific use cases.
- **JSON support:** PostgreSQL provides native support for storing and querying JSON data, making it easy to work with modern web and mobile applications that rely on JSON for data exchange.
- **Security:** PostgreSQL provides a high level of security, with features such as SSL support, client authentication, and role-based access control. It also provides encryption for both data at rest and data in transit.
- **Scalability:** PostgreSQL is designed to scale horizontally and vertically, allowing you to add more nodes to a cluster or increase the resources of a single node to handle more load.
# Install PostgreSQL on Arch | Manjaro | Garuda Linux
Now with all that fluff out of the way, let's get to business. The steps have been tested on Arch Linux with the KDE desktop.
> **Note:** Commands that should be run as the _postgres_ user are prefixed by `[postgres]$` in this article.
## Step 1: Installing the PostgreSQL Package
```sh
sudo pacman -Syu postgresql
```
This command will update the package database and update all packages on the system then install the PostgreSQL package from your distribution mirrors. Never install a package without updating the system first. On a rolling release, this can lead to an unbootable system. Installing the package will also create a system user called _postgres_. You can now switch to the _postgres_ user using a privilege elevation program.
You can switch to the PostgreSQL user by executing the following command:
- If you have sudo and are in sudoers
```sh
sudo -iu postgres
```
- Otherwise using su:
```sh
su
su -l postgres
```
## Step 2: Initial Configuration
Before PostgreSQL can function correctly, the database cluster must be initialized.
### 2.1 We can confirm the installed PostgreSQL version by running
```sh
postgres --version ─╯
postgres (PostgreSQL) 15.1
```
### 2.2 Set applicable entries in **/etc/locale.gen**
```sh
echo "en_US.UTF-8 UTF-8" | sudo tee /etc/locale.gen
```
### 2.3 Then run **\*\*locale-gen\*\*** to generate locale settings
```sh
sudo locale-gen
Generating locales...
en_US.UTF-8... done
Generation complete.
```
### 2.4 Initialize Postgres Data Directory
You must first log in as the **postgres** user using the following command before you can initialize PostgreSQL’s data directory:
```sh
sudo su - postgres
```
### 2.5 With the following command, you can now initialize PostgreSQL’s data directory
```sh
[postgres]$ initdb -D /var/lib/postgres/data
```
### Step 3: PostgreSQL Service Management
### 3.1 Check PostgreSQL status with the following command
```sh
systemctl status postgresql ─╯
postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; preset: disabled)
Active: inactive (dead)
```
### 3.2 Start the PostgreSQL service by running the following command
```sh
sudo systemctl start postgresql
```
### 3.3 Enable the PostgreSQL service to start automatically at boot by running the following command
```sh
sudo systemctl enable postgresql
```
### 3.4 Verify that PostgreSQL is running by running the following command
```sh
sudo systemctl status postgresql ─╯
● postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: disabled)
Active: active (running) since Thu 2023-02-16 22:52:43 EAT; 20s ago
Main PID: 26106 (postgres)
Tasks: 6 (limit: 8790)
Memory: 16.9M
CPU: 113ms
CGroup: /system.slice/postgresql.service
├─26106 /usr/bin/postgres -D /var/lib/postgres/data
├─26107 "postgres: checkpointer "
├─26108 "postgres: background writer "
├─26110 "postgres: walwriter "
├─26111 "postgres: autovacuum launcher "
└─26112 "postgres: logical replication launcher "
```
### Change postgres user password
To change the postgres user password execute the following command:
```sh
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '$PGPASSWORD';"
```
# Resources
- [Arch Linux Wiki](https://wiki.archlinux.org/title/PostgreSQL)
- [Wikipedia](https://en.wikipedia.org/wiki/PostgreSQL)
- [PostgreSQL Documentation](https://www.postgresql.org/docs/)
# Conclusion
Installing PostgreSQL on Arch Linux-based distribution is a straightforward process that can be completed in just a few steps. By following the steps outlined above, you can install, configure, and start the PostgreSQL database server on your Arch Linux system. Once installed, you can use PostgreSQL to store, manage, and query data for a wide range of applications and use cases. With its advanced features and high level of extensibility, PostgreSQL is a popular choice for developers and businesses seeking a robust and reliable database management system.
You can connect to the PostgreSQL server using the psql command-line client or a graphical tool such as pgAdmin.
-150
View File
@@ -1,150 +0,0 @@
---
title: "Integrating Netlify CMS"
description: "Integrating netlify cms"
date: "2022-11-24"
tags: ["blog", "hugo", "netlify", "netlify-cms", "github"]
---
Migrating to a better content management system through Netlify CMS
# Heavy Lifting
I use [Visual Studio Code](https://code.visualstudio.com/) to manually edit the blog post content on this website. This is quite a hassle because I have to deal with
markdown files. There are many problems with this approach and several gotchas. I have to work on a local site repository to be able to edit the content. My GitHub credentials are also required to push my local changes to my remote repository on GitHub so that it can trigger the build process and publish the site.
This process has helped me a lot to master markdown syntax and some practice on my git skills. It’s fun to update the website content following these steps but sometimes it can be frustrating. At those times, I really miss the user interface of content management systems. After careful consideration, I moved on with Netlify CMS. At its core, Netlify CMS is an open-source React app that acts as a wrapper for the Git workflow, using the GitHub, GitLab, or Bitbucket API. This provides many advantages, including:
- **Fast, web-based UI:** With rich-text editing, real-time preview, and drag-and-drop media uploads.
- **Platform agnostic:** Works with most static site generators.
- **Easy installation:** Add two files to your site and hook up the backend by including those files in your build process or linking to our Content Delivery Network (CDN).
- **Modern authentication:** Using GitHub, GitLab, or Bitbucket and JSON web tokens.
- **Flexible content types:** Specify an unlimited number of content types with custom fields.
- **Fully extensible:** Create custom-styled previews, UI widgets, and editor plugins.
# Redeploying to Netlify
I decided to move the site from GitHub pages to Netlify hosting to take full control of the platform. Hugo sites on Netlify can benefit from automatic framework detection and control over Hugo version selection. When you link a repository for a project, Netlify tries to detect the framework your site is using. If your site is built with Hugo, Netlify provides a suggested build command and publish directory: Hugo and public. The build process is straight forward but you can add custom options to your `netlify.toml` file, here are my options:
```toml
[build]
command = "hugo"
publish = "public"
[build.environment]
HUGO_VERSION = "0.105.0"
```
# Setting up Netlify CMS
You can adapt Netlify CMS to a wide variety of projects. It works with any content written in markdown, JSON, YAML, or TOML files, stored in a repo on GitHub, GitLab, or Bitbucket. You can Netlify CMS to a site that's built with a common static site generator, like Jekyll, Hugo, Hexo, or Gatsby. The official documentation for installing on your website can be found at the [official site](https://www.netlifycms.org/docs/intro/)
## Steps
**Step 1**
Create a static admin folder containing all Netlify CMS files, stored at the root of your published site. Where you store this folder in the source files depends on your static site generator. For Hugo, it is the `static` folder.
`/static/admin`
**Step 2**
Inside the admin folder, create two files: `index.html` and `config.yml`. The first file `admin/index.html` is an entry point to Netlify CMS. You will access the CMS interface from `yourwebsite.com/admin` when everything is ready.
**Step 3**
The first file, `admin/index.html`, is the entry point for the Netlify CMS admin interface. Paste this code in index.html and save. This HTML starter page will load the Netlify CMS Javascript file:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Content Manager</title>
</head>
<body>
<!-- Include the script that builds the page and powers Netlify CMS -->
<script src="https://unpkg.com/netlify-cms@^2.0.0/dist/netlify-cms.js"></script>
</body>
</html>
```
**Step 4**
Now let’s move to the configuration section. These are the configurations that go into the `config.yml` file. This process is different for every site. I followed the guidelines on the website and made minor adjustments. It worked on my website. The configuration options are available at the [docs](<https://www.netlifycms.org/docs/add-to-your-site/#:~:text=%2C%20MyTemplate)-,Configuration,-Configuration%20is%20different>). This is how I configured my config.yml file:
```yaml
backend:
name: git-gateway
branch: netlify-cms # Branch to update (optional; defaults to master)
# This line should *not* be indented
publish_mode: editorial_workflow
media_folder: 'static/images/uploads' # Media files will be stored in the repo under static/images/uploads
public_folder: '/images/uploads' # The src attribute for uploaded media will begin with /images/uploads
collections:
- name: 'post' # Used in routes, e.g., /admin/collections/blog
label: 'posts' # Used in the UI
folder: 'content/post' # The path to the folder where the documents are stored
create: true # Allow users to create new documents in this collection
slug: '{{year}}-{{month}}-{{day}}-{{slug}}' # Filename template, e.g., YYYY-MM-DD-title.md
fields: # The fields for each document, usually in front matter
- { label: 'Layout', name: 'layout', widget: 'hidden', default: 'blog' }
- { label: 'Title', name: 'title', widget: 'string' }
- { label: 'Draft', name: 'draft', widget: 'boolean', default: true }
- { label: 'Publish Date', name: 'date', widget: 'datetime' }
- { label: 'Last Modified', name: 'lastmod', widget: 'datetime' }
- { label: 'Body', name: 'body', widget: 'markdown' }
- { label: 'Keywords', name: 'keywords', widget: 'list' }
- { label: 'Tags', name: 'tags', widget: 'list' }
- { label: 'Categories', name: 'categories', widget: 'list' }
- { label: 'Comments', name: 'comment', widget: 'boolean', default: true }
- { label: 'Table of Contents', name: 'toc', widget: 'boolean', default: true }
```
**Step 5**
**Authentication**
Now that the Netlify CMS files are in place and configured, all that's left is to enable authentication.
Netlify offers a built-in authentication service called Identity. In order to use it, connect your site repo with Netlify. Netlify has published a general [Step-by-Step Guide](https://www.netlify.com/blog/2016/10/27/a-step-by-step-guide-deploying-a-static-site-or-single-page-app/) for this, along with detailed guides for many popular static site generators
Let’s first enable Netlify Identity and Git Gateway:
- On your Netlify account, go to **Settings > Identity** and select **Enable Identity Service**
- Under **Registration preferences**, select **Invite Only**.
- If you want to enable login from external providers such as Google and GitHub, check the boxes you want to use, under **External Providers** section. I find it practical to log in with GitHub, so I added it.
- Go to **Services > Git Gateway**, and click **Enable Git Gateway**. This authenticates with your Git Host and generates and API token.
- Everything is almost set up. What we need now is a front-end interface to connect. We will add the following script in two places, to include the **Netlify Identity Widget** on our website:
```html
<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
```
We will use Netlify's [script injection](https://docs.netlify.com/site-deploys/post-processing/snippet-injection/) feature to add the script to our site. To use snippet injection, go to **Site Settings > Build & Deploy > Post processing**. Find the Snippet Injection section and select **Add Snippet**. Write a name for the script in the first box (e.g. Netlify Identity Widget). Paste the script inside the second box. Choose Insert before the `</body>` option and save.
Lastly, we will add the following script before the closing `<body>` tag of our website’s main index page. This script allows the user to redirect back to the `/admin/` path after completing the login with the Netlify Identity Widget:
```html
<script>
if (window.netlifyIdentity) {
window.netlifyIdentity.on('init', (user) => {
if (!user) {
window.netlifyIdentity.on('login', () => {
document.location.href = '/admin/';
});
}
});
}
</script>
```
**Step 5**
Now we’re all set. Since we set our registration preferences to **“Invite Only”**, we need to invite ourselves as site users. To do this, select the Identity tab from the Netlify site dashboard and select the Invite Users button. Add your email address and send an invitation. You will receive an email. In your email, click **“accept the invitation”**. You will be directed to your website admin sign-up panel. Choose a password. Now you are ready to log in to Netlify CMS.
# Setting up a custom domain
I bought a custom domain from [Namecheap](https://namecheap.com), they provide some pretty good deals. After pointing the nameservers for the domain to the Netlify nameservers, voila! everything worked smoothly. For HTTPS support, Netlify enables automatic TLS certificates with Let’s Encrypt.
@@ -1,194 +0,0 @@
---
title: "Export default and module.exports in Javascript"
description: "Modules are the building blocks of modern JavaScript applications, allowing for the encapsulation of code into reusable components. Two primary systems govern the exportation of these modules: export default in ES6 and module.exports in CommonJS. "
date: "2024-01-17"
tags: ["javascript", "node"]
---
Modules are the building blocks of modern JavaScript applications, allowing for the encapsulation of code into reusable components. Two primary systems govern the exportation of these modules: export default in ES6 and module.exports in CommonJS.
Javascript is a popular programming language that can run both in the browser and on the server. However, different environments may have different ways of organizing and importing Javascript modules. In this article, we will compare two common methods of exporting and importing modules: **export default** and **module.exports**.
## What are modules?
Modules are reusable pieces of code that can be separated into different files. Modules can export values, functions, classes, or objects that can be imported by other modules. This way, modules can avoid polluting the global scope and enable code reuse and modularity.
## How to export modules in Node.js?
Node.js is a runtime environment that allows Javascript to run on the server. Node.js uses a module system called CommonJS, which is based on the require and module.exports syntax.
To export a module in Node.js, you can assign the value that you want to export to the module.exports object. For example:
```javascript
// my-module.js
// export a function
module.exports = function add(a, b) {
return a + b;
};
// export an object
module.exports = {
name: 'Alice',
age: 25,
};
```
To import a module in Node.js, you can use the require function and pass the path of the module file as an argument. The require function will return the value of module.exports from the module file. For example:
```javascript
// main.js
// import a function
const add = require('./my-module.js');
console.log(add(2, 3)); // 5
// import an object
const person = require('./my-module.js');
console.log(person.name); // Alice
console.log(person.age); // 25
```
Note that Node.js will cache the modules that are imported with require, so if you import the same module multiple times, you will get the same instance of the module.
## How to export modules in ES6?
ES6 is the version of Javascript that introduced many new features, including a native module system. ES6 modules use the `import` and `export` syntax.
To export a module in ES6, you can use the `export` keyword followed by the declaration of the value that you want to export. You can also use the export keyword with curly braces to export a list of named values. For example:
```javascript
// my-module.js
// export a function
export function add(a, b) {
return a + b;
}
// export a class
export class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
// export an object
export const person = {
name: 'Alice',
age: 25,
};
```
To import a module in ES6, you can use the `import` keyword followed by the name of the value that you want to import and the path of the module file. You can also use the import keyword with curly braces to import a list of named values. For example:
```javascript
// main.js
// import a function
import { add } from './my-module.js';
console.log(add(2, 3)); // 5
// import a class
import { Person } from './my-module.js';
const person = new Person('Bob', 30);
console.log(person.name); // Bob
console.log(person.age); // 30
// import an object
import { person as Alice } from './my-module.js';
console.log(Alice.name); // Alice
console.log(Alice.age); // 25
```
Note that ES6 modules are imported and executed only once, so if you import the same module multiple times, you will get the same instance of the module.
## What is the difference between export default and module.exports?
One of the main differences between export default and module.exports is that export default is an ES6 feature, while module.exports is a CommonJS feature. Therefore, they are not compatible with each other by default. However, some tools like Babel or Webpack can transpile ES6 modules to CommonJS modules, or vice versa, to make them work together.
Another difference is that export default can only export one value per module, while module.exports can export any value, including multiple values. For example:
```javascript
// my-module.js
// export default a function
export default function add(a, b) {
return a + b;
}
// export default an object
export default {
name: "Alice",
age: 25,
};
// export default a class
export default class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
```
```javascript
// my-module.js
// export a function
module.exports = function add(a, b) {
return a + b;
};
// export an object
module.exports = {
name: 'Alice',
age: 25,
};
// export a class
module.exports = class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
};
```
Note that you can only have one export default statement per module, but you can have multiple module.exports statements. However, each module.exports statement will overwrite the previous one, so only the last one will be exported.
To import a default export, you can use the import keyword without curly braces and assign any name to the imported value. For example:
```javascript
// main.js
// import a default export
import add from './my-module.js';
console.log(add(2, 3)); // 5
// import another default export
import person from './my-module.js';
console.log(person.name); // Alice
console.log(person.age); // 25
// import another default export
import Person from './my-module.js';
const person = new Person('Bob', 30);
console.log(person.name); // Bob
console.log(person.age); // 30
```
To import a module.exports value, you can use the require function and assign any name to the imported value. For example:
```javascript
// main.js
// import a module.exports value
const add = require('./my-module.js');
console.log(add(2, 3)); // 5
// import another module.exports value
const person = require('./my-module.js');
console.log(person.name); // Alice
console.log(person.age); // 25
// import another module.exports value
const Person = require('./my-module.js');
const person = new Person('Bob', 30);
console.log(person.name); // Bob
console.log(person.age); // 30
```
Node’s JavaScript has diverged from that of the browser. Understanding both CommonJS modules and ES6 modules is your first step in becoming a 10X developer. Happy coding!
-407
View File
@@ -1,407 +0,0 @@
---
title: "mmuctf 2025 writeup"
description: "mmuctf 2025 challenges writeup"
date: "2025-08-03"
tags: ["ctf", "rev", "web", "forensics"]
---
Over the weekend, I had the opportunity to participate in the mmuctf 2025. It was an individual jeopardy style CTF targeted towards beginners and intermediate people in cybersecurity. This is a write-up to explore some challenges I did, or at least almost did.
## Welcome
> Through the shadows of the cave, at the door I had a zeal to get a welcome flag, but I couldn't see it though
> I could hear it calling for me to get it. Happy hacking
> {: .prompt-info }
This was a sanity check flag. I believe competitions pose such challenges that you can't get zero points. It's the same as flags in Discord servers, a flag after completing the feedback form, or just other free points.
The challenge description talked about the `door`, my first instinct was to view the source of the front page. I got this html comment with what looked liked a base64 encoded string `<!--bW11Y3Rme3dlbGNvbWVfZmxhZ19hZGlvc19NdWNoQGNob30= -->`
```zsh
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ echo -n "bW11Y3Rme3dlbGNvbWVfZmxhZ19hZGlvc19NdWNoQGNob30=" | base64 -d
mmuctf{welcome_flag_adios_Much@cho}
```
## My First App
> Our intern dev swears this app’s secure...
This was a web challenge with an account creation form. Let's fire up Burp. The account creation request didn't seem suspicious for now, so I sent it to the repeater to abuse it some more. The response seemed interesting, the user id was in the query parameter: `GET /profile.php?id=5 HTTP/1.1`. This was a nice candidate for an Insecure Direct Object Reference(IDOR). I tried repeating the request with values from 0-4. The flag was at 1, the admin user's account.
```txt
mmuctf{1d0r_4dm1n_4cc3ss_1s_c0mpr0m1s3d}
```
## Ledilect
> Sometimes the path you take is just a jump away.
This was a simple one, I knew what the challenge wanted, but I couldn't get myself to exploit it, definitely a skill issue. The webapp had a landing page that had a button that made this request:
```txt
GET /portal/jump.php?url=https://example.com HTTP/1.1
Host: redacted
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US, en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Referer: redacted
Cookie: PHPSESSID=ce7743f6cd447d7a1ee94e230c3d9cdb
Upgrade-Insecure-Requests: 1
Priority: u=0, i
```
Looking at that, I suspected an open redirect vulnerability, but I don't know anything about this bug class. I let it rest.
## Meet my X
> In the�days оf cοmfort i met this girl at the Jobless соrner. Аt the�doоrs and windows of iddleness i approached, oops she smiled and thats how i knew she was the one. I guess thatsss whyyy i learned on getting Flags because be warned she later left me at first it feels like a green flag i guess no life was there on blood(heart_break)
This challenge involved homoglyphs, a character or a sequence of characters that looks very similar or identical to another character or sequence of characters, but has a different meaning, encoding, or origin.
A sentence might look normal, but if you copy it into a text editor that shows Unicode details or a specialized homoglyph detector, you'll see different underlying character codes.
I used these online decoders, <https://wulfsige.com/crypto/> and <https://holloway.nz/steg/> to get the flag:
```txt
mmuctf{oops_twitter_steg_1s_fun}
```
## Shadow
> Look beyond the appearance, perhaps their numerical essence will guide you to the flag.
> Can you reveal what lurks in the shadow?
This was another stego challenge; there is an image with what looks like a color palette. The description hints at 'numerical essence', so it might be something to deal with the hex values of the colors. I used this site <https://imagecolorpicker.com/> to extract the hex values.
```txt
#6d6d75
#637466
#7b346c
#773479
#355f68
#316464
#336e5f
#316e35
#64335f
#6d337d
```
Decoded becomes
```txt
mmuctf{4lw4y5_h1dd3n_1n5d3_m3}
```
## Revealme
> We found this mysterious executable on an old USB stick... Can you figure out how to get it to reveal the flag?
The provided file is an ELF executable binary.
```zsh
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ file revealme
revealme: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=d8546bb2c10c0226384fb2771684af9bc150b55e, for GNU/Linux 3.2.0, stripped
```
```zsh
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ checksec --file=revealme
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Partial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH No Symbols No 0 2 revealme
```
Opening it with Binary Ninja gives us a quick win:
```asm
00401179 int32_t main(int32_t argc, char** argv, char** envp)
00401179 55 push rbp {__saved_rbp}
0040117a 4889e5 mov rbp, rsp {__saved_rbp}
0040117d 4883ec70 sub rsp, 0x70
00401181 488d05800e0000 lea rax, [rel data_402008]
00401188 4889c7 mov rdi, rax {data_402008, "Enter the secret passphrase: "}
0040118b b800000000 mov eax, 0x0
00401190 e8abfeffff call printf
00401195 488b15a42e0000 mov rdx, qword [rel stdin]
0040119c 488d4590 lea rax, [rbp-0x70 {buf}]
004011a0 be64000000 mov esi, 0x64
004011a5 4889c7 mov rdi, rax {buf}
004011a8 e8b3feffff call fgets
004011ad 488d4590 lea rax, [rbp-0x70 {buf}]
004011b1 488d156e0e0000 lea rdx, [rel data_402026]
004011b8 4889d6 mov rsi, rdx {data_402026}
004011bb 4889c7 mov rdi, rax {buf}
004011be e88dfeffff call strcspn
004011c3 c644059000 mov byte [rbp+rax-0x70 {buf}], 0x0
004011c8 488d4590 lea rax, [rbp-0x70 {buf}]
004011cc 488d15550e0000 lea rdx, [rel data_402028]
004011d3 4889d6 mov rsi, rdx {data_402028, "OpenSesame123!"}
004011d6 4889c7 mov rdi, rax {buf}
004011d9 e892feffff call strcmp
004011de 85c0 test eax, eax
004011e0 7511 jne 0x4011f3
004011e2 488d054f0e0000 lea rax, [rel data_402038]
004011e9 4889c7 mov rdi, rax {data_402038, "Correct! The flag is: mmuctf{r3v3rs1ng_st4rt3r}"}
004011ec e83ffeffff call puts
004011f1 eb0f jmp 0x401202
004011f3 488d056e0e0000 lea rax, [rel data_402068]
004011fa 4889c7 mov rdi, rax {data_402068, "Nope, try again."}
004011fd e82efeffff call puts
00401202 b800000000 mov eax, 0x0
00401207 c9 leave {__saved_rbp}
00401208 c3 retn {__return_addr}
```
Flag:
```txt
mmuctf{r3v3rs1ng_st4rt3r}
```
## Flicker
> An ordinary looking Android app... or is it?
The provided app is an Android APK. Let's fire up jadx-gui. The package name is `com.example.blink`. There is an interesting class `r2d2`. In the onCreate method, there is an image string variable that seems to contain base64 image data.
```zsh
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ cat output.txt | base64 -d > decoded_image.png
```
flag:
```txt
CTF{PUCKMAN}
```
## Open_Secrets
> Someone trusted the wrong site and network didn’t forget. Can you piece together what was left behind?
> Some people still think locks are optional on digital doors.\*
The provided file was a network capture pcap file. For people who don't know, pcap (a packet capture) consists of an application programming interface (API) for capturing network traffic.The challenge title and filename hint at unencrypted traffic. Open up Wireshark and apply an HTTP filter. There is an HTTP stream that leaks the flag:
```txt
mmuctf{plaintext_login_leak}
```
## C-x C-s
> Ugh, I keep typing ^x ^s in my shell instead of saving, should’ve stuck with Emacs
This one made me mad. I thought I had the flag, but I couldn't get it. The provided file is a PCAP file. Another network forensics challenge, or so I thought.
opened the file with Wireshark packet and noticed a new kind of communication, to be honest, I didn't know this was possible until I understood what was happening...
I found some articles dealing with this
- <https://abawazeeer.medium.com/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4>
- <https://res260.medium.com/usb-pcap-forensics-barcode-scanner-nsec-ctf-2021-writeup-part-1-3-b0a5392c9313>
- <https://steemit.com/reverseengineering/@nileshevrywhr/auth0-ctf-reverse-engineering-usb-keystrokes-from-pcaps>
The source and destination use object IDs for communication, something I gathered when reading about the SNMP
protocol, USB(Universal Serial Bus)
it's apparent I'm not dealing with any 802.x traffic
Interrupts happen whenever you press a key or click a button, anything that "interrupts" the CPU, after which it has to process your input. Each URB_INTERRUPT in the file corresponds to a key pressed, and the Leftover Capture Data field shows the hex value of the key in 8-byte format.
Creating a filter to list all interrupt communication with non-empty 8 bytes
```txt
usb.transfer_type == 0x01
```
```txt
usb.transfer_type == 0x01 && usb.dst == "host" && !(usb.capdata == 00:00:00:00:00:00:00:00)
```
Crafting a tshark command to get the leftover capture data for the above filters and redirect it into a file
```zsh
tshark -r log.pcap -Tfields -Eseparator=, -e thekey.pcapng -Y 'usb.transfer_type == 0x01 && usb.dst == "host" && !(usb.capdata == 00:00:00:00:00:00:00:00)' | sed 's/://g' > usb.capdata
```
```zsh
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ tshark -r thekey.pcapng -Tfields -Eseparator=, -e usb.capdata -Y 'usb.transfer_type == 0x01 && usb.dst == "host" && !(usb.capdata == 00:00:00:00:00:00:00:00)' | sed 's/://g' > usb.capdata
┌──(mockingspectre㉿blackout)-[~/ctf/mmuctf2025]
└─$ cat usb.capdata
0000190000000000
00000c0000000000
00000c1000000000
0000102c00000000
00002c0000000000
0000090000000000
00000f0000000000
0000040000000000
0000040a00000000
................
```
Python script to decode the hex values to strings:
```python
keyboard = {
2: "PostFail", 4: "a", 5: "b", 6: "c", 7: "d", 8: "e", 9: "f", 10: "g", 11: "h", 12: "i", 13: "j", 14: "k", 15: "l", 16: "m", 17: "n", 18: "o", 19: "p", 20: "q", 21: "r", 22: "s", 23: "t", 24: "u", 25: "v", 26: "w", 27: "x", 28: "y", 29: "z", 30: "1", 31: "2", 32: "3", 33: "4", 34: "5", 35: "6", 36: "7", 37: "8", 38: "9", 39: "0", 40: "Enter", 41: "esc", 2: "del", 43: "tab", 44: "space", 45: "-", 47: "[", 48: "]", 51: "DownArrow", 54: "1", 55: "*", 56: "/", 57: "CapsLock", 79: "RightArrow", 80: "LeftArrow"
}
with open("usb.capdata") as file:
i = 1
for line in file:
bytesArray = bytearray.fromhex(line.strip())
for byte in bytesArray:
if byte != 0:
keyVal = int(byte)
if keyVal in keyboard:
print(keyboard[keyVal])
else:
print("no map found for this value: " + str(keyVal))
i += 1
```
Running the code outputs what seems to be Vim motions. I wasn't able to decipher this to a correct flag:
```txt
v
i
m
space
space
f
l
a
g
g
*
t
t
x
t
Enter
i
3
t
t
h
e
space
f
l
a
g
g
space
i
s
space
c
t
f
esc
v
b
3
u
u
3
a
3
[
[
m
y
3
-
3
f
a
v
o
r
i
t
e
e
3
-
e
d
i
t
o
r
3
-
3
i
s
3
-
v
i
m
3
]
esc
h
h
h
h
h
h
h
h
h
h
h
h
h
h
h
h
h
h
h
a
u
esc
v
i
3
[
3
3
u
3
esc
3
DownArrow
DownArrow
w
q
Enter
a
tab
a
e
```
These are the challenges I had the time to tackle. if you have any insights or suggestions. Share them in the comments
-116
View File
@@ -1,116 +0,0 @@
---
title: "Setting up Obsidian sync in Windows"
description: "Syncing Obsidian in Windows with Windows Task Scheduler with git"
date: "2023-10-01"
tags: ["obsidian", "git", "sync", "windows", "cron", "task-scheduler", "powershell"]
---
Syncing Obsidian in Windows with Windows Task Scheduler and git
[Obsidian](https://obsidian.md/) is a powerful note-taking and knowledge management tool that has gained a dedicated following among researchers, writers, and knowledge workers. To make the most of Obsidian, it's essential to keep your notes synchronized across devices and ensure your data is regularly backed up.Obsidian is the private and flexible writing app that adapts to the way you think.
Obsidian is free for personal use.It does not charge based on features or usage.You only pay if you use Obsidian commercially.
In this article, we'll guide you through the process of setting up automated synchronization for your Obsidian vault on Windows using Windows Task Scheduler and a PowerShell script.[^note]
## Prerequisites
Before we dive into setting up the synchronization task, ensure you have the following prerequisites in place:
1. **Obsidian Installed:** Make sure Obsidian is [installed](https://obsidian.md/download) on your Windows computer, and you have an existing Obsidian vault that you want to sync.
1. **Git Installed:** You'll need Git installed and configured with your Obsidian vault's repository. If you haven't already done this, you can download Git from the [official website](https://git-scm.com/downloads) and follow the installation instructions.
1. **PowerShell Script:** The provided PowerShell script, sync.ps1, should be located in your Obsidian vault folder.
## Understanding the PowerShell Script
The provided PowerShell script, sync.ps1, is the heart of our synchronization task. It automates the process of committing changes in your Obsidian vault's Git repository and pushing them to your remote repository (e.g., GitHub or GitLab). Here's a brief overview of the script:
```ps1
# Define the folder path
$FolderPath = "C:\path\to\obsidian-vault"
# Change directory to the repository folder
Set-Location -Path $FolderPath
# Check if the working tree is clean
$IsClean = (git diff-index --quiet HEAD --) -or (git diff-files --quiet)
if ($IsClean) {
Write-Host "Working tree is clean. Skipping commit and pushing changes."
git push
} else {
# Get the current date in the desired format (Day - Date)
$CommitMessage = "$(Get-Date -Format 'dddd - yyyy-MM-dd HH:mm:ss')"
# Commit the changes
git add .
git commit -m $CommitMessage
# Push the changes
git push
}
```
This script does the following:
- Sets the folder path to your Obsidian vault.
- Checks if there are any changes to commit. If the vault is clean (no changes), it skips the commit and only pushes changes.
- If there are changes, it commits them with a timestamped message and then pushes them to the remote repository.
## Setting up Windows Task Scheduler
Now that we have our PowerShell script ready, let's set up a scheduled task using Windows Task Scheduler to automate the synchronization process. Follow these steps:
1. **Open an Elevated PowerShell Prompt:** To run the necessary commands, open PowerShell as an administrator.
1. **Define Task Variables:** Execute the following commands to define variables for your task:
```ps1
$ScriptPath = "C:\path\to\obsidian-vault\sync.ps1"
$TaskName = "obsidian-sync"
$UserAccount = "$env:USERDOMAIN\$env:USERNAME"
```
Replace $ScriptPath with the actual path to your sync.ps1 script, $TaskName with a name for your task.
1. **Configure Task Trigger:** Set up a trigger for your task. In this example, we'll schedule the task to run daily at 9:00 PM:
```ps1
$Trigger = New-ScheduledTaskTrigger -Daily -At '9:00 PM'
```
You can adjust the schedule according to your preference.
1. Define Task Principal and Settings: Configure the task's principal (the user account under which the task will run) and settings:
```ps1
$Principal = New-ScheduledTaskPrincipal -UserId $UserAccount -RunLevel Highest
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -RunOnlyIfNetworkAvailable -WakeToRun
```
These settings ensure that the task runs with the necessary privileges and conditions.
1. **Define Task Action:** Specify the action that the task will perform, which is running the PowerShell script:
```ps1
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ScriptPath`""
```
This action runs PowerShell with the provided script.
1. **Create the Scheduled Task:** Finally, create the scheduled task and register it with Windows Task Scheduler:
```ps1
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings
Register-ScheduledTask -TaskName $TaskName -InputObject $Task
```
The Obsidian synchronization task is now set up and ready to run automatically based on the schedule you defined.
# Inspiration
When looking up on how to implement this I found some breakthrough from this [stack overflow](https://stackoverflow.com/questions/7195503/setting-up-a-cron-job-in-windows) post. There are suggestions on how to do this using cron jobs in wsl. They are worth a look at. This article on [powershell](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtask?view=windowsserver2022-ps) with windows server was also helpful.
[^note]: This method is only optimal for desktop sync. To sync across devices obsidian has a paid plan that has some extra features Such as Sync notes across devices, End-to-end encryption, Version history, Priority email support. Consider checking it out at [https://obsidian.md/pricing](https://obsidian.md/pricing)
File diff suppressed because one or more lines are too long
@@ -1,237 +0,0 @@
---
title: "Self-Hosting Gitea and Automating GitHub Mirrors"
description: "Self-Hosting Gitea and Automating GitHub Mirrors (and Everything Cloudflare Broke Along the Way)"
date: "2026-08-19"
tags: ["self-hosting", "gitea", "dokploy", "cloudflare", "github-actions", "bash"]
---
I run a Hetzner box with [Dokploy](https://docs.dokploy.com) for most of my personal infrastructure. I'd been meaning to get a self-hosted git server on it for a while, mainly so I have a durable mirror of my GitHub repos that doesn't depend on GitHub staying up, staying free, or staying interested in hosting my code. This is the log of actually doing it: what I picked, what broke, and the debugging trail for the parts that took longer than they should have.
Full script and workflow are on [github.com/andwati/gitea-mirror-sync](https://github.com/andwati/gitea-mirror-sync) if you want to skip straight to the code.
## Why not GitLab
GitLab CE was my first instinct. It's the "serious" self-hosted option, and Dokploy ships a template for it out of the box. But the omnibus image bundles Postgres, Redis, Sidekiq, Puma, Gitaly, Workhorse, and a Prometheus stack into a single container, with an official minimum of 4GB RAM. My box has 8GB total, already shared with a handful of other services. Giving GitLab half the machine just to get merge requests and a UI I mostly wouldn't use felt like the wrong trade.
Gitea is a single Go binary. Idle footprint is a few hundred MB against GitLab's multiple gigabytes, boot time is seconds instead of minutes, and there's no `trusted_proxies` CIDR guessing or five-minute health check grace periods to plan around. For a personal git server, it's the right-sized tool. The trade-off is CI maturity (Gitea Actions is newer than GitLab CI) and no built-in SAST/DAST scanning, neither of which I actually needed here.
## The stack
Gitea and Postgres, both in one Dokploy compose file, with everything pushed out to environment variables so the compose itself never needs touching again:
```yaml
services:
gitea:
image: docker.gitea.com/gitea:${GITEA_IMAGE_TAG}
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment:
- USER_UID=${GITEA_USER_UID:-1000}
- USER_GID=${GITEA_USER_GID:-1000}
- GITEA__database__DB_TYPE=${GITEA_DB_TYPE}
- GITEA__database__HOST=${GITEA_DB_HOST}:${POSTGRES_PORT}
- GITEA__database__NAME=${POSTGRES_DB}
- GITEA__database__USER=${POSTGRES_USER}
- GITEA__database__PASSWD=${GITEA_DB_PASSWORD}
- GITEA__server__DOMAIN=${GITEA_HOST}
- GITEA__server__ROOT_URL=${GITEA_PROTOCOL:-https}://${GITEA_HOST}/
- GITEA__server__HTTP_PORT=${GITEA_HTTP_PORT:-3000}
- GITEA__server__PROTOCOL=${GITEA_INTERNAL_PROTOCOL:-http}
- GITEA__server__DISABLE_SSH=true
- GITEA__server__SSH_PORT=${GITEA_SSH_EXTERNAL_PORT:-2222}
- GITEA__server__SSH_LISTEN_PORT=${GITEA_SSH_LISTEN_PORT:-22}
- GITEA__server__REVERSE_PROXY_TRUSTED_PROXIES=${GITEA_TRUSTED_PROXIES:-172.16.0.0/12,10.0.0.0/8}
- GITEA__mailer__ENABLED=${GITEA_MAILER_ENABLED:-true}
- GITEA__mailer__PROTOCOL=${GITEA_MAILER_PROTOCOL:-smtp+starttls}
- GITEA__mailer__SMTP_ADDR=${GITEA_MAILER_SMTP_ADDR:-smtp.gmail.com}
- GITEA__mailer__SMTP_PORT=${GITEA_MAILER_SMTP_PORT:-587}
- GITEA__mailer__USER=${GMAIL_ADDRESS}
- GITEA__mailer__PASSWD=${GMAIL_APP_PASSWORD}
- GITEA__mailer__FROM=${GITEA_MAILER_FROM:-${GMAIL_ADDRESS}}
- GITEA__mirror__ENABLED=${GITEA_MIRROR_ENABLED:-true}
- GITEA__mirror__DEFAULT_INTERVAL=${GITEA_MIRROR_DEFAULT_INTERVAL:-8h}
- GITEA__mirror__MIN_INTERVAL=${GITEA_MIRROR_MIN_INTERVAL:-10m}
- GITEA__packages__ENABLED=${GITEA_PACKAGES_ENABLED:-true}
- GITEA__service__DISABLE_REGISTRATION=${GITEA_DISABLE_REGISTRATION:-true}
- GITEA__service__REQUIRE_SIGNIN_VIEW=${GITEA_REQUIRE_SIGNIN_VIEW:-false}
- GITEA__other__SHOW_FOOTER_VERSION=false
volumes:
- gitea-data:/data
ports:
- "${GITEA_SSH_EXTERNAL_PORT:-2222}:${GITEA_SSH_LISTEN_PORT:-22}"
expose:
- "${GITEA_HTTP_PORT:-3000}"
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:${GITEA_HTTP_PORT:-3000}/api/healthz"]
interval: ${GITEA_HEALTHCHECK_INTERVAL:-15s}
timeout: ${GITEA_HEALTHCHECK_TIMEOUT:-5s}
retries: ${GITEA_HEALTHCHECK_RETRIES:-10}
start_period: ${GITEA_HEALTHCHECK_START_PERIOD:-30s}
postgres:
image: docker.io/library/postgres:${POSTGRES_IMAGE_TAG:-17-alpine}
restart: unless-stopped
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${GITEA_DB_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB}
volumes:
- pg-data:/var/lib/postgresql/data
expose:
- "${POSTGRES_PORT}"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
interval: ${POSTGRES_HEALTHCHECK_INTERVAL:-10s}
timeout: ${POSTGRES_HEALTHCHECK_TIMEOUT:-5s}
retries: ${POSTGRES_HEALTHCHECK_RETRIES:-5}
volumes:
gitea-data: {}
pg-data: {}
```
The GitHub Actions workflow that runs the mirror script:
```yaml
name: Mirror GitHub repos to Gitea
on:
schedule:
# Runs at 00:00 UTC daily. Midnight EAT (UTC+3) would be "0 21 * * *" the day before.
- cron: "0 0 * * *"
workflow_dispatch:
inputs:
debug_http:
description: "Print request/response headers for every Gitea write call"
type: boolean
default: false
jobs:
mirror:
runs-on: ubuntu-latest
steps:
- name: Checkout (for the script)
uses: actions/checkout@v5
- name: Install jq
run: sudo apt-get update && sudo apt-get install -y jq
# The mirror runs from a GitHub-hosted runner, not the network I usually test from,
# so it can hit Gitea through a different proxy path than my laptop does. This POSTs
# a harmless JSON body and reports whether Content-Type survived the trip. A 422
# "Empty Content-Type" here means something between the runner and Gitea is dropping
# the header, not that the mirror payload itself is wrong.
- name: Preflight - can this runner POST JSON to Gitea?
env:
GITEA_URL: ${{ secrets.GITEA_URL }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
url="${GITEA_URL%/}"
echo "GET /api/v1/version -> $(curl -s -o /dev/null -w '%{http_code}' \
-H "Authorization: token ${GITEA_TOKEN}" "${url}/api/v1/version")"
for proto in --http2 --http1.1; do
code=$(curl -s $proto -o /tmp/pre.json -w '%{http_code}' \
-X POST "${url}/api/v1/markdown" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-H "Expect:" \
--data-binary '{"text":"preflight","mode":"markdown"}')
echo "POST /api/v1/markdown ${proto} -> ${code}"
[ "$code" = "200" ] || head -c 300 /tmp/pre.json; echo
done
- name: Mirror all repos to Gitea
env:
GITHUB_TOKEN: ${{ secrets.GH_PAT }}
GITEA_URL: ${{ secrets.GITEA_URL }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_OWNER: ${{ secrets.GITEA_OWNER }}
DEBUG_HTTP: ${{ inputs.debug_http && '1' || '' }}
run: ./mirror-github-to-gitea.sh
```
A few decisions worth explaining.
**SSH on 2222, not 22.** The host's own sshd already owns port 22, so Gitea's internal SSH got mapped to 2222, with [`SSH_PORT`](https://docs.gitea.com/administration/config-cheat-sheet/) set to match so Gitea generates correct clone URLs.
<aside class="callout callout-note">
I later set `GITEA__server__DISABLE_SSH=true` (see [`DISABLE_SSH`](https://docs.gitea.com/administration/config-cheat-sheet/) in Gitea's config cheat sheet) and dropped the port mapping entirely. Cloudflare's proxy only forwards HTTP and HTTPS traffic, not arbitrary TCP, so SSH on 2222 was simply unreachable once `gitea.andwati.com` sat behind the orange cloud. The two ways around that were a DNS-only subdomain, which leaks the origin IP to anyone who runs `dig`, or a Cloudflare Tunnel, which is more moving parts than a personal git server's SSH clone was worth. HTTPS clone already worked fine through the proxy, so disabling SSH was the simpler trade.
</aside>
**Traefik/Dokploy terminates TLS, Gitea speaks plain HTTP internally.** [Dokploy's domain manager](https://docs.dokploy.com/docs/core/domains) handles the Let's Encrypt cert and routes to the container on port 3000. `REVERSE_PROXY_TRUSTED_PROXIES` is set so Gitea trusts the forwarded headers instead of thinking every request comes from the internal Docker network.
**Mail via Gmail SMTP**, gated behind an App Password since Google dropped plain password auth for SMTP a while back.
**Everything as env vars with sane defaults**, so the only things I actually type into Dokploy per deploy are the domain, the DB password, and the mail credentials.
## Token scopes
Two tokens drive the mirror script, and both need to be scoped correctly or the migrate call fails in ways that look unrelated to permissions.
### **GitHub token (`GH_PAT`).**
A classic Personal Access Token with the `repo` scope, generated at [github.com/settings/tokens](https://github.com/settings/tokens). This is the scope GitHub's own docs point to for reading private repositories, and it's also what Gitea's own migration guide recommends when the source is GitHub. A fine-grained token works too, provided it has read access to Contents and Metadata across all the repos you want mirrored, but classic `repo` is simpler to reason about for a personal account with dozens of repos rather than picking them one by one.
### **Gitea token (`GITEA_TOKEN`).**
Needs the `write:repository` scope, generated from your Gitea instance at Settings → Applications → Generate New Token (`https://<your-gitea-domain>/user/settings/applications`). `write:repository` covers both the `/repos/migrate` call that creates new mirrors and the `PATCH` call the script uses to sync visibility on existing ones. `read:repository` alone isn't enough since both of those are write operations.
### **Where they get set.**
Both live as encrypted secrets on the `gitea-mirror-sync` repo, not in the script or the workflow file: Settings → Secrets and variables → Actions → New repository secret, alongside `GITEA_URL` and `GITEA_OWNER`. The workflow references them only as `${{ secrets.GH_PAT }}` and `${{ secrets.GITEA_TOKEN }}`, so neither value is ever visible in a log or checked into the repo itself.
## Bot Fight Mode: the wall you can't route around
The bot-challenge problem looked like a quick fix at first. Add a WAF custom rule that matches the hostname and skips security checks: Bot Fight Mode, managed rules, browser integrity check, all of it. That got a plain `curl` from my own machine through cleanly. It did nothing for the GitHub Actions runner, which kept getting served a JS challenge page on every write request.
The reason turned out to be a real platform limit, not a rule I'd written wrong. Cloudflare's free-tier [Bot Fight Mode](https://developers.cloudflare.com/bots/get-started/bot-fight-mode/) doesn't run on the Ruleset Engine at all. It's a separate evaluation pipeline where `Skip`, `Bypass`, and `Allow` actions have no effect. Only Super Bot Fight Mode, which needs a Pro plan, runs on the Ruleset Engine and actually respects skip rules. On Free there's no way to carve out an exception for a specific host or path. It's off or it's on for the whole zone.
For a git server whose traffic is almost entirely programmatic (API calls, `git clone`, CI runs, registry pushes), Bot Fight Mode was fighting the exact use case the server exists for. I turned it off zone-wide (Security → Settings → Bot traffic) rather than pay for Pro just to get a skip rule that would only ever have applied to this one subdomain anyway.
## The 422 that took a while to track down
With Cloudflare out of the way, the mirror script started reaching Gitea and immediately failed every single repo with:
```
{"message":"[]: Empty Content-Type","url":".../api/swagger"}
```
`Content-Type: application/json` was set explicitly on every `curl` call, so the error made no sense at first glance. The actual cause was structural. The migrate request was built with `curl -d @- <<EOF ... EOF` inside a `while read` loop that was itself fed by a pipe: `jq ... | while read -r entry; do ... done`. The loop's own `read` and curl's `-d @-` were both drawing from the same stdin, and the heredoc body wasn't landing in the request the way it should have on paper.
The fix was to stop routing anything through stdin inside the loop:
- Build the JSON payload with `jq -n` into a file instead of a heredoc, so there's no ambiguity about where the body comes from.
- Switch the loop from a pipe into process substitution, `done < <(...)`, so the loop body never shares stdin with anything running inside it.
- Send the body with `--data-binary "@file"` instead of `-d @-`.
That fixed it, but chasing it down surfaced a second, sneakier failure mode worth guarding against for good: a secret pasted into a GitHub Actions secret with a trailing newline. If a token has a trailing `\n`, curl writes `Authorization: token <value>\n`, and that bare newline terminates the header block early. Every header written after it, `Content-Type` included, lands in the request body instead of staying a header. GETs survive this because nothing they need comes after `Authorization`. Writes don't. The final version of the script trims all four credentials on load, warns if any of them needed trimming, and falls back to retrying over HTTP/1.1 if a write still comes back with "Empty Content-Type," since some reverse proxies handle HTTP/2 header framing differently than HTTP/1.1.
## What the script does now
It pages through `/user/repos` on GitHub, not the public-only `/users/{user}/repos`, so private repos are included. For each one:
- **Doesn't exist in Gitea yet** → migrates it as a pull mirror, matching GitHub's visibility (`private` flows straight through).
- **Already mirrored, visibility has drifted** → `PATCH`es the Gitea repo to match GitHub's current visibility. Covers the case where a repo gets made private on GitHub after the mirror was first created.
- **Already mirrored, visibility matches** → no-op.
It also picked up an `ONLY=<repo-name>` escape hatch for smoke-testing one repo before running the whole account through it, and a `DEBUG_HTTP=1` flag that dumps redacted request and response headers when something's misbehaving.
The [workflow](https://github.com/andwati/gitea-mirror-sync/blob/main/.github/workflows/mirror-to-gitea.yml) runs it daily on a [cron schedule](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule), with a `workflow_dispatch` trigger for manual runs, plus a preflight step that POSTs a harmless request to Gitea's markdown-render endpoint first and reports whether `Content-Type` survived the trip. If Cloudflare or the proxy chain ever regresses again, the workflow fails fast on the preflight instead of quietly mangling every repo migration.
## Takeaways
- **Resource-match the tool to the box.** GitLab is the obvious choice and the wrong one for an 8GB personal server running other things too. Gitea's footprint fits reality.
- **Cloudflare's proxy has real, non-obvious interactions with anything that isn't a browser.** TLS issuance and bot protection both assume the traffic model is "human on a webpage." A git server's actual traffic model is closer to machine talking to machine, on a schedule, indefinitely.
- **Free-tier Bot Fight Mode is not configurable, full stop.** If your infrastructure sees more API and CI traffic than browser traffic, know going in that the free bot protection can't be scoped down. It's off or it's Pro.
- **Heredocs and piped `while read` loops don't mix well when something inside the loop also wants stdin.** Process substitution sidesteps the whole category of bug.
- **Trim your secrets.** A trailing newline in a pasted token is invisible in every UI that shows it back to you, and it will produce an error message that points nowhere near the actual cause.
@@ -1,81 +0,0 @@
---
title: "Semantic Versioning(SemVer) and Conventional Commits"
description: "Adopting best practices in your git and build workflows."
date: "2023-01-24"
tags: ["git", "semver", "workflow", "conventional-commits"]
---
Adopting best practices in your git and build workflows.
# What is Semver?
Semantic versioning or just SemVer is a dependency naming guideline that aims to bring some sanity into naming libraries and packages in software development. It is a standard versioning system created by **Tom Preston Werner** (co-founder of Github) that’s used to communicate what changes are in a release.
An efficient and smooth versioning becomes crucial for efficient software delivery expecially for projects that expose a public API. This saves the developers the chaos that is **dependency hell**.Dependency hell is a colloquial term for the frustration of some software users who have installed software packages which have dependencies on specific versions of other software packages.
The dependency issue arises when several packages have dependencies on the same shared packages or libraries, but they depend on different and incompatible versions of the shared packages. If the shared package or library can only be installed in a single version, the user may need to address the problem by obtaining newer or older versions of the dependent packages. This, in turn, may break other dependencies and push the problem to another set of packages.
## Semantic Versioning Specifications
### Summary
Semantic versioning is based on three numbers that indicate the versions of the software and the compatibilities.They are `X.Y.Z` corresponding to `Major.Minor.Patch`
- **Major Version (X):**Introduces major changes to the code and breaking changes toward backward compatibility
- **Minor Version (Y):** These code changes don’t introduce breaking changes. This could be adding a new feature that doesn't break changes but are not exactly bug fixes.
- **Patches (Z):** Mainly correspond to bug fixes
### Examples in common packages
#### React(v18.2.0)
- **Major -> 18**
- **Minor -> 2**
- **Patch -> 0**
---
#### Pipx(v1.1.0)
- **Major -> 1**
- **Minor -> 1**
- **Patch -> 0**
---
## Start at v0.1.0 or v1.0.0?
Convention recommends that in the initial development phase the starting version should be 0.1.0 which makes sense since it’s not in production yet.
The version should only be bumped to 1.0.0 only if it is being used in production and stable.
If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.
# Conventional Commits
Conventional Commits is a convention on top of commit messages that are used to automate version changes. It provides an easy set of rules for creating commit messages and works well with SemVer by describing features, fixes and breaking changes that correspond to SemVer standards.
## Summary
The commit message should be structured as follows:
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
The commit contains the following structural elements, to communicate intent to the consumers of your library:
1. fix: a commit of the type fix patches a bug in your codebase (this correlates with PATCH in Semantic Versioning).
2. feat: a commit of the type feat introduces a new feature to the codebase (this correlates with MINOR in Semantic Versioning).
3. BREAKING CHANGE: a commit that has a footer BREAKING CHANGE:, or appends a ! after the type/scope, introduces a breaking API change (correlating with MAJOR in Semantic Versioning). A BREAKING CHANGE can be part of commits of any type.
4. types other than fix: and feat: are allowed, for example @commitlint/config-conventional (based on the Angular convention) recommends build:, chore:, ci:, docs:, style:, refactor:, perf:, test:, and others.
5. footers other than BREAKING CHANGE: <description> may be provided and follow a convention similar to git trailer format.
# Resources
<https://semver.org/>
<https://www.conventionalcommits.org/en/v1.0.0/>
-115
View File
@@ -1,115 +0,0 @@
---
title: "Subresource Integrity"
description: "Understanding Subresource Integrity"
date: "2023-04-29"
tags: ["subresource-integrity", "csp", "cors"]
---
Understanding Subresource Integrity
In my junior year while I was learning HTML and CSS I got to use the Bootstrap css library.The easiest way to obtain the files was from a Content Delivery Network(CDN). I could see links such as:
```html
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"
crossorigin="anonymous"
/>
```
I didn't bother with the `integrity` attribute of the link(guess I wasn't curios enough). The integrity attribute has a cryptographic hash value that is important in CDNs and its called the Subresource Integrity.
Subresource Integrity (SRI) is a security feature in web browsers that helps prevent malicious or compromised scripts from being loaded and executed on a website.a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.
When a resource, such as a script or stylesheet, fails the SRI check, the browser will block the resource from being loaded and displayed on the website.
# How Subresource Integrity Helps
Subresource Integrity (SRI) is a security feature that helps protect against certain types of attacks, such as those that involve malicious modifications to third-party resources that a website loads.
SRI works by allowing a website to specify a cryptographic hash for a particular external resource (such as a JavaScript file or a CSS stylesheet) that it expects to load. When a user's browser fetches that resource, it checks the hash against the actual contents of the resource. If the hash doesn't match, the browser will refuse to load the resource, indicating that it may have been tampered with.
This can help prevent a variety of attacks, such as those involving a compromised content delivery network (CDN) or a man-in-the-middle attacker who intercepts and modifies network traffic. By using SRI, a website can help ensure that it is loading only the resources it expects, and that those resources have not been tampered with in transit.
# Using it
Using Subresource Integrity (SRI) involves a few steps, but it is relatively straightforward.An integrity value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base64-encoded hash.
- Generate a cryptographic hash(a base64-encoded cryptographic hash) of the external resource you want to load on your website. This can be done using a hash function such as SHA-256.
- Add the hash as an attribute to the tag that loads the external resource. For example, for a JavaScript file, you would add the integrity attribute to the `<script>` tag like this:
```html
<script src="https://example.com/example.js" integrity="sha256-ABC123XYZ456"></script>
```
> An integrity value may contain multiple hashes separated by whitespace. A resource will be loaded if it matches one of those hashes.
Make sure the hash you've generated matches the actual contents of the external resource.
Test your website to ensure that the external resource is loading correctly and that the SRI feature is working as intended.
# Tools for generating SRI hashes
You can use a tool such as the [SRI Hash Generator](https://www.srihash.org/) to generate the hash and check it against the file's contents.
You can generate SRI hashes from the command-line with openssl using a command invocation such as:
```sh
cat FILENAME.py | openssl dgst -sha384 -binary | openssl base64 -A
```
or with shasum using a command invocation such as:
```sh
shasum -b -a 384 FILENAME.js | awk '{ print $1 }' | xxd -r -p | base64
```
> The pipe-through xxd step takes the hexadecimal output from shasum and converts it to binary.
> The pipe-through awk step is necessary because shasum will pass the hashed filename in its output to xxd. That can have disastrous consequences if the filename happens to have valid hex characters in it — because xxd will also decode that and pass it to base64.
In a Windows environment, you can create a tool for generating SRI hashes with the following code:
```bat
@echo off
set bits=384
openssl dgst -sha%bits% -binary %1% | openssl base64 -A > tmp
set /p a= < tmp
del tmp
echo sha%bits%-%a%
pause
```
To use that code:
1. Save that code in a file named sri-hash.bat in the Windows SendTo folder in your environment (for example, C:\Users\USER\AppData\Roaming\Microsoft\Windows\SendTo).
1. Right-click a file in the File Explorer, select Send to…, and then select sri-hash. You will see the integrity value in a command box.
1. Select the integrity value and right-click to copy it to the Clipboard.
1. Press any key to dismiss the command box
# Cross-Origin Resource Sharing and Subresource Integrity
When verifying the subresource integrity of a resource that originates from a different domain than the document it's embedded in, web browsers will check the resource using Cross-Origin Resource Sharing (CORS) to ensure that the domain serving the resource allows it to be shared with the requesting domain.
As a result, the resource must be served with an Access-Control-Allow-Origin header that permits the resource to be shared with the requesting domain. For example, the header could include a wildcard (\*) to allow any domain to access the resource.
```
Access-Control-Allow-Origin: *
```
# How browsers handle Subresource Integrity
Web browsers employ several mechanisms to handle Subresource Integrity (SRI). When a **script** or **link** element with an integrity attribute is encountered by the browser, it compares the script or stylesheet to the expected hash given in the integrity value before executing the script or applying the stylesheet.
For resources served from a different domain than the document in which it's embedded, the browser also checks the resource using Cross-Origin Resource Sharing (CORS) to ensure that the origin serving the resource allows it to be shared with the requesting domain. This additional check is important for preventing unauthorized access to sensitive resources.
If the script or stylesheet fails to match its associated integrity value, the browser will refuse to execute the script or apply the stylesheet and return a network error, indicating that the fetching of that script or stylesheet failed. This behavior ensures that the resource being loaded is trustworthy and helps to protect users from potential security threats.
# References
- [https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
- [https://www.srihash.org/](https://www.srihash.org/)
- [https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
- [https://html.spec.whatwg.org/multipage/semantics.html#attr-script-integrity](https://html.spec.whatwg.org/multipage/semantics.html#attr-script-integrity)
- [https://html.spec.whatwg.org/multipage/semantics.html#attr-link-integrity](https://html.spec.whatwg.org/multipage/semantics.html#attr-link-integrity)
- [https://w3c.github.io/webappsec-subresource-integrity/#the-integrity-attribute](https://w3c.github.io/webappsec-subresource-integrity/#the-integrity-attribute)
@@ -1,77 +0,0 @@
---
title: "The Single Byte That Kills Your Exploit: Understanding Endianness"
description: "Problem: Computers speak different languages, like people"
date: "2025-11-09"
tags: ["blog"]
---
If you’ve ever crafted a perfect shellcode and ROP chain only to have your exploit immediately crash with a SIGSEGV(a signal sent by the operating system to a program when it attempts to access a protected or invalid memory location) or EIP(a 32-bit CPU register in the x86 architecture that holds the memory address of the next machine instruction to be executed) pointing to garbage, you’ve likely met the silent killer of beginners: Endianness.
Endianness is fundamental; it defines the order in which a multi-byte value (like a 4-byte integer or an 8-byte memory address) is stored in a machine’s memory. For us in the pwn game, this translates directly to whether the addresses we pack into our exploit payloads are interpreted correctly by the target program. A single misplaced byte means the difference between a shell and a stack smash(stack buffer overflow**)**.
## Little vs. Big: The Two Orders
There are two primary byte orders
Little-Endian (LE): The Least Significant Byte (LSB) is stored first, at the lowest memory address. This is the byte order used by the vast majority of personal computers, including all modern Intel/AMD (x86/x64) architectures.
Big-Endian (BE): The Most Significant Byte (MSB) is stored first, at the lowest memory address. This is often called Network Byte Order (NBO) and is common in network protocols, as well as some older or embedded architectures like PowerPC, MIPS, and SPARC.
## Cross-architecture exploitation (LE <-> BE)
If you’re attacking an embedded device, router, or IoT target, it might be Big-Endian. Always confirm the target architecture and ABI. Common mistakes when cross-compiling or reusing gadgets:
Using x86/x86_64 gadgets and packers on a MIPS/PowerPC target (different endianness and instruction set) will not work.
pwntools and other frameworks allow you to set `context.arch` and `context.endian` So packers and disassemblers behave correctly.
## How to detect the target’s endianness quickly
Run the small C program above on the target if you have code execution. Use `readelf`, `file`, or `objdump` On binaries from the target filesystem, some formats indicate endianness.
In GDB, examine the memory representation of a known constant or pointer. Put a known value in a register or memory, and inspect the byte order with `x/4xb address`.
```gdb
(gdb) p/x 0x41424344
$1 = 0x41424344
(gdb) set {int}0x601000 = 0x41424344
(gdb) x/4xb 0x601000
0x601000: 0x44 0x43 0x42 0x41 # little-endian: ‘DCBA’
```
## Debugging tips when an exploit “looks right” but crashes
Print the raw payload bytes you are sending, compare with what the target receives (packet capture or logging), and what the target’s memory shows in a debugger.
Verify pointer size. Are you packing 32-bit or 64-bit addresses?
Check alignment and padding. Are there extra bytes inserted by the protocol or `scanf`/`fgets` behavior?
Confirm endianness on the target; don’t assume x86 for embedded devices.
Use tool packing (`struct.pack`, `pwntools`) instead of hand-reversing where possible.
If attacking over the network, confirm whether fields are consumed in network byte order.
## Short checklist for exploit authors
- Confirm target architecture (x86, x86_64, MIPS, ARM, PowerPC).
- Confirm endianness (LE or BE).
- Use correct pointer width (`p32` vs `p64`) and pack accordingly.
- Use library packing (`struct`, `pwntools`) to avoid manual reversal mistakes.
- For network services, encode multi-byte protocol fields in network (big-endian) byte order unless the protocol documentation says otherwise.
- Check struct padding and alignment on the target.
- Inspect the target’s memory with a debugger to verify the actual byte layout.
## Final thoughts
Endianness is simple in concept but vital in practice. For most modern exploit work, you’ll be on x86*64 (Little-Endian), so make it a habit to pack addresses in reverse byte order relative to how you read them in a disassembler. Use `pwntools`, `struct`, or equivalent to do the packing for you, but keep in mind \_why* bytes are reversed; that understanding is what will let you debug the next crash quickly and confidently.
Recommended reading:
- <https://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/>
- <https://medium.com/coderscorner/byte-ordering-e4737416d906>
- <https://devopedia.org/byte-ordering>
- <https://www.geeksforgeeks.org/dsa/little-and-big-endian-mystery/>
Disclaimer: This article was written with AI assistance, for a bit of brainstorming and proofreading.
-63
View File
@@ -1,63 +0,0 @@
---
title: "What say you?"
description: "Adding a comment system by utterances"
date: "2023-08-24"
tags: ["blog", "utterances"]
---
Free speech enhanced
There is no point in writing online if your readers cannot provide feedback for your writings. You might as well be shouting at a void. My ideal commenting system has to be free, open source and should not be a hassle to setup. Luckily, [utterances 🔮](https://github.com/utterance/utterances) checks all of these conditions
It is a lightweight comments widget built on GitHub issues. Use GitHub issues for blog comments, wiki pages and more! The notable features are:
- Open source. 🙌
- No tracking, no ads, always free. 📡🚫
- No lock-in. All data stored in GitHub issues. 🔓
- Styled with Primer, the css toolkit that powers GitHub. 💅
- Dark theme. 🌘
- Lightweight. Vanilla TypeScript. No font downloads, JavaScript frameworks or polyfills for evergreen browsers. 🐦🌲
## How it works
When Utterances loads, the GitHub [issue search API](https://developer.github.com/v3/search/#search-issues) is used to find the issue associated with the page based on url, pathname or title. If it cannot find an issue that matches the page, [utterances-bot](https://github.com/utterances-bot) will automatically create an issue the first time someone comments.
To comment, users must authorize the utterances app to post on their behalf using the GitHub [OAuth flow](https://developer.github.com/v3/oauth/#web-application-flow). Alternatively, users can comment on the GitHub issue directly.
# Setting up Utterances
### Repository
Choose the repository utterances will connect to.
Make sure the repo is public, otherwise your readers will not be able to view the issues/comments.
Make sure the utterances app is installed on the repo, otherwise users will not be able to post comments.
If your repo is a fork, navigate to its settings tab and confirm the issues feature is turned on.
```
repo:
username/repo
```
A public GitHub repository. This is where the blog post issues and issue-comments will be posted.
### Theme
Choose an Utterances theme that matches your blog.
### Enable Utterances
Add the following script tag to your blog's template. Position it where you want the comments to appear. Customize the layout using the .utterances and .utterances-frame selectors.
```js
<script
src="https://utteranc.es/client.js"
repo="[ENTER REPO HERE]"
issue-term="title"
theme="gruvbox-dark"
crossorigin="anonymous"
async
></script>
```
The complete documentation can be found at [https://utteranc.es](https://utteranc.es/)
-121
View File
@@ -1,121 +0,0 @@
---
title: "Configure Vue.js app With Tailwind CSS"
description: "Tailwindcss in vuejs "
date: "2021-06-12"
tags: ["javascript", "vuejs", "tailwindcss"]
---
A guide on how to use [Tailwind CSS](https://tailwindcss.com/) in your Vue project.
> **Note**
> This article was originally published on my old medium blog. I moved it here for archival purposes.
Tailwind is a utility-first CSS framework for rapidly building custom user interfaces. It is an un-opinionated framework which means that it doesn't come with custom configurations like Bootstrap or Bulma(Yeah, I know, no one should tell you how to live your life).
Now let's get to the juicy part that brought us all here. I'll assume that we are using Vue 3 and the Vue CLI is already installed.
## Create a new Vue project
Open a terminal window and type the following commands to create a new Vue project in the current directory.
```sh
vue create vue-app
```
wait for the dependencies installation to finish then
```sh
cd vue-app
```
to change into the project directory.
## Install the Tailwind CSS and its peer dependencies as a dev dependency using npm
```sh
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
```
## Create your configuration files
Next, generate your `tailwind.config.js` and `postcss.config.js` files:
```sh
npx tailwindcss init -p
```
This command will create a minimal `tailwind.config.js` file at the root of your project:
```js
// tailwind.config.js
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
```
It will also create a `postcss.config.js` file that includes tailwindcss and autoprefixer already configured.Postcss is needed to process tailwind:
```js
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
```
## Configure Tailwind to remove unused styles in production
In your tailwind.config.js file, configure the purge option with the paths to all of your pages and components so Tailwind can tree-shake unused styles in production builds:
```js
// tailwind.config.js
module.exports = {
purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
```
## Include Tailwind in your CSS
Navigate to `src/assets/css` and create a new `tailwind.css` file in the folder, and use the @tailwind directive to include Tailwind’s base, components, and utilities styles in the file.
```css
/* ./src/assets/css/tailwind.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
```
Tailwind will swap these directives out at build-time with all of the styles it generates based on your configured design system.
## Import Tailwind into your Vue app
Finally, ensure your CSS file is being imported in your `./src/main.js` file:
```js
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import './index.css';
createApp(App).mount('#app');
```
You're finished! Now when you run npm run dev, Tailwind CSS will be ready to use in your Vue app! You can now proceed to create awesome stuff
-148
View File
@@ -1,148 +0,0 @@
---
title: "What is pwn?"
description: "No not that one"
date: "2025-09-03"
tags: ["blog"]
---
> Binary Exploitation is a broad topic within Cyber Security which really comes down to finding a vulnerability in the program and exploiting it to gain control of a shell or modifying the program's functions ~ctf101
In most challenges, you’ll be given a Linux binary to exploit, and occasionally a Windows executable. The goal is to find a way to get the program to run in a way that was not intended.
Over the course of this series, we will look at the basics of a binary from simple to advanced concepts. This will be a multipart post covering the concepts over a couple of months. I’ll also use it as a reference to track my own progress.
> This assumes that the reader has some significant experience with programming, i will not be explaining how to write software. The tutorials will be in C, simple enough while being low level for some of the things well do. I recommend reading :
>
> _[The C Programming Language](https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628)_[, 2nd Edition, by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall, 1988).](https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628)
---
## Concepts to Cover
This roadmap will take you from _“I don’t know how the stack works”_ to _“I can write exploits for CTFs and understand real-world CVEs.”_
### **Episode 1: Getting Started**
- Why binary exploitation matters (CTFs, real-world, research).
- Computer architecture basics (x86/x64 registers, stack vs heap, memory layout).
- Compiling and running simple C programs.
- Intro to ELF binaries.
---
### **Episode 2: Assembly & Tools Crash Course**
- Function calls in assembly (prologue/epilogue, stack frames).
- Common instructions (`mov`, `call`, `jmp`, `ret`).
- Debugging with `gdb`, `gef`/`pwndbg`.
- Disassembly with `objdump`, `radare2`, and `Ghidra`.
---
### **Episode 3: Memory Corruption 101**
- What is a segmentation fault?
- Stack buffer overflows (first crashes).
- Off-by-one errors.
- Writing your first shellcode and executing it locally.
---
### **Episode 4: Exploiting Control Flow**
- Overwriting return addresses.
- NOP sleds and shellcode execution.
- Return-to-libc attacks (ret2libc).
- Environment variables and argument tricks.
---
### **Episode 5: Format String Vulnerabilities**
- How `printf` becomes an exploit primitive.
- Memory leaks via format strings.
- Overwriting memory using `%n`.
---
### **Episode 6: Modern Protections & Bypasses (Part 1)**
- NX (non-executable stack) and its bypass with ROP.
- Intro to ROP gadgets and building small chains.
- Automating with Pwntools and ROPgadget.
---
### **Episode 7: Modern Protections & Bypasses (Part 2)**
- ASLR: how randomization works.
- Leaking addresses to defeat ASLR.
- Stack canaries and partial overwrites.
---
### **Episode 8: Heap Exploitation (Basics)**
- Understanding malloc/free and heap metadata.
- Classic heap overflows.
- Use-after-free and double free.
- Simple heap exploitation demos.
---
### **Episode 9: Heap Exploitation (Advanced)**
- Unlink attacks and unsafe unlink.
- Fastbin dup tricks.
- The “House of” techniques:
- House of Force
- House of Spirit
- House of Lore
- House of Einherjar
- Tcache poisoning in modern glibc.
---
### **Episode 10: Advanced Exploitation Techniques**
- GOT/PLT overwrites.
- Ret2dlresolve.
- Sigreturn-oriented programming (SROP).
- JOP (Jump-Oriented Programming).
---
### **Episode 11: Kernel & Windows Exploitation (Intro)**
- Userland vs kernel space.
- Exploiting syscalls for privilege escalation.
- Windows basics: SEH overwrites, DEP/ASLR bypass.
- Kernel driver exploitation.
---
### **Episode 12: Modern Defenses & Mitigations**
- Control-Flow Integrity (CFI).
- Shadow stacks & CET.
- Hardened malloc and allocator security.
- Sandboxing & seccomp-bpf.
---
### **Episode 13: Exploit Workflow in Practice**
- Solving a CTF challenge step-by-step.
- Remote exploitation (exploiting over sockets).
- Exploit reliability (stability, bruteforcing).
- Post-exploitation steps (getting a shell, escalating privileges).
---
### **Episode 14: Beyond the Basics**
- Automating exploit discovery with fuzzing (AFL, honggfuzz).
- Symbolic execution with angr.
- Real-world case studies (Heartbleed, Dirty COW, Shellshock).
- Writing weaponized exploits responsibly.
-80
View File
@@ -1,80 +0,0 @@
---
title: "The One Thing Nobody Tells You About WiFi Hotspots on Arch Linux"
description: "A minimal Arch install is great until NetworkManager silently fails to find a binary you didn't know you needed"
date: "2026-04-16"
tags: ["arch", "linux", "networking", "kde"]
---
I spent longer than I'd like to admit trying to get a simple WiFi hotspot running on Arch. Not because it's hard — it genuinely isn't — but because of one missing piece that the NetworkManager documentation buries so deep you'd think it was classified.
For context: I'm running a minimal Arch Linux install with KDE Plasma. No bloat, no extras, just what I explicitly put there. Which, as it turns out, is exactly why this bit me.
Here's the whole story, and more importantly, the fix.
## It starts innocently enough
You fire up `nmcli`, throw together what looks like a perfectly reasonable hotspot command, and get slapped with this:
```
Error: Connection activation failed: IP configuration could not be reserved (no available address, timeout, etc.)
```
Vague. Unhelpful. The kind of error message that was clearly written by someone who never had to debug it.
Your first instinct is probably to check if your WiFi card even supports AP mode — reasonable. Mine does. Maybe NetworkManager picked the wrong interface — also reasonable, so you specify `ifname wlp61s0` explicitly. Still fails. You check for a conflicting `dnsmasq` service. It doesn't even exist on the system.
At this point the error message has told you nothing useful, and you're running out of obvious things to blame.
## The actual culprit
Dig into the NetworkManager journal and you'll find the real error hiding two lines below the surface:
```
device (wlp61s0): ip:shared4: could not start dnsmasq: Could not find "dnsmasq" binary
```
There it is. NetworkManager's hotspot mode uses `dnsmasq` internally to hand out IP addresses to devices that connect to your hotspot. It doesn't use the system `dnsmasq` service — it manages its own instance entirely in the background. But it does need the binary to actually exist on your machine.
On a minimal Arch install, it doesn't come pre-installed — and if you're not pulling in a full desktop environment with all its recommended packages, nothing drags it in for you either. So the whole thing silently falls apart at the IP configuration stage, and you get that useless generic error instead of "hey, install dnsmasq."
The fix is one line:
```bash
sudo pacman -S dnsmasq
```
Don't enable it, don't start it. Just having it on the system is enough. NetworkManager will find it and handle the rest.
## Getting internet to actually work
Once the hotspot is up, you'll notice connected devices get an IP but no internet. The hotspot being active and internet being shared are two separate things — your machine needs to be explicitly told to forward traffic between its WiFi and ethernet interfaces.
First, tell the kernel it's allowed to forward packets at all:
```bash
sudo sysctl -w net.ipv4.ip_forward=1
```
Then set up NAT so traffic from WiFi clients gets routed out through your ethernet connection and back:
```bash
sudo iptables -t nat -A POSTROUTING -o enp0s31f6 -j MASQUERADE
sudo iptables -A FORWARD -i wlp61s0 -o enp0s31f6 -j ACCEPT
sudo iptables -A FORWARD -i enp0s31f6 -o wlp61s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
```
Swap out `enp0s31f6` and `wlp61s0` for whatever your ethernet and WiFi interfaces are actually named. After that, clients connecting to your hotspot will have full internet access.
These settings don't survive a reboot, so if you want them permanent, save them:
```bash
echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-ipforward.conf
sudo iptables-save | sudo tee /etc/iptables/iptables.rules
sudo systemctl enable iptables
```
## The short version
If your NetworkManager hotspot is failing on Arch, install `dnsmasq`. That's almost certainly it. The error message won't tell you that, the hotspot command won't tell you that, but the journal will — and now so does this article.
Everything else is just routing.
-17
View File
@@ -1,17 +0,0 @@
{
"version": "0.2",
"language": "en",
"files": ["content/**/*.md"],
"dictionaries": ["project-words"],
"dictionaryDefinitions": [
{ "name": "project-words", "path": "./.cspell/words.txt", "addWords": true }
],
"ignoreRegExpList": [
"/^\\s*```[\\s\\S]*?^\\s*```/gm",
"/`[^`\\n]+`/g",
"/\\$\\$[\\s\\S]*?\\$\\$/g",
"/\\$[^$\\n]+\\$/g",
"/\\b[0-9a-f]{16,}\\b/gi",
"/\\w+\\{[^}\\n]*\\}/g"
]
}
+6
View File
@@ -0,0 +1,6 @@
// @ts-check
import withNuxt from './.nuxt/eslint.config.mjs'
export default withNuxt(
// Your custom configs here
)
-11
View File
@@ -1,11 +0,0 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactCompiler: true,
// Fully static site: `next build` writes plain files to ./out for static-web-server.
output: "export",
// The site uses plain <img>, not next/image.
images: { unoptimized: true },
};
export default nextConfig;
+14
View File
@@ -0,0 +1,14 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
modules: [
'@nuxt/content',
'@nuxt/eslint',
'@nuxt/image',
'@nuxt/scripts',
'@nuxt/ui',
'@nuxt/test-utils'
]
})
+20 -51
View File
@@ -1,58 +1,27 @@
{
"name": "andwati-nextgen",
"version": "0.1.0",
"name": "nuxt-app",
"type": "module",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "biome check",
"format": "biome format --write",
"lint:content": "prettier --check \"content/**/*.md\" && cspell --no-progress",
"format:content": "prettier --write \"content/**/*.md\"",
"spell": "cspell --no-progress",
"check": "biome check && pnpm lint:content",
"prepare": "husky"
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"dependencies": {
"gray-matter": "^4.0.3",
"katex": "^0.18.9",
"next": "16.3.6",
"next-mdx-remote": "^6.0.0",
"react": "19.2.8",
"react-dom": "19.2.8",
"rehype-katex": "^7.0.1",
"rehype-pretty-code": "^0.14.5",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"shiki": "^4.4.3",
"unified": "^11.0.5"
},
"devDependencies": {
"@biomejs/biome": "2.4.2",
"@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.20",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"cspell": "^10.3.5",
"husky": "^9.1.7",
"lint-staged": "^17.6.0",
"prettier": "^3.9.9",
"tailwindcss": "^4",
"typescript": "^5"
},
"packageManager": "[email protected]",
"lint-staged": {
"content/**/*.md": [
"prettier --write",
"cspell --no-progress --no-must-find-files"
],
"*.{ts,tsx,mjs,json,css}": "biome check --write --no-errors-on-unmatched"
"@nuxt/content": "3.6.3",
"@nuxt/eslint": "1.8.0",
"@nuxt/image": "1.11.0",
"@nuxt/scripts": "0.11.10",
"@nuxt/test-utils": "3.19.2",
"@nuxt/ui": "3.3.2",
"@unhead/vue": "^2.0.14",
"better-sqlite3": "^12.2.0",
"eslint": "^9.33.0",
"nuxt": "^4.0.3",
"typescript": "^5.9.2",
"vue": "^3.5.18",
"vue-router": "^4.5.1"
}
}
+11214 -2479
View File
File diff suppressed because it is too large Load Diff
-2
View File
@@ -1,2 +0,0 @@
allowBuilds:
sharp: false
-7
View File
@@ -1,7 +0,0 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
-13
View File
@@ -1,13 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEalcjtBYJKwYBBAHaRw8BAQdA55X1mRCKw9DA35kCAy+7Z30ye0rUHWBZsl7O
Wmar+RS0IklhbiBBbmR3YXRpIDxhbmR3YXRpaWFuQGdtYWlsLmNvbT6IkwQTFgoA
OxYhBK1YqreiDYUjy/WaeR8g/tCqBbDaBQJqVyO0AhsDBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEB8g/tCqBbDace8BAN1SpkEMSYll+XupKHiaIUwnhm4N
eS79G1i+345Gl6CyAQDjgn+3rzG6sexjKh+10EKiy5omsQEGzUW03s7gS0T1Drg4
BGpXI7QSCisGAQQBl1UBBQEBB0CXofBIYYXG2+dZqgllhsbkNPF4qlyfPgbRW+zb
7Kw3IAMBCAeIeAQYFgoAIBYhBK1YqreiDYUjy/WaeR8g/tCqBbDaBQJqVyO0AhsM
AAoJEB8g/tCqBbDauMkA/RG4iqtPZOI3DQzFJYu7SnxaD81vdP0LyTLKDQkynySu
AQDrlWyF8LRlad4iX1yQPCuOV0aUpTNq5kPlWurtX99/BQ==
=uKsS
-----END PGP PUBLIC KEY BLOCK-----
-17
View File
@@ -1,17 +0,0 @@
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
Contact: mailto:[email protected]
Expires: 2027-07-16T00:00:00.000Z
Encryption: https://andwati.com/.well-known/pgp-key.txt
Encryption: https://keys.openpgp.org/vks/v1/by-fingerprint/AD58AAB7A20D8523CBF59A791F20FED0AA05B0DA
Encryption: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xAD58AAB7A20D8523CBF59A791F20FED0AA05B0DA
Preferred-Languages: en
Canonical: https://andwati.com/.well-known/security.txt
-----BEGIN PGP SIGNATURE-----
iHUEARYKAB0WIQStWKq3og2FI8v1mnkfIP7QqgWw2gUCaljXlQAKCRAfIP7QqgWw
2qAoAP0Q7Cc0YsP2dvV7fqDlqcnjuJepQQSTZBz7ehkPyjGV5gEA3K9ZqQmuI2ea
KKADWxuKTTY43PBmuV9rMqLm8ZOPlAY=
=NUkY
-----END PGP SIGNATURE-----
Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

+2
View File
@@ -0,0 +1,2 @@
User-Agent: *
Disallow:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-29
View File
@@ -1,29 +0,0 @@
import { getFeedItems } from "@/lib/feed";
import { abs, site } from "@/lib/site";
export const dynamic = "force-static";
export async function GET() {
const items = await getFeedItems();
const feed = {
version: "https://jsonfeed.org/version/1.1",
title: site.name,
home_page_url: site.baseUrl,
feed_url: abs("/feed.json"),
description: site.description,
language: "en",
authors: [{ name: site.name, url: site.baseUrl }],
items: items.map((i) => ({
id: i.url,
url: i.url,
title: i.title,
summary: i.description,
content_html: i.html,
date_published: i.date.toISOString(),
tags: i.tags,
})),
};
return new Response(JSON.stringify(feed), {
headers: { "Content-Type": "application/feed+json; charset=utf-8" },
});
}
-111
View File
@@ -1,111 +0,0 @@
@import "tailwindcss";
@plugin "@tailwindcss/typography";
@theme {
--breakpoint-sm: 30rem;
--breakpoint-lg: 62rem;
--font-sans: var(--font-lora), ui-serif, Georgia, serif;
--color-gray-100: #edf2f7;
--color-gray-200: #e2e8f0;
--color-gray-400: #a0aec0;
--color-gray-500: #718096;
--color-gray-600: #4a5568;
--color-gray-800: #1a202c;
--color-blue-500: #3182ce;
--color-blue-600: #2b6cb0;
}
body {
background: #fff;
color: var(--color-gray-800);
font-family: var(--font-sans);
line-height: 1.5;
}
/* Prose overrides mirroring adammaj.com's chakra-ui-prose config */
hr {
width: 100%;
height: 0;
border: 0;
border-bottom: 1px solid var(--color-gray-200);
opacity: 0.6;
}
.prose {
line-height: 1.5;
--tw-prose-body: var(--color-gray-800);
--tw-prose-headings: var(--color-gray-800);
--tw-prose-links: var(--color-blue-500);
max-width: none;
}
.prose :where(h1, h2, h3, h4):not(:where(.not-prose *)) {
margin-top: 1rem;
margin-bottom: 1rem;
}
.prose :where(p):not(:where(.not-prose *)) {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
}
.prose :where(a):not(:where(.not-prose *)) {
color: var(--color-blue-500);
font-weight: inherit;
text-decoration: underline;
}
.prose :where(pre):not(:where(.not-prose *)) {
background: #f6f8fa;
color: var(--color-gray-800);
border: 1px solid #e1e4e8;
}
.prose :where(code):not(:where(pre *)):not(:where(.not-prose *))::before,
.prose :where(code):not(:where(pre *)):not(:where(.not-prose *))::after {
content: none;
}
.callout {
margin: 1rem 0;
padding: 0.25rem 1rem;
border-left: 4px solid var(--color-blue-500);
border-radius: 0 0.375rem 0.375rem 0;
background: rgb(49 130 206 / 0.05);
}
.callout-tip {
border-color: #10b981;
background: rgb(16 185 129 / 0.05);
}
.callout-warning {
border-color: #f59e0b;
background: rgb(245 158 11 / 0.05);
}
.callout-danger {
border-color: #ef4444;
background: rgb(239 68 68 / 0.05);
}
.youtube {
position: relative;
margin: 1rem 0;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 0.375rem;
}
.youtube iframe {
width: 100%;
height: 100%;
border: 0;
}
/* Shiki (rehype-pretty-code): theme colours are inline; keep block chrome from .prose pre */
pre[data-language] {
overflow-x: auto;
padding: 1rem;
border-radius: 0.375rem;
font-size: 0.875rem;
line-height: 1.6;
}
pre[data-language] code {
background: none;
padding: 0;
font-size: inherit;
}
-90
View File
@@ -1,90 +0,0 @@
import type { Metadata, Viewport } from "next";
import { Lora } from "next/font/google";
import Script from "next/script";
import { JsonLd } from "@/components/JsonLd";
import { Layout } from "@/components/Layout";
import { site } from "@/lib/site";
import "./globals.css";
import "katex/dist/katex.min.css";
const lora = Lora({
variable: "--font-lora",
subsets: ["latin"],
display: "swap",
});
export const viewport: Viewport = { themeColor: "#ffffff" };
export const metadata: Metadata = {
metadataBase: new URL(site.baseUrl),
title: { default: site.title, template: `%s | ${site.name}` },
description: site.description,
keywords: site.keywords,
authors: [{ name: site.name, url: site.baseUrl }],
creator: site.name,
publisher: site.name,
openGraph: {
siteName: site.name,
type: "website",
locale: site.locale,
url: "/",
title: site.title,
description: site.description,
},
twitter: {
card: "summary_large_image",
site: site.twitter,
creator: site.twitter,
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
"max-image-preview": "large",
"max-snippet": -1,
},
},
};
const websiteLd = {
"@context": "https://schema.org",
"@type": "WebSite",
name: site.name,
alternateName: site.tagline,
url: site.baseUrl,
inLanguage: "en",
author: { "@type": "Person", name: site.name },
};
const umamiScript = process.env.PUBLIC_UMAMI_SCRIPT_URL;
const umamiId = process.env.PUBLIC_UMAMI_WEBSITE_ID;
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="en" className={lora.variable}>
<head>
<link
rel="alternate"
type="application/rss+xml"
title={`${site.name} RSS`}
href="/rss.xml"
/>
<link
rel="alternate"
type="application/feed+json"
title={`${site.name} JSON Feed`}
href="/feed.json"
/>
</head>
<body>
<JsonLd data={websiteLd} />
<Layout>{children}</Layout>
{umamiScript && umamiId && (
<Script defer src={umamiScript} data-website-id={umamiId} />
)}
</body>
</html>
);
}
-38
View File
@@ -1,38 +0,0 @@
import { getBooks, getWritings } from "@/lib/content";
import { abs, site } from "@/lib/site";
export const dynamic = "force-static";
export function GET() {
const body = `# ${site.name}
> ${site.description}
${site.name} (also known as ${site.alias}) is a software engineer and the captain of the binarysith CTF team. This site collects his original essays, CTF writeups, reading list and projects.
## Writing
${getWritings()
.map(
(p) =>
`- [${p.data.title}](${abs(`/writing/${p.slug}`)})${p.data.description ? `: ${p.data.description}` : ""}`,
)
.join("\n")}
## Reading
${getBooks()
.map((b) => `- [${b.data.title}](${abs(`/reading/${b.slug}`)})`)
.join("\n")}
## Other
- [About](${abs("/")})
- [Portfolio](${abs("/portfolio")})
- [RSS](${abs("/rss.xml")})
- [Sitemap](${abs("/sitemap.xml")})
`;
return new Response(body, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}
-5
View File
@@ -1,5 +0,0 @@
import { redirect } from "next/navigation";
export default function NotFound() {
redirect("/");
}
-11
View File
@@ -1,11 +0,0 @@
import { ogContentType, ogImage, ogSize } from "@/lib/og";
import { site } from "@/lib/site";
export const alt = site.title;
export const size = ogSize;
export const dynamic = "force-static";
export const contentType = ogContentType;
export default function Image() {
return ogImage(site.name, "Software engineer · CTF player");
}
-44
View File
@@ -1,44 +0,0 @@
import type { Metadata } from "next";
import { JsonLd } from "@/components/JsonLd";
import { Mdx } from "@/components/Mdx";
import { getAbout } from "@/lib/content";
import { site } from "@/lib/site";
export const metadata: Metadata = {
alternates: { canonical: "/" },
};
const personLd = {
"@context": "https://schema.org",
"@type": "Person",
name: site.name,
alternateName: site.alias,
url: site.baseUrl,
jobTitle: "Software Engineer",
description: site.description,
sameAs: site.sameAs,
knowsAbout: [
"Cyber security",
"Capture the flag",
"Binary exploitation",
"Reverse engineering",
"Low-level programming",
"Distributed systems",
"Compiler design",
"Database internals",
],
memberOf: {
"@type": "Organization",
name: "binarysith",
url: "https://ctftime.org/team/379200",
},
};
export default function Home() {
return (
<div className="prose">
<JsonLd data={personLd} />
<Mdx source={getAbout()} />
</div>
);
}
-46
View File
@@ -1,46 +0,0 @@
import type { Metadata } from "next";
import { Mdx } from "@/components/Mdx";
import { getPortfolio } from "@/lib/content";
export const metadata: Metadata = {
title: "Portfolio",
description: "Projects and infrastructure-level software by Ian Andwati.",
alternates: { canonical: "/portfolio" },
};
export default function PortfolioPage() {
const items = getPortfolio();
return (
<div className="flex flex-col gap-4">
<h1 className="sr-only">Portfolio</h1>
<hr />
{items.map((item) => (
<div key={item.slug} className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h2 className="font-bold">{item.data.title}</h2>
<p className="pb-4 text-sm text-gray-600">
{item.data.description}
</p>
<div className="prose text-sm text-gray-600">
<Mdx source={item.content} />
</div>
<div className="flex gap-6 pt-2">
{item.data.links?.map((l) => (
<a
key={l.url}
href={l.url}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 hover:underline"
>
{l.label}
</a>
))}
</div>
</div>
<hr />
</div>
))}
</div>
);
}
@@ -1,20 +0,0 @@
import { getBooks } from "@/lib/content";
import { ogContentType, ogImage, ogSize } from "@/lib/og";
export const size = ogSize;
export const dynamic = "force-static";
export const contentType = ogContentType;
export function generateStaticParams() {
return getBooks().map((b) => ({ slug: b.slug }));
}
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const book = getBooks().find((b) => b.slug === slug);
return ogImage(book?.data.title ?? "Reading", "Reading");
}
-95
View File
@@ -1,95 +0,0 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { breadcrumbs, JsonLd } from "@/components/JsonLd";
import { Mdx } from "@/components/Mdx";
import { byline } from "@/lib/books";
import { getBooks } from "@/lib/content";
import { abs, site } from "@/lib/site";
export function generateStaticParams() {
return getBooks().map((b) => ({ slug: b.slug }));
}
export async function generateMetadata({
params,
}: PageProps<"/reading/[slug]">): Promise<Metadata> {
const { slug } = await params;
const book = getBooks().find((b) => b.slug === slug);
if (!book) return {};
const url = `/reading/${slug}`;
const description = byline(book.data) || site.description;
return {
title: book.data.title,
description,
keywords: book.data.tags,
alternates: { canonical: url },
openGraph: {
type: "article",
url,
title: book.data.title,
description,
siteName: site.name,
locale: site.locale,
},
twitter: {
card: "summary_large_image",
title: book.data.title,
description,
},
};
}
export default async function Book({ params }: PageProps<"/reading/[slug]">) {
const { slug } = await params;
const book = getBooks().find((b) => b.slug === slug);
if (!book) notFound();
const url = abs(`/reading/${slug}`);
const item = {
"@type": book.data.kind === "paper" ? "ScholarlyArticle" : "Book",
name: book.data.title,
url: book.data.url,
author: book.data.authors?.map((name) => ({ "@type": "Person", name })),
};
const reviewLd = book.data.rating
? {
"@context": "https://schema.org",
"@type": "Review",
url,
name: `Review: ${book.data.title}`,
datePublished: book.data.dateFinished,
author: { "@type": "Person", name: site.name, url: site.baseUrl },
itemReviewed: item,
reviewRating: {
"@type": "Rating",
ratingValue: book.data.rating,
bestRating: 5,
worstRating: 1,
},
}
: null;
return (
<article className="flex flex-col gap-2">
<JsonLd
data={[
...(reviewLd ? [reviewLd] : []),
breadcrumbs([
{ name: "Home", url: site.baseUrl },
{ name: "Reading", url: abs("/reading") },
{ name: book.data.title, url },
]),
]}
/>
<div className="flex flex-col">
<h1 className="text-[36px] leading-[1.2] font-bold">
{book.data.title}
</h1>
<p className="mt-2 text-[20px] leading-[30px] text-gray-400">
{byline(book.data)}
</p>
</div>
<div className="prose">
<Mdx source={book.content} />
</div>
</article>
);
}
-12
View File
@@ -1,12 +0,0 @@
import { Bookshelf } from "@/components/Bookshelf";
import { getShelf } from "@/lib/books";
export default function ReadingLayout({ children }: LayoutProps<"/reading">) {
return (
<div className="flex flex-col gap-8">
<Bookshelf books={getShelf()} />
<hr />
{children}
</div>
);
}
-70
View File
@@ -1,70 +0,0 @@
import type { Metadata } from "next";
import Link from "next/link";
import { Mdx } from "@/components/Mdx";
import { readLine } from "@/lib/books";
import { coverExists, getBooks, spineFor, summarize } from "@/lib/content";
export const metadata: Metadata = {
title: "Reading",
description: "Books and papers I have read, with ratings and notes.",
alternates: { canonical: "/reading" },
};
export default function ReadingIndex() {
return (
<div className="flex flex-col">
<h1 className="sr-only">Reading</h1>
{getBooks().map((b, i) => {
const cover = coverExists(b.data.coverImage)
? b.data.coverImage
: undefined;
const { spineColor, textColor } = spineFor(b.data.title);
const summary = summarize(b.content);
return (
<div key={b.slug} className={i > 0 ? "mt-5" : undefined}>
{i > 0 && <hr className="mb-3" />}
<div className="flex gap-6">
{cover ? (
// biome-ignore lint/performance/noImgElement: small local cover
<img
src={cover}
alt={b.data.title}
className="h-[100px] border border-gray-200 sm:h-[140px] md:h-[160px]"
style={{ width: "auto" }}
/>
) : (
<div
className="flex h-[100px] w-[68px] shrink-0 items-center border border-gray-200 p-2 text-xs font-bold sm:h-[140px] sm:w-24 md:h-[160px] md:w-28"
style={{ backgroundColor: spineColor, color: textColor }}
>
{b.data.title}
</div>
)}
<div className="flex min-w-0 flex-col">
<Link
href={`/reading/${b.slug}`}
className="block hover:underline"
>
<h2 className="text-[20px] leading-6 font-bold">
{b.data.title}
</h2>
</Link>
{b.data.authors?.length ? (
<p className="mt-2 text-[#999]">
{b.data.authors.join(", ")}
</p>
) : null}
<p className="mt-2 text-[#666]">{readLine(b.data)}</p>
{summary && (
<article className="prose mt-2">
<Mdx source={summary} />
</article>
)}
</div>
</div>
</div>
);
})}
</div>
);
}
-12
View File
@@ -1,12 +0,0 @@
import type { MetadataRoute } from "next";
import { abs, site } from "@/lib/site";
export const dynamic = "force-static";
export default function robots(): MetadataRoute.Robots {
return {
rules: [{ userAgent: "*", allow: "/" }],
sitemap: abs("/sitemap.xml"),
host: site.baseUrl,
};
}
-36
View File
@@ -1,36 +0,0 @@
import { getFeedItems, xml } from "@/lib/feed";
import { abs, site } from "@/lib/site";
export const dynamic = "force-static";
export async function GET() {
const items = await getFeedItems();
const body = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>${xml(site.name)}</title>
<link>${site.baseUrl}</link>
<description>${xml(site.description)}</description>
<language>en</language>
<lastBuildDate>${(items[0]?.date ?? new Date()).toUTCString()}</lastBuildDate>
<atom:link href="${abs("/rss.xml")}" rel="self" type="application/rss+xml"/>
${items
.map(
(i) => `<item>
<title>${xml(i.title)}</title>
<link>${i.url}</link>
<guid isPermaLink="true">${i.url}</guid>
<pubDate>${i.date.toUTCString()}</pubDate>
<description>${xml(i.description)}</description>
${i.tags.map((t) => `<category>${xml(t)}</category>`).join("\n")}
<content:encoded><![CDATA[${i.html.replace(/]]>/g, "]]]]><![CDATA[>")}]]></content:encoded>
</item>`,
)
.join("\n")}
</channel>
</rss>
`;
return new Response(body, {
headers: { "Content-Type": "application/rss+xml; charset=utf-8" },
});
}
-35
View File
@@ -1,35 +0,0 @@
import type { MetadataRoute } from "next";
import { getBooks, getWritings } from "@/lib/content";
import { abs } from "@/lib/site";
export const dynamic = "force-static";
export default function sitemap(): MetadataRoute.Sitemap {
const posts = getWritings();
const latest = posts[0]?.data.date;
return [
{ url: abs("/"), changeFrequency: "monthly", priority: 1 },
{
url: abs("/writing"),
lastModified: latest ? new Date(String(latest)) : undefined,
changeFrequency: "weekly",
priority: 0.9,
},
{ url: abs("/reading"), changeFrequency: "monthly", priority: 0.6 },
{ url: abs("/portfolio"), changeFrequency: "monthly", priority: 0.6 },
...posts.map((p) => ({
url: abs(`/writing/${p.slug}`),
lastModified: new Date(String(p.data.date)),
changeFrequency: "yearly" as const,
priority: 0.8,
})),
...getBooks().map((b) => ({
url: abs(`/reading/${b.slug}`),
lastModified: b.data.dateFinished
? new Date(b.data.dateFinished)
: undefined,
changeFrequency: "yearly" as const,
priority: 0.4,
})),
];
}
@@ -1,20 +0,0 @@
import { getWritings } from "@/lib/content";
import { ogContentType, ogImage, ogSize } from "@/lib/og";
export const size = ogSize;
export const dynamic = "force-static";
export const contentType = ogContentType;
export function generateStaticParams() {
return getWritings().map((p) => ({ slug: p.slug }));
}
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = getWritings().find((p) => p.slug === slug);
return ogImage(post?.data.title ?? "Writing", "Writing");
}
-86
View File
@@ -1,86 +0,0 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { breadcrumbs, JsonLd } from "@/components/JsonLd";
import { Mdx } from "@/components/Mdx";
import { formatDate, getWritings } from "@/lib/content";
import { abs, site } from "@/lib/site";
export function generateStaticParams() {
return getWritings().map((p) => ({ slug: p.slug }));
}
export async function generateMetadata({
params,
}: PageProps<"/writing/[slug]">): Promise<Metadata> {
const { slug } = await params;
const post = getWritings().find((p) => p.slug === slug);
if (!post) return {};
const url = `/writing/${slug}`;
const description = post.data.description || site.description;
return {
title: post.data.title,
description,
keywords: post.data.tags,
alternates: { canonical: url },
openGraph: {
type: "article",
url,
title: post.data.title,
description,
siteName: site.name,
locale: site.locale,
publishedTime: String(post.data.date),
modifiedTime: String(post.data.date),
authors: [site.name],
tags: post.data.tags,
},
twitter: {
card: "summary_large_image",
title: post.data.title,
description,
},
};
}
export default async function Post({ params }: PageProps<"/writing/[slug]">) {
const { slug } = await params;
const post = getWritings().find((p) => p.slug === slug);
if (!post) notFound();
const url = abs(`/writing/${slug}`);
const postLd = {
"@context": "https://schema.org",
"@type": "BlogPosting",
headline: post.data.title,
description: post.data.description || site.description,
datePublished: String(post.data.date),
dateModified: String(post.data.date),
inLanguage: "en",
keywords: post.data.tags?.join(", "),
url,
mainEntityOfPage: { "@type": "WebPage", "@id": url },
image: abs(`/writing/${slug}/opengraph-image`),
author: { "@type": "Person", name: site.name, url: site.baseUrl },
publisher: { "@type": "Person", name: site.name, url: site.baseUrl },
};
return (
<article className="flex flex-col gap-2">
<JsonLd
data={[
postLd,
breadcrumbs([
{ name: "Home", url: site.baseUrl },
{ name: "Writing", url: abs("/writing") },
{ name: post.data.title, url },
]),
]}
/>
<h1 className="text-3xl font-bold md:text-4xl">{post.data.title}</h1>
<time dateTime={String(post.data.date)} className="text-sm text-gray-500">
{formatDate(String(post.data.date))}
</time>
<div className="prose">
<Mdx source={post.content} />
</div>
</article>
);
}
-36
View File
@@ -1,36 +0,0 @@
import type { Metadata } from "next";
import Link from "next/link";
import { formatDate, getWritings } from "@/lib/content";
export const metadata: Metadata = {
title: "Writing",
description:
"Essays and CTF writeups on software development, security, binary exploitation and Linux.",
alternates: { canonical: "/writing" },
};
export default function WritingIndex() {
const posts = getWritings();
return (
<div className="flex flex-col gap-3">
<h1 className="sr-only">Writing</h1>
<hr />
{posts.map((post) => (
<div key={post.slug} className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<Link
href={`/writing/${post.slug}`}
className="text-blue-600 hover:underline"
>
{post.data.title}
</Link>
<span className="text-right text-sm text-gray-500">
{formatDate(String(post.data.date))}
</span>
</div>
<hr />
</div>
))}
</div>
);
}
-248
View File
@@ -1,248 +0,0 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import type { ShelfBook } from "@/lib/books";
const W = 41.5;
const H = 220;
const SPINE = `${W}px`;
const COVER = `${W * 4}px`;
const BOOK = `${W * 5}px`;
const FILTER = "brightness(0.8) contrast(2)";
const PAPER = {
pointerEvents: "none",
opacity: 0.4,
filter: "url(#paper)",
zIndex: 50,
} as const;
export function Bookshelf({ books }: { books: ShelfBook[] }) {
const router = useRouter();
const pathname = usePathname();
const slug = pathname.split("/")[2];
const bookIndex = slug ? books.findIndex((b) => b.slug === slug) : -1;
const viewportRef = useRef<HTMLDivElement>(null);
const timer = useRef<ReturnType<typeof setInterval> | null>(null);
const [scroll, setScroll] = useState(0);
const [inView, setInView] = useState(0);
const [isScrolling, setIsScrolling] = useState(false);
const maxScroll =
(W + 12) * (books.length - inView) + (bookIndex > -1 ? W * 4 : 0) + 5;
const clamp = (x: number) => Math.max(0, Math.min(maxScroll, x));
useEffect(() => {
const el = viewportRef.current;
if (!el) return;
const measure = () => setInView(el.clientWidth / (W + 11));
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, []);
useEffect(() => {
if (bookIndex === -1) setScroll((s) => Math.max(0, s));
else setScroll(Math.max(0, (bookIndex - (inView - 4.5) / 2) * (W + 11)));
}, [bookIndex, inView]);
useEffect(
() => () => {
if (timer.current) clearInterval(timer.current);
},
[],
);
const start = (dir: 1 | -1) => {
if (timer.current) clearInterval(timer.current);
setIsScrolling(true);
timer.current = setInterval(() => setScroll((s) => clamp(s + dir * 3)), 10);
};
const stop = () => {
setIsScrolling(false);
if (timer.current) clearInterval(timer.current);
timer.current = null;
};
const arrow = (dir: 1 | -1) => ({
onMouseEnter: () => start(dir),
onMouseLeave: stop,
onTouchStart: () => start(dir),
onTouchEnd: stop,
});
return (
<>
<svg className="invisible absolute inset-0" aria-hidden="true">
<defs>
<filter id="paper" x="0%" y="0%" width="100%" height="100%">
<feTurbulence
type="fractalNoise"
baseFrequency="0.9"
numOctaves="8"
result="noise"
/>
<feDiffuseLighting
in="noise"
lightingColor="white"
surfaceScale="1"
result="diffLight"
>
<feDistantLight azimuth="45" elevation="35" />
</feDiffuseLighting>
</filter>
</defs>
</svg>
<div className="relative">
<div
className={`absolute -left-7 h-full md:-left-9 ${scroll > 0 ? "block" : "hidden"}`}
>
<div
{...arrow(-1)}
className="flex h-full w-7 items-center justify-center rounded-md max-md:rounded-r-none hover:bg-gray-100"
>
<Chevron dir="left" />
</div>
</div>
<div
ref={viewportRef}
className="flex cursor-grab items-center gap-3 overflow-x-hidden"
>
{books.map((book, i) => {
const open = bookIndex === i;
return (
<button
type="button"
key={book.slug}
onClick={() => router.push(open ? "/reading" : book.href)}
style={{
display: "flex",
alignItems: "center",
justifyContent: "flex-start",
outline: "none",
flexShrink: 0,
transform: `translateX(-${scroll}px)`,
width: open ? BOOK : SPINE,
perspective: "1000px",
transition: isScrolling
? "transform 100ms linear"
: "all 500ms ease",
}}
>
<div
className="flex shrink-0 items-start justify-center"
style={{
width: SPINE,
height: H,
transformOrigin: "right",
backgroundColor: book.spineColor,
color: book.textColor,
transform: `rotateY(${open ? "-60deg" : "0deg"})`,
transition: "all 500ms ease",
filter: FILTER,
transformStyle: "preserve-3d",
}}
>
<span
className="fixed top-0 left-0"
style={{ ...PAPER, height: H, width: SPINE }}
/>
<span
className="mt-3 block select-none overflow-hidden text-ellipsis whitespace-nowrap text-[12px] leading-[1.2] font-bold"
style={{
writingMode: "vertical-rl",
maxHeight: H - 24,
fontFamily: '"DM Sans", sans-serif',
}}
>
{book.title}
</span>
</div>
<div
className="relative shrink-0 overflow-hidden"
style={{
transformOrigin: "left",
transform: `rotateY(${open ? "30deg" : "88.8deg"})`,
transition: "all 500ms ease",
filter: FILTER,
transformStyle: "preserve-3d",
}}
>
<span
className="fixed top-0 right-0"
style={{ ...PAPER, height: H, width: COVER }}
/>
<span
className="absolute top-0 left-0"
style={{
pointerEvents: "none",
zIndex: 50,
height: H,
width: COVER,
background:
"linear-gradient(to right, rgba(255,255,255,0) 2px, rgba(255,255,255,0.5) 3px, rgba(255,255,255,0.25) 4px, rgba(255,255,255,0.25) 6px, transparent 7px, transparent 9px, rgba(255,255,255,0.25) 9px, transparent 12px)",
}}
/>
{book.coverImage ? (
// biome-ignore lint/performance/noImgElement: fixed-size local cover inside a 3D transform
<img
src={book.coverImage}
alt={book.title}
width={W * 4}
height={H}
style={{ width: COVER, height: H }}
/>
) : (
<div
className="flex items-center p-4 text-left text-sm font-bold"
style={{
width: COVER,
height: H,
backgroundColor: book.spineColor,
color: book.textColor,
}}
>
{book.title}
</div>
)}
</div>
</button>
);
})}
</div>
<div
className={`absolute top-0 -right-7 h-full pl-2.5 md:-right-9 ${scroll < maxScroll ? "block" : "hidden"}`}
>
<div
{...arrow(1)}
className="flex h-full w-7 items-center justify-center rounded-md max-md:rounded-l-none hover:bg-gray-100"
>
<Chevron dir="right" />
</div>
</div>
</div>
</>
);
}
function Chevron({ dir }: { dir: "left" | "right" }) {
return (
<svg
viewBox="0 0 24 24"
className="size-3"
fill="none"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d={dir === "left" ? "M15 4l-8 8 8 8" : "M9 4l8 8-8 8"} />
</svg>
);
}
-29
View File
@@ -1,29 +0,0 @@
/** Renders a JSON-LD block. `<` is escaped so content can't close the script tag. */
export function JsonLd({
data,
}: {
data: Record<string, unknown> | Record<string, unknown>[];
}) {
return (
<script
type="application/ld+json"
// biome-ignore lint/security/noDangerouslySetInnerHtml: JSON-LD must be inlined; `<` is escaped
dangerouslySetInnerHTML={{
__html: JSON.stringify(data).replace(/</g, "\\u003c"),
}}
/>
);
}
export function breadcrumbs(items: { name: string; url: string }[]) {
return {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: items.map((item, i) => ({
"@type": "ListItem",
position: i + 1,
name: item.name,
item: item.url,
})),
};
}
-15
View File
@@ -1,15 +0,0 @@
import { MobileNav } from "@/components/MobileNav";
import { Sidebar } from "@/components/Sidebar";
// Mirrors adammaj.com: a 596px wrapper (Chakra container) centred on the page, with a
// second, equally wide container inside it whose 16px padding offsets the text column.
export function Layout({ children }: { children: React.ReactNode }) {
return (
<div className="relative mx-auto mt-16 w-full max-w-[596.161px] px-4 pb-8 md:pb-40">
<div className="fixed inset-x-0 top-0 z-100 hidden h-16 bg-white lg:block" />
<MobileNav />
<Sidebar />
<main className="relative px-4 md:w-[596.161px]">{children}</main>
</div>
);
}
-33
View File
@@ -1,33 +0,0 @@
import { MDXRemote } from "next-mdx-remote/rsc";
import rehypeKatex from "rehype-katex";
import rehypePrettyCode from "rehype-pretty-code";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
/** Renders exported markdown: GFM, raw HTML (callouts, embeds), and KaTeX math. */
export function Mdx({ source }: { source: string }) {
return (
<MDXRemote
source={source}
options={{
mdxOptions: {
format: "md",
remarkPlugins: [remarkGfm, remarkMath],
rehypePlugins: [
rehypeRaw,
rehypeKatex,
[
rehypePrettyCode,
{
theme: "github-light",
keepBackground: false,
defaultLanguage: "txt",
},
],
],
},
}}
/>
);
}
-85
View File
@@ -1,85 +0,0 @@
"use client";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { NavLink } from "@/components/NavLink";
import { site } from "@/lib/site";
export function MobileNav() {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const pathname = usePathname();
// biome-ignore lint/correctness/useExhaustiveDependencies: close the menu when the route changes
useEffect(() => setOpen(false), [pathname]);
useEffect(() => {
if (!open) return;
const close = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", close);
return () => document.removeEventListener("mousedown", close);
}, [open]);
return (
<header className="fixed inset-x-0 top-0 z-50 h-12 border-b border-gray-200 bg-white lg:hidden">
<div className="mx-auto flex h-full max-w-5xl items-center justify-between px-8">
<div className="flex gap-8">
{site.nav.slice(0, 3).map((item) => (
<NavLink key={item.href} href={item.href}>
{item.name}
</NavLink>
))}
</div>
<div ref={ref} className="relative">
<button
type="button"
aria-label="Menu"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="flex h-8 w-8 items-center justify-center rounded-md border border-gray-200 hover:bg-gray-100"
>
<svg
viewBox="0 0 24 24"
className="size-4"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
aria-hidden="true"
>
<path d="M3 12h18M3 6h18M3 18h18" />
</svg>
</button>
{open && (
<div className="absolute right-0 top-10 flex w-44 flex-col gap-4 rounded-md border border-gray-200 bg-white py-4 shadow-lg">
<div className="flex flex-col gap-3 px-4">
<h2 className="text-xs font-bold">NAVIGATION</h2>
{site.nav.map((item) => (
<NavLink key={item.href} href={item.href}>
{item.name}
</NavLink>
))}
</div>
<div className="flex flex-col gap-3 px-4">
<h2 className="text-xs font-bold">FIND ME ON</h2>
{site.social.map((item) => (
<a
key={item.href}
href={item.href}
target="_blank"
rel="noopener noreferrer"
className="text-gray-500 hover:text-black"
>
{item.name}
</a>
))}
</div>
</div>
)}
</div>
</div>
</header>
);
}
-25
View File
@@ -1,25 +0,0 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
export function NavLink({
href,
className = "",
children,
}: {
href: string;
className?: string;
children: React.ReactNode;
}) {
const pathname = usePathname();
const active = href === "/" ? pathname === "/" : pathname.startsWith(href);
return (
<Link
href={href}
className={`${active ? "text-black" : "text-[#718096]"} hover:text-black ${className}`}
>
{children}
</Link>
);
}
-35
View File
@@ -1,35 +0,0 @@
import { NavLink } from "@/components/NavLink";
import { site } from "@/lib/site";
const link = "mt-2 block w-fit text-[18px] leading-[27px]";
export function Sidebar() {
return (
<aside className="absolute right-full mr-40 hidden lg:flex">
<div className="fixed flex flex-col items-start whitespace-nowrap">
<nav>
<p className="text-[13.3333px] leading-5 font-bold">NAVIGATION</p>
{site.nav.map((item) => (
<NavLink key={item.href} href={item.href} className={link}>
{item.name}
</NavLink>
))}
</nav>
<div className="mt-10">
<p className="text-[13.3333px] leading-5 font-bold">FIND ME ON</p>
{site.social.map((item) => (
<a
key={item.href}
href={item.href}
target="_blank"
rel="noopener noreferrer"
className={`${link} text-gray-500 hover:text-black`}
>
{item.name}
</a>
))}
</div>
</div>
</aside>
);
}
-44
View File
@@ -1,44 +0,0 @@
import {
type Book,
coverExists,
formatDate,
getBooks,
spineFor,
} from "@/lib/content";
export type ShelfBook = {
slug: string;
href: string;
title: string;
coverImage?: string;
spineColor: string;
textColor: string;
};
export function getShelf(): ShelfBook[] {
return getBooks().map((b) => ({
slug: b.slug,
href: `/reading/${b.slug}`,
title: b.data.title,
coverImage: coverExists(b.data.coverImage) ? b.data.coverImage : undefined,
...spineFor(b.data.title),
}));
}
export function readLine(b: Book) {
return [
b.dateFinished && `Read: ${formatDate(b.dateFinished)}`,
b.rating && `Rating: ${b.rating}/5`,
]
.filter(Boolean)
.join(" • ");
}
export function byline(b: Book) {
const parts = [
b.authors?.length && `By: ${b.authors.join(", ")}`,
b.dateFinished && `Read: ${formatDate(b.dateFinished)}`,
b.rating && `Rating: ${b.rating}/5`,
];
return parts.filter(Boolean).join(" - ");
}
-118
View File
@@ -1,118 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import matter from "gray-matter";
const ROOT = path.join(process.cwd(), "content");
export type Entry<T> = { slug: string; data: T; content: string };
export type Writing = {
title: string;
description?: string;
date: string;
tags?: string[];
};
export type Portfolio = {
title: string;
description?: string;
role?: string;
dateStart?: string;
dateEnd?: string;
outcome?: string;
links?: { label: string; url: string }[];
};
export type Book = {
title: string;
kind: "book" | "paper";
authors?: string[];
url?: string;
coverImage?: string;
rating?: number;
status?: string;
dateFinished?: string;
tags?: string[];
};
function readDir<T>(dir: string): Entry<T>[] {
const full = path.join(ROOT, dir);
if (!fs.existsSync(full)) return [];
return fs
.readdirSync(full)
.filter((f) => f.endsWith(".md"))
.map((f) => {
const { data, content } = matter(
fs.readFileSync(path.join(full, f), "utf8"),
);
return { slug: f.replace(/\.md$/, ""), data: data as T, content };
});
}
export function getWritings() {
return readDir<Writing>("writing").sort((a, b) =>
String(b.data.date).localeCompare(String(a.data.date)),
);
}
export function getPortfolio() {
return readDir<Portfolio>("portfolio").sort((a, b) =>
String(b.data.dateStart ?? "").localeCompare(
String(a.data.dateStart ?? ""),
),
);
}
export function getBooks() {
return readDir<Book>("reading").sort(
(a, b) =>
(b.data.rating ?? 0) - (a.data.rating ?? 0) ||
a.data.title.localeCompare(b.data.title),
);
}
export function getAbout() {
const { content } = matter(
fs.readFileSync(path.join(ROOT, "about.md"), "utf8"),
);
return content;
}
/** The part of a review shown on the index: everything before "## My Notes". */
export function summarize(content: string) {
return content.split(/^## My Notes/m)[0].trim();
}
export function formatDate(date: string) {
return new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
timeZone: "UTC",
});
}
const SPINES: [string, string][] = [
["#7c3a2d", "#fbe9d0"],
["#264653", "#e9f5f2"],
["#2a4d3a", "#f1f7e8"],
["#5b3a6b", "#f6ecfa"],
["#c9a227", "#2b2110"],
["#1d3557", "#f1faee"],
["#8d5a3b", "#fff4e6"],
["#3b3b3b", "#f0f0f0"],
];
export function spineFor(title: string) {
let h = 0;
for (const c of title) h = (h * 31 + c.charCodeAt(0)) >>> 0;
const [spineColor, textColor] = SPINES[h % SPINES.length];
return { spineColor, textColor };
}
export function coverExists(coverImage?: string) {
return (
!!coverImage &&
fs.existsSync(path.join(process.cwd(), "public", coverImage))
);
}
-43
View File
@@ -1,43 +0,0 @@
import rehypeRaw from "rehype-raw";
import rehypeStringify from "rehype-stringify";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import { getWritings } from "@/lib/content";
import { abs } from "@/lib/site";
const processor = unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeStringify);
/** Post bodies as HTML with root-relative links made absolute, for feed readers. */
export async function getFeedItems() {
return Promise.all(
getWritings().map(async (p) => {
const html = String(await processor.process(p.content)).replace(
/(src|href)="\/(?!\/)/g,
`$1="${abs("/")}`,
);
return {
slug: p.slug,
url: abs(`/writing/${p.slug}`),
title: p.data.title,
description: p.data.description ?? "",
date: new Date(String(p.data.date)),
tags: p.data.tags ?? [],
html,
};
}),
);
}
export const xml = (s: string) =>
s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
-56
View File
@@ -1,56 +0,0 @@
import { ImageResponse } from "next/og";
import { site } from "@/lib/site";
export const ogSize = { width: 1200, height: 630 };
export const ogContentType = "image/png";
/** 1200x630 social card: title on white, name and domain along the bottom. */
export function ogImage(title: string, kicker?: string) {
return new ImageResponse(
<div
style={{
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
background: "#ffffff",
color: "#1a202c",
padding: "72px 80px",
borderLeft: "16px solid #2b6cb0",
}}
>
<div
style={{
fontSize: 30,
color: "#718096",
textTransform: "uppercase",
letterSpacing: 3,
}}
>
{kicker ?? ""}
</div>
<div
style={{
fontSize: title.length > 60 ? 56 : 72,
fontWeight: 700,
lineHeight: 1.15,
display: "flex",
}}
>
{title}
</div>
<div
style={{
display: "flex",
justifyContent: "space-between",
fontSize: 30,
}}
>
<span style={{ color: "#1a202c" }}>{site.name}</span>
<span style={{ color: "#718096" }}>andwati.com</span>
</div>
</div>,
ogSize,
);
}
-45
View File
@@ -1,45 +0,0 @@
export const site = {
name: "Ian Andwati",
alias: "mockingspectre",
title: "Ian Andwati (mockingspectre) | Software Engineer & CTF Player",
tagline: "Thoughts and musings",
description:
"Software engineer and captain of the binarysith CTF team. Essays on low-level programming, distributed systems, compilers, database internals and security.",
baseUrl: "https://andwati.com",
locale: "en_US",
twitter: "@andwati_",
keywords: [
"Ian Andwati",
"mockingspectre",
"binarysith",
"software engineering",
"cyber security",
"CTF writeups",
"binary exploitation",
"reverse engineering",
"low-level programming",
"distributed systems",
"compiler design",
"database internals",
],
nav: [
{ name: "Home", href: "/" },
{ name: "Reading", href: "/reading" },
{ name: "Writing", href: "/writing" },
{ name: "Portfolio", href: "/portfolio" },
],
social: [
{ name: "GitHub", href: "https://github.com/andwati" },
{ name: "Twitter", href: "https://twitter.com/andwati_" },
{ name: "YouTube", href: "https://www.youtube.com/@pwnforfunandprofit" },
{ name: "Email", href: "mailto:[email protected]" },
],
sameAs: [
"https://github.com/andwati",
"https://twitter.com/andwati_",
"https://www.youtube.com/@pwnforfunandprofit",
"https://ctftime.org/team/379200",
],
};
export const abs = (path: string) => new URL(path, site.baseUrl).toString();
-30
View File
@@ -1,30 +0,0 @@
[general]
page404 = "./404.html"
# Next exports /writing as writing.html, so serve it without forcing a trailing slash.
redirect-trailing-slash = false
# Serve /.well-known (PGP key, security.txt).
ignore-hidden-files = false
[advanced]
[[advanced.headers]]
source = "**"
[advanced.headers.headers]
Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline' https://utteranc.es https://analytics.andwati.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.andwati.com; frame-src https://www.youtube-nocookie.com https://utteranc.es; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
X-Frame-Options = "DENY"
X-Content-Type-Options = "nosniff"
Referrer-Policy = "strict-origin-when-cross-origin"
Permissions-Policy = "camera=(), microphone=(), geolocation=(), interest-cohort=()"
Strict-Transport-Security = "max-age=63072000; includeSubDomains; preload"
# Generated social images are exported without a file extension.
[[advanced.headers]]
source = "**/opengraph-image"
[advanced.headers.headers]
Content-Type = "image/png"
# Hashed build assets never change.
[[advanced.headers]]
source = "/_next/static/**"
[advanced.headers.headers]
Cache-Control = "public, max-age=31536000, immutable"
+15 -31
View File
@@ -1,34 +1,18 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
// https://nuxt.com/docs/guide/concepts/typescript
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
]
}