File size: 15,282 Bytes
0e7f115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5e5ce
0e7f115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5e5ce
0e7f115
 
9b5e5ce
0e7f115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5e5ce
0e7f115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5e5ce
 
 
 
 
0e7f115
9b5e5ce
 
 
 
0e7f115
 
 
 
 
 
 
 
3ae26a8
0e7f115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// 充輝亭 web server: serves the static site + the in-site shop API (Stripe, no SDK).
// Env: STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY (payments), STAFF_PIN (staff ticket/member check), PORT.
// Stripe is the order database: tickets live in PaymentIntent metadata, members are Stripe subscriptions,
// so an HF rebuild loses nothing.
'use strict';
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');

const ROOT = __dirname;
const PORT = Number(process.env.PORT || 7860);
const SK = process.env.STRIPE_SECRET_KEY || '';
const PK = process.env.STRIPE_PUBLISHABLE_KEY || '';
const STAFF_PIN = process.env.STAFF_PIN || '';
const STRIPE_API = process.env.STRIPE_API_BASE || 'https://api.stripe.com';
const CATALOG = JSON.parse(fs.readFileSync(path.join(ROOT, 'shop/catalog.json'), 'utf8'));
const PRODUCTS = new Map(CATALOG.products.map(p => [p.id, p]));
const PLANS = new Map(CATALOG.plans.map(p => [p.id, p]));
const TICKET_DAYS = 183; // 有効期限 ご購入日から6ヶ月
const MAX_QTY = 20, MAX_LINES = 30;

// ---------- Stripe over fetch (JPY is zero-decimal: amounts are yen as-is) ----------
function form(obj, prefix, out = []) {
  for (const [k, v] of Object.entries(obj)) {
    if (v === undefined || v === null) continue;
    const key = prefix ? `${prefix}[${k}]` : k;
    if (typeof v === 'object') form(v, key, out);
    else out.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(v)));
  }
  return out.join('&');
}
async function stripe(method, url, body) {
  const r = await fetch(STRIPE_API + url, {
    method,
    headers: { Authorization: `Bearer ${SK}`, 'Content-Type': 'application/x-www-form-urlencoded', 'Stripe-Version': '2024-06-20' },
    body: body ? form(body) : undefined,
  });
  const j = await r.json().catch(() => ({}));
  if (!r.ok) { const e = new Error(j.error?.message || `stripe ${r.status}`); e.status = r.status; throw e; }
  return j;
}

// ---------- helpers ----------
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
  '.webp': 'image/webp', '.gif': 'image/gif', '.ico': 'image/x-icon', '.xml': 'application/xml; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
  '.woff2': 'font/woff2', '.mp4': 'video/mp4' };
function send(res, code, obj) {
  res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
  res.end(JSON.stringify(obj));
}
function readBody(req) {
  return new Promise((ok, bad) => {
    let n = 0; const c = [];
    req.on('data', d => { n += d.length; if (n > 64 * 1024) { bad(new Error('too large')); req.destroy(); } else c.push(d); });
    req.on('end', () => { try { ok(c.length ? JSON.parse(Buffer.concat(c).toString('utf8')) : {}); } catch { bad(new Error('bad json')); } });
  });
}
function origin(req) {
  const proto = (req.headers['x-forwarded-proto'] || 'http').split(',')[0];
  return `${proto}://${req.headers['x-forwarded-host'] || req.headers.host}`;
}
function ticketCode() { // 8 chars, no look-alikes (0/O, 1/I)
  const A = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const b = crypto.randomBytes(8);
  return Array.from(b, x => A[x % A.length]).join('').replace(/^(.{4})/, '$1-');
}
const pinOk = pin => STAFF_PIN && typeof pin === 'string' && pin.length === STAFF_PIN.length &&
  crypto.timingSafeEqual(Buffer.from(pin), Buffer.from(STAFF_PIN));
const fails = new Map(); // ip -> [count, firstTs]  brute-force guard for the staff PIN
function staffGuard(req) {
  const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
  const f = fails.get(ip); if (f && Date.now() - f[1] < 15 * 60e3 && f[0] >= 8) return { ip, locked: true };
  return { ip, locked: false };
}
function staffFail(ip) { const f = fails.get(ip); if (!f || Date.now() - f[1] > 15 * 60e3) fails.set(ip, [1, Date.now()]); else f[0]++; }

// ticket items are stored compactly in PaymentIntent metadata: "id:qty:used,id:qty:used"
const packItems = items => items.map(i => `${i.id}:${i.qty}:${i.used || 0}`).join(',');
const unpackItems = s => (s || '').split(',').filter(Boolean).map(x => { const [id, q, u] = x.split(':'); const p = PRODUCTS.get(id);
  return { id, name: p ? p.name : id, price: p ? p.price : 0, qty: +q, used: +u || 0 }; });
function ticketView(pi) {
  const created = pi.created * 1000, expires = created + TICKET_DAYS * 864e5;
  return { code: pi.metadata.ticket, paid: pi.status === 'succeeded', amount: pi.amount, created, expires,
    expired: Date.now() > expires, items: unpackItems(pi.metadata.items), buyer: pi.metadata.buyer || '' };
}

// ---------- API ----------
async function api(req, res, url) {
  const p = url.pathname;
  if (p === '/api/shop/config') return send(res, 200, { enabled: !!(SK && PK), publishableKey: PK || null });
  if (!SK || !PK) return send(res, 503, { error: 'オンライン決済は現在準備中です。お電話(050-1793-6755)でご注文ください。' });

  // cart -> embedded Checkout (one-time, 飲食券)
  if (p === '/api/checkout' && req.method === 'POST') {
    const b = await readBody(req);
    const lines = Array.isArray(b.items) ? b.items.slice(0, MAX_LINES) : [];
    const items = [];
    for (const l of lines) {
      const pr = PRODUCTS.get(String(l.id)); const qty = Math.floor(Number(l.qty));
      if (!pr || !(qty >= 1 && qty <= MAX_QTY)) return send(res, 400, { error: '商品または数量が正しくありません。' });
      const ex = items.find(i => i.id === pr.id); if (ex) ex.qty = Math.min(MAX_QTY, ex.qty + qty); else items.push({ id: pr.id, qty });
    }
    if (!items.length) return send(res, 400, { error: 'カートが空です。' });
    const packed = packItems(items);
    if (packed.length > 480) return send(res, 400, { error: '一度にご購入いただける品目数を超えています。分けてご購入ください。' });
    const code = ticketCode();
    const s = await stripe('POST', '/v1/checkout/sessions', {
      mode: 'payment', ui_mode: 'embedded', locale: 'ja', currency: 'jpy',
      return_url: `${origin(req)}/shop/complete?session_id={CHECKOUT_SESSION_ID}`,
      line_items: items.map(i => { const pr = PRODUCTS.get(i.id); return { quantity: i.qty, price_data: { currency: 'jpy', unit_amount: pr.price,
        product_data: { name: `飲食券|${pr.name}`, description: '居酒屋 充輝 飲食券(ご購入日から6ヶ月有効・1枚につき1品)', metadata: { item: pr.id } } } }; }),
      customer_creation: 'always',
      payment_intent_data: { description: `充輝亭 飲食券 ${code}`, metadata: { kind: 'ticket', ticket: code, items: packed } },
      metadata: { kind: 'ticket', ticket: code },
    });
    return send(res, 200, { clientSecret: s.client_secret });
  }

  // subscription plan -> embedded Checkout (subscription)
  if (p === '/api/subscribe' && req.method === 'POST') {
    const b = await readBody(req); const pl = PLANS.get(String(b.plan));
    if (!pl) return send(res, 400, { error: 'プランが正しくありません。' });
    const s = await stripe('POST', '/v1/checkout/sessions', {
      mode: 'subscription', ui_mode: 'embedded', locale: 'ja', currency: 'jpy',
      return_url: `${origin(req)}/shop/complete?session_id={CHECKOUT_SESSION_ID}`,
      line_items: [{ quantity: 1, price_data: { currency: 'jpy', unit_amount: pl.price, recurring: { interval: 'month' },
        product_data: { name: `充輝の月額サブスク|${pl.name}`, metadata: { plan: pl.id } } } }],
      custom_text: { submit: { message: `お申し込みにより会員規約(${origin(req)}/#sub-terms)に同意したものとみなします。ご入会は20歳以上の方に限ります。解約は次回決済日の3日前までに。` } },
      subscription_data: { description: `充輝の月額サブスク ${pl.name}`, metadata: { kind: 'member', plan: pl.id } },
      metadata: { kind: 'member', plan: pl.id },
    });
    return send(res, 200, { clientSecret: s.client_secret });
  }

  // completion page: what was bought (ticket code / membership)
  if (p === '/api/order' && req.method === 'GET') {
    const id = url.searchParams.get('session_id') || '';
    if (!/^cs_(test|live)_[A-Za-z0-9]+$/.test(id)) return send(res, 400, { error: 'bad session' });
    const s = await stripe('GET', `/v1/checkout/sessions/${id}?expand[]=payment_intent&expand[]=subscription`);
    const base = { status: s.status, paid: s.payment_status === 'paid', email: s.customer_details?.email || '', name: s.customer_details?.name || '' };
    if (s.mode === 'payment' && s.payment_intent) return send(res, 200, { ...base, kind: 'ticket', ticket: ticketView(s.payment_intent) });
    if (s.mode === 'subscription' && s.subscription) {
      const pl = PLANS.get(s.subscription.metadata?.plan);
      return send(res, 200, { ...base, kind: 'member', plan: pl ? pl.name : '', member: s.subscription.id.slice(-8).toUpperCase(),
        subStatus: s.subscription.status, canManage: true });
    }
    return send(res, 200, base);
  }

  // member self-service (Stripe customer portal), reachable from the completion page
  if (p === '/api/portal' && req.method === 'POST') {
    const b = await readBody(req); const id = String(b.session_id || '');
    if (!/^cs_(test|live)_[A-Za-z0-9]+$/.test(id)) return send(res, 400, { error: 'bad session' });
    const s = await stripe('GET', `/v1/checkout/sessions/${id}`);
    if (s.mode !== 'subscription' || !s.customer) return send(res, 400, { error: 'not a membership' });
    const ps = await stripe('POST', '/v1/billing_portal/sessions', { customer: s.customer, return_url: `${origin(req)}/shop/complete?session_id=${id}`, locale: 'ja' });
    return send(res, 200, { url: ps.url });
  }

  // ---- staff: ticket lookup / redeem, member check (STAFF_PIN) ----
  if (p.startsWith('/api/staff/') && req.method === 'POST') {
    const g = staffGuard(req);
    if (g.locked) return send(res, 429, { error: '試行回数が多すぎます。15分後にお試しください。' });
    const b = await readBody(req);
    if (!pinOk(b.pin)) { staffFail(g.ip); return send(res, 401, { error: 'PINが違います。' }); }
    if (p === '/api/staff/login') return send(res, 200, { ok: true });
    if (p === '/api/staff/ticket' || p === '/api/staff/redeem') {
      const code = String(b.code || '').toUpperCase().replace(/[^A-Z0-9]/g, '').replace(/^(.{4})/, '$1-');
      if (!/^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(code)) return send(res, 400, { error: 'コードは8文字です(例 ABCD-2345)。' });
      const r = await stripe('GET', `/v1/payment_intents/search?query=${encodeURIComponent(`metadata['ticket']:'${code}'`)}`);
      const pi = (r.data || []).find(x => x.status === 'succeeded');
      if (!pi) return send(res, 404, { error: 'この飲食券は見つかりません(購入直後は1分ほどかかる場合があります)。' });
      if (p === '/api/staff/redeem') {
        const t = ticketView(pi);
        if (t.expired) return send(res, 400, { error: '有効期限切れの飲食券です。' });
        const items = unpackItems(pi.metadata.items); const it = items.find(i => i.id === String(b.item));
        if (!it) return send(res, 400, { error: '品目が見つかりません。' });
        const n = Math.floor(Number(b.n || 1));
        if (!(n >= 1) || it.used + n > it.qty) return send(res, 400, { error: '残り枚数を超えています。' });
        it.used += n;
        const up = await stripe('POST', `/v1/payment_intents/${pi.id}`, { metadata: { items: packItems(items), last_redeemed: new Date().toISOString() } });
        return send(res, 200, { ticket: ticketView(up) });
      }
      return send(res, 200, { ticket: ticketView(pi) });
    }
    if (p === '/api/staff/member') {
      const email = String(b.email || '').trim().toLowerCase();
      if (!/^\S+@\S+\.\S+$/.test(email)) return send(res, 400, { error: 'メールアドレスを入力してください。' });
      const cs = await stripe('GET', `/v1/customers?email=${encodeURIComponent(email)}&limit=10`);
      const subs = [];
      for (const c of cs.data || []) {
        const ss = await stripe('GET', `/v1/subscriptions?customer=${c.id}&status=all&limit=10`);
        for (const s of ss.data || []) if (s.metadata?.kind === 'member') {
          const pl = PLANS.get(s.metadata.plan);
          subs.push({ plan: pl ? pl.name : s.metadata.plan, status: s.status, member: s.id.slice(-8).toUpperCase(), name: c.name || '',
            periodEnd: (s.current_period_end || s.items?.data?.[0]?.current_period_end || 0) * 1000, cancelAtEnd: !!s.cancel_at_period_end });
        }
      }
      return send(res, 200, { members: subs });
    }
  }
  return send(res, 404, { error: 'not found' });
}

// ---------- static ----------
function serveStatic(req, res, url) {
  let rel = decodeURIComponent(url.pathname);
  // clean URLs: /menu.html -> /menu, /index.html -> /, /blog/index.html -> /blog/
  if (/\.html$/i.test(rel)) {
    const clean = rel.replace(/(^|\/)index\.html$/i, '$1').replace(/\.html$/i, '');
    res.writeHead(301, { Location: (clean || '/') + url.search }); return res.end();
  }
  if (rel.endsWith('/')) rel += 'index.html';
  else if (!path.extname(rel)) {
    const f = path.normalize(path.join(ROOT, rel + '.html'));
    if (f.startsWith(ROOT + path.sep) && fs.existsSync(f)) rel += '.html';
  }
  const file = path.normalize(path.join(ROOT, rel));
  if (!file.startsWith(ROOT + path.sep) || /(^|[\\/])(\.|server\.js|Dockerfile|node_modules)/.test(path.relative(ROOT, file))) { res.writeHead(404); return res.end('Not found'); }
  fs.stat(file, (err, st) => {
    if (err || !st.isFile()) {
      if (!path.extname(rel)) { res.writeHead(302, { Location: rel + '/' }); return res.end(); }
      res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<h1>404</h1><p><a href="/">充輝亭 トップへ</a></p>');
    }
    const ext = path.extname(file).toLowerCase();
    const long = /^\/(img|sq|menu|brand|og)\//.test(rel);
    res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream', 'Content-Length': st.size,
      'Cache-Control': long ? 'public, max-age=86400' : 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' });
    if (req.method === 'HEAD') return res.end();
    fs.createReadStream(file).pipe(res);
  });
}

http.createServer(async (req, res) => {
  const url = new URL(req.url, 'http://x');
  try {
    if (url.pathname.startsWith('/api/')) return await api(req, res, url);
    if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
    serveStatic(req, res, url);
  } catch (e) {
    console.error(url.pathname, e.message);
    if (!res.headersSent) send(res, e.status && e.status < 500 ? 400 : 502, { error: '決済サーバーとの通信に失敗しました。時間をおいてお試しください。' });
  }
}).listen(PORT, () => console.log(`mitsuki on :${PORT} payments=${!!(SK && PK)} staff=${!!STAFF_PIN}`));