-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlucchetto.js
323 lines (283 loc) · 10.1 KB
/
lucchetto.js
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
const METADATA_REGEX = /,metadata=([^,]*)/;
/**
* List of lucchetto providing servers for production: these are shown as options in a dropdown, when this is constructed with `!isTest`:
*/
const LUCCHETTO_PROVIDERS = [
'@rs.overhide.io'
]
/**
* List of lucchetto providing servers for testnets: these are shown as options in a dropdown, when this is constructed with `isTest`:
*/
const LUCCHETTO_PROVIDERS_4_TEST = [
'@test.rs.overhide.io',
'@localhost:8000'
]
/**
* Helper class; reacts to remotestorage.js `onConnected` events to parse metadata out of newly available token.
*/
class Lucchetto {
/**
* @param {*} remoteStorage - the RS instance available from client. This is an RS instance connected to the the client-user's data.
* @param {bool} isTest - flag whether this is all working against testnets or mainnets/prod servers.
* @param {*} hub - pay2my.app hub to instrument with credentials coming out of the remoteStorage instance (iff armadietto+luccheto).
*/
constructor(remoteStorage, isTest = false, hub = null) {
this.remoteStorage = remoteStorage;
this.metadata = {};
this.previousToken = null;
this.currentUserAddress = null;
this.isTest = isTest;
this.hub = hub;
this.lastImparterToken = null;
this.reinitConnectionPromise();
this.reinitLucchettoPromise();
document.addEventListener('DOMContentLoaded', this.onDomLoad);
}
/**
* Regular DOM "loaded" event handler.
*/
onDomLoad = () => {
this.extendWidget();
this.initHub();
this.remoteStorage.on('connected', this.onConnected);
this.remoteStorage.on('not-connected', this.onNotConnected);
this.remoteStorage.on('error', this.onError);
}
/**
* remotestorage.js `onConnected` event handler.
*/
onConnected = () => {
this.metadata = {};
const token = this.remoteStorage.remote.token;
if (!token) return;
this.metadata = this._getMetadata(token);
this.rewriteUsername();
this.instrumentHub();
this.resolveConnection();
if (this.previousToken) {
this.resolveLucchetto();
}
}
/**
* remotestorage.js `onNotConnected` event handler.
*/
onNotConnected = () => {
this.metadata = {};
this.reinitConnectionPromise();
this.reinitLucchettoPromise();
this.logout();
}
/**
* remotestorage.js `onError` event handler.
*/
onError = (event) => {
console.warn(`lucchetto :: onError ${event}`);
this.metadata = {};
this.reinitConnectionPromise();
this.reinitLucchettoPromise();
this.logout();
}
_getMetadata = (token) => {
let metadata = {};
if (!token) return metadata;
const matched = token.match(METADATA_REGEX);
if (matched) {
metadata = JSON.parse(atob(matched[1]));
}
return metadata;
}
rewriteUsername = () => {
if (!this.remoteStorage.remote.userAddress) return;
const oldName = this.remoteStorage.remote.userAddress.split('@')[0];
const host = this.remoteStorage.remote.userAddress.split('@')[1];
if ('p2ma_address' in this.metadata) {
this.currentUserAddress = `${this.metadata.p2ma_address}@${host}`;
if (oldName !== this.metadata.p2ma_address
&& this.previousToken !== this.remoteStorage.remote.token) {
console.log(`lucchetto :: rewriting username ${oldName} => ${this.metadata.p2ma_address}`);
this.remoteStorage.connect(this.currentUserAddress, this.remoteStorage.remote.token);
}
this.previousToken = this.remoteStorage.remote.token;
}
}
initHub = () => {
if (!this.hub) {
console.warn(`lucchetto :: no pay2my.app hub configured for lucchetto therefore no IAPs`);
return;
}
if (this.isTest) {
this.hub.setAttribute('apiKey', `0x9a6aef977a293b5c49ac5fcdd6376010e027549b8aa0ff97bc65a1d8649aef62`);
} else {
this.hub.setAttribute('apiKey', `0xc16f6e6d8666fdd835d909422fc141dfe5efcbcca3125bf746ef63019c486e47`);
}
}
instrumentHub = () => {
const currentImparterToken = JSON.stringify(this.metadata);;
if (this.hub && 'p2ma_address' in this.metadata && this.lastImparterToken !== currentImparterToken) {
console.log(`lucchetto :: instrumenting hub`);
this.hub.setCurrentImparterChecked(
this.metadata.p2ma_imparter,
this.metadata.p2ma_token,
this.metadata.p2ma_signature,
this.metadata.p2ma_address
);
this.lastImparterToken = currentImparterToken;
}
}
logout = () => {
if (this.hub && this.lastImparterToken) {
console.log(`lucchetto :: logging out`);
this.hub.setCurrentImparterChecked(
'unknown',
null,
null,
null
);
this.lastImparterToken = null;
}
}
extendWidget = () => {
this.attempt = 0;
this._extendWidget();
}
_extendWidget = () => {
const el = document.querySelector(`input[name='rs-user-address']`);
const providers = this.isTest ? LUCCHETTO_PROVIDERS_4_TEST : LUCCHETTO_PROVIDERS;
this.attempt++;
if (this.attempt > 20) return;
if (el) {
try {
el.setAttribute('placeholder',providers[0]);
el.setAttribute('list', 'rs-user-address-list');
const dl = document.createElement('datalist');
dl.setAttribute('id', 'rs-user-address-list');
for(const item of providers){
const itemEl = document.createElement('option');
itemEl.setAttribute('value', item);
dl.appendChild(itemEl);
}
el.after(dl);
} catch {}
return;
}
setTimeout(this.extendWidget, 250);
}
reinitLucchettoPromise = () => {
if (this.rejectLucchetto) this.rejectLucchetto('lucchetto not available');
this.lucchettoPromise = new Promise((rs, rj) => {this.resolveLucchetto = rs; this.rejectLucchetto = rj;});
}
reinitConnectionPromise = () => {
if (this.rejectConnection) this.rejectConnection('not connected');
this.connectionPromise = new Promise((rs, rj) => {this.resolveConnection = rs; this.rejectConnection = rj;});
}
/**
* Helper method to wait until user is fully connected to any remotestorage server, lucchetto enabled or not.
*
* @returns {Promise} to be resolved when RS is connected.
*/
waitRSConnected = (key) => {
return this.connectionPromise;
}
/**
* Helper method to wait until user is fully connected to a lucchetto enabled remotestorage server..
*
* @returns {Promise} to be resolved when RS is connected.
*/
waitRSIsLucchetto = (key) => {
return this.lucchettoPromise;
}
/**
* Get all metadata from the token
*
* @returns {*} the metadata object, it may include:
* - p2ma_address - the pay2my.app address iff pay2myapp extension enabled in armadietto server: this is the defacto remotestorage.js username
* - p2ma_token - the pay2my.app token iff pay2myapp extension enabled in armadietto server
* - p2ma_signature - the pay2my.app p2ma_token signed by p2ma_address
*/
getMetadata = () => {
return this.metadata;
}
/**
* @returns {string} the user address last seen upon last connection
*/
getUserAddress = () => {
return this.currentUserAddress && this.currentUserAddress === this.remoteStorage.remote.userAddress ? this.currentUserAddress : null;
}
/**
* @returns {string} the lucchetto namespace: under which lucchetto in-app purchase SKU data is stored.
*/
getNamespace = () => `pay2my.app`;
/**
* Retrieve a remotestorage path to in-app purchase SKUs.
*
* @param {*} sku - tag must be a a string comprised of 2 to 20 numbers, lower case letters, hypens, and periods
* @param {*} price - must be in US dollars, optionally with a period and cents
* @param {*} within - must be a whole number
* @throws {string} if parameters not parsable
* @returns {string}
*/
getPath = (sku, price, within) => {
if (!price || !price.match(/^\d{0,7}(\.\d{2})?$/)) {
throw '"price" must be in dollars, optionally with a period and cents, e.g. `2.00`';
}
if (!within || !within.match(/^\d{1,8}$/)) {
throw '"within" must be a whole number, e.g. `525600`';
}
if (!sku || !sku.match(/^[0-9a-z.-]{2,20}$/)) {
throw '"SKU" must be a a string comprised of 2 to 20 numbers, lower case letters, hypens, and periods, e.g. `item`';
}
price = (+price).toFixed(2);
if (price < .5) {
throw '"price" must be > "0.50"';
}
return `/${sku}/${price}/${within}`;
}
/**
* Retrieve data for a SKU.
*
* Leverages metadata from the user's armadietto+lucchetto remotestorage connection this instance was constructed with.
*
* @param {string} url - the URL to your, the developer's, armadietto+lucchetto that contains your IAP definitions.
* @param {*} detail - the `detail` object from the `pay2myapp-appsell-sku-clicked` event, see https://www.npmjs.com/package/pay2my.app
* @throws {*} if error
* @returns {string} the data payload for the SKU
*/
getSku = async (url, detail) => {
try {
// Call back-end and ensure it verifies before saying it's handled.
const response = await fetch(`${url}/pay2myapp`
+`?sku=${detail.sku}`
+`&priceDollars=${(+detail.priceDollars).toFixed(2)}`
+`&withinMinutes=${detail.withinMinutes}`
+`¤cy=${detail.currency}`
+`&from=${detail.from}`
+`&to=${detail.to}`
+`&isTest=${detail.isTest}`
+`&asOf=${detail.asOf}`
+`&message=${btoa(detail.message)}`
+`&signature=${btoa(detail.signature)}`);
if (response.ok) {
const type = response.headers.get("Content-Type");
if (type && type.includes('text')) {
return await response.text();
} else if (type && type.includes('json')) {
return await response.json();
}
return await response.blob();
} else {
throw `error talking to back-end — ${response.status} — ${response.statusText}`;
}
} catch (e) {
if (this.hub) {
this.hub.refresh();
}
throw e;
}
}
}
var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this ||
{};
root.Lucchetto = Lucchetto;
module.exports = { Lucchetto };