wiki-plugin-shoppe 0.0.15 → 0.0.17

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wiki-plugin-shoppe",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "description": "Multi-tenant digital goods shoppe for federated wiki, powered by Sanora",
5
5
  "keywords": [
6
6
  "wiki",
package/server/server.js CHANGED
@@ -14,9 +14,6 @@ const RECOVER_STRIPE_TMPL = fs.readFileSync(path.join(TEMPLATES_DIR, 'generic-r
14
14
  const ADDRESS_STRIPE_TMPL = fs.readFileSync(path.join(TEMPLATES_DIR, 'generic-address-stripe.html'), 'utf8');
15
15
  const EBOOK_DOWNLOAD_TMPL = fs.readFileSync(path.join(TEMPLATES_DIR, 'ebook-download.html'), 'utf8');
16
16
 
17
- function getAllyabaseOrigin() {
18
- try { return new URL(getSanoraUrl()).origin; } catch { return getSanoraUrl(); }
19
- }
20
17
 
21
18
  function fillTemplate(tmpl, vars) {
22
19
  return Object.entries(vars).reduce((html, [k, v]) =>
@@ -25,6 +22,7 @@ function fillTemplate(tmpl, vars) {
25
22
 
26
23
  const DATA_DIR = path.join(process.env.HOME || '/root', '.shoppe');
27
24
  const TENANTS_FILE = path.join(DATA_DIR, 'tenants.json');
25
+ const BUYERS_FILE = path.join(DATA_DIR, 'buyers.json');
28
26
  const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
29
27
  const TMP_DIR = '/tmp/shoppe-uploads';
30
28
 
@@ -47,6 +45,47 @@ function getSanoraUrl() {
47
45
  return `http://localhost:${process.env.SANORA_PORT || 7243}`;
48
46
  }
49
47
 
48
+ function getAddieUrl(wikiOrigin) {
49
+ if (wikiOrigin) return `${wikiOrigin}/plugin/allyabase/addie`;
50
+ try { return new URL(getSanoraUrl()).origin + '/plugin/allyabase/addie'; } catch { /* fall through */ }
51
+ return `http://localhost:${process.env.ADDIE_PORT || 3005}`;
52
+ }
53
+
54
+ function loadBuyers() {
55
+ if (!fs.existsSync(BUYERS_FILE)) return {};
56
+ try { return JSON.parse(fs.readFileSync(BUYERS_FILE, 'utf8')); } catch { return {}; }
57
+ }
58
+
59
+ function saveBuyers(buyers) {
60
+ fs.writeFileSync(BUYERS_FILE, JSON.stringify(buyers, null, 2));
61
+ }
62
+
63
+ async function getOrCreateBuyerAddieUser(recoveryKey, productId, wikiOrigin) {
64
+ const buyerKey = recoveryKey + productId;
65
+ const buyers = loadBuyers();
66
+ if (buyers[buyerKey]) return buyers[buyerKey];
67
+
68
+ const addieKeys = await sessionless.generateKeys(() => {}, () => null);
69
+ sessionless.getKeys = () => addieKeys;
70
+ const timestamp = Date.now().toString();
71
+ const message = timestamp + addieKeys.pubKey;
72
+ const signature = await sessionless.sign(message);
73
+
74
+ const resp = await fetch(`${getAddieUrl(wikiOrigin)}/user/create`, {
75
+ method: 'PUT',
76
+ headers: { 'Content-Type': 'application/json' },
77
+ body: JSON.stringify({ timestamp, pubKey: addieKeys.pubKey, signature })
78
+ });
79
+
80
+ const addieUser = await resp.json();
81
+ if (addieUser.error) throw new Error(`Addie: ${addieUser.error}`);
82
+
83
+ const buyer = { uuid: addieUser.uuid, pubKey: addieKeys.pubKey, privateKey: addieKeys.privateKey };
84
+ buyers[buyerKey] = buyer;
85
+ saveBuyers(buyers);
86
+ return buyer;
87
+ }
88
+
50
89
  // Same diverse palette as BDO emojicoding
51
90
  const EMOJI_PALETTE = [
52
91
  '🌟', '🌙', '🌍', '🌊', '🔥', '💎', '🎨', '🎭', '🎪', '🎯',
@@ -152,6 +191,25 @@ function generateEmojicode(tenants) {
152
191
  throw new Error('Failed to generate unique emojicode after 100 attempts');
153
192
  }
154
193
 
194
+ async function addieCreateUser() {
195
+ const addieKeys = await sessionless.generateKeys(() => {}, () => null);
196
+ sessionless.getKeys = () => addieKeys;
197
+ const timestamp = Date.now().toString();
198
+ const message = timestamp + addieKeys.pubKey;
199
+ const signature = await sessionless.sign(message);
200
+
201
+ const resp = await fetch(`${getAddieUrl()}/user/create`, {
202
+ method: 'PUT',
203
+ headers: { 'Content-Type': 'application/json' },
204
+ body: JSON.stringify({ timestamp, pubKey: addieKeys.pubKey, signature })
205
+ });
206
+
207
+ const addieUser = await resp.json();
208
+ if (addieUser.error) throw new Error(`Addie: ${addieUser.error}`);
209
+
210
+ return { uuid: addieUser.uuid, pubKey: addieKeys.pubKey, privateKey: addieKeys.privateKey };
211
+ }
212
+
155
213
  async function registerTenant(name) {
156
214
  const tenants = loadTenants();
157
215
 
@@ -173,12 +231,21 @@ async function registerTenant(name) {
173
231
 
174
232
  const emojicode = generateEmojicode(tenants);
175
233
 
234
+ // Create a dedicated Addie user for payee splits
235
+ let addieKeys = null;
236
+ try {
237
+ addieKeys = await addieCreateUser();
238
+ } catch (err) {
239
+ console.warn('[shoppe] Could not create addie user (payouts unavailable):', err.message);
240
+ }
241
+
176
242
  const tenant = {
177
243
  uuid: sanoraUser.uuid,
178
244
  emojicode,
179
245
  name: name || 'Unnamed Shoppe',
180
246
  keys,
181
247
  sanoraUser,
248
+ addieKeys,
182
249
  createdAt: Date.now()
183
250
  };
184
251
 
@@ -937,10 +1004,11 @@ async function startServer(params) {
937
1004
 
938
1005
  // Save config (owner only)
939
1006
  app.post('/plugin/shoppe/config', owner, (req, res) => {
940
- const { sanoraUrl } = req.body;
1007
+ const { sanoraUrl, addieUrl } = req.body;
941
1008
  if (!sanoraUrl) return res.status(400).json({ success: false, error: 'sanoraUrl required' });
942
1009
  const config = loadConfig();
943
1010
  config.sanoraUrl = sanoraUrl;
1011
+ if (addieUrl) config.addieUrl = addieUrl;
944
1012
  saveConfig(config);
945
1013
  console.log('[shoppe] Sanora URL set to:', sanoraUrl);
946
1014
  res.json({ success: true });
@@ -953,15 +1021,20 @@ async function startServer(params) {
953
1021
  if (!tenant) return res.status(404).send('<h1>Shoppe not found</h1>');
954
1022
 
955
1023
  const title = decodeURIComponent(req.params.title);
956
- const sanoraUrl = getSanoraUrl();
957
- const productsResp = await fetch(`${sanoraUrl}/products/${tenant.uuid}`);
1024
+ const sanoraUrlInternal = getSanoraUrl();
1025
+ const wikiOrigin = `${req.protocol}://${req.get('host')}`;
1026
+ const sanoraUrl = `${wikiOrigin}/plugin/allyabase/sanora`;
1027
+ const productsResp = await fetch(`${sanoraUrlInternal}/products/${tenant.uuid}`);
958
1028
  const products = await productsResp.json();
959
1029
  const product = products[title] || Object.values(products).find(p => p.title === title);
960
1030
  if (!product) return res.status(404).send('<h1>Product not found</h1>');
961
1031
 
962
- const imageUrl = product.image ? `${sanoraUrl}/images/${product.image}` : '';
963
- const ebookUrl = `${req.protocol}://${req.get('host')}/plugin/shoppe/${tenant.uuid}/download/${encodeURIComponent(title)}`;
964
- const shoppeUrl = `${req.protocol}://${req.get('host')}/plugin/shoppe/${tenant.uuid}`;
1032
+ const imageUrl = product.image ? `${sanoraUrlInternal}/images/${product.image}` : '';
1033
+ const ebookUrl = `${wikiOrigin}/plugin/shoppe/${tenant.uuid}/download/${encodeURIComponent(title)}`;
1034
+ const shoppeUrl = `${wikiOrigin}/plugin/shoppe/${tenant.uuid}`;
1035
+ const payees = tenant.addieKeys
1036
+ ? JSON.stringify([{ pubKey: tenant.addieKeys.pubKey, amount: product.price || 0 }])
1037
+ : '[]';
965
1038
 
966
1039
  const html = fillTemplate(templateHtml, {
967
1040
  title: product.title || title,
@@ -973,9 +1046,11 @@ async function startServer(params) {
973
1046
  pubKey: '',
974
1047
  signature: '',
975
1048
  sanoraUrl,
976
- allyabaseOrigin: getAllyabaseOrigin(),
1049
+ allyabaseOrigin: wikiOrigin,
977
1050
  ebookUrl,
978
- shoppeUrl
1051
+ shoppeUrl,
1052
+ payees,
1053
+ tenantUuid: tenant.uuid
979
1054
  });
980
1055
 
981
1056
  res.set('Content-Type', 'text/html');
@@ -994,6 +1069,80 @@ async function startServer(params) {
994
1069
  app.get('/plugin/shoppe/:identifier/buy/:title/address', (req, res) =>
995
1070
  renderPurchasePage(req, res, ADDRESS_STRIPE_TMPL));
996
1071
 
1072
+ // Purchase intent — creates buyer Addie user, checks recovery hash, returns Stripe client secret
1073
+ app.post('/plugin/shoppe/:identifier/purchase/intent', async (req, res) => {
1074
+ try {
1075
+ const tenant = getTenantByIdentifier(req.params.identifier);
1076
+ if (!tenant) return res.status(404).json({ error: 'Shoppe not found' });
1077
+
1078
+ const { recoveryKey, productId, title } = req.body;
1079
+ if (!recoveryKey || !productId) return res.status(400).json({ error: 'recoveryKey and productId required' });
1080
+
1081
+ const sanoraUrlInternal = getSanoraUrl();
1082
+ const wikiOrigin = `${req.protocol}://${req.get('host')}`;
1083
+ const recoveryHash = recoveryKey + productId;
1084
+
1085
+ // Check if already purchased
1086
+ const checkResp = await fetch(`${sanoraUrlInternal}/user/check-hash/${encodeURIComponent(recoveryHash)}/product/${encodeURIComponent(productId)}`);
1087
+ const checkJson = await checkResp.json();
1088
+ if (checkJson.success) return res.json({ purchased: true });
1089
+
1090
+ // Get product price
1091
+ const productsResp = await fetch(`${sanoraUrlInternal}/products/${tenant.uuid}`);
1092
+ const products = await productsResp.json();
1093
+ const product = (title && products[title]) || Object.values(products).find(p => p.productId === productId);
1094
+ const amount = product?.price || 0;
1095
+
1096
+ // Create/retrieve buyer Addie user
1097
+ const buyer = await getOrCreateBuyerAddieUser(recoveryKey, productId, wikiOrigin);
1098
+
1099
+ // Create Stripe intent via Addie
1100
+ const payees = tenant.addieKeys ? [{ pubKey: tenant.addieKeys.pubKey, amount }] : [];
1101
+ const intentResp = await fetch(`${getAddieUrl(wikiOrigin)}/user/${buyer.uuid}/processor/stripe/intent`, {
1102
+ method: 'PUT',
1103
+ headers: { 'Content-Type': 'application/json' },
1104
+ body: JSON.stringify({ timestamp: Date.now().toString(), amount, currency: 'USD', payees })
1105
+ });
1106
+
1107
+ const intentJson = await intentResp.json();
1108
+ if (intentJson.error) return res.status(500).json({ error: intentJson.error });
1109
+
1110
+ res.json({ purchased: false, clientSecret: intentJson.paymentIntent, publishableKey: intentJson.publishableKey });
1111
+ } catch (err) {
1112
+ console.error('[shoppe] purchase intent error:', err);
1113
+ res.status(500).json({ error: err.message });
1114
+ }
1115
+ });
1116
+
1117
+ // Purchase complete — creates recovery hash in Sanora after successful payment
1118
+ app.post('/plugin/shoppe/:identifier/purchase/complete', async (req, res) => {
1119
+ try {
1120
+ const tenant = getTenantByIdentifier(req.params.identifier);
1121
+ if (!tenant) return res.status(404).json({ error: 'Shoppe not found' });
1122
+
1123
+ const { recoveryKey, productId, order } = req.body;
1124
+ if (!recoveryKey || !productId) return res.status(400).json({ error: 'recoveryKey and productId required' });
1125
+
1126
+ const sanoraUrlInternal = getSanoraUrl();
1127
+ const recoveryHash = recoveryKey + productId;
1128
+
1129
+ if (order) {
1130
+ await fetch(`${sanoraUrlInternal}/user/orders`, {
1131
+ method: 'PUT',
1132
+ headers: { 'Content-Type': 'application/json' },
1133
+ body: JSON.stringify({ timestamp: Date.now().toString(), order })
1134
+ });
1135
+ }
1136
+
1137
+ const createResp = await fetch(`${sanoraUrlInternal}/user/create-hash/${encodeURIComponent(recoveryHash)}/product/${encodeURIComponent(productId)}`);
1138
+ const createJson = await createResp.json();
1139
+ res.json({ success: createJson.success });
1140
+ } catch (err) {
1141
+ console.error('[shoppe] purchase complete error:', err);
1142
+ res.status(500).json({ error: err.message });
1143
+ }
1144
+ });
1145
+
997
1146
  // Ebook download page (reached after successful payment + hash creation)
998
1147
  app.get('/plugin/shoppe/:identifier/download/:title', async (req, res) => {
999
1148
  try {
@@ -481,7 +481,7 @@
481
481
  timestamp: new Date().getTime() + '',
482
482
  amount: {{amount}},
483
483
  currency: 'USD',
484
- payees: []
484
+ payees: {{payees}}
485
485
  };
486
486
 
487
487
  const res = await fetch(`{{allyabaseOrigin}}/plugin/allyabase/addie/processor/stripe/intent`, {
@@ -83,7 +83,7 @@
83
83
  </div>
84
84
 
85
85
  <!-- Payment Form -->
86
- <div>
86
+ <div id="payment-section" style="display:none">
87
87
  <h3 style="margin-bottom: 20px; color: #10b981;">Payment Details</h3>
88
88
  <form id="payment-form" class="payment-form" style="
89
89
  background: #2a2a2e;
@@ -137,29 +137,18 @@
137
137
  </style>
138
138
 
139
139
  <script type="text/javascript">
140
- // Buy button functionality
140
+ // Buy button — just reveal the forms section (payment init happens after recovery key submitted)
141
141
  document.getElementById('buy-button').addEventListener('click', function() {
142
142
  const formsSection = document.getElementById('forms-section');
143
143
  formsSection.style.display = 'block';
144
-
145
- // Smooth scroll to forms section
146
- formsSection.scrollIntoView({
147
- behavior: 'smooth',
148
- block: 'start'
149
- });
150
-
151
- // Initialize payment form
152
- window.addPaymentForm();
144
+ formsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
153
145
  });
154
-
155
- // Form validation for both forms
146
+
147
+ // Enable submit once Stripe payment element is ready
156
148
  function validateAllForms() {
157
- const recoveryValid = validateForm(formConfig);
158
- const paymentValid = stripe && elements; // Basic check that payment is initialized
159
-
149
+ const paymentValid = stripe && elements;
160
150
  const submitButton = document.getElementById('submit-button');
161
-
162
- if (recoveryValid && paymentValid) {
151
+ if (paymentValid) {
163
152
  submitButton.style.background = 'linear-gradient(90deg, #10b981, #8b5cf6)';
164
153
  submitButton.style.color = 'white';
165
154
  submitButton.style.cursor = 'pointer';
@@ -170,7 +159,6 @@
170
159
  submitButton.style.color = '#999999';
171
160
  submitButton.style.cursor = 'not-allowed';
172
161
  submitButton.disabled = true;
173
- submitButton.textContent = 'Complete Purchase';
174
162
  }
175
163
  }
176
164
  </script>
@@ -582,23 +570,43 @@
582
570
  };
583
571
 
584
572
  async function handleSubmit(formData) {
585
- console.log('Form submitted:', formData);
586
- // Do whatever you want with the form data
587
- const recoveryHash = formData.Recovery + "{{productId}}";
588
- const checkHashURL = `{{sanoraUrl}}/user/check-hash/${recoveryHash}/product/{{productId}}`
573
+ window.formData = formData;
574
+ const recoveryKey = formData.Recovery;
575
+
576
+ const submitBtn = document.querySelector('[type=submit]');
577
+ if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = 'Checking…'; }
578
+
579
+ try {
580
+ const resp = await fetch('/plugin/shoppe/{{tenantUuid}}/purchase/intent', {
581
+ method: 'POST',
582
+ headers: { 'Content-Type': 'application/json' },
583
+ body: JSON.stringify({ recoveryKey, productId: '{{productId}}', title: '{{title}}' })
584
+ });
585
+ const json = await resp.json();
586
+
587
+ if (json.purchased) {
588
+ window.location.href = '{{ebookUrl}}';
589
+ return;
590
+ }
589
591
 
590
- const resp = await fetch(checkHashURL);
591
- const json = await resp.json();
592
+ if (json.error) {
593
+ alert('Error: ' + json.error);
594
+ return;
595
+ }
592
596
 
593
- if(json.success) {
594
- window.location.href = '{{ebookUrl}}';
595
- return;
597
+ // Show payment element
598
+ document.getElementById('payment-section').style.display = 'block';
599
+ stripe = Stripe(json.publishableKey);
600
+ elements = stripe.elements({ clientSecret: json.clientSecret });
601
+ const paymentElement = elements.create('payment');
602
+ paymentElement.mount('#payment-element');
603
+ paymentElement.on('ready', () => setTimeout(validateAllForms, 500));
604
+ paymentElement.on('change', () => setTimeout(validateAllForms, 100));
605
+ } catch (err) {
606
+ alert('Unexpected error: ' + err.message);
607
+ } finally {
608
+ if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = 'Check'; }
596
609
  }
597
-
598
- window.formData = formData;
599
- // Don't show payment form here anymore, it's already visible
600
- // Just trigger validation
601
- validateAllForms();
602
610
  }
603
611
 
604
612
  const form = getForm(formConfig, handleSubmit);
@@ -608,130 +616,59 @@
608
616
  <script type="text/javascript">
609
617
  let stripe;
610
618
  let elements;
611
- let response;
612
619
 
613
620
  const paymentForm = document.getElementById('payment-form');
614
621
  const submitButton = document.getElementById('submit-button');
615
622
  const errorMessage = document.getElementById('error-message');
616
623
  const loadingMessage = document.getElementById('loading');
617
624
 
618
- async function getPaymentIntentWithoutSplits(amount, currency) {
619
- try {
620
- const payload = {
621
- timestamp: new Date().getTime() + '',
622
- amount: {{amount}},
623
- currency: 'USD',
624
- payees: []
625
- };
626
-
627
- const res = await fetch(`{{allyabaseOrigin}}/plugin/allyabase/addie/processor/stripe/intent`, {
628
- method: 'put',
629
- body: JSON.stringify(payload),
630
- headers: {'Content-Type': 'application/json'}
631
- });
632
-
633
- const response = await res.json();
634
- console.log('got intent response', response);
635
-
636
- stripe = Stripe(response.publishableKey);
637
- elements = stripe.elements({
638
- clientSecret: response.paymentIntent
639
- });
640
-
641
- const paymentElement = elements.create('payment');
642
- paymentElement.mount('#payment-element');
643
-
644
- // Trigger validation when payment element is ready
645
- paymentElement.on('ready', () => {
646
- setTimeout(() => validateAllForms(), 500);
647
- });
648
-
649
- paymentElement.on('change', () => {
650
- setTimeout(() => validateAllForms(), 100);
651
- });
652
- } catch(err) {
653
- console.warn(err);
654
- }
655
- };
656
-
657
625
  window.confirmPayment = async () => {
658
- const order = {
659
- title: "{{title}}",
660
- productId: "{{productId}}",
661
- formData
662
- };
663
-
664
626
  try {
665
627
  const { error } = await stripe.confirmPayment({
666
- elements,
667
- confirmParams: {
668
- return_url: 'http://wiki.planetnineisaspaceship.com'
669
- },
670
- redirect: 'if_required'
628
+ elements,
629
+ confirmParams: { return_url: '{{shoppeUrl}}' },
630
+ redirect: 'if_required'
671
631
  });
672
632
 
673
- if(error) {
674
- return showError(error.message);
675
- }
633
+ if (error) return showError(error.message);
676
634
 
677
- await fetch('{{sanoraUrl}}/user/orders', {
678
- method: 'PUT',
679
- headers: {'Content-Type': 'application/json'},
680
- body: JSON.stringify({timestamp: new Date().getTime() + '', order})
635
+ const order = { title: '{{title}}', productId: '{{productId}}', formData: window.formData };
636
+ const resp = await fetch('/plugin/shoppe/{{tenantUuid}}/purchase/complete', {
637
+ method: 'POST',
638
+ headers: { 'Content-Type': 'application/json' },
639
+ body: JSON.stringify({ recoveryKey: window.formData.Recovery, productId: '{{productId}}', order })
681
640
  });
682
- const recoveryHash = formData.Recovery + "{{productId}}";
683
- const createHashURL = `{{sanoraUrl}}/user/create-hash/${recoveryHash}/product/{{productId}}`
684
-
685
- const resp = await fetch(createHashURL);
686
641
  const json = await resp.json();
687
642
 
688
- if(json.success) {
689
- window.location.href = '{{ebookUrl}}';
690
- return;
643
+ if (json.success) {
644
+ window.location.href = '{{ebookUrl}}';
645
+ } else {
646
+ window.alert('Payment successful, but error recording purchase. Contact greetings@planetnine.app');
691
647
  }
692
-
693
- window.alert('Your payment was successful, but there was an error creating this recovery hash. Please contact greetings@planetnine.app for support.');
694
-
695
- } catch(err) {
648
+ } catch (err) {
696
649
  showError('An unexpected error occurred.');
697
- console.warn('payment error: ', err);
650
+ console.warn('payment error:', err);
698
651
  }
699
652
  };
700
653
 
701
654
  paymentForm.addEventListener('submit', async (event) => {
702
655
  event.preventDefault();
703
-
704
- if (!stripe || !elements) {
705
- return;
706
- }
707
-
708
- // Disable payment form submission while processing
656
+ if (!stripe || !elements) return;
709
657
  setLoading(true);
710
-
711
658
  await window.confirmPayment();
712
-
713
659
  setLoading(false);
714
660
  });
715
661
 
716
662
  const showError = (message) => {
717
663
  errorMessage.textContent = message;
718
664
  errorMessage.style.display = 'block';
719
- setTimeout(() => {
720
- errorMessage.style.display = 'none';
721
- errorMessage.textContent = '';
722
- }, 5000);
665
+ setTimeout(() => { errorMessage.style.display = 'none'; errorMessage.textContent = ''; }, 5000);
723
666
  };
724
667
 
725
668
  const setLoading = (isLoading) => {
726
669
  submitButton.disabled = isLoading;
727
670
  loadingMessage.style.display = isLoading ? 'block' : 'none';
728
671
  };
729
-
730
- const start = () => {
731
- getPaymentIntentWithoutSplits({{amount}}, 'USD');
732
- };
733
-
734
- window.addPaymentForm = start;
735
672
  </script>
736
673
  </body>
737
674
  </html>