@milofly/app-server 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-27)
4
+
5
+ - First version: `verifyWebhook`, `verifySessionToken`, `buildInstallUrl`, `exchangeCode`, `createClient`, `signingKeyId`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alper Baydeniz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @milofly/app-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-side helpers for Milofly apps. Zero dependencies; runs on Node.js ≥ 20, Deno, Bun and edge runtimes (Web Crypto + fetch).
4
+
5
+ ```
6
+ npm install @milofly/app-server
7
+ ```
8
+
9
+ | Function | Purpose |
10
+ |---|---|
11
+ | `verifyWebhook` | Verify `X-Milofly-Hmac-Sha256` (topic, store and timestamp are signed), the 5-minute replay window, and return the envelope (`eventId` for de-duplication). |
12
+ | `verifySessionToken` | Verify the session token your embedded page got from App Bridge; returns store, region, panel user (`userId`), surface and host origin. |
13
+ | `buildInstallUrl` | URL of the install (consent) screen for a merchant. |
14
+ | `exchangeCode` | Install code → access token (server only, needs the client secret). |
15
+ | `createClient` | Authenticated client for `/api/apps/**` (typed operations are generated from the published OpenAPI document). |
16
+ | `signingKeyId` | Id of a signing secret; matches `X-Milofly-Key-Id` / the token's `Kid`. |
17
+
18
+ There is no implicit environment: pass `MILOFLY_ENVIRONMENTS.production` or your own `{ apiBaseUrl, panelOrigin }`.
19
+
20
+ ```ts
21
+ import { verifyWebhook, WebhookVerificationError } from "@milofly/app-server";
22
+
23
+ app.post("/webhooks/milofly", express.raw({ type: "application/json" }), async (req, res) => {
24
+ try {
25
+ const { envelope } = await verifyWebhook({ secret: process.env.MILOFLY_WEBHOOK_SECRET!, headers: req.headers, rawBody: req.body });
26
+ if (await alreadyProcessed(envelope.eventId)) return res.sendStatus(200);
27
+ await handle(envelope);
28
+ res.sendStatus(200);
29
+ } catch (err) {
30
+ if (err instanceof WebhookVerificationError) return res.sendStatus(401);
31
+ throw err;
32
+ }
33
+ });
34
+ ```
35
+
36
+ Always pass the raw body. Parsing and re-serializing JSON changes the bytes and breaks the signature.
37
+
38
+ Pass a list of secrets (`[current, previous]`) during a secret rotation: the `X-Milofly-Key-Id` header / `Kid`
39
+ claim selects the matching one.
package/client.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { MiloflyApiError } from "./errors.js";
2
+ import type { MiloflyEnvironment } from "./environments.js";
3
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
4
+ export type QueryValue = string | number | boolean | null | undefined | readonly (string | number | boolean)[];
5
+ export interface RequestOptions {
6
+ method: HttpMethod;
7
+ /** Full API path, e.g. `/api/apps/v1/products`. Path parameters already substituted. */
8
+ path: string;
9
+ query?: Record<string, QueryValue>;
10
+ body?: unknown;
11
+ /**
12
+ * Region to act on. Store-wide installations must pin a region on most endpoints; region
13
+ * installations are locked to their own region (sending another one is refused by the API).
14
+ */
15
+ regionId?: number;
16
+ headers?: Record<string, string>;
17
+ signal?: AbortSignal;
18
+ }
19
+ export interface RateLimitRetry {
20
+ /** How many times a 429 is retried. */
21
+ maxRetries: number;
22
+ /** Largest `Retry-After` the client is willing to wait (ms); a longer one fails immediately. */
23
+ maxWaitMs: number;
24
+ }
25
+ export interface ClientOptions {
26
+ environment: Pick<MiloflyEnvironment, "apiBaseUrl">;
27
+ /** Access token from the install (`exchangeCode`). */
28
+ accessToken: string;
29
+ /** Region used when a request does not set one. */
30
+ regionId?: number;
31
+ /** `false`: a 429 fails at once. Otherwise the client waits `Retry-After` within these bounds. */
32
+ rateLimitRetry: RateLimitRetry | false;
33
+ fetch?: typeof fetch;
34
+ }
35
+ export interface MiloflyClient {
36
+ request<T = unknown>(options: RequestOptions): Promise<T>;
37
+ }
38
+ /** Builds a {@link MiloflyApiError} from a non-success response and its parsed body. */
39
+ export declare function readApiError(res: Response, body: unknown): MiloflyApiError;
40
+ /**
41
+ * Minimal authenticated client for `/api/apps/**`. Typed operations are generated on top of it.
42
+ *
43
+ * - Every non-2xx answer, and every 2xx answer with `success: false`, throws {@link MiloflyApiError}.
44
+ * - 429 is retried only within {@link RateLimitRetry}; nothing is retried silently beyond it.
45
+ */
46
+ export declare function createClient(options: ClientOptions): MiloflyClient;
package/client.js ADDED
@@ -0,0 +1,96 @@
1
+ import { MiloflyApiError } from "./errors.js";
2
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
3
+ const t = setTimeout(resolve, ms);
4
+ signal?.addEventListener("abort", () => {
5
+ clearTimeout(t);
6
+ reject(signal.reason);
7
+ }, { once: true });
8
+ });
9
+ function retryAfterSeconds(res) {
10
+ const raw = res.headers.get("retry-after");
11
+ if (raw === null)
12
+ return null;
13
+ if (/^[0-9]+$/.test(raw.trim()))
14
+ return Number(raw.trim());
15
+ const at = Date.parse(raw);
16
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
17
+ }
18
+ /** Builds a {@link MiloflyApiError} from a non-success response and its parsed body. */
19
+ export function readApiError(res, body) {
20
+ const rec = body && typeof body === "object" && !Array.isArray(body) ? body : null;
21
+ const code = typeof rec?.code === "string" && rec.code.length > 0 ? rec.code : null;
22
+ const params = rec?.params && typeof rec.params === "object" && !Array.isArray(rec.params) ? rec.params : null;
23
+ const message = typeof rec?.message === "string" && rec.message.length > 0 ? rec.message : `Milofly API responded ${res.status}${code ? ` (${code})` : ""}.`;
24
+ return new MiloflyApiError({ status: res.status, code, params, message, body, retryAfterSeconds: retryAfterSeconds(res) });
25
+ }
26
+ function appendQuery(url, query) {
27
+ if (!query)
28
+ return;
29
+ for (const [k, v] of Object.entries(query)) {
30
+ if (v === undefined || v === null)
31
+ continue;
32
+ if (Array.isArray(v))
33
+ for (const item of v)
34
+ url.searchParams.append(k, String(item));
35
+ else
36
+ url.searchParams.set(k, String(v));
37
+ }
38
+ }
39
+ /**
40
+ * Minimal authenticated client for `/api/apps/**`. Typed operations are generated on top of it.
41
+ *
42
+ * - Every non-2xx answer, and every 2xx answer with `success: false`, throws {@link MiloflyApiError}.
43
+ * - 429 is retried only within {@link RateLimitRetry}; nothing is retried silently beyond it.
44
+ */
45
+ export function createClient(options) {
46
+ if (!options.accessToken)
47
+ throw new TypeError("accessToken is required.");
48
+ const doFetch = options.fetch ?? globalThis.fetch;
49
+ return {
50
+ async request(req) {
51
+ if (!req.path.startsWith("/api/apps/"))
52
+ throw new TypeError(`path must start with /api/apps/ (got ${req.path}).`);
53
+ const url = new URL(req.path, options.environment.apiBaseUrl);
54
+ appendQuery(url, req.query);
55
+ const regionId = req.regionId ?? options.regionId;
56
+ const headers = {
57
+ Accept: "application/json",
58
+ Authorization: `Bearer ${options.accessToken}`,
59
+ ...(regionId !== undefined ? { "X-Region-Id": String(regionId) } : {}),
60
+ ...(req.body !== undefined ? { "Content-Type": "application/json" } : {}),
61
+ ...req.headers,
62
+ };
63
+ const init = {
64
+ method: req.method,
65
+ headers,
66
+ body: req.body === undefined ? undefined : JSON.stringify(req.body),
67
+ signal: req.signal,
68
+ };
69
+ for (let attempt = 0;; attempt++) {
70
+ const res = await doFetch(url, init);
71
+ const text = await res.text();
72
+ let body = null;
73
+ if (text.length > 0) {
74
+ try {
75
+ body = JSON.parse(text);
76
+ }
77
+ catch {
78
+ body = text;
79
+ }
80
+ }
81
+ if (res.status === 429 && options.rateLimitRetry && attempt < options.rateLimitRetry.maxRetries) {
82
+ const wait = retryAfterSeconds(res);
83
+ if (wait !== null && wait * 1000 <= options.rateLimitRetry.maxWaitMs) {
84
+ await sleep(wait * 1000, req.signal);
85
+ continue;
86
+ }
87
+ }
88
+ if (!res.ok)
89
+ throw readApiError(res, body);
90
+ if (body && typeof body === "object" && body.success === false)
91
+ throw readApiError(res, body);
92
+ return body;
93
+ }
94
+ },
95
+ };
96
+ }
package/crypto.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * HMAC helpers on Web Crypto (Node ≥ 20, Deno, Bun, edge runtimes). Signatures are compared with
3
+ * `crypto.subtle.verify`, which is constant-time; no string equality on secrets or signatures.
4
+ */
5
+ export declare function utf8(value: string): Uint8Array;
6
+ export declare function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array;
7
+ /** Lower-case hex → bytes. `null` when the text is not even-length hex. */
8
+ export declare function hexToBytes(hex: string): Uint8Array | null;
9
+ export declare function bytesToHex(bytes: ArrayBuffer | Uint8Array): string;
10
+ /** HMAC-SHA256 as lower-case hex. */
11
+ export declare function hmacSha256Hex(secret: string, data: Uint8Array): Promise<string>;
12
+ /** Constant-time check of a hex HMAC-SHA256 signature. */
13
+ export declare function verifyHmacSha256Hex(secret: string, data: Uint8Array, signatureHex: string): Promise<boolean>;
14
+ /**
15
+ * Identifier of a signing secret, sent by Milofly as `X-Milofly-Key-Id` (webhooks) and `Kid`
16
+ * (session tokens). Derived from the secret itself, so it changes when the secret is rotated and
17
+ * both sides compute it without any registry: first 16 hex characters of
18
+ * HMAC-SHA256(key = secret, message = "milofly-key-id-v1"). It reveals nothing about the secret.
19
+ */
20
+ export declare function signingKeyId(secret: string): Promise<string>;
21
+ export declare const KEY_ID_DOMAIN = "milofly-key-id-v1";
22
+ /**
23
+ * Chooses the secrets to try. With a key id, only the matching secret (none → `null`); without one
24
+ * (older deliveries), every configured secret in order.
25
+ */
26
+ export declare function secretsFor(secrets: readonly string[], keyId: string | null): Promise<readonly string[] | null>;
27
+ export declare function normalizeSecrets(secret: string | readonly string[]): readonly string[];
package/crypto.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * HMAC helpers on Web Crypto (Node ≥ 20, Deno, Bun, edge runtimes). Signatures are compared with
3
+ * `crypto.subtle.verify`, which is constant-time; no string equality on secrets or signatures.
4
+ */
5
+ const encoder = new TextEncoder();
6
+ function subtle() {
7
+ const s = globalThis.crypto?.subtle;
8
+ if (!s)
9
+ throw new Error("@milofly/app-server needs Web Crypto (globalThis.crypto.subtle). Use Node.js 20 or newer.");
10
+ return s;
11
+ }
12
+ async function hmacKey(secret, usage) {
13
+ return subtle().importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
14
+ }
15
+ export function utf8(value) {
16
+ return encoder.encode(value);
17
+ }
18
+ export function concatBytes(a, b) {
19
+ const out = new Uint8Array(a.length + b.length);
20
+ out.set(a, 0);
21
+ out.set(b, a.length);
22
+ return out;
23
+ }
24
+ /** Lower-case hex → bytes. `null` when the text is not even-length hex. */
25
+ export function hexToBytes(hex) {
26
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex))
27
+ return null;
28
+ const out = new Uint8Array(hex.length / 2);
29
+ for (let i = 0; i < out.length; i++)
30
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
31
+ return out;
32
+ }
33
+ export function bytesToHex(bytes) {
34
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
35
+ let out = "";
36
+ for (const b of view)
37
+ out += b.toString(16).padStart(2, "0");
38
+ return out;
39
+ }
40
+ /** HMAC-SHA256 as lower-case hex. */
41
+ export async function hmacSha256Hex(secret, data) {
42
+ const sig = await subtle().sign("HMAC", await hmacKey(secret, "sign"), data);
43
+ return bytesToHex(sig);
44
+ }
45
+ /** Constant-time check of a hex HMAC-SHA256 signature. */
46
+ export async function verifyHmacSha256Hex(secret, data, signatureHex) {
47
+ const sig = hexToBytes(signatureHex);
48
+ if (!sig || sig.length !== 32)
49
+ return false;
50
+ return subtle().verify("HMAC", await hmacKey(secret, "verify"), sig, data);
51
+ }
52
+ /**
53
+ * Identifier of a signing secret, sent by Milofly as `X-Milofly-Key-Id` (webhooks) and `Kid`
54
+ * (session tokens). Derived from the secret itself, so it changes when the secret is rotated and
55
+ * both sides compute it without any registry: first 16 hex characters of
56
+ * HMAC-SHA256(key = secret, message = "milofly-key-id-v1"). It reveals nothing about the secret.
57
+ */
58
+ export async function signingKeyId(secret) {
59
+ return (await hmacSha256Hex(secret, utf8(KEY_ID_DOMAIN))).slice(0, 16);
60
+ }
61
+ export const KEY_ID_DOMAIN = "milofly-key-id-v1";
62
+ /**
63
+ * Chooses the secrets to try. With a key id, only the matching secret (none → `null`); without one
64
+ * (older deliveries), every configured secret in order.
65
+ */
66
+ export async function secretsFor(secrets, keyId) {
67
+ if (keyId === null)
68
+ return secrets;
69
+ for (const s of secrets)
70
+ if ((await signingKeyId(s)) === keyId)
71
+ return [s];
72
+ return null;
73
+ }
74
+ export function normalizeSecrets(secret) {
75
+ const list = typeof secret === "string" ? [secret] : [...secret];
76
+ if (list.length === 0 || list.some((s) => typeof s !== "string" || s.length === 0))
77
+ throw new TypeError("secret must be a non-empty string or a non-empty list of non-empty strings.");
78
+ return list;
79
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Published Milofly endpoints. There is no implicit environment: pass one of these (or your own
3
+ * object for a local Milofly) to `createClient`, `exchangeCode` and `buildInstallUrl`.
4
+ */
5
+ export interface MiloflyEnvironment {
6
+ /** Base of the app API (`/api/apps/**`). */
7
+ apiBaseUrl: string;
8
+ /** Origin of the store panel that embeds apps and shows the install (consent) screen. */
9
+ panelOrigin: string;
10
+ }
11
+ export declare const MILOFLY_ENVIRONMENTS: Readonly<{
12
+ production: Readonly<{
13
+ apiBaseUrl: string;
14
+ panelOrigin: string;
15
+ }>;
16
+ }>;
@@ -0,0 +1,6 @@
1
+ export const MILOFLY_ENVIRONMENTS = Object.freeze({
2
+ production: Object.freeze({
3
+ apiBaseUrl: "https://api.milofly.com",
4
+ panelOrigin: "https://app.milofly.com",
5
+ }),
6
+ });
package/errors.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** Webhook request rejected. `code` is stable; answer the request with 401 and do not process it. */
2
+ export declare class WebhookVerificationError extends Error {
3
+ readonly code: "missing_header" | "malformed_header" | "timestamp_out_of_range" | "unknown_key" | "signature_mismatch" | "body_invalid" | "envelope_mismatch";
4
+ constructor(code: WebhookVerificationError["code"], message?: string);
5
+ }
6
+ /** Session token rejected. `code` is stable; treat the request as unauthenticated. */
7
+ export declare class SessionTokenError extends Error {
8
+ readonly code: "malformed" | "unknown_key" | "signature_mismatch" | "unsupported_version" | "app_mismatch" | "expired" | "not_yet_valid" | "host_origin_mismatch";
9
+ constructor(code: SessionTokenError["code"], message?: string);
10
+ }
11
+ /**
12
+ * Non-success answer of the Milofly API (HTTP status outside 2xx, or `success: false`).
13
+ * `code`/`params` come from the API error envelope; `code` is `null` when the API sent none.
14
+ */
15
+ export declare class MiloflyApiError extends Error {
16
+ readonly status: number;
17
+ readonly code: string | null;
18
+ readonly params: Record<string, unknown> | null;
19
+ readonly body: unknown;
20
+ readonly retryAfterSeconds: number | null;
21
+ constructor(init: {
22
+ status: number;
23
+ code: string | null;
24
+ params: Record<string, unknown> | null;
25
+ message: string;
26
+ body: unknown;
27
+ retryAfterSeconds: number | null;
28
+ });
29
+ }
package/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ /** Webhook request rejected. `code` is stable; answer the request with 401 and do not process it. */
2
+ export class WebhookVerificationError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message ?? code);
6
+ this.name = "WebhookVerificationError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ /** Session token rejected. `code` is stable; treat the request as unauthenticated. */
11
+ export class SessionTokenError extends Error {
12
+ code;
13
+ constructor(code, message) {
14
+ super(message ?? code);
15
+ this.name = "SessionTokenError";
16
+ this.code = code;
17
+ }
18
+ }
19
+ /**
20
+ * Non-success answer of the Milofly API (HTTP status outside 2xx, or `success: false`).
21
+ * `code`/`params` come from the API error envelope; `code` is `null` when the API sent none.
22
+ */
23
+ export class MiloflyApiError extends Error {
24
+ status;
25
+ code;
26
+ params;
27
+ body;
28
+ retryAfterSeconds;
29
+ constructor(init) {
30
+ super(init.message);
31
+ this.name = "MiloflyApiError";
32
+ this.status = init.status;
33
+ this.code = init.code;
34
+ this.params = init.params;
35
+ this.body = init.body;
36
+ this.retryAfterSeconds = init.retryAfterSeconds;
37
+ }
38
+ }
package/index.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @milofly/app-server — server-side helpers for Milofly apps (Node.js ≥ 20, Deno, Bun, edge runtimes).
3
+ *
4
+ * - `verifyWebhook` verify a webhook delivery and read its envelope
5
+ * - `verifySessionToken` verify the session token your embedded page received from App Bridge
6
+ * - `buildInstallUrl` send a merchant to the install screen
7
+ * - `exchangeCode` turn the install code into an access token
8
+ * - `createClient` call `/api/apps/**`
9
+ */
10
+ export { MILOFLY_ENVIRONMENTS, type MiloflyEnvironment } from "./environments.js";
11
+ export { MiloflyApiError, SessionTokenError, WebhookVerificationError } from "./errors.js";
12
+ export { KEY_ID_DOMAIN, signingKeyId } from "./crypto.js";
13
+ export { WEBHOOK_TOLERANCE_SECONDS, WebhookHeader, verifyWebhook, type HeaderSource, type VerifiedWebhook, type VerifyWebhookOptions, type WebhookEnvelope, } from "./webhook.js";
14
+ export { SESSION_TOKEN_CLOCK_SKEW_SECONDS, SESSION_TOKEN_DOMAIN, verifySessionToken, type SessionTokenClaims, type VerifySessionTokenOptions, } from "./session-token.js";
15
+ export { INSTALL_PATH, buildInstallUrl, exchangeCode, type ExchangeCodeOptions, type InstallGrant, type InstallUrlOptions } from "./oauth.js";
16
+ export { createClient, type ClientOptions, type HttpMethod, type MiloflyClient, type QueryValue, type RateLimitRetry, type RequestOptions, } from "./client.js";
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @milofly/app-server — server-side helpers for Milofly apps (Node.js ≥ 20, Deno, Bun, edge runtimes).
3
+ *
4
+ * - `verifyWebhook` verify a webhook delivery and read its envelope
5
+ * - `verifySessionToken` verify the session token your embedded page received from App Bridge
6
+ * - `buildInstallUrl` send a merchant to the install screen
7
+ * - `exchangeCode` turn the install code into an access token
8
+ * - `createClient` call `/api/apps/**`
9
+ */
10
+ export { MILOFLY_ENVIRONMENTS } from "./environments.js";
11
+ export { MiloflyApiError, SessionTokenError, WebhookVerificationError } from "./errors.js";
12
+ export { KEY_ID_DOMAIN, signingKeyId } from "./crypto.js";
13
+ export { WEBHOOK_TOLERANCE_SECONDS, WebhookHeader, verifyWebhook, } from "./webhook.js";
14
+ export { SESSION_TOKEN_CLOCK_SKEW_SECONDS, SESSION_TOKEN_DOMAIN, verifySessionToken, } from "./session-token.js";
15
+ export { INSTALL_PATH, buildInstallUrl, exchangeCode } from "./oauth.js";
16
+ export { createClient, } from "./client.js";
package/oauth.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { MiloflyEnvironment } from "./environments.js";
2
+ /** Path of the install (consent) screen in the store panel. */
3
+ export declare const INSTALL_PATH = "/plugins/install/";
4
+ export interface InstallUrlOptions {
5
+ environment: Pick<MiloflyEnvironment, "panelOrigin">;
6
+ appKey: string;
7
+ clientId: string;
8
+ /** Opaque, signed value you verify on your OAuth callback (CSRF protection). Returned unchanged. */
9
+ state: string;
10
+ /** Scopes to request; must be within the scopes registered for the app. Omit to request all of them. */
11
+ scopes?: readonly string[];
12
+ }
13
+ /**
14
+ * URL that opens the install screen for a merchant. The redirect URI is not part of it: Milofly
15
+ * returns to the first redirect URI registered for your app, with `?code=…&state=…`
16
+ * (or `?error=access_denied&state=…` when the merchant cancels).
17
+ */
18
+ export declare function buildInstallUrl(options: InstallUrlOptions): string;
19
+ /** A completed installation. Store the access token encrypted; it is shown only once. */
20
+ export interface InstallGrant {
21
+ accessToken: string;
22
+ tokenType: "Bearer";
23
+ scopes: string[];
24
+ appKey: string;
25
+ storeId: number;
26
+ regionId: number | null;
27
+ installScope: "region" | "store";
28
+ /** Regions the installation serves (store-wide installations only). */
29
+ regions: {
30
+ id: number;
31
+ code: string;
32
+ currency: string;
33
+ domain: string | null;
34
+ }[] | null;
35
+ storeName: string | null;
36
+ storeDomain: string | null;
37
+ }
38
+ export interface ExchangeCodeOptions {
39
+ environment: Pick<MiloflyEnvironment, "apiBaseUrl">;
40
+ clientId: string;
41
+ clientSecret: string;
42
+ code: string;
43
+ fetch?: typeof fetch;
44
+ }
45
+ /** Exchanges the one-time install code for an access token (server side only: needs the client secret). */
46
+ export declare function exchangeCode(options: ExchangeCodeOptions): Promise<InstallGrant>;
package/oauth.js ADDED
@@ -0,0 +1,47 @@
1
+ import { MiloflyApiError } from "./errors.js";
2
+ import { readApiError } from "./client.js";
3
+ /** Path of the install (consent) screen in the store panel. */
4
+ export const INSTALL_PATH = "/plugins/install/";
5
+ /**
6
+ * URL that opens the install screen for a merchant. The redirect URI is not part of it: Milofly
7
+ * returns to the first redirect URI registered for your app, with `?code=…&state=…`
8
+ * (or `?error=access_denied&state=…` when the merchant cancels).
9
+ */
10
+ export function buildInstallUrl(options) {
11
+ if (!options.state)
12
+ throw new TypeError("state is required.");
13
+ const url = new URL(INSTALL_PATH + encodeURIComponent(options.appKey), options.environment.panelOrigin);
14
+ url.searchParams.set("response_type", "code");
15
+ url.searchParams.set("client_id", options.clientId);
16
+ if (options.scopes && options.scopes.length > 0)
17
+ url.searchParams.set("scope", options.scopes.join(" "));
18
+ url.searchParams.set("state", options.state);
19
+ return url.toString();
20
+ }
21
+ /** Exchanges the one-time install code for an access token (server side only: needs the client secret). */
22
+ export async function exchangeCode(options) {
23
+ const doFetch = options.fetch ?? globalThis.fetch;
24
+ const res = await doFetch(new URL("/api/apps/oauth/token", options.environment.apiBaseUrl), {
25
+ method: "POST",
26
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
27
+ body: JSON.stringify({ clientId: options.clientId, clientSecret: options.clientSecret, code: options.code }),
28
+ });
29
+ const body = (await res.json().catch(() => null));
30
+ if (!res.ok || !body || body.success !== true)
31
+ throw readApiError(res, body);
32
+ const scope = body.install_scope;
33
+ if (typeof body.access_token !== "string" || typeof body.app_key !== "string" || typeof body.store_id !== "number" || (scope !== "region" && scope !== "store"))
34
+ throw new MiloflyApiError({ status: res.status, code: "unexpected_response", params: null, message: "Token response is missing required fields.", body, retryAfterSeconds: null });
35
+ return {
36
+ accessToken: body.access_token,
37
+ tokenType: "Bearer",
38
+ scopes: Array.isArray(body.scopes) ? body.scopes.filter((s) => typeof s === "string") : [],
39
+ appKey: body.app_key,
40
+ storeId: body.store_id,
41
+ regionId: typeof body.region_id === "number" ? body.region_id : null,
42
+ installScope: scope,
43
+ regions: Array.isArray(body.regions) ? body.regions : null,
44
+ storeName: typeof body.store_name === "string" ? body.store_name : null,
45
+ storeDomain: typeof body.store_domain === "string" ? body.store_domain : null,
46
+ };
47
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@milofly/app-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Milofly app server helpers: webhook and session token verification, OAuth install, API client.",
5
+ "license": "MIT",
6
+ "homepage": "https://developer.milofly.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Milofly/milofly-sdk.git",
10
+ "directory": "js/app-server"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Milofly/milofly-sdk/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "import": "./index.js"
24
+ }
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ }
29
+ }
@@ -0,0 +1,48 @@
1
+ /** Domain prefix of the signed string; a webhook signature can never be valid here (and vice versa). */
2
+ export declare const SESSION_TOKEN_DOMAIN = "milofly-embed-v1";
3
+ /** Tolerance for tokens issued slightly in the future (clock skew between Milofly and your server). */
4
+ export declare const SESSION_TOKEN_CLOCK_SKEW_SECONDS = 60;
5
+ /**
6
+ * Claims of a verified session token. Issued by Milofly for the merchant who opened your app; the
7
+ * panel refreshes it every couple of minutes over App Bridge.
8
+ */
9
+ export interface SessionTokenClaims {
10
+ appKey: string;
11
+ storeId: number;
12
+ /** Region the panel is on. */
13
+ regionId: number | null;
14
+ storeCode: string | null;
15
+ /** Installation scope: one region, or the whole store. */
16
+ scope: "region" | "store";
17
+ issuedAt: number;
18
+ expiresAt: number;
19
+ /** Panel user (identity id) who is viewing the app. Newer tokens only. */
20
+ userId: number | null;
21
+ /** Unique token id. Newer tokens only. */
22
+ tokenId: string | null;
23
+ /** Origin of the panel the token was issued to. Newer tokens only. */
24
+ hostOrigin: string | null;
25
+ /** Panel surface the token was issued for (`fullpage`, `order-detail`, …). Newer tokens only. */
26
+ surface: string | null;
27
+ /** Id of the secret that signed the token. Newer tokens only. */
28
+ keyId: string | null;
29
+ }
30
+ export interface VerifySessionTokenOptions {
31
+ /** Your app's signing secret(s) — the same secret that signs your webhooks. */
32
+ secret: string | readonly string[];
33
+ /** Your app key. A token issued for another app is refused. */
34
+ appKey: string;
35
+ /**
36
+ * The host origin your frame talked to (`app.hostOrigin` on the client). When given, the token
37
+ * must carry the same `HostOrigin`: a token issued to the real panel is refused if your frame was
38
+ * opened by another page.
39
+ */
40
+ hostOrigin?: string;
41
+ /** Unix seconds; defaults to the current time. */
42
+ now?: number;
43
+ }
44
+ /**
45
+ * Verifies a session token (`base64url(claims).hex(HMAC-SHA256(secret, "milofly-embed-v1\n" + body))`).
46
+ * The signature is checked before the body is parsed. Throws {@link SessionTokenError}.
47
+ */
48
+ export declare function verifySessionToken(token: string, options: VerifySessionTokenOptions): Promise<SessionTokenClaims>;
@@ -0,0 +1,95 @@
1
+ import { normalizeSecrets, signingKeyId, utf8, verifyHmacSha256Hex } from "./crypto.js";
2
+ import { SessionTokenError } from "./errors.js";
3
+ /** Domain prefix of the signed string; a webhook signature can never be valid here (and vice versa). */
4
+ export const SESSION_TOKEN_DOMAIN = "milofly-embed-v1";
5
+ /** Tolerance for tokens issued slightly in the future (clock skew between Milofly and your server). */
6
+ export const SESSION_TOKEN_CLOCK_SKEW_SECONDS = 60;
7
+ function b64urlDecode(value) {
8
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
9
+ return null;
10
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
11
+ try {
12
+ const bin = atob(b64.padEnd(b64.length + ((4 - (b64.length % 4)) % 4), "="));
13
+ return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ const str = (v) => (typeof v === "string" && v.length > 0 ? v : null);
20
+ const int = (v) => (typeof v === "number" && Number.isSafeInteger(v) ? v : null);
21
+ /**
22
+ * Verifies a session token (`base64url(claims).hex(HMAC-SHA256(secret, "milofly-embed-v1\n" + body))`).
23
+ * The signature is checked before the body is parsed. Throws {@link SessionTokenError}.
24
+ */
25
+ export async function verifySessionToken(token, options) {
26
+ const secrets = normalizeSecrets(options.secret);
27
+ if (typeof token !== "string")
28
+ throw new SessionTokenError("malformed");
29
+ const dot = token.indexOf(".");
30
+ if (dot <= 0 || dot !== token.lastIndexOf(".") || dot === token.length - 1)
31
+ throw new SessionTokenError("malformed");
32
+ const body = token.slice(0, dot);
33
+ const signature = token.slice(dot + 1);
34
+ // Signature FIRST, body after: unverified input is never parsed. Every configured secret is tried
35
+ // (one, or two during a rotation); the claimed key id is then checked against the secret that matched.
36
+ const signed = utf8(`${SESSION_TOKEN_DOMAIN}\n${body}`);
37
+ let signer = null;
38
+ for (const s of secrets) {
39
+ if (await verifyHmacSha256Hex(s, signed, signature.toLowerCase())) {
40
+ signer = s;
41
+ break;
42
+ }
43
+ }
44
+ if (signer === null)
45
+ throw new SessionTokenError("signature_mismatch");
46
+ const decoded = b64urlDecode(body);
47
+ if (decoded === null)
48
+ throw new SessionTokenError("malformed");
49
+ let claims;
50
+ try {
51
+ const parsed = JSON.parse(decoded);
52
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
53
+ throw new Error();
54
+ claims = parsed;
55
+ }
56
+ catch {
57
+ throw new SessionTokenError("malformed");
58
+ }
59
+ const keyId = str(claims.Kid);
60
+ if (keyId !== null && keyId !== (await signingKeyId(signer)))
61
+ throw new SessionTokenError("unknown_key");
62
+ if (claims.V !== 1)
63
+ throw new SessionTokenError("unsupported_version");
64
+ const appKey = str(claims.AppKey);
65
+ const storeId = int(claims.StoreId);
66
+ const iat = int(claims.Iat);
67
+ const exp = int(claims.Exp);
68
+ const scope = claims.Scope;
69
+ if (appKey === null || storeId === null || storeId <= 0 || iat === null || exp === null || (scope !== "region" && scope !== "store"))
70
+ throw new SessionTokenError("malformed");
71
+ if (appKey !== options.appKey)
72
+ throw new SessionTokenError("app_mismatch");
73
+ const now = options.now ?? Math.floor(Date.now() / 1000);
74
+ if (now > exp)
75
+ throw new SessionTokenError("expired");
76
+ if (iat > now + SESSION_TOKEN_CLOCK_SKEW_SECONDS)
77
+ throw new SessionTokenError("not_yet_valid");
78
+ const hostOrigin = str(claims.HostOrigin);
79
+ if (options.hostOrigin !== undefined && hostOrigin !== options.hostOrigin)
80
+ throw new SessionTokenError("host_origin_mismatch");
81
+ return {
82
+ appKey,
83
+ storeId,
84
+ regionId: int(claims.RegionId),
85
+ storeCode: str(claims.StoreCode),
86
+ scope,
87
+ issuedAt: iat,
88
+ expiresAt: exp,
89
+ userId: int(claims.Sub),
90
+ tokenId: str(claims.Jti),
91
+ hostOrigin,
92
+ surface: str(claims.Surface),
93
+ keyId,
94
+ };
95
+ }
package/webhook.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /** Headers Milofly sends with every webhook delivery. */
2
+ export declare const WebhookHeader: {
3
+ readonly Signature: "x-milofly-hmac-sha256";
4
+ readonly Topic: "x-milofly-topic";
5
+ readonly Store: "x-milofly-store";
6
+ readonly Timestamp: "x-milofly-timestamp";
7
+ /** Identifier of the secret that signed the delivery (see `signingKeyId`). Absent on older deliveries. */
8
+ readonly KeyId: "x-milofly-key-id";
9
+ };
10
+ /**
11
+ * Replay window. Milofly signs each delivery attempt with a fresh timestamp, so a retried delivery is
12
+ * never outside this window; anything older (or this far in the future) is refused.
13
+ */
14
+ export declare const WEBHOOK_TOLERANCE_SECONDS = 300;
15
+ /** Webhook envelope shared by every topic. `data` is topic specific. */
16
+ export interface WebhookEnvelope<TData = unknown> {
17
+ version: string;
18
+ topic: string;
19
+ storeId: number;
20
+ regionId: number | null;
21
+ /** Stable per event: store it and ignore a second delivery with the same id. */
22
+ eventId: string;
23
+ occurredAt: string;
24
+ data: TData;
25
+ }
26
+ export interface VerifiedWebhook<TData = unknown> {
27
+ topic: string;
28
+ storeId: number;
29
+ timestamp: number;
30
+ keyId: string | null;
31
+ envelope: WebhookEnvelope<TData>;
32
+ }
33
+ /** Plain header map (Node `IncomingHttpHeaders`, Express `req.headers`) or a Fetch `Headers`. */
34
+ export type HeaderSource = Headers | Record<string, string | string[] | undefined>;
35
+ export interface VerifyWebhookOptions {
36
+ /** Webhook signing secret(s) of your app. Pass the previous one too while a rotation is in progress. */
37
+ secret: string | readonly string[];
38
+ headers: HeaderSource;
39
+ /**
40
+ * The request body EXACTLY as received (string or bytes). Do not parse and re-serialize it:
41
+ * whitespace or key order changes break the signature.
42
+ */
43
+ rawBody: string | Uint8Array;
44
+ /** Unix seconds; defaults to the current time. */
45
+ now?: number;
46
+ toleranceSeconds?: number;
47
+ }
48
+ /**
49
+ * Verifies a Milofly webhook delivery and returns its envelope.
50
+ *
51
+ * Signature: `HMAC-SHA256(secret, "{topic}\n{storeId}\n{timestamp}\n{body}")`, lower-case hex, in
52
+ * `X-Milofly-Hmac-Sha256`. Topic, store and timestamp are inside the signature, so none of the
53
+ * headers can be swapped. Throws {@link WebhookVerificationError}; never returns an unverified body.
54
+ */
55
+ export declare function verifyWebhook<TData = unknown>(options: VerifyWebhookOptions): Promise<VerifiedWebhook<TData>>;
package/webhook.js ADDED
@@ -0,0 +1,78 @@
1
+ import { concatBytes, normalizeSecrets, secretsFor, utf8, verifyHmacSha256Hex } from "./crypto.js";
2
+ import { WebhookVerificationError } from "./errors.js";
3
+ /** Headers Milofly sends with every webhook delivery. */
4
+ export const WebhookHeader = {
5
+ Signature: "x-milofly-hmac-sha256",
6
+ Topic: "x-milofly-topic",
7
+ Store: "x-milofly-store",
8
+ Timestamp: "x-milofly-timestamp",
9
+ /** Identifier of the secret that signed the delivery (see `signingKeyId`). Absent on older deliveries. */
10
+ KeyId: "x-milofly-key-id",
11
+ };
12
+ /**
13
+ * Replay window. Milofly signs each delivery attempt with a fresh timestamp, so a retried delivery is
14
+ * never outside this window; anything older (or this far in the future) is refused.
15
+ */
16
+ export const WEBHOOK_TOLERANCE_SECONDS = 300;
17
+ function header(source, name) {
18
+ if (typeof source.get === "function")
19
+ return source.get(name);
20
+ const record = source;
21
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name);
22
+ const value = key === undefined ? undefined : record[key];
23
+ if (Array.isArray(value))
24
+ return value.length === 1 ? value[0] : null;
25
+ return value ?? null;
26
+ }
27
+ const INTEGER = /^-?[0-9]{1,19}$/;
28
+ /**
29
+ * Verifies a Milofly webhook delivery and returns its envelope.
30
+ *
31
+ * Signature: `HMAC-SHA256(secret, "{topic}\n{storeId}\n{timestamp}\n{body}")`, lower-case hex, in
32
+ * `X-Milofly-Hmac-Sha256`. Topic, store and timestamp are inside the signature, so none of the
33
+ * headers can be swapped. Throws {@link WebhookVerificationError}; never returns an unverified body.
34
+ */
35
+ export async function verifyWebhook(options) {
36
+ const secrets = normalizeSecrets(options.secret);
37
+ const signature = header(options.headers, WebhookHeader.Signature);
38
+ const topic = header(options.headers, WebhookHeader.Topic);
39
+ const storeHeader = header(options.headers, WebhookHeader.Store);
40
+ const tsHeader = header(options.headers, WebhookHeader.Timestamp);
41
+ const keyId = header(options.headers, WebhookHeader.KeyId);
42
+ if (!signature || !topic || !storeHeader || !tsHeader)
43
+ throw new WebhookVerificationError("missing_header");
44
+ if (!INTEGER.test(storeHeader) || !INTEGER.test(tsHeader))
45
+ throw new WebhookVerificationError("malformed_header");
46
+ const timestamp = Number(tsHeader);
47
+ const now = options.now ?? Math.floor(Date.now() / 1000);
48
+ const tolerance = options.toleranceSeconds ?? WEBHOOK_TOLERANCE_SECONDS;
49
+ if (Math.abs(now - timestamp) > tolerance)
50
+ throw new WebhookVerificationError("timestamp_out_of_range");
51
+ const candidates = await secretsFor(secrets, keyId);
52
+ if (candidates === null)
53
+ throw new WebhookVerificationError("unknown_key", `No configured secret has key id ${keyId}.`);
54
+ const body = typeof options.rawBody === "string" ? utf8(options.rawBody) : options.rawBody;
55
+ const signed = concatBytes(utf8(`${topic}\n${storeHeader}\n${tsHeader}\n`), body);
56
+ let valid = false;
57
+ for (const s of candidates) {
58
+ if (await verifyHmacSha256Hex(s, signed, signature.trim())) {
59
+ valid = true;
60
+ break;
61
+ }
62
+ }
63
+ if (!valid)
64
+ throw new WebhookVerificationError("signature_mismatch");
65
+ let envelope;
66
+ try {
67
+ envelope = JSON.parse(typeof options.rawBody === "string" ? options.rawBody : new TextDecoder().decode(options.rawBody));
68
+ }
69
+ catch {
70
+ throw new WebhookVerificationError("body_invalid");
71
+ }
72
+ if (!envelope || typeof envelope !== "object" || typeof envelope.eventId !== "string")
73
+ throw new WebhookVerificationError("body_invalid");
74
+ // The body is signed too, but it must also agree with the signed headers.
75
+ if (envelope.topic !== topic || String(envelope.storeId) !== storeHeader)
76
+ throw new WebhookVerificationError("envelope_mismatch");
77
+ return { topic, storeId: Number(storeHeader), timestamp, keyId, envelope };
78
+ }