ordinary-build 0.7.0

Build & codegen tool for Ordinary
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

const ACCESS_TOKEN = 'ORDINARY_ACCESS_TOKEN';
const REFRESH_TOKEN = 'ORDINARY_REFRESH_TOKEN';
const TOKEN_SIGNING_KEY = 'ORDINARY_TOKEN_SIGNING_KEY';
const SCHEMA = 'ORDINARY_SCHEMA';
const CORRELATION = 'ORDINARY_CORRELATION_ID';

const DEFAULT_CLIENT_EXP_S = 3;

const MIN_EVENT_DELAY_S = 5;
const MAX_EVENT_DELAY_S = 10;
const MAX_EVENT_BUFFER = 20;
const MAX_EVENT_BATCH = 15;

export const ALG = {
    // 'Sha512': 'SHA-512',
    // 'Sha384': 'SHA-384',
    'Sha256': 'SHA-256',
};


function getCorrelationId() {
    const correlationId = sessionStorage.getItem(CORRELATION);

    if (correlationId) {
        return correlationId;
    }

    const newCorrelationId = crypto.randomUUID();
    sessionStorage.setItem(CORRELATION, newCorrelationId);

    return newCorrelationId;
}

export async function getHeaders({
                                     cookies = true,
                                     requestId = true,
                                     correlationId = true,
                                     authorization = false,
                                 } = {}) {
    const token = authorization ? await getAccess(cookies) : new Uint8Array([]);

    return {
        ...(requestId ? {'x-request-id': crypto.randomUUID()} : {}),
        ...(correlationId ? {'x-correlation-id': getCorrelationId()} : {}),
        ...(authorization ? {'authorization': `Bearer ${base64encode(token)}`} : {}),
    }
}

export async function getSchema() {
    const schema = localStorage.getItem(SCHEMA);

    if (schema) {
        const [compression, encoded] = schema.split(',');

        const decoded = base64decode(encoded);
        const decompressed = decompress(decoded, 'application/json', compression);

        const json = await decompressed.json();

        if (json.version === '{{ version }}') {
            return json;
        }
    }

    let json;

    try {
        const res = await fetch('/.ordinary/schema', {
            headers: await getHeaders(),
        });
        json = await res.json();
    } catch (e) {
        json = {
            version: '{{ version }}',
            flags: [],
            auth: {
                cookies_enabled: false,
            }
        };
    }

    const [compression, compressed] = await compress(JSON.stringify(json), 'application/json');
    const encoded = base64encode(compressed);

    localStorage.setItem(SCHEMA, `${compression},${encoded}`);

    return json;
}

export async function getFlag(flagName) {
    const FLAG = `ORDINARY_FLAG_${flagName.toUpperCase()}`;
    const flag = localStorage.getItem(FLAG);

    if (!flag) {
        const schema = await getSchema();

        for (let i = 0; i < schema.flags.length; i += 1) {
            const flag = schema.flags[i];

            if (flag.name === flagName) {
                const select = Math.floor(Math.random() * 101);

                let acc = 0;

                for (let j = 0; j < flag.options.length; j += 1) {
                    const option = flag.options[j];

                    acc += option.percentage;

                    if (acc >= select) {
                        localStorage.setItem(FLAG, option.name);
                        return option.name;
                    }
                }
            }
        }
    }

    return flag;
}

async function getFlags() {
    const schema = await getSchema();
    const flags = {};

    for (let i = 0; i < schema.flags.length; i += 1) {
        const name = schema.flags[i].name;


        flags[name] = await getFlag(name);
    }

    return flags;
}

export function base64encode(value) {
    return value.toBase64({
        omitPadding: true,
        alphabet: "base64url"
    });
}

export function base64decode(value) {
    return Uint8Array.fromBase64(value, {
        alphabet: "base64url",
    });
}

async function compress(value, mime) {
    const blob = new Blob([value], {type: mime});

    const deflate = await (new Response(blob.stream().pipeThrough(
        new CompressionStream('deflate'),
    ))).bytes();

    return ['deflate', deflate];
}

function decompress(value, mime, compression) {
    const blob = new Blob([value], {type: mime});

    return (new Response(blob.stream().pipeThrough(
        new DecompressionStream(compression),
    )));
}

export async function tryCompress(value, mime, force) {
    const [compression, compressed] = await compress(value, mime)
    const useCompressed = compressed.length < value.length || force;

    return {
        body: useCompressed ? compressed : value,
        headers: {
            'content-type': mime,
            ...(useCompressed ? {'content-encoding': compression} : {}),
        },
    };
}

export function setTokenSigningKey(key) {
    const encoded = base64encode(key);
    // ?? encrypt/decrypt with a hashed passcode that lives in SessionStorage
    localStorage.setItem(TOKEN_SIGNING_KEY, encoded);

    localStorage.removeItem(REFRESH_TOKEN);
    localStorage.removeItem(ACCESS_TOKEN);
}

async function trySigningToken(token) {
    const encoded = localStorage.getItem(TOKEN_SIGNING_KEY);

    if (!encoded) return token;

    const exp = new ArrayBuffer(8);
    const buf = new DataView(exp);

    // todo: make the client exp settable in config
    buf.setBigUint64(0, BigInt(Math.floor(Date.now() / 1000) + DEFAULT_CLIENT_EXP_S), false);

    const withExp = new Uint8Array([...token, ...new Uint8Array(exp)]);
    const decoded = base64decode(encoded);

    const signingKey = await crypto.subtle.importKey(
        'pkcs8',
        decoded,
        {
            name: 'Ed25519'
        },
        false,
        ['sign']
    );

    const signature = await crypto.subtle.sign("Ed25519", signingKey, withExp);
    return new Uint8Array([...withExp, ...new Uint8Array(signature)]);
}

export function setRefresh(token) {
    const encoded = base64encode(token);
    localStorage.setItem(REFRESH_TOKEN, encoded);
    localStorage.removeItem(ACCESS_TOKEN);
}

async function refetchAccess(withCookies) {
    const encoded = localStorage.getItem(REFRESH_TOKEN);

    if (!encoded) {
        throw new Error('not logged in.');
    }

    const refresh_token = base64decode(encoded);
    const exp = new DataView(refresh_token.buffer).getBigUint64(0, false);

    if (exp < Math.round(new Date().getTime() / 1000)) {
        localStorage.removeItem(REFRESH_TOKEN);
        localStorage.removeItem(ACCESS_TOKEN);

        throw new Error('refresh token expired.');
    }

    const signed_token = await trySigningToken(refresh_token);

    let access_res;

    const schema = await getSchema();

    if (withCookies && schema.auth.cookies_enabled) {
        access_res = await fetch('/accounts/access/cookies', {
            credentials: 'include',
            headers: {...await getHeaders(), authorization: `Bearer ${base64encode(signed_token)}`},
        });
    } else {
        access_res = await fetch('/accounts/access', {
            headers: {...await getHeaders(), authorization: `Bearer ${base64encode(signed_token)}`},
        });
    }

    const token = await access_res.bytes();
    setAccess(token);

    return token;
}

function setAccess(token) {
    const encoded = base64encode(token);
    localStorage.setItem(ACCESS_TOKEN, encoded);
}

export async function getAccess(withCookies) {
    const encoded = localStorage.getItem(ACCESS_TOKEN);

    let access_token;

    if (!encoded) {
        access_token = await refetchAccess(withCookies);
    } else {
        access_token = base64decode(encoded);
        const exp = new DataView(access_token.buffer).getBigUint64(0, false);

        if (exp < Math.round(new Date().getTime() / 1000)) {
            access_token = await refetchAccess(withCookies);
        }
    }

    return await trySigningToken(access_token);
}

async function getActualDelayS() {
    const clientConfig = (await getSchema())?.logging?.client;

    const maxDelayS = clientConfig?.max_delay ?? MAX_EVENT_DELAY_S;
    const minDelayS = clientConfig?.min_delay ?? MIN_EVENT_DELAY_S;

    return Math.floor(Math.random() * (maxDelayS - minDelayS + 1) + minDelayS);
}

let eventFlushTimeout = null;

async function flushEventsDelayed(db) {
    if (eventFlushTimeout) clearTimeout(eventFlushTimeout);

    eventFlushTimeout = setTimeout(() => {
        flushEvents(db);
    }, (await getActualDelayS()) * 1000);
}

async function flushEvents(db, immediate) {
    const clientConfig = (await getSchema())?.logging?.client;

    const maxBuffer = clientConfig?.max_buffer ?? MAX_EVENT_BUFFER;
    const maxBatch = clientConfig?.max_buffer ?? MAX_EVENT_BATCH;

    const actualDelayS = await getActualDelayS();

    const now = new Date();
    now.setHours(now.getSeconds() - actualDelayS);
    const tsThreshold = now.toISOString();

    const eventsStore = db
        .transaction("events", "readwrite")
        .objectStore("events");

    const lvlIndex = eventsStore.index("lvl");

    const outEvents = immediate ? [immediate] : [];
    let lastCount = 0;

    lvlIndex.openCursor().onsuccess = async (evt) => {
        const cursor = evt.target.result;

        if (cursor) {
            lastCount = lvlIndex.count();

            if (cursor.value.ts < tsThreshold || lastCount > maxBuffer || outEvents.length < maxBatch) {
                outEvents.push(cursor.value);
                eventsStore.delete(cursor.primaryKey);

                cursor.continue();
                return;
            }
        }

        if (outEvents.length) {
            const req = await tryCompress(
                JSON.stringify(outEvents),
                'application/json',
                true
            );

            if (navigator.sendBeacon) {
                navigator.sendBeacon("/events", req.body);
            }

            if (lastCount) await flushEventsDelayed(db);
        }
    };
}

async function recordEvent(lvl, msg, fields) {
    const now = new Date();
    const flags = await getFlags();

    const event = {
        ts: now.toISOString(),
        lvl,
        version: '{{ version }}',
        correlation: getCorrelationId(),
        path: location.pathname,
        query: location.search ? location.search : null,
        fragment: location.hash ? location.hash : null,
        fields: fields ?? null,
        flags: Object.getOwnPropertyNames(flags).length ? flags : null,
        msg,
    };

    const eventsDB = indexedDB.open("OrdinaryEvents", 1);

    eventsDB.onerror = (evt) => {
        console.error(evt);
    };

    eventsDB.onupgradeneeded = (evt) => {
        const db = evt.target.result;

        const eventsStore = db.createObjectStore(
            "events",
            {keyPath: "ts", autoIncrement: true}
        );

        eventsStore.createIndex("lvl", "lvl", {unique: false});
    };

    eventsDB.onsuccess = (evt) => {
        const db = evt.target.result;

        if (lvl === 'error') {
            flushEvents(db, event);
        } else {
            const eventsStore = db
                .transaction("events", "readwrite")
                .objectStore("events")

            eventsStore.add(event);
            flushEventsDelayed(db);
        }
    };
}

export const events = {
    trace: (msg, fields) => recordEvent('trace', msg, fields),
    debug: (msg, fields) => recordEvent('debug', msg, fields),
    info: (msg, fields) => recordEvent('info', msg, fields),
    warn: (msg, fields) => recordEvent('warn', msg, fields),
    error: (msg, fields) => recordEvent('error', msg, fields),
};