-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-db.js
More file actions
2399 lines (2113 loc) · 95 KB
/
Copy pathgithub-db.js
File metadata and controls
2399 lines (2113 loc) · 95 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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
* ║ github-db.js ║
* ║ A JSON / GitHub based database where every write is a git commit ║
* ╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
*
* ═══ QUICK START ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
*
* Create instance — embed bot tokens so visitors can interact without their own PAT:
* const db = await GitHubDB.instance({ owner, repo, tokens: ['ghdb_enc_...', 'ghdb_enc_...'] })
* const db = await GitHubDB.instance({ owner, repo, tokens, branch, rawBranches, basePath, useRaw })
*
* Raw mode — recommended for public read-heavy apps (reads bypass API rate limits via raw.githubusercontent.com):
* const db = await GitHubDB.instance({ ..., useRaw: true, branch: main })
* // branch — branch used for GitHub API reads/writes and raw reads (default: 'main')
*
* ═══ PERMISSIONS ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
*
* Call db.permissions() after init to set per-collection or per-KV-key access.
* Any entry not listed defaults to { read: 'admin', write: 'admin' }.
*
* Permission levels:
* 'public' — anyone, no login required
* 'auth' — any logged-in user
* 'admin' — admin role only (the first registered user is automatically admin)
* custom — any string or array of strings, e.g. 'moderator' or ['editor', 'moderator']
* Admins always pass any permission check regardless of the required level.
*
* db.permissions({
* posts: { read: 'public', write: 'auth' },
* settings: { read: 'admin', write: 'admin' },
* reports: { read: ['moderator', 'analyst', 'auditor'], write: ['moderator', 'admin'] },
* 'posts.abc123': { read: 'admin', write: 'admin' },
* _kv: { read: 'auth', write: 'admin' },
* '_kv.theme': { read: 'public', write: ['moderator', 'designer'] },
* })
*
* Lookup priority per operation:
* collection.recordId -> collection segments -> root collection -> default 'admin'
* _kv.keyName -> _kv -> default 'admin'
*
* ═══ COLLECTIONS (stored at <basePath>/<collection>/<id>.json) ═════════════════════════════════════════════════════════════════════════
*
* const posts = db.collection('posts')
*
* await posts.add({ title: 'Hello' }) // create
* await posts.get(id) // fetch one -> record | null
* await posts.query() // fetch all (replaces list)
* await posts.update(id, { title: 'New' }) // partial patch
* await posts.replace(id, { title: 'New' }) // full replace
* await posts.remove(id) // delete
* await posts.upsert(id, data) // create-or-patch
* await posts.query(record => record.published) // filter in memory
* await posts.query(fn, { sort, limit, offset }) // with options
* await posts.count() // total count
* await posts.count(record => record.published) // filtered count
* await posts.exists(id) // boolean
* await posts.bulkAdd([{ ... }, { ... }]) // add many
* await posts.bulkRemove([id1, id2]) // remove many
* await posts.uploadFile(fileBlob, 'avatar') // upload a file
* await posts.deleteUpload('2026-05-18-photo.jpg') // delete an upload by safe name
* await posts.getUpload('2026-05-18-photo.jpg') // exact -> string url
* await posts.getUpload('photo') // partial -> array of matches
* await posts.listUploads() // list all uploads
* await posts.clear() // delete all (irreversible)
* const stop = posts.subscribe(({ records, added, changed, removed }) => { }, 5000) // poll for changes
* stop() // cancel subscription
*
* ═══ SUBCOLLECTIONS (nested collections inside a collection) ═══════════════════════════════════════════════════════════════════════════
*
* // Nesting can go as deep as needed:
* const members = db.collection('orgs', 'acme', 'teams', 'eng', 'members')
* await members.add({ name: 'Alice' })
* await members.list()
*
* ═══ KEY-VALUE STORE (stored at <basePath>/_kv/<key>.json) ═════════════════════════════════════════════════════════════════════════════
*
* await db.kv.set('theme', 'dark')
* await db.kv.get('theme') // value | null
* await db.kv.delete('theme')
* await db.kv.has('theme') // boolean
* await db.kv.increment('views') // atomic-ish counter
* await db.kv.increment('score', 5) // increment by N
* await db.kv.getMany('key1', 'key2') // { key1: v1, key2: v2 }
* await db.kv.getMany(['key1', 'key2']) // array form also accepted
* await db.kv.setMany({ key1: v1, key2: v2 })
* await db.kv.getAll() // { key: value } for all KV entries
* const stop = db.kv.subscribe(({ entries, added, changed, removed }) => { }, 5000) // poll for changes
* stop() // cancel subscription
*
* ═══ AUTH (stored at <basePath>/_auth/<username>.json per user) ════════════════════════════════════════════════════════════════════════
*
* await db.auth.register(username, password) // -> safe user object { id, username, roles, createdAt }
* await db.auth.login(username, password) // -> safe user object
* await db.auth.verifySession() // -> boolean
* await db.auth.changePassword(username, oldPassword, newPassword) // admin bypasses oldPassword check
* await db.auth.deleteAccount(username, password) // admin bypasses password check
* await db.auth.listUsers() // safe fields only
* await db.auth.setRoles(username, roles) // admin only
* db.auth.currentUser // { id, username, roles, createdAt } | null
* db.auth.isLoggedIn // boolean
* db.auth.logout()
*
* Roles: the first registered user gets ['admin']. All others default to ['user'].
* Users can hold multiple roles — e.g. ['editor', 'moderator'].
* Admins always pass any permission check.
* 'public' and 'auth' are reserved and cannot be used as role names.
*
* ═══ HASHING (PBKDF2-SHA256, 200 000 iterations) ═══════════════════════════════════════════════════════════════════════════════════════
*
* const hash = await GitHubDB.hashSecret('my-password', 'optional-context')
* const ok = await GitHubDB.verifySecret('my-password', hash, 'optional-context')
*
* ═══ TOKEN ENCODING (obfuscate a PAT before embedding in client-side code) ═════════════════════════════════════════════════════════════
*
* const encoded = GitHubDB.obfuscateToken('ghp_myRealToken') // Note: obfuscation deters casual scraping only; it is not encryption.
* // Pass the encoded string as token — the library decodes it automatically.
*
* ═══ UTILITIES ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
*
* await db.getCommitHistory(path?, limit?) // git audit log
* await db.validateConnection() // throws if token / repo is unreachable
* GitHubDB.obfuscateToken(plainToken) // obfuscate PAT for embedding
*/
'use strict'
// ═══ Constants ════════════════════════════════════════════════════════════════
const DATABASE_VERSION = '3.3.0'
const GITHUB_API_BASE = 'https://api.github.com'
const RAW_GITHUB_BASE = 'https://raw.githubusercontent.com'
const GITHUB_API_VERSION = '2026-03-10'
const SESSION_STORAGE_KEY = '__githubdb_session__'
const SESSION_LIFETIME_MS = 8 * 60 * 60 * 1000 // 8 hours
const MIN_PASSWORD_LENGTH = 8 // Minimum length for user passwords
const MAX_WRITE_RETRIES = 5 // GitHub 409 SHA-mismatch retry ceiling
const CONCURRENCY_LIMIT = 10 // Max in-flight GitHub API calls
const QUERY_BATCH_SIZE = 50 // Records streamed per chunk in batched queries
const REQUEST_TIMEOUT_MS = 30_000 // 30 seconds
// Changing any of the following constants invalidates all existing password hashes.
const PASSWORD_PEPPER = 'ghdb-pepper-4269'
const PBKDF2_ITERATIONS = 200_000
const OBFUSCATE_PREFIX = 'ghdb_enc_' // 'ghdb_obf_'
const TOKEN_XOR_KEY = 'GHDB'
// ═══ Addons ═══════════════════════════════════════════════════════════════════
const ADDON_BASE = 'https://imduck42.github.io/GHDB/addons'
/** Check for library updates and log changes if a newer version is available. */
const DATABASE_UPDATER = await import(`${ADDON_BASE}/updater.js`)
.then(async addon => {
await addon.checkForUpdate(DATABASE_VERSION)
return addon
})
.catch(error => { /* updater is optional */
console.warn('[GitHubDB] Updater addon unavailable:', error?.message)
return null
})
/** Import the workflow indexer addon. */
const INDEX_WORKFLOW = await import(`${ADDON_BASE}/workflow.js`)
.catch(error => { /* You really shouldn't get here */
console.warn('[GitHubDB] Workflow addon failed to load:', error?.message)
return null
})
/**
* Uses the imported workflow module to create a wrapper function.
* @param {string} owner
* @param {string} repo
* @param {string[]} tokens
* @param {string} basePath
*/
async function installWorkflow(owner, repo, tokens, basePath) {
try {
const token = resolveToken(tokens[0])
if (INDEX_WORKFLOW?.generateIndexerWorkflow) {
await INDEX_WORKFLOW.generateIndexerWorkflow(owner, repo, token, basePath)
}
} catch (error) {
throw new DatabaseError(`Workflow installation failed: ${error.message}`, 500)
}
}
// ═══ Error ════════════════════════════════════════════════════════════════════
/** All errors thrown by this library are instances of DatabaseError. */
class DatabaseError extends Error {
/**
* @param {string} message Human-readable description of the error.
* @param {number} [httpStatus=0] HTTP status code that triggered this error (0 if not HTTP-related).
*/
constructor(message, httpStatus = 0) {
super(message)
this.name = 'DatabaseError'
this.httpStatus = httpStatus
}
}
// ═══ Validation ═══════════════════════════════════════════════════════════════
/**
* Asserts that an ID or key only contains safe characters.
* Prevents path traversal — only letters, numbers, hyphens, and underscores are allowed.
* @param {string} id
*/
function assertValidId(id) {
if (typeof id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_\-]*$/.test(id)) {
throw new DatabaseError(
`Invalid ID or key: "${id}". Must use letters, numbers, hyphens, and underscores only.`, 400
)
}
}
/**
* Validates factory configuration to catch misconfigurations early.
* @param {{owner:string, repo:string, branch:string, tokens?:string[], basePath:string}} config
*/
function assertValidConfig({ owner, repo, branch, tokens, basePath }) {
if (!owner || !repo || !branch) {
throw new DatabaseError('owner, repo, and branch are required', 400)
}
const tokenArray = tokens
if (!Array.isArray(tokenArray) || !tokenArray.length) {
throw new DatabaseError('At least one token is required', 400)
}
if (/[?#]|(?:^|\/)\.\.?(?:\/|$)/.test(basePath)) {
throw new DatabaseError('Invalid basePath', 400)
}
}
/**
* Recursively strip prototype-pollution keys from a plain object.
* @param {unknown} object
* @returns {unknown}
*/
function sanitizeKeys(object) {
if (!object || typeof object !== 'object' || Array.isArray(object)) return object
const clean = {}
for (const key of Object.keys(object)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue
clean[key] = sanitizeKeys(object[key])
}
return clean
}
// ═══ ID Generation ════════════════════════════════════════════════════════════
/**
* Generate a collision-resistant record ID in the form `<timestamp-base36>-<random-base36>`.
* @returns {string}
*/
function generateId() {
const timestamp = Date.now().toString(36)
const randomPart = Array.from(crypto.getRandomValues(new Uint8Array(6)))
.map(byte => byte.toString(36).padStart(2, '0'))
.join('')
return `${timestamp}-${randomPart}`
}
// ═══ Base64 ═══════════════════════════════════════════════════════════════════
/**
* Encode a UTF-8 string to base64.
* @param {string} text
* @returns {string}
*/
function encodeBase64(text) {
const bytes = new TextEncoder().encode(text)
const chunks = []
for (let offset = 0; offset < bytes.length; offset += 8192) {
chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + 8192)))
}
return btoa(chunks.join(''))
}
/**
* Convert a File/Blob to a base64 string.
* @param {File|Blob} file
* @returns {Promise<string>}
*/
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result.split(',')[1])
reader.onerror = () => reject(new Error('File read failed'))
})
}
/**
* Decode a base64 string to UTF-8.
* @param {string} base64
* @returns {string}
*/
function decodeBase64(base64) {
const binaryString = atob(base64.replace(/\s/g, ''))
const bytes = new Uint8Array(binaryString.length)
for (let index = 0; index < binaryString.length; index++) {
bytes[index] = binaryString.charCodeAt(index)
}
return new TextDecoder().decode(bytes)
}
/** Serialize a value to base64-encoded JSON for the GitHub Contents API. */
const encodeFileContent = value => encodeBase64(JSON.stringify(value, null, 2))
/** Deserialize a base64-encoded string returned by the GitHub Contents API. */
const decodeFileContent = base64 => JSON.parse(decodeBase64(base64))
// ═══ Token Obfuscation ════════════════════════════════════════════════════════
/**
* XOR a string against the repeating TOKEN_XOR_KEY — shared by encode and resolve.
* @param {string} input
* @returns {string}
*/
function xorToken(input) {
return Array.from(input)
.map((char, index) =>
String.fromCharCode(char.charCodeAt(0) ^ TOKEN_XOR_KEY.charCodeAt(index % TOKEN_XOR_KEY.length))
)
.join('')
}
/**
* Obfuscate a plain PAT to a prefixed base64+XOR string suitable for embedding in client code.
* @param {string} plainToken
* @returns {string}
*/
const obfuscateToken = plainToken => OBFUSCATE_PREFIX + encodeBase64(xorToken(plainToken))
/**
* Resolve a token that may be plain or obfuscated.
* @param {string} token
* @returns {string}
*/
function resolveToken(token) {
if (!token.startsWith(OBFUSCATE_PREFIX)) { return token }
return xorToken(decodeBase64(token.slice(OBFUSCATE_PREFIX.length)))
}
// ═══ Cryptographic Hashing (PBKDF2-SHA256) ═══════════════════════════════════
/**
* Internal PBKDF2 driver — returns a hex-encoded derived key.
* @param {string} secret
* @param {string} context Optional binding context (e.g. username).
* @param {Uint8Array} salt
* @param {string} pepper Optional pepper override.
* @returns {Promise<string>}
*/
async function deriveKey(secret, context, salt, pepper) {
const keyMaterial = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret + pepper + context),
{ name: 'PBKDF2' },
false,
['deriveBits']
)
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: PBKDF2_ITERATIONS },
keyMaterial,
256
)
return Array.from(new Uint8Array(bits))
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
}
/**
* Convert a byte array to a hex string.
* @param {Uint8Array} bytes
* @returns {string}
*/
const bytesToHex = bytes =>
Array.from(bytes)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
/**
* Hash a secret using PBKDF2-SHA256.
* Output format: `<hex-salt>:<hex-derived-key>`.
* @param {string} secret
* @param {string} [context=''] Extra binding context (e.g. the username).
* @param {string} [pepper=PASSWORD_PEPPER] Optional custom pepper.
* @returns {Promise<string>}
*/
async function hashSecret(secret, context = '', pepper = PASSWORD_PEPPER) {
const saltBytes = crypto.getRandomValues(new Uint8Array(16))
return `${bytesToHex(saltBytes)}:${await deriveKey(secret, context, saltBytes, pepper)}`
}
/**
* Verify a plaintext secret against a hash produced by {@link hashSecret}.
* Uses constant-time comparison to prevent timing attacks.
* @param {string} secret
* @param {string} storedHash Value returned by `hashSecret`.
* @param {string} [context=''] Must match the context used during hashing.
* @param {string} [pepper=PASSWORD_PEPPER] Optional custom pepper.
* @returns {Promise<boolean>}
*/
async function verifySecret(secret, storedHash, context = '', pepper = PASSWORD_PEPPER) {
const [saltHex, expectedKey] = storedHash.split(':')
if (!saltHex || !expectedKey) return false
const saltBytes = new Uint8Array(saltHex.match(/.{2}/g).map(pair => parseInt(pair, 16)))
const candidateKey = await deriveKey(secret, context, saltBytes, pepper)
if (candidateKey.length !== expectedKey.length) return false
let bitDifferences = 0
for (let index = 0; index < candidateKey.length; index++) {
bitDifferences |= candidateKey.charCodeAt(index) ^ expectedKey.charCodeAt(index)
}
return bitDifferences === 0
}
// ═══ Concurrency Helpers ══════════════════════════════════════════════════════
/**
* Run an async task over each item with at most `limit` tasks in-flight at once.
* @template type
* @param {type[]} items
* @param {function(type): Promise} taskFn
* @param {number} [limit=CONCURRENCY_LIMIT]
* @returns {Promise<any[]>}
*/
async function runConcurrently(items, taskFn, limit = CONCURRENCY_LIMIT) {
if (items.length <= limit) {
return Promise.all(items.map(item => taskFn(item)))
}
const results = []
const inFlight = new Set()
for (const item of items) {
const promise = Promise.resolve().then(() => taskFn(item))
results.push(promise)
inFlight.add(promise)
promise.then(() => inFlight.delete(promise), () => inFlight.delete(promise))
if (inFlight.size >= limit) { await Promise.race(inFlight) }
}
return Promise.all(results)
}
/**
* Retry an async operation on HTTP 409 (SHA race condition), up to `maxRetries` times.
* Uses exponential backoff: 100ms, 200ms, 400ms, 800ms, 1.6s (total 3.1s) by default.
* @param {function(): Promise} operation
* @param {number} [maxRetries=MAX_WRITE_RETRIES]
* @returns {Promise<any>}
*/
async function retryOnConflict(operation, maxRetries = MAX_WRITE_RETRIES) {
let lastError = new DatabaseError('Operation failed after maximum retries', 500)
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await operation()
} catch (error) {
if (error.httpStatus === 409 && attempt < maxRetries) {
lastError = error
const delay = Math.min(100 * Math.pow(2, attempt), 5000)
await new Promise(resolve => setTimeout(resolve, delay))
continue
}
throw error
}
}
throw lastError
}
// ═══ Permission Helpers ═══════════════════════════════════════════════════════
/**
* Returns `true` if `userRoles` satisfies `requiredLevel`.
* Supported levels: `'public'`, `'auth'`, `'admin'`, or any custom role string / array.
* @param {string|string[]} requiredLevel
* @param {string[]} userRoles
* @returns {boolean}
*/
function hasRequiredRole(requiredLevel, userRoles) {
if (userRoles.includes('admin')) { return true }
if (requiredLevel === 'auth') { return userRoles.length > 0 }
const required = Array.isArray(requiredLevel) ? requiredLevel : [requiredLevel]
return required.some(role => userRoles.includes(role))
}
/**
* Shared permission gate used by Collection and KeyValueStore.
* Throws DatabaseError 401 or 403 if the current session is insufficient.
* @param {string} subject Human-readable subject name for error messages.
* @param {'read'|'write'} operation
* @param {object|null} rule Matched `{ read, write }` rule, or null.
* @param {SessionState} session
*/
function enforcePermission(subject, operation, rule, session) {
const requiredLevel = operation === 'read' ? (rule?.read ?? 'admin') : (rule?.write ?? 'admin')
if (!requiredLevel || requiredLevel === 'public' || (Array.isArray(requiredLevel) && !requiredLevel.length)) {
return
}
if (!session.isLoggedIn) {
throw new DatabaseError(`${subject} requires a logged-in user for ${operation} operations`, 401)
}
const userRoles = session.currentUser?.roles ?? []
if (!hasRequiredRole(requiredLevel, userRoles)) {
const humanRequired = Array.isArray(requiredLevel) ? requiredLevel.join(' or ') : requiredLevel
throw new DatabaseError(`${subject} requires "${humanRequired}" role for ${operation} operations`, 403)
}
}
// ═══ Polling / Subscribe Utility ══════════════════════════════════════════════
/**
* Generic polling subscription used by both {@link Collection} and {@link KeyValueStore}.
* Calls `callback` immediately on first poll, then again on any data change.
*
* @param {object} options
* @param {function(): Promise<object[]>} options.listEntries Return raw directory entries for the target path.
* @param {function(string): Promise<any>} options.fetchRecord Fetch a single record / value by its ID or key.
* @param {function(object): string|null} options.entryToId Map a directory entry to its logical ID (null to skip the entry).
* @param {function({ records, added, changed, removed }): void} options.callback
* @param {number} [options.intervalMs=5000]
* @param {function(Error): void} [options.onError]
* @returns {function(): void} A stop function — call it to cancel polling.
*/
function subscribeToDirectory({ listEntries, fetchRecord, entryToId, callback, intervalMs = 5000, onError = null }) {
const knownShas = new Map() // id -> sha from last successful poll
const cachedData = new Map() // id -> record / value
let isPolling = false
let initialized = false
const poll = async () => {
if (isPolling) { return }
isPolling = true
try {
const dirEntries = await listEntries()
const currentShas = new Map(
dirEntries
.map(entry => {
const id = entryToId(entry)
return id ? [id, entry.sha] : null
})
.filter(Boolean)
)
const toFetch = [...currentShas.keys()].filter(id => knownShas.get(id) !== currentShas.get(id))
const deletedIds = [...knownShas.keys()].filter(id => !currentShas.has(id))
if (toFetch.length > 0 || deletedIds.length > 0 || !initialized) {
const added = []
const changed = []
if (toFetch.length > 0) {
const fetched = await runConcurrently(toFetch, id => fetchRecord(id))
fetched.forEach((record, index) => {
if (record == null) { return }
const id = toFetch[index]
if (!knownShas.has(id)) {
added.push(record)
} else {
const oldRecord = cachedData.get(id)
if (!oldRecord || JSON.stringify(oldRecord) !== JSON.stringify(record)) {
changed.push(record)
}
}
cachedData.set(id, record)
})
}
const removedIds = deletedIds.filter(id => cachedData.has(id))
removedIds.forEach(id => cachedData.delete(id))
knownShas.clear()
currentShas.forEach((sha, id) => knownShas.set(id, sha))
callback({
records: Array.from(cachedData.values()),
added,
changed,
removed: removedIds,
})
}
} catch (error) {
if (onError) { onError(error) }
} finally {
initialized = true
isPolling = false
}
}
poll()
const intervalId = setInterval(poll, intervalMs)
return () => clearInterval(intervalId)
}
// ═══ Session State ════════════════════════════════════════════════════════════
/**
* Manages in-memory and sessionStorage login state.
* Sessions expire after SESSION_LIFETIME_MS (8 hours).
*/
class SessionState {
constructor() {
this.activeUser = null
this.restoreSession()
}
// ══ Storage Adapters ══════════════════════════════════════════════════════════
storageGet(key) {
try { return sessionStorage.getItem(key) }
catch { return null }
}
storageSet(key, value) {
try { sessionStorage.setItem(key, value) }
catch (error) { console.error('[GitHubDB] Storage write error:', error) }
}
storageDelete(key) {
try { sessionStorage.removeItem(key) }
catch (error) { console.error('[GitHubDB] Storage delete error:', error) }
}
// ══ Session Lifecycle ═════════════════════════════════════════════════════════
/** Restore a previously persisted session, discarding it if expired. */
restoreSession() {
try {
const raw = this.storageGet(SESSION_STORAGE_KEY)
if (!raw) { return }
const session = JSON.parse(raw)
if (session.expiresAt && Date.now() > session.expiresAt) {
this.storageDelete(SESSION_STORAGE_KEY)
return
}
if (!session.user || typeof session.user.username !== 'string'
|| !Array.isArray(session.user.roles)
|| typeof session.user.id !== 'string') {
this.storageDelete(SESSION_STORAGE_KEY)
return
}
this.activeUser = session.user
} catch (error) {
if (typeof console !== 'undefined' && console.warn) {
console.warn('[GitHubDB] Session restore failed:', error?.message)
}
this.storageDelete(SESSION_STORAGE_KEY)
}
}
/**
* Persist a user object to session storage and memory.
* @param {{ id: string, username: string, roles: string[], createdAt: string }} user
*/
persistUser(user) {
this.activeUser = user
this.storageSet(
SESSION_STORAGE_KEY,
JSON.stringify({ user, expiresAt: Date.now() + SESSION_LIFETIME_MS })
)
}
/** Clear all session data. */
clearSession() {
this.activeUser = null
this.storageDelete(SESSION_STORAGE_KEY)
}
/** The currently logged-in user, or `null`. */
get currentUser() { return this.activeUser }
/** `true` if a user is currently logged in. */
get isLoggedIn() { return this.activeUser !== null }
}
// ═══ Timeout Wrapper ══════════════════════════════════════════════════════════
/**
* Fetch with timeout support.
* @param {string} url
* @param {RequestInit} [init={}]
* @param {number} [timeoutMs=REQUEST_TIMEOUT_MS]
* @returns {Promise<Response>}
*/
async function fetchWithTimeout(url, init = {}, timeoutMs = REQUEST_TIMEOUT_MS) {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
try {
const response = await fetch(url, { ...init, signal: controller.signal })
return response
} catch (error) {
if (error.name === 'AbortError') {
throw new DatabaseError(`Request timeout after ${timeoutMs}ms: ${url}`, 408)
}
throw error
} finally {
clearTimeout(timeoutId)
}
}
// ═══ GitHub Filesystem Layer ══════════════════════════════════════════════════
/** Low-level wrapper around the GitHub Contents API and raw.githubusercontent.com. */
class GitHubFilesystem {
/**
* @param {object} config
* @param {string} config.owner
* @param {string} config.repo
* @param {string[]} config.tokens Array of GitHub PATs with content/workflows read/write and metadata/commits read scopes.
* @param {string} [config.branch='main'] Branch used for GitHub API reads/writes.
* @param {string[]} [config.rawBranches=['main']] Array of branches used for raw reads where the branch whose file has the most recent Last-Modified timestamp is used.
*/
constructor({ owner, repo, tokens, branch = 'main', rawBranches = null }) {
this.owner = owner
this.repo = repo
this.tokens = tokens
this.branch = branch
this.rawBranches = rawBranches ?? [branch]
this.preferredToken = 0
/** ETag cache for directory listings: path -> { etag, data } */
this.etagCache = new Map()
}
// ══ Request Helpers ═══════════════════════════════════════════════════════════
/**
* Pick a random token from the pool.
* @param {Set<string>} [exclude] Tokens to skip (already tried and failed).
* @returns {string|null} A token, or `null` if all are excluded.
*/
pickToken(exclude = new Set()) {
const preferred = this.tokens[this.preferredToken]
if (preferred && !exclude.has(preferred)) { return preferred }
const available = this.tokens.filter(token => !exclude.has(token))
if (!available.length) { return null }
const token = available[Math.floor(Math.random() * available.length)]
this.preferredToken = this.tokens.indexOf(token)
return token
}
/**
* Build Authorization headers for a specific token.
* @param {string} token
* @returns {object}
*/
headersForToken(token) {
return {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': GITHUB_API_VERSION,
}
}
/**
* Execute a request using a token from the pool.
* If the chosen token fails the call is retried with a different random token.
* @param {string} url
* @param {RequestInit} [init]
* @returns {Promise<Response>}
*/
async apiRequest(url, init = {}) {
const tried = new Set()
for (let attempt = 0; attempt < this.tokens.length; attempt++) {
const token = this.pickToken(tried)
if (!token) {
throw new DatabaseError('GitHub API request failed: all tokens in the pool are rate-limited or invalid', 429)
}
tried.add(token)
const response = await fetchWithTimeout(url, {
...init,
headers: { ...init.headers, ...this.headersForToken(token) }
})
if (this.isRateLimited(response)) {
if (tried.size < this.tokens.length) { continue }
this.throwRateLimitError(response)
}
if (response.status === 401) {
if (tried.size < this.tokens.length) { continue }
throw new DatabaseError('GitHub API authentication failed — check that your token is valid and has not expired', 401)
}
return response
}
throw new DatabaseError('GitHub API request failed: all tokens exhausted', 429)
}
/**
* Build the GitHub Contents API URL for a given file path.
* @param {string} filePath Repo-relative path (e.g. `data/posts/abc.json`).
* @returns {string}
*/
contentsUrl(filePath) {
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/')
return `${GITHUB_API_BASE}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}/contents/${encodedPath}`
}
/**
* Parse a failed GitHub API response and throw a DatabaseError.
* @param {Response} response
* @param {string} fallbackMessage
*/
async throwApiError(response, fallbackMessage) {
const body = await response.json().catch(() => ({}))
throw new DatabaseError(body.message || fallbackMessage, response.status)
}
throwRateLimitError(response) {
const resetTimestamp = response.headers.get('x-ratelimit-reset')
const resetMessage = resetTimestamp
? ` Resets at ${new Date(Number(resetTimestamp) * 1000).toISOString()}.`
: ''
throw new DatabaseError(`GitHub API rate limit exceeded.${resetMessage}`, 429)
}
isRateLimited(response) {
return response.status === 429
|| (response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0')
}
// ══ File Read Operations ══════════════════════════════════════════════════════
/**
* Fetches the freshest branch from `rawBranches` for a given file path by comparing HTTP Last-Modified headers.
* Falls back to the first branch if no timestamps are available.
* @param {string} filePath
* @returns {Promise<string>} The branch name with the most recently updated file.
*/
async fetchFreshestRaw(filePath) {
const results = await Promise.all(
this.rawBranches.map(async branch => {
const encodedBranch = branch.split('/').map(encodeURIComponent).join('/')
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/')
const encodedUrl = `${RAW_GITHUB_BASE}/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}/${encodedBranch}/${encodedPath}`
try {
const response = await fetchWithTimeout(encodedUrl, { cache: 'reload' })
if (!response.ok) { return { data: null, ms: -1 } }
let data = null
try { data = await response.json() } catch { }
const lastMod = response.headers.get('last-modified')
const ms = lastMod ? new Date(lastMod).getTime() : (data?.updatedAt ? new Date(data.updatedAt).getTime() : 0)
return { data, ms }
} catch {
return { data: null, ms: -1 }
}
})
)
const best = results.reduce((a, b) => (b.ms > a.ms ? b : a))
return best.data ?? null
}
/**
* Read a JSON file. Dispatches to raw.githubusercontent.com or the GitHub API (ETag cached).
* When using raw mode, the branch with the most recently updated file is selected from `rawBranches`.
* @param {string} filePath
* @param {boolean} [raw=false]
* @returns {Promise<any|{content: string,sha: string}|null>} raw -> parsed JSON | api -> { content, sha } | null
*/
async readFile(filePath, raw = false) {
if (raw) {
return this.fetchFreshestRaw(filePath)
}
const cached = this.etagCache.get(filePath)
const response = await this.apiRequest(`${this.contentsUrl(filePath)}?ref=${encodeURIComponent(this.branch)}`, {
headers: cached?.etag ? { 'If-None-Match': cached.etag } : {},
})
if (response.status === 304) { return cached.data }
if (response.status === 404) { return null }
if (this.isRateLimited(response)) { this.throwRateLimitError(response) }
if (!response.ok) { await this.throwApiError(response, `Read failed (${response.status})`) }
const data = await response.json()
if (Array.isArray(data)) { return null }
let parsedContent = null
try { parsedContent = decodeFileContent(data.content) } catch { }
const result = { content: parsedContent, sha: data.sha }
const etag = response.headers.get('etag')
if (etag) {
this.etagCache.set(filePath, { etag, data: result })
}
return result
}
/**
* Returns the files array from the directory index, or `null` if the index file does not exist yet.
* @param {string} dirPath
* @returns {Promise<string[]|null>}
*/
async readIndex(dirPath) {
const data = await this.readFile(`${dirPath}/_index.json`, true)
return data
}
/**
* Returns lightweight `{ name, type }` objects from the index, falling back to the API.
* @param {string} dirPath
* @returns {Promise<object[]>}
*/
async listDirectoryRaw(dirPath) {
const index = await this.readIndex(dirPath)
if (index === null) { return this.listDirectory(dirPath) }
const sha = index.updatedAt || ''
return (index.files ?? []).map(name => ({ name, type: 'file', sha }))
}
// ══ File Write / Delete Operations ════════════════════════════════════════════
/**
* Write (create or update) a file in the repo.
* Pass `raw: true` to write base64 content as-is (images/binaries).
*
* @param {string} filePath
* @param {object|string} content JSON object or raw base64 string.
* @param {string} commitMessage
* @param {string} [existingSha] Required for updates.
* @param {boolean} [isRaw=false]
* @returns {Promise<object>} GitHub API response.
* @throws {DatabaseError}
*/
async writeFile(filePath, content, commitMessage, existingSha, options = {}) {
const { raw: isRaw = false } = options
const body = {
message: commitMessage,
content: isRaw ? content : encodeFileContent(content),
branch: this.branch,
}
this.etagCache.delete(filePath)
if (existingSha) body.sha = existingSha
const response = await this.apiRequest(this.contentsUrl(filePath), {
method: 'PUT',
body: JSON.stringify(body),
})
if (!response.ok) {
await this.throwApiError(response, `Write failed (${response.status})`)
}
return response.json()
}
/**
* Delete a file from the repo.
* Returns `false` if the file did not exist, `true` on success.
* @param {string} filePath
* @param {string} commitMessage
* @param {string} [existingSha]
* @returns {Promise<boolean>}
*/
async deleteFile(filePath, commitMessage, existingSha) {
return retryOnConflict(async () => {
let sha = existingSha
if (!sha) {
this.etagCache.delete(filePath)
const existing = await this.readFile(filePath)
if (!existing) { return false }
sha = existing.sha
}
const response = await this.apiRequest(this.contentsUrl(filePath), {
method: 'DELETE',
body: JSON.stringify({ message: commitMessage, sha, branch: this.branch }),
})
if (!response.ok) { await this.throwApiError(response, `Delete failed (${response.status})`) }
return true
})
}
/**
* List the direct children of a directory.