-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
179 lines (152 loc) · 8.14 KB
/
server.js
File metadata and controls
179 lines (152 loc) · 8.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
require("dotenv").config();
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const { spawn, execSync } = require("child_process");
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const SHOP = process.env.SHOP;
const SCOPES = process.env.SCOPES || "read_products";
const PORT = process.env.PORT || 3000;
const TOML_PATH = path.join(__dirname, "shopify.app.toml");
if (!CLIENT_ID || !CLIENT_SECRET || !SHOP) {
console.error("Missing required env vars. Copy .env.example to .env and fill in values.");
process.exit(1);
}
// ── HTML ────────────────────────────────────────────────────────────────────
const CSS = `
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400;9..40,500;9..40,600&display=swap');
*{margin:0;padding:0;box-sizing:border-box}
body{min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:'DM Sans',sans-serif;
background:radial-gradient(ellipse at 30% 20%,#fde8d8 0%,transparent 50%),radial-gradient(ellipse at 70% 80%,#f5e6d8 0%,transparent 50%),#f8f0e8;color:#3a3a3a}
.card{max-width:520px;width:100%;padding:48px 40px;border-radius:24px;
background:rgba(255,255,255,0.45);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);
box-shadow:0 1px 3px rgba(0,0,0,0.04),0 8px 32px rgba(0,0,0,0.06);border:1px solid rgba(255,255,255,0.6)}
h1{font-size:22px;font-weight:600;letter-spacing:-0.02em;margin-bottom:8px}
.sub{font-size:14px;color:#8a8078;margin-bottom:32px}
.btn{display:inline-block;padding:14px 36px;border-radius:9999px;border:none;cursor:pointer;
font-family:inherit;font-size:15px;font-weight:600;letter-spacing:-0.01em;text-decoration:none;
color:#2d5a3d;background:rgba(142,190,152,0.4);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);
box-shadow:0 1px 3px rgba(45,90,61,0.08),0 4px 12px rgba(45,90,61,0.06),inset 0 1.5px 1px rgba(255,255,255,0.55);
transition:all 0.25s ease}
.btn:hover{background:rgba(142,190,152,0.52);transform:translateY(-1px);
box-shadow:0 2px 6px rgba(45,90,61,0.1),0 8px 20px rgba(45,90,61,0.08),inset 0 1.5px 1px rgba(255,255,255,0.6)}
.btn:active{transform:translateY(0.5px) scale(0.98)}
.field{margin-bottom:20px}
.label{font-size:12px;font-weight:500;color:#8a8078;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px}
.value{font-size:14px;padding:12px 16px;border-radius:12px;background:rgba(255,255,255,0.5);
border:1px solid rgba(0,0,0,0.06);word-break:break-all;font-family:'DM Sans',monospace}
.token-value{font-size:13px;padding:14px 16px;border-radius:12px;background:rgba(142,190,152,0.12);
border:1px solid rgba(142,190,152,0.2);word-break:break-all;font-family:monospace;user-select:all}
.muted{color:#b0a090;font-size:14px}
pre{font-size:12px;padding:16px;border-radius:12px;background:rgba(0,0,0,0.03);
border:1px solid rgba(0,0,0,0.06);overflow-x:auto;white-space:pre-wrap;word-break:break-all}
`;
function html(body) {
return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Shopify OAuth</title><style>${CSS}</style></head><body><div class="card">${body}</div></body></html>`;
}
function authorizeUrl(redirectUri) {
return `https://${SHOP}/admin/oauth/authorize?client_id=${CLIENT_ID}&scope=${SCOPES}&redirect_uri=${encodeURIComponent(redirectUri)}&state=nonce123`;
}
// ── Shopify CLI deploy ──────────────────────────────────────────────────────
function updateTomlAndDeploy(tunnelUrl) {
let toml = fs.readFileSync(TOML_PATH, "utf-8");
toml = toml.replace(/^application_url\s*=\s*".*"$/m, `application_url = "${tunnelUrl}"`);
toml = toml.replace(/^redirect_urls\s*=\s*\[.*\]$/m, `redirect_urls = [ "${tunnelUrl}/callback" ]`);
fs.writeFileSync(TOML_PATH, toml);
console.log("Updated shopify.app.toml");
try {
execSync("shopify app deploy --force", { cwd: __dirname, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
console.log("Deployed app config to Shopify");
} catch (err) {
console.error("Deploy failed:", err.stderr || err.message);
}
}
// ── Token exchange ──────────────────────────────────────────────────────────
function exchangeToken(code, res) {
const payload = JSON.stringify({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code });
const req = https.request({
hostname: SHOP,
path: "/admin/oauth/access_token",
method: "POST",
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) },
}, (tokenRes) => {
let body = "";
tokenRes.on("data", (chunk) => (body += chunk));
tokenRes.on("end", () => {
console.log(`Token response (${tokenRes.statusCode}): ${body}`);
try {
const data = JSON.parse(body);
const ok = tokenRes.statusCode === 200;
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html(`
<h1>${ok ? "Token Obtained" : `Error (${tokenRes.statusCode})`}</h1>
<p class="sub">${ok ? "Offline access token for " + SHOP : "Something went wrong"}</p>
${ok ? `
<div class="field"><div class="label">Access Token</div><div class="token-value">${data.access_token}</div></div>
<div class="field"><div class="label">Scope</div><div class="value">${data.scope}</div></div>
` : ""}
<div class="field"><div class="label">Full Response</div><pre>${JSON.stringify(data, null, 2)}</pre></div>
`));
} catch {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html(`<h1>Error (${tokenRes.statusCode})</h1><p class="sub">Could not parse response</p><pre>${body}</pre>`));
}
});
});
req.on("error", (err) => {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Token exchange failed: " + err.message);
});
req.write(payload);
req.end();
}
// ── Server ──────────────────────────────────────────────────────────────────
let tunnelUrl = null;
const server = http.createServer((req, res) => {
const parsed = new URL(req.url, `http://${req.headers.host}`);
if (parsed.pathname === "/callback") {
const code = parsed.searchParams.get("code");
if (!code) {
res.writeHead(302, { Location: authorizeUrl(`${tunnelUrl}/callback`) });
res.end();
return;
}
console.log(`Callback received (code: ${code.slice(0, 8)}...)`);
exchangeToken(code, res);
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html(`
<h1>Shopify OAuth</h1>
<p class="sub">${SHOP}</p>
${tunnelUrl
? `<a class="btn" href="${authorizeUrl(`${tunnelUrl}/callback`)}">Authorize App</a>`
: `<p class="muted">Starting tunnel...</p>`}
`));
}
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
startTunnel();
});
// ── Cloudflare tunnel ───────────────────────────────────────────────────────
function startTunnel() {
const cf = spawn("cloudflared", ["tunnel", "--url", `http://localhost:${PORT}`], {
stdio: ["ignore", "pipe", "pipe"],
});
cf.stderr.on("data", (chunk) => {
const match = chunk.toString().match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
if (match && !tunnelUrl) {
tunnelUrl = match[0];
console.log(`Tunnel: ${tunnelUrl}`);
updateTomlAndDeploy(tunnelUrl);
console.log(`\nOpen ${tunnelUrl} to start the OAuth flow\n`);
}
});
cf.on("close", (code) => {
if (code) console.error(`cloudflared exited (${code})`);
process.exit(code || 0);
});
process.on("SIGINT", () => { cf.kill(); process.exit(0); });
}