An Expo app for iOS and Android: enter birth details and get a North Indian chart drawn with react-native-svg and the planets' signs, houses and degrees - fetched through a tiny Node proxy, because an API key shipped inside an app can be read out of it.
unzip react-native-chart-app.zip && cd react-native-chart-app
npm install && cp .env.example .env # ASTRONODE_API_KEY for the proxy, EXPO_PUBLIC_PROXY_URL for the app
npm run proxy # the key stays here, on :4333
npm start # then i, a, or scan with Expo Go
Files (20)
.env.example1 KB
.gitignore1 KB
App.tsx8 KB
README.md5 KB
app.json1 KB
fixtures/birth-chart.recorded.json2 KB
fixtures/error-401.recorded.json1 KB
index.ts1 KB
package.json1 KB
scripts/render-svg.mts2 KB
server/package.json1 KB
server/proxy.mjs9 KB
src/NorthIndianChart.tsx2 KB
src/api.ts3 KB
src/birth-input.ts2 KB
src/chart-layout.ts9 KB
test/birth-input.test.mts1 KB
test/chart-layout.test.mts6 KB
test/proxy.test.mjs6 KB
tsconfig.json1 KB
server/proxy.mjs
javascript
#!/usr/bin/env node
/**
* AstroNode key-holding proxy for the React Native chart app.
*
* An API key shipped inside a mobile app is a public key: anyone can unzip the
* APK/IPA and read it. So the app talks to this server instead, and only this
* server knows ASTRONODE_API_KEY.
*
* POST /chart { date, time, tz_offset_minutes, lat, lng }
* -> forwards to POST {ASTRONODE_API_URL}/v1/charts/birth
* <- the API's response, status and JSON body unchanged
* GET /health -> { ok: true }
*
* Zero dependencies: node:http and the global fetch (Node 18+).
*
* Env:
* ASTRONODE_API_KEY required
* ASTRONODE_API_URL default https://api.astronode.dev
* PORT default 4333
* HOST default 0.0.0.0 (so a phone on your LAN can reach it)
* RATE_LIMIT_PER_MINUTE default 30 requests per client IP; 0 turns it off
* ALLOWED_ORIGIN CORS origin for Expo web; default *
*/
import { createServer } from "node:http";
import { pathToFileURL } from "node:url";
export const DEFAULT_API_URL = "https://api.astronode.dev";
const MAX_BODY_BYTES = 4096;
const UPSTREAM_TIMEOUT_MS = 15_000;
/** The error envelope the AstroNode API uses; the proxy uses it too, so the app has one shape to read. */
export const errorBody = (code, message, details) => ({
error: details === undefined ? { code, message } : { code, message, details },
});
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
// The API rolls 1985-02-30 over to 2 March; refuse it here instead.
const isRealDate = (s) => {
const d = new Date(`${s}T00:00:00Z`);
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
};
/**
* Check the app's input and keep only the fields the birth-chart endpoint
* takes. Returns { ok: true, body } or { ok: false, problems: string[] }.
* The API validates again; this just fails fast and refuses to forward junk.
*/
export const validateBirthInput = (input) => {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return { ok: false, problems: ["body must be a JSON object"] };
}
const problems = [];
const { date, time, tz_offset_minutes, lat, lng } = input;
if (typeof date !== "string" || !DATE_RE.test(date) || !isRealDate(date)) problems.push("date must be a real date, YYYY-MM-DD");
if (typeof time !== "string" || !TIME_RE.test(time)) problems.push("time must be HH:MM or HH:MM:SS");
if (!Number.isInteger(tz_offset_minutes) || tz_offset_minutes < -840 || tz_offset_minutes > 840) {
problems.push("tz_offset_minutes must be an integer between -840 and 840");
}
if (typeof lat !== "number" || !Number.isFinite(lat) || lat < -90 || lat > 90) {
problems.push("lat must be a number between -90 and 90");
}
if (typeof lng !== "number" || !Number.isFinite(lng) || lng < -180 || lng > 180) {
problems.push("lng must be a number between -180 and 180");
}
if (problems.length) return { ok: false, problems };
return { ok: true, body: { date, time, tz_offset_minutes, lat, lng } };
};
/** The exact upstream request the proxy sends for a validated body. */
export const buildUpstreamRequest = (body, { apiUrl = DEFAULT_API_URL, apiKey }) => ({
url: `${apiUrl.replace(/\/+$/, "")}/v1/charts/birth`,
init: {
method: "POST",
headers: {
authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
accept: "application/json",
"user-agent": "astronode-react-native-chart-app-proxy",
},
body: JSON.stringify(body),
},
});
/** Fixed-window per-IP counter. Good enough for one process; use your platform's limiter at scale. */
export const createRateLimiter = (perMinute, now = () => Date.now()) => {
const hits = new Map();
return (key) => {
if (!perMinute) return true;
const t = now();
const entry = hits.get(key);
if (!entry || t - entry.start >= 60_000) {
if (hits.size > 10_000) hits.clear();
hits.set(key, { start: t, count: 1 });
return true;
}
entry.count += 1;
return entry.count <= perMinute;
};
};
const readBody = (req) =>
new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on("data", (c) => {
size += c.length;
// Keep draining so the client still gets the 413 response; just stop buffering.
if (size <= MAX_BODY_BYTES) chunks.push(c);
});
req.on("end", () => {
if (size > MAX_BODY_BYTES) reject(Object.assign(new Error("body too large"), { status: 413 }));
else resolve(Buffer.concat(chunks).toString("utf8"));
});
req.on("error", reject);
});
/**
* Build the request handler. `fetchImpl` is injectable so the tests can
* replay a recorded response with no network and no key.
*/
export const createHandler = ({
apiKey,
apiUrl = DEFAULT_API_URL,
fetchImpl = globalThis.fetch,
rateLimitPerMinute = 30,
allowedOrigin = "*",
timeoutMs = UPSTREAM_TIMEOUT_MS,
}) => {
if (!apiKey) throw new Error("ASTRONODE_API_KEY is required");
const allow = createRateLimiter(rateLimitPerMinute);
return async (req, res) => {
const send = (status, payload) => {
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"access-control-allow-origin": allowedOrigin,
"access-control-allow-methods": "POST, GET, OPTIONS",
"access-control-allow-headers": "content-type",
"cache-control": "no-store",
});
res.end(typeof payload === "string" ? payload : JSON.stringify(payload));
};
const path = (req.url ?? "/").split("?")[0];
if (req.method === "OPTIONS") return send(204, "");
if (req.method === "GET" && path === "/health") return send(200, { ok: true });
if (path !== "/chart") return send(404, errorBody("NOT_FOUND", "Use POST /chart"));
if (req.method !== "POST") return send(405, errorBody("METHOD_NOT_ALLOWED", "Use POST /chart"));
const ip = req.socket.remoteAddress ?? "unknown";
if (!allow(ip)) return send(429, errorBody("RATE_LIMITED", "Too many requests, try again in a minute"));
let parsed;
try {
parsed = JSON.parse(await readBody(req));
} catch (err) {
if (err && err.status === 413) return send(413, errorBody("PAYLOAD_TOO_LARGE", "Request body too large"));
return send(400, errorBody("VALIDATION_ERROR", "Request body must be JSON"));
}
const checked = validateBirthInput(parsed);
if (!checked.ok) {
return send(400, errorBody("VALIDATION_ERROR", "Invalid birth details", checked.problems));
}
const { url, init } = buildUpstreamRequest(checked.body, { apiUrl, apiKey });
let upstream;
try {
upstream = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
const timedOut = err && (err.name === "TimeoutError" || err.name === "AbortError");
console.error(`[proxy] upstream ${timedOut ? "timed out" : "unreachable"}:`, err?.message ?? err);
return send(
timedOut ? 504 : 502,
errorBody("UPSTREAM_UNAVAILABLE", timedOut ? "The chart service timed out" : "The chart service is unreachable"),
);
}
const text = await upstream.text();
try {
JSON.parse(text);
} catch {
console.error(`[proxy] upstream returned non-JSON (HTTP ${upstream.status})`);
return send(502, errorBody("BAD_UPSTREAM_RESPONSE", `The chart service returned HTTP ${upstream.status}`));
}
if (!upstream.ok) console.warn(`[proxy] upstream HTTP ${upstream.status}: ${text.slice(0, 300)}`);
// Pass the API's status and envelope through untouched: the app shows `error.message`.
return send(upstream.status, text);
};
};
export const startServer = ({ port = 4333, host = "0.0.0.0", ...options }) => {
const server = createServer(createHandler(options));
return new Promise((resolve) => server.listen(port, host, () => resolve(server)));
};
const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
const apiKey = process.env.ASTRONODE_API_KEY;
if (!apiKey) {
console.error("ASTRONODE_API_KEY is not set. Create a key at https://www.astronode.dev and export it.");
process.exit(1);
}
const port = Number(process.env.PORT ?? 4333);
const host = process.env.HOST ?? "0.0.0.0";
const apiUrl = process.env.ASTRONODE_API_URL || DEFAULT_API_URL;
const server = await startServer({
port,
host,
apiKey,
apiUrl,
rateLimitPerMinute: Number(process.env.RATE_LIMIT_PER_MINUTE ?? 30),
allowedOrigin: process.env.ALLOWED_ORIGIN || "*",
});
const addr = server.address();
console.log(`AstroNode chart proxy on http://${host}:${addr.port} -> ${apiUrl}`);
}
src/chart-layout.ts
typescript
/**
* North Indian (diamond) chart geometry - pure TypeScript, no React, no
* react-native-svg. The screen component draws whatever this returns, and
* `npm run check` unit-tests it in plain Node.
*
* The chart is a square with both diagonals and an inner diamond joining the
* edge midpoints. That cuts it into 12 cells: four diamonds (houses 1, 4, 7,
* 10) and eight triangles. House 1 is the top diamond and the houses run
* counter-clockwise from there. Houses are whole-sign, so house 1 holds the
* ascendant's sign and each following house holds the next sign.
*/
export const SIGNS = [
"Aries",
"Taurus",
"Gemini",
"Cancer",
"Leo",
"Virgo",
"Libra",
"Scorpio",
"Sagittarius",
"Capricorn",
"Aquarius",
"Pisces",
] as const;
const SIGN_ABBR: Record<string, string> = {
Aries: "Ar",
Taurus: "Ta",
Gemini: "Ge",
Cancer: "Cn",
Leo: "Le",
Virgo: "Vi",
Libra: "Li",
Scorpio: "Sc",
Sagittarius: "Sg",
Capricorn: "Cp",
Aquarius: "Aq",
Pisces: "Pi",
};
const PLANET_ABBR: Record<string, string> = {
Sun: "Su",
Moon: "Mo",
Mars: "Ma",
Mercury: "Me",
Jupiter: "Ju",
Venus: "Ve",
Saturn: "Sa",
Rahu: "Ra",
Ketu: "Ke",
};
/** One planet as `POST /v1/charts/birth` returns it (in `data.planets`). */
export interface ChartPlanet {
name: string;
sign: string;
house: number;
degree_in_sign: number;
nakshatra: string;
nakshatra_pada: number;
retrograde: boolean;
}
/** The `data` object of a `POST /v1/charts/birth` response. */
export interface BirthChart {
ascendant: { sign: string; degree: number };
planets: ChartPlanet[];
meta?: { ayanamsa?: string; house_system?: string; engine_version?: string };
}
export interface Point {
x: number;
y: number;
}
export interface PlacedPlanet {
name: string;
/** Two-letter label drawn in the cell ("Su", "Mo", ...). */
abbr: string;
retrograde: boolean;
/** Text anchor (middle of the label's baseline). */
x: number;
y: number;
/** Where a small superscript retrograde mark goes, when `retrograde`. */
retroMark: Point | null;
}
export interface HouseCell {
/** 1..12, house 1 = ascendant. */
house: number;
sign: string;
/** 1 = Aries ... 12 = Pisces; the number a North Indian chart prints in each cell. */
signNumber: number;
signAbbr: string;
isAscendant: boolean;
/** Cell outline, for `<Polygon points=...>`. */
polygon: Point[];
/** Where the sign label goes. */
label: Point;
planets: PlacedPlanet[];
}
export interface ChartLayout {
size: number;
/** Outer square, then the lines that divide it, for drawing the frame. */
frame: { square: Point[]; diagonals: [Point, Point][]; diamond: Point[] };
houses: HouseCell[];
}
export const signAbbr = (sign: string): string => SIGN_ABBR[sign] ?? sign.slice(0, 2);
export const planetAbbr = (name: string): string => PLANET_ABBR[name] ?? name.slice(0, 2);
/** Sign occupying `house` (1..12) when the ascendant is `ascendantSign`. */
export const houseSign = (ascendantSign: string, house: number): string => {
const asc = SIGNS.indexOf(ascendantSign as (typeof SIGNS)[number]);
if (asc < 0) throw new Error(`Unknown ascendant sign: ${ascendantSign}`);
return SIGNS[(asc + house - 1) % 12]!;
};
/** Planets bucketed by house number (1..12); every house has an array, possibly empty. */
export const planetsByHouse = (planets: readonly ChartPlanet[]): Map<number, ChartPlanet[]> => {
const out = new Map<number, ChartPlanet[]>();
for (let h = 1; h <= 12; h++) out.set(h, []);
for (const p of planets) {
const bucket = out.get(p.house);
if (!bucket) throw new Error(`Planet ${p.name} has house ${p.house}, expected 1..12`);
bucket.push(p);
}
return out;
};
/** "DD°MM'" for a degree within a sign. */
export const formatDegree = (deg: number): string => {
let d = Math.floor(deg);
let m = Math.round((deg - d) * 60);
if (m === 60) {
d += 1;
m = 0;
}
return `${d}°${String(m).padStart(2, "0")}'`;
};
/**
* Cell outlines in a unit square (0..1). Corners, edge midpoints, centre and
* the four points where the diagonals cross the inner diamond.
*/
const P = {
tl: { x: 0, y: 0 },
tr: { x: 1, y: 0 },
br: { x: 1, y: 1 },
bl: { x: 0, y: 1 },
t: { x: 0.5, y: 0 },
r: { x: 1, y: 0.5 },
b: { x: 0.5, y: 1 },
l: { x: 0, y: 0.5 },
c: { x: 0.5, y: 0.5 },
q1: { x: 0.25, y: 0.25 },
q2: { x: 0.75, y: 0.25 },
q3: { x: 0.75, y: 0.75 },
q4: { x: 0.25, y: 0.75 },
};
const UNIT_CELLS: Point[][] = [
[P.t, P.q1, P.c, P.q2], // 1 top diamond
[P.tl, P.t, P.q1], // 2 upper-left triangle
[P.tl, P.q1, P.l], // 3 left-upper triangle
[P.l, P.q1, P.c, P.q4], // 4 left diamond
[P.l, P.q4, P.bl], // 5 left-lower triangle
[P.bl, P.q4, P.b], // 6 lower-left triangle
[P.b, P.q4, P.c, P.q3], // 7 bottom diamond
[P.b, P.q3, P.br], // 8 lower-right triangle
[P.br, P.q3, P.r], // 9 right-lower triangle
[P.r, P.q3, P.c, P.q2], // 10 right diamond
[P.r, P.q2, P.tr], // 11 right-upper triangle
[P.tr, P.q2, P.t], // 12 upper-right triangle
];
/**
* Text anchor of each cell's content block in the unit square. Diamonds use
* their centre; triangles are pushed toward their wide side, where there is
* room for a row of three labels.
*/
const UNIT_ANCHORS: Point[] = [
{ x: 0.5, y: 0.25 },
{ x: 0.25, y: 0.1 },
{ x: 0.1, y: 0.25 },
{ x: 0.25, y: 0.5 },
{ x: 0.1, y: 0.75 },
{ x: 0.25, y: 0.9 },
{ x: 0.5, y: 0.75 },
{ x: 0.75, y: 0.9 },
{ x: 0.9, y: 0.75 },
{ x: 0.75, y: 0.5 },
{ x: 0.9, y: 0.25 },
{ x: 0.75, y: 0.1 },
];
/** Diamonds have more room than triangles. */
const isDiamond = (house: number): boolean => house % 3 === 1;
/**
* Planet label positions, relative to a cell's content anchor, for a 360
* unit chart. Rows of up to 3 (diamonds) or 2 (triangles), 24 units apart -
* a two-letter label is ~17 units wide at font size 13, plus ~5 for a
* superscript retrograde mark - and rows 15 apart.
* The block is centred on the anchor, so a crowded cell grows both ways.
*/
const planetOffsets = (house: number, count: number): Point[] => {
const perRow = isDiamond(house) ? 3 : 2;
const rows = Math.ceil(count / perRow);
const out: Point[] = [];
for (let i = 0; i < count; i++) {
const row = Math.floor(i / perRow);
const inRow = Math.min(perRow, count - row * perRow);
const col = i % perRow;
out.push({
x: col * 24 - ((inRow - 1) * 24) / 2,
// +4 nudges the label baseline down so the visual block (cap height ~9) is centred.
y: row * 15 - ((rows - 1) * 15) / 2 + 4,
});
}
return out;
};
/** Distance of the sign label above the planet block, in 360 units. */
const LABEL_GAP = 16;
/**
* Lay out a chart in a `size` x `size` box (inset by `pad` so strokes are
* not clipped). Returns everything a renderer needs; it draws no pixels.
*/
export const layoutChart = (chart: BirthChart, size = 360, pad = 4): ChartLayout => {
const span = size - pad * 2;
const k = size / 360; // the offsets above are tuned on a 360 chart
const at = (p: Point): Point => ({ x: pad + p.x * span, y: pad + p.y * span });
const grouped = planetsByHouse(chart.planets);
const houses: HouseCell[] = UNIT_CELLS.map((cell, i) => {
const house = i + 1;
const sign = houseSign(chart.ascendant.sign, house);
const anchor = at(UNIT_ANCHORS[i]!);
const inHouse = grouped.get(house)!;
const offsets = planetOffsets(house, inHouse.length);
const blockTop = offsets.length ? Math.min(...offsets.map((o) => o.y)) : 0;
return {
house,
sign,
signNumber: SIGNS.indexOf(sign as (typeof SIGNS)[number]) + 1,
signAbbr: signAbbr(sign),
isAscendant: house === 1,
polygon: cell.map(at),
label: { x: anchor.x, y: anchor.y + (blockTop - LABEL_GAP) * k },
planets: inHouse.map((p, j) => ({
name: p.name,
abbr: planetAbbr(p.name),
retrograde: p.retrograde,
x: anchor.x + offsets[j]!.x * k,
y: anchor.y + offsets[j]!.y * k,
retroMark: p.retrograde
? { x: anchor.x + (offsets[j]!.x + 9) * k, y: anchor.y + (offsets[j]!.y - 7) * k }
: null,
})),
};
});
return {
size,
frame: {
square: [P.tl, P.tr, P.br, P.bl].map(at),
diagonals: [
[at(P.tl), at(P.br)],
[at(P.tr), at(P.bl)],
],
diamond: [P.t, P.r, P.b, P.l].map(at),
},
houses,
};
};
/** "x1,y1 x2,y2 ..." for an SVG `points` attribute. */
export const toPoints = (poly: readonly Point[]): string =>
poly.map((p) => `${round(p.x)},${round(p.y)}`).join(" ");
export const round = (n: number): number => Math.round(n * 100) / 100;
/** Even-odd ray cast; used by the tests and handy for hit-testing taps. */
export const pointInPolygon = (pt: Point, poly: readonly Point[]): boolean => {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i]!;
const b = poly[j]!;
if (a.y > pt.y !== b.y > pt.y && pt.x < ((b.x - a.x) * (pt.y - a.y)) / (b.y - a.y) + a.x) {
inside = !inside;
}
}
return inside;
};
/** Shoelace area, used by the tests to prove the 12 cells tile the square. */
export const polygonArea = (poly: readonly Point[]): number => {
let s = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i]!;
const b = poly[(i + 1) % poly.length]!;
s += a.x * b.y - b.x * a.y;
}
return Math.abs(s) / 2;
};
A form for date, time, UTC offset (+05:30 style) and coordinates; the app calls the proxy at EXPO_PUBLIC_PROXY_URL, never AstroNode directly.
The proxy (server/proxy.mjs, no dependencies) validates input including real calendar dates, forwards only the five fields the API takes, adds the key, and applies a timeout and a per-IP rate limit.
Draws the North Indian chart with react-native-svg from a pure geometry module, so the layout is tested in Node without a device.
API errors come back unchanged with their status, and the app shows their message.
Endpoints and plan
API calls the template makes
Endpoint
Used for
Plan
POST /v1/charts/birth
Ascendant and the nine planets: sign, house, degree, retrograde
Free
Everything it calls is on the Free plan, so a Free test key runs the whole template.
Where things live
File
What it holds
server/proxy.mjs
The key-holding proxy: POST /chart, GET /health
src/chart-layout.ts
House polygons, label points, planets grouped per house
src/NorthIndianChart.tsx
The chart, drawn with react-native-svg
src/birth-input.ts
Form parsing and validation
src/api.ts
The app's call to the proxy
App.tsx
The screen
Keys and deployment
The API key is read from the server's environment and sent as Authorization: Bearer <key>; it never reaches a browser or an app bundle.
npm run check type-checks the app and runs 23 tests offline - chart geometry, form parsing and the proxy against recorded responses - with no key and no network.
Deploy the proxy anywhere Node runs and point EXPO_PUBLIC_PROXY_URL at it; Expo inlines that value at build time, so rebuild after changing it.
Only the proxy URL is in the app bundle - ASTRONODE_API_KEY is never prefixed EXPO_PUBLIC_.
Build store binaries with EAS Build or expo prebuild as for any Expo app.
Questions
Why does the React Native app need a proxy?
Anything inside an app bundle can be extracted, including an API key. The proxy keeps the key on a server and lets you rate-limit what the app can spend.
Does it need a paid plan?
No. It calls only POST /v1/charts/birth, which is on the Free plan.
Can I use the chart in a bare React Native app without Expo?
Yes. src/NorthIndianChart.tsx and src/chart-layout.ts need only React Native and react-native-svg.