@milofly/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,217 @@
1
+ /**
2
+ * First Milofly app — a complete, dependency-free example (Node.js ≥ 20):
3
+ *
4
+ * GET /install → sends the merchant to the Milofly install screen
5
+ * GET /oauth/callback → exchanges the install code for an access token
6
+ * POST /webhooks/milofly → verifies and de-duplicates webhook deliveries
7
+ * GET / → the page Milofly embeds in the store panel (App Bridge)
8
+ * POST /api/session → verifies the session token and calls the Milofly API
9
+ *
10
+ * Code between `// @belge:<name>` and `// @belge-son` is quoted by the developer documentation.
11
+ */
12
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
13
+ import { randomBytes, timingSafeEqual } from "node:crypto";
14
+ import { readFile } from "node:fs/promises";
15
+ import { dirname, join, normalize } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import {
18
+ MiloflyApiError,
19
+ SessionTokenError,
20
+ WebhookVerificationError,
21
+ buildInstallUrl,
22
+ createClient,
23
+ exchangeCode,
24
+ verifySessionToken,
25
+ verifyWebhook,
26
+ } from "@milofly/app-server";
27
+ import { config } from "./config.js";
28
+ import { findInstallation, firstDelivery, removeInstallation, saveInstallation } from "./store.js";
29
+
30
+ const publicDir = join(dirname(fileURLToPath(import.meta.url)), "..", "public");
31
+ // The browser loads App Bridge straight from the installed package (see the import map in index.html).
32
+ const bridgeDir = dirname(fileURLToPath(import.meta.resolve("@milofly/app-bridge")));
33
+ const secure = config.appOrigin.startsWith("https://");
34
+ const STATE_COOKIE = "mf_install_state";
35
+
36
+ function readBody(req: IncomingMessage): Promise<Buffer> {
37
+ return new Promise((resolve, reject) => {
38
+ const chunks: Buffer[] = [];
39
+ req.on("data", (c: Buffer) => chunks.push(c));
40
+ req.on("end", () => resolve(Buffer.concat(chunks)));
41
+ req.on("error", reject);
42
+ });
43
+ }
44
+
45
+ function send(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}) {
46
+ const text = typeof body === "string" ? body : JSON.stringify(body);
47
+ res.writeHead(status, { "Content-Type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json", ...headers });
48
+ res.end(text);
49
+ }
50
+
51
+ function cookie(req: IncomingMessage, name: string): string | null {
52
+ for (const part of (req.headers.cookie ?? "").split(";")) {
53
+ const [k, ...v] = part.trim().split("=");
54
+ if (k === name) return decodeURIComponent(v.join("="));
55
+ }
56
+ return null;
57
+ }
58
+
59
+ function sameText(a: string, b: string): boolean {
60
+ const x = Buffer.from(a);
61
+ const y = Buffer.from(b);
62
+ return x.length === y.length && timingSafeEqual(x, y);
63
+ }
64
+
65
+ // @belge:kurulum-baglantisi
66
+ /** App-initiated install: a random state in a cookie, the same state in the install URL. */
67
+ function startInstall(res: ServerResponse) {
68
+ const state = randomBytes(32).toString("hex");
69
+ const url = buildInstallUrl({
70
+ environment: config.environment,
71
+ appKey: config.appKey,
72
+ clientId: config.clientId,
73
+ state,
74
+ });
75
+ res.writeHead(302, {
76
+ Location: url,
77
+ "Set-Cookie": `${STATE_COOKIE}=${state}; Path=/oauth; Max-Age=900; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`,
78
+ });
79
+ res.end();
80
+ }
81
+ // @belge-son
82
+
83
+ // @belge:kod-takasi
84
+ /**
85
+ * Milofly returns to your registered redirect URI with `code` (and `state` when YOU started the install;
86
+ * an install started from the Milofly app store arrives without state). The code is single-use and only
87
+ * your client secret can redeem it.
88
+ */
89
+ async function finishInstall(req: IncomingMessage, res: ServerResponse, url: URL) {
90
+ if (url.searchParams.get("error") === "access_denied") return send(res, 200, "Installation cancelled.");
91
+ const code = url.searchParams.get("code");
92
+ const state = url.searchParams.get("state");
93
+ if (!code) return send(res, 400, "Missing code.");
94
+ if (state !== null) {
95
+ const expected = cookie(req, STATE_COOKIE);
96
+ if (!expected || !sameText(state, expected)) return send(res, 403, "Install state does not match.");
97
+ }
98
+
99
+ const grant = await exchangeCode({
100
+ environment: config.environment,
101
+ clientId: config.clientId,
102
+ clientSecret: config.clientSecret,
103
+ code,
104
+ });
105
+ saveInstallation(grant); // store grant.accessToken ENCRYPTED in a real app
106
+
107
+ // Back to the merchant's panel, straight into this app.
108
+ const panel = new URL(`/plugins/manage/${encodeURIComponent(config.appKey)}`, config.environment.panelOrigin);
109
+ res.writeHead(302, { Location: panel.toString(), "Set-Cookie": `${STATE_COOKIE}=; Path=/oauth; Max-Age=0` });
110
+ res.end();
111
+ }
112
+ // @belge-son
113
+
114
+ // @belge:webhook-dogrulama
115
+ async function receiveWebhook(req: IncomingMessage, res: ServerResponse) {
116
+ const rawBody = await readBody(req); // raw bytes: never parse and re-serialize before verifying
117
+ let hook;
118
+ try {
119
+ hook = await verifyWebhook({ secret: config.signingSecret, headers: req.headers, rawBody });
120
+ } catch (err) {
121
+ if (err instanceof WebhookVerificationError) return send(res, 401, { error: err.code });
122
+ throw err;
123
+ }
124
+ // Retries carry the same eventId: process each event once.
125
+ if (!firstDelivery(hook.envelope.eventId)) return send(res, 200, { duplicate: true });
126
+
127
+ const { topic, storeId, regionId, data } = hook.envelope;
128
+ if (topic === "app.uninstalled") {
129
+ const d = data as { scope: "region" | "store" };
130
+ removeInstallation(storeId, regionId, d.scope);
131
+ }
132
+ console.log(`[webhook] ${topic} store=${storeId} region=${regionId ?? "-"} event=${hook.envelope.eventId}`);
133
+ send(res, 200, { ok: true });
134
+ }
135
+ // @belge-son
136
+
137
+ // @belge:oturum-jetonu
138
+ /**
139
+ * The embedded page sends its session token on every call. The token says which store, region and
140
+ * panel user is looking at the app; verify it on every request (it lives two minutes, App Bridge renews it).
141
+ */
142
+ async function session(req: IncomingMessage, res: ServerResponse) {
143
+ const auth = req.headers.authorization ?? "";
144
+ const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
145
+ const hostOrigin = req.headers["x-milofly-host"];
146
+ let claims;
147
+ try {
148
+ claims = await verifySessionToken(token, {
149
+ secret: config.signingSecret,
150
+ appKey: config.appKey,
151
+ hostOrigin: typeof hostOrigin === "string" ? hostOrigin : undefined,
152
+ });
153
+ } catch (err) {
154
+ if (err instanceof SessionTokenError) return send(res, 401, { error: err.code });
155
+ throw err;
156
+ }
157
+ // @belge-son
158
+
159
+ const installation = findInstallation(claims.storeId, claims.regionId);
160
+ if (!installation) return send(res, 409, { error: "not_installed_here" });
161
+
162
+ // @belge:api-cagrisi
163
+ const milofly = createClient({
164
+ environment: config.environment,
165
+ accessToken: installation.accessToken,
166
+ rateLimitRetry: { maxRetries: 2, maxWaitMs: 5_000 },
167
+ });
168
+ try {
169
+ const context = await milofly.request<{ store: { id: number; code: string }; regions: unknown[]; scopes: string[] }>({
170
+ method: "GET",
171
+ path: "/api/apps/v1/context",
172
+ });
173
+ send(res, 200, { claims, context });
174
+ } catch (err) {
175
+ if (err instanceof MiloflyApiError) return send(res, 502, { error: "milofly_api", status: err.status, code: err.code });
176
+ throw err;
177
+ }
178
+ // @belge-son
179
+ }
180
+
181
+ async function staticFile(res: ServerResponse, root: string, rel: string, type: string) {
182
+ const file = normalize(join(root, rel));
183
+ if (!file.startsWith(root) || !/\.(html|js)$/.test(file)) return send(res, 404, "Not found");
184
+ let content: Buffer;
185
+ try {
186
+ content = await readFile(file);
187
+ } catch (err) {
188
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return send(res, 404, "Not found");
189
+ throw err;
190
+ }
191
+ res.writeHead(200, { "Content-Type": type });
192
+ res.end(content);
193
+ }
194
+
195
+ const server = createServer((req, res) => {
196
+ const url = new URL(req.url ?? "/", config.appOrigin);
197
+ const route = `${req.method} ${url.pathname}`;
198
+ const run = async () => {
199
+ // The panel frames this app: allow ONLY the Milofly panel origin as a parent (never X-Frame-Options).
200
+ res.setHeader("Content-Security-Policy", `frame-ancestors ${config.environment.panelOrigin}`);
201
+ if (route === "GET /install") return startInstall(res);
202
+ if (route === "GET /oauth/callback") return finishInstall(req, res, url);
203
+ if (route === "POST /webhooks/milofly") return receiveWebhook(req, res);
204
+ if (route === "POST /api/session") return session(req, res);
205
+ if (route === "GET /") return staticFile(res, publicDir, "index.html", "text/html; charset=utf-8");
206
+ if (route === "GET /app.js") return staticFile(res, publicDir, "app.js", "text/javascript; charset=utf-8");
207
+ if (req.method === "GET" && url.pathname.startsWith("/vendor/app-bridge/"))
208
+ return staticFile(res, bridgeDir, url.pathname.slice("/vendor/app-bridge/".length), "text/javascript; charset=utf-8");
209
+ send(res, 404, "Not found");
210
+ };
211
+ run().catch((err: unknown) => {
212
+ console.error(`[error] ${route}`, err);
213
+ if (!res.headersSent) send(res, 500, { error: "internal" });
214
+ });
215
+ });
216
+
217
+ server.listen(config.port, () => console.log(`First Milofly app listening on ${config.appOrigin} (port ${config.port})`));
@@ -0,0 +1,34 @@
1
+ import type { InstallGrant } from "@milofly/app-server";
2
+
3
+ /**
4
+ * In-memory storage for the example. A real app keeps installations in its database with the access
5
+ * token ENCRYPTED, and keeps processed event ids long enough to cover retries (Milofly retries a failed
6
+ * delivery for about half an hour).
7
+ */
8
+ const installations = new Map<string, InstallGrant>();
9
+ const processedEvents = new Set<string>();
10
+
11
+ /** One installation per store and region (region-scoped) or per store (store-wide). */
12
+ function key(storeId: number, regionId: number | null): string {
13
+ return `${storeId}:${regionId ?? "*"}`;
14
+ }
15
+
16
+ export function saveInstallation(grant: InstallGrant): void {
17
+ installations.set(key(grant.storeId, grant.installScope === "store" ? null : grant.regionId), grant);
18
+ }
19
+
20
+ /** Installation serving `regionId` of `storeId` (store-wide first match, else the exact region). */
21
+ export function findInstallation(storeId: number, regionId: number | null): InstallGrant | null {
22
+ return installations.get(key(storeId, null)) ?? (regionId === null ? null : installations.get(key(storeId, regionId)) ?? null);
23
+ }
24
+
25
+ export function removeInstallation(storeId: number, regionId: number | null, scope: "region" | "store"): void {
26
+ installations.delete(key(storeId, scope === "store" ? null : regionId));
27
+ }
28
+
29
+ /** `true` the first time an event id is seen. */
30
+ export function firstDelivery(eventId: string): boolean {
31
+ if (processedEvents.has(eventId)) return false;
32
+ processedEvents.add(eventId);
33
+ return true;
34
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022", "DOM"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "rootDir": "src",
10
+ "outDir": "dist",
11
+ "skipLibCheck": true
12
+ },
13
+ "include": ["src"]
14
+ }