javascript-solid-server 0.0.220 → 0.0.222
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/.claude/settings.local.json +31 -7
- package/package.json +1 -1
- package/src/handlers/container.js +7 -5
- package/src/handlers/pay.js +19 -3
- package/src/handlers/resource.js +37 -4
- package/src/ldp/headers.js +1 -1
- package/src/notifications/index.js +6 -2
- package/src/rdf/turtle.js +0 -0
- package/src/server.js +27 -0
- package/src/storage/quota.js +92 -7
- package/src/wac/parser.js +96 -19
- package/src/webledger.js +38 -1
- package/test/git-plugin-prefix.test.js +94 -0
- package/test/quota-reserve.test.js +85 -0
- package/test/wac.test.js +226 -4
- package/test/webledger-credit-once.test.js +106 -0
- package/test/websocket-registration.test.js +45 -0
|
@@ -1,14 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"permissions": {
|
|
3
3
|
"allow": [
|
|
4
|
-
"Bash(node bin/jss.js start:*)",
|
|
5
|
-
"Bash(node:*)",
|
|
6
|
-
"Bash(source ~/.nvm/nvm.sh)",
|
|
7
|
-
"Bash(nvm use:*)",
|
|
8
4
|
"Bash(gh issue *)",
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"Bash(
|
|
5
|
+
"WebFetch(domain:did-nostr.com)",
|
|
6
|
+
"WebFetch(domain:nostrcg.github.io)",
|
|
7
|
+
"Bash(node --test test/nostr-key-parity.test.js)",
|
|
8
|
+
"Bash(node --test test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js test/keys-provision.test.js test/keys-provision-integration.test.js test/nostr-event.test.js test/well-known-nostr-json.test.js)",
|
|
9
|
+
"Bash(npm test *)",
|
|
10
|
+
"Bash(git checkout *)",
|
|
11
|
+
"Bash(git add *)",
|
|
12
|
+
"Bash(cd *)",
|
|
13
|
+
"Bash(git push *)",
|
|
14
|
+
"Bash(gh pr create --base gh-pages --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
|
|
15
|
+
"Bash(gh pr create --repo JavaScriptSolidServer/JavaScriptSolidServer --base gh-pages --head issue-571-multikey-jwk-parity-consistency --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
|
|
16
|
+
"Bash(gh pr *)",
|
|
17
|
+
"Bash(gh api *)",
|
|
18
|
+
"Bash(node --test test/nostr-key-parity.test.js test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js)",
|
|
19
|
+
"Bash(git commit *)",
|
|
20
|
+
"Bash(git config *)",
|
|
21
|
+
"Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --msg-filter 'grep -v -e \"^Co-Authored-By: Claude\" -e \"Generated with \\\\[Claude Code\\\\]\"' gh-pages..HEAD)",
|
|
22
|
+
"Bash(git fetch *)",
|
|
23
|
+
"Bash(git ls-remote *)",
|
|
24
|
+
"Bash(echo \"exit=$?\")",
|
|
25
|
+
"Bash(cd /home/melvin/.claude/projects/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/memory/)",
|
|
26
|
+
"Bash(cat MEMORY.md)",
|
|
27
|
+
"Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --env-filter ' *)",
|
|
28
|
+
"Bash(git pull *)",
|
|
29
|
+
"Bash(git branch *)",
|
|
30
|
+
"Bash(git remote *)",
|
|
31
|
+
"Bash(node --check src/handlers/container.js)",
|
|
32
|
+
"Bash(node --test /tmp/claude-1000/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/47629faf-bc8f-4e26-9878-091c550812d5/scratchpad/repro.test.js)",
|
|
33
|
+
"Bash(node --test test/auth.test.js)",
|
|
34
|
+
"Bash(git stash *)",
|
|
35
|
+
"Bash(node --check src/wac/checker.js)"
|
|
12
36
|
]
|
|
13
37
|
}
|
|
14
38
|
}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as storage from '../storage/filesystem.js';
|
|
2
|
-
import { initializeQuota,
|
|
2
|
+
import { initializeQuota, reserveQuota, updateQuotaUsage } from '../storage/quota.js';
|
|
3
3
|
import { getAllHeaders } from '../ldp/headers.js';
|
|
4
4
|
import { isContainer, getEffectiveUrlPath, getPodName } from '../utils/url.js';
|
|
5
5
|
import { generateProfile, generatePreferences, generateTypeIndex, serialize } from '../webid/profile.js';
|
|
@@ -159,8 +159,10 @@ export async function handlePost(request, reply) {
|
|
|
159
159
|
|
|
160
160
|
// Check storage quota before writing (skip in public mode - no pod structure)
|
|
161
161
|
const podName = request.config?.public ? null : getPodName(request);
|
|
162
|
+
// Atomically reserve before writing so concurrent creates can't both pass
|
|
163
|
+
// the check and overshoot the limit; release the reservation on failure.
|
|
162
164
|
if (podName) {
|
|
163
|
-
const { allowed, error } = await
|
|
165
|
+
const { allowed, error } = await reserveQuota(podName, content.length, request.defaultQuota || 0);
|
|
164
166
|
if (!allowed) {
|
|
165
167
|
return reply.code(507).send({ error: 'Insufficient Storage', message: error });
|
|
166
168
|
}
|
|
@@ -168,9 +170,9 @@ export async function handlePost(request, reply) {
|
|
|
168
170
|
|
|
169
171
|
success = await storage.write(newStoragePath, content);
|
|
170
172
|
|
|
171
|
-
//
|
|
172
|
-
if (success && podName) {
|
|
173
|
-
await updateQuotaUsage(podName, content.length);
|
|
173
|
+
// reserveQuota already recorded the usage; release it if the write failed.
|
|
174
|
+
if (!success && podName) {
|
|
175
|
+
await updateQuotaUsage(podName, -content.length);
|
|
174
176
|
}
|
|
175
177
|
}
|
|
176
178
|
|
package/src/handlers/pay.js
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
|
|
28
28
|
import crypto from 'crypto';
|
|
29
29
|
import { getNostrPubkey, pubkeyToDidNostr } from '../auth/nostr.js';
|
|
30
|
-
import { readLedger, writeLedger, getBalance, credit, debit } from '../webledger.js';
|
|
30
|
+
import { readLedger, writeLedger, getBalance, credit, creditOnce, debit } from '../webledger.js';
|
|
31
31
|
import { verifyMrc20Deposit, verifyMrc20Anchor, jcs, btAddress } from '../mrc20.js';
|
|
32
32
|
import { loadTrail, transferToken, buildTransaction, broadcastTx, p2trScript, btDeriveChainedPrivkey } from '../token.js';
|
|
33
33
|
import { secp256k1 } from '@noble/curves/secp256k1';
|
|
@@ -319,6 +319,7 @@ export function createPayHandler(options = {}) {
|
|
|
319
319
|
const utxos = await loadUtxos();
|
|
320
320
|
const ledger = await readLedger();
|
|
321
321
|
let credited = 0;
|
|
322
|
+
let appended = false;
|
|
322
323
|
|
|
323
324
|
for (const chainId of payChains) {
|
|
324
325
|
const chain = CHAIN_REGISTRY[chainId];
|
|
@@ -341,14 +342,29 @@ export function createPayHandler(options = {}) {
|
|
|
341
342
|
}
|
|
342
343
|
} catch { /* best effort */ }
|
|
343
344
|
const currency = chain.unit;
|
|
344
|
-
credit
|
|
345
|
+
// Idempotent credit keyed on the outpoint: the balance and the
|
|
346
|
+
// "already counted" marker commit together in the ledger, so a
|
|
347
|
+
// crash before saveUtxos below can't double-credit on the next
|
|
348
|
+
// balance poll (the scanner re-runs on every GET /pay/.balance).
|
|
349
|
+
const depositKey = `${chainId}:${u.txid}:${u.vout}`;
|
|
350
|
+
const { credited: didCredit } = creditOnce(ledger, depositKey, didUri, u.value, currency);
|
|
345
351
|
utxos.push({ txid: u.txid, vout: u.vout, amount: u.value, scriptpubkey, chain: chainId, tweak: didUri, spent: false });
|
|
346
|
-
|
|
352
|
+
appended = true;
|
|
353
|
+
if (didCredit) credited += u.value;
|
|
347
354
|
}
|
|
348
355
|
}
|
|
349
356
|
|
|
357
|
+
// Ledger first: a crash before saveUtxos leaves the credit recorded
|
|
358
|
+
// together with its idempotency key, so the rescan is a no-op rather
|
|
359
|
+
// than a double-credit. The reverse order would under-credit.
|
|
350
360
|
if (credited > 0) {
|
|
351
361
|
await writeLedger(ledger);
|
|
362
|
+
}
|
|
363
|
+
// Keyed on `appended`, not `credited`: a replayed outpoint credits
|
|
364
|
+
// nothing (didCredit === false) but must still land in the cache.
|
|
365
|
+
// Otherwise the crash window never heals — the scanner re-queries the
|
|
366
|
+
// explorer for that outpoint on every single balance poll.
|
|
367
|
+
if (appended) {
|
|
352
368
|
await saveUtxos(utxos);
|
|
353
369
|
}
|
|
354
370
|
} catch { /* scan failure is non-fatal */ }
|
package/src/handlers/resource.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as storage from '../storage/filesystem.js';
|
|
2
|
-
import {
|
|
2
|
+
import { reserveQuota, updateQuotaUsage } from '../storage/quota.js';
|
|
3
3
|
import { getAllHeaders, getNotFoundHeaders } from '../ldp/headers.js';
|
|
4
4
|
import { generateContainerJsonLd, serializeJsonLd } from '../ldp/container.js';
|
|
5
5
|
import { isContainer, getContentType, isRdfContentType, getEffectiveUrlPath, safeJsonParse, getPodName } from '../utils/url.js';
|
|
@@ -17,6 +17,10 @@ import { emitChange } from '../notifications/events.js';
|
|
|
17
17
|
import { checkIfMatch, checkIfNoneMatchForGet, checkIfNoneMatchForWrite } from '../utils/conditional.js';
|
|
18
18
|
import { generateDatabrowserHtml, generateModuleDatabrowserHtml, shouldServeMashlib, DATA_ISLAND_MAX_BYTES } from '../mashlib/index.js';
|
|
19
19
|
import { turtleToJsonLd } from '../rdf/turtle.js';
|
|
20
|
+
import { parseAcl, grantsAccess } from '../wac/parser.js';
|
|
21
|
+
|
|
22
|
+
// Shared by the PUT and PATCH guards for .acl resources (#631).
|
|
23
|
+
const ACL_GRANTS_NOTHING = 'ACL document has no authorization that grants a mode to an agent, agent class or group; refusing to store it, as it would grant nobody access.';
|
|
20
24
|
|
|
21
25
|
/**
|
|
22
26
|
* Live reload script - injected into HTML when --live-reload is enabled
|
|
@@ -974,6 +978,24 @@ export async function handlePut(request, reply) {
|
|
|
974
978
|
});
|
|
975
979
|
}
|
|
976
980
|
|
|
981
|
+
// An ACL that parses to no authorizations would lock everyone out of the
|
|
982
|
+
// resource (and of the .acl itself, so it couldn't be repaired over HTTP).
|
|
983
|
+
// Refuse it up front instead of storing it. See #631.
|
|
984
|
+
if (urlPath.endsWith('.acl')) {
|
|
985
|
+
let aclDoc = request.body;
|
|
986
|
+
if (Buffer.isBuffer(aclDoc)) aclDoc = aclDoc.toString('utf8');
|
|
987
|
+
if (typeof aclDoc === 'string') {
|
|
988
|
+
try {
|
|
989
|
+
aclDoc = safeJsonParse(aclDoc);
|
|
990
|
+
} catch (e) {
|
|
991
|
+
return reply.code(400).send({ error: 'Bad Request', message: 'ACL body is not valid JSON: ' + e.message });
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
if (!grantsAccess(await parseAcl(aclDoc, resourceUrl))) {
|
|
995
|
+
return reply.code(400).send({ error: 'Bad Request', message: ACL_GRANTS_NOTHING });
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
977
999
|
// Check if we can accept this input type
|
|
978
1000
|
if (!canAcceptInput(contentType, connegEnabled)) {
|
|
979
1001
|
const acceptValue = connegEnabled
|
|
@@ -1045,8 +1067,11 @@ export async function handlePut(request, reply) {
|
|
|
1045
1067
|
const oldSize = stats?.size || 0;
|
|
1046
1068
|
const sizeDelta = content.length - oldSize;
|
|
1047
1069
|
|
|
1070
|
+
// Atomically reserve the growth before writing so concurrent writers can't
|
|
1071
|
+
// both pass the check and overshoot the limit. reserveQuota commits the
|
|
1072
|
+
// reservation, so we must release it if the write then fails.
|
|
1048
1073
|
if (podName && sizeDelta > 0) {
|
|
1049
|
-
const { allowed, error } = await
|
|
1074
|
+
const { allowed, error } = await reserveQuota(podName, sizeDelta, request.defaultQuota || 0);
|
|
1050
1075
|
if (!allowed) {
|
|
1051
1076
|
return reply.code(507).send({ error: 'Insufficient Storage', message: error });
|
|
1052
1077
|
}
|
|
@@ -1054,11 +1079,14 @@ export async function handlePut(request, reply) {
|
|
|
1054
1079
|
|
|
1055
1080
|
const success = await storage.write(storagePath, content);
|
|
1056
1081
|
if (!success) {
|
|
1082
|
+
if (podName && sizeDelta > 0) {
|
|
1083
|
+
await updateQuotaUsage(podName, -sizeDelta); // release the reservation
|
|
1084
|
+
}
|
|
1057
1085
|
return reply.code(500).send({ error: 'Write failed' });
|
|
1058
1086
|
}
|
|
1059
1087
|
|
|
1060
|
-
//
|
|
1061
|
-
if (podName && sizeDelta
|
|
1088
|
+
// Growth was already recorded by reserveQuota; only a shrink needs recording.
|
|
1089
|
+
if (podName && sizeDelta < 0) {
|
|
1062
1090
|
await updateQuotaUsage(podName, sizeDelta);
|
|
1063
1091
|
}
|
|
1064
1092
|
|
|
@@ -1379,6 +1407,11 @@ export async function handlePatch(request, reply) {
|
|
|
1379
1407
|
}
|
|
1380
1408
|
}
|
|
1381
1409
|
|
|
1410
|
+
// A patch must not leave an ACL that grants nobody access (#631).
|
|
1411
|
+
if (urlPath.endsWith('.acl') && !grantsAccess(await parseAcl(updatedDocument, resourceUrl))) {
|
|
1412
|
+
return reply.code(409).send({ error: 'Conflict', message: ACL_GRANTS_NOTHING });
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1382
1415
|
// Write updated document
|
|
1383
1416
|
let updatedContent;
|
|
1384
1417
|
if (htmlWrapper) {
|
package/src/ldp/headers.js
CHANGED
|
@@ -96,7 +96,7 @@ export function getCorsHeaders(origin) {
|
|
|
96
96
|
'Access-Control-Allow-Origin': origin || '*',
|
|
97
97
|
'Access-Control-Allow-Methods': 'GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS',
|
|
98
98
|
'Access-Control-Allow-Headers': 'Accept, Authorization, Content-Type, DPoP, If-Match, If-None-Match, Link, Range, Slug, Origin',
|
|
99
|
-
'Access-Control-Expose-Headers': 'Accept-Patch, Accept-Post, Accept-Ranges, Allow, Content-Length, Content-Range, Content-Type, ETag, Link, Location, Updates-Via, WAC-Allow, X-Cost, X-Balance, X-Pay-Currency',
|
|
99
|
+
'Access-Control-Expose-Headers': 'Accept-Patch, Accept-Post, Accept-Query, Accept-Ranges, Allow, Content-Length, Content-Range, Content-Type, ETag, Last-Modified, Link, Location, Updates-Via, WAC-Allow, WWW-Authenticate, X-Cost, X-Balance, X-Pay-Currency',
|
|
100
100
|
'Access-Control-Allow-Credentials': 'true',
|
|
101
101
|
'Access-Control-Max-Age': '86400'
|
|
102
102
|
};
|
|
@@ -27,8 +27,12 @@ export { emitChange } from './events.js';
|
|
|
27
27
|
* @param {object} options
|
|
28
28
|
*/
|
|
29
29
|
export async function notificationsPlugin(fastify, options) {
|
|
30
|
-
// Register the WebSocket plugin
|
|
31
|
-
|
|
30
|
+
// Register the WebSocket plugin unless the root already did (it normally
|
|
31
|
+
// has; see the note in server.js). Registering again would add a second
|
|
32
|
+
// 'upgrade' listener to the shared HTTP server (#545).
|
|
33
|
+
if (!fastify.websocketServer) {
|
|
34
|
+
await fastify.register(websocket);
|
|
35
|
+
}
|
|
32
36
|
|
|
33
37
|
// WebSocket route for notifications (dedicated path to avoid route conflicts)
|
|
34
38
|
// Clients discover this via Updates-Via header
|
package/src/rdf/turtle.js
CHANGED
|
Binary file
|
package/src/server.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import Fastify from 'fastify';
|
|
2
2
|
import sjson from 'secure-json-parse';
|
|
3
3
|
import rateLimit from '@fastify/rate-limit';
|
|
4
|
+
import websocket from '@fastify/websocket';
|
|
4
5
|
import { readFile } from 'fs/promises';
|
|
5
6
|
import { readFileSync } from 'fs';
|
|
6
7
|
import { STATUS_CODES } from 'node:http';
|
|
@@ -391,6 +392,21 @@ export function createServer(options = {}) {
|
|
|
391
392
|
}, `${request.method} ${request.url} ${reply.statusCode} ${Math.round(reply.elapsedTime)}ms`);
|
|
392
393
|
});
|
|
393
394
|
|
|
395
|
+
// @fastify/websocket must be registered exactly once, here at the root.
|
|
396
|
+
// Every registration adds an 'upgrade' listener to the one shared HTTP
|
|
397
|
+
// server, and the websocketServer decorator it sets is scoped to the
|
|
398
|
+
// registering context, so a child plugin's `if (!fastify.websocketServer)`
|
|
399
|
+
// guard cannot see a sibling plugin's registration. Registering at the root
|
|
400
|
+
// makes the decorator visible to all children, so each guard below skips
|
|
401
|
+
// and the server keeps a single listener. With one listener per feature,
|
|
402
|
+
// every upgrade logged N-1 spurious "websocket upgrade failed" warnings
|
|
403
|
+
// (ERR_HTTP_SOCKET_ASSIGNED) — see #545.
|
|
404
|
+
const websocketNeeded = notificationsEnabled || liveReloadEnabled || nostrEnabled
|
|
405
|
+
|| webrtcEnabled || terminalEnabled || tunnelEnabled || pluginEntries.length > 0;
|
|
406
|
+
if (websocketNeeded) {
|
|
407
|
+
fastify.register(websocket);
|
|
408
|
+
}
|
|
409
|
+
|
|
394
410
|
// Register WebSocket notifications plugin if enabled (or live reload needs it)
|
|
395
411
|
if (notificationsEnabled || liveReloadEnabled) {
|
|
396
412
|
fastify.register(notificationsPlugin);
|
|
@@ -612,6 +628,17 @@ export function createServer(options = {}) {
|
|
|
612
628
|
return;
|
|
613
629
|
}
|
|
614
630
|
|
|
631
|
+
// App plugins own their prefix (#206, #616): a plugin that serves git
|
|
632
|
+
// smart-HTTP under its mount (the forge at /forge/<owner>/<name>.git)
|
|
633
|
+
// does its own authorization and runs its own backend. Core's git lane
|
|
634
|
+
// is for the pod's repos; a git-looking URL below an app path falls
|
|
635
|
+
// through to the plugin, exactly as the WAC hook and the dotfile guard
|
|
636
|
+
// already defer to appPaths. Read per request: activation pushes entries.
|
|
637
|
+
const urlNoQuery = request.url.split('?')[0];
|
|
638
|
+
if (appPaths.some(p => urlNoQuery === p || urlNoQuery.startsWith(p + '/'))) {
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
|
|
615
642
|
// Determine required mode: Write for push, Read for clone/fetch
|
|
616
643
|
const needsWrite = isGitWriteOperation(request.url);
|
|
617
644
|
const requiredMode = needsWrite ? AccessMode.WRITE : AccessMode.READ;
|
package/src/storage/quota.js
CHANGED
|
@@ -13,6 +13,35 @@ const QUOTA_FILE = '.quota.json';
|
|
|
13
13
|
// between writeFile and rename) doesn't inflate pod usage.
|
|
14
14
|
const QUOTA_TMP_PREFIX = `${QUOTA_FILE}.tmp.`;
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Per-pod serialization of read-modify-write on .quota.json.
|
|
18
|
+
*
|
|
19
|
+
* saveQuota is already atomic (temp file + rename), which stops a concurrent
|
|
20
|
+
* reader from seeing a truncated file (#309). But atomicity of a single write
|
|
21
|
+
* does not stop a lost update: two writers that both `loadQuota` the same
|
|
22
|
+
* `used` value, each add their bytes and `saveQuota`, race to clobber one
|
|
23
|
+
* another — and, worse, both can pass a `checkQuota` before either records its
|
|
24
|
+
* usage, letting concurrent writes overshoot the limit. Serializing the whole
|
|
25
|
+
* load→mutate→save critical section per pod closes both windows. This mirrors
|
|
26
|
+
* QuotaPolicy::reserve in the solid-pod-rs parity port, which holds a per-pod
|
|
27
|
+
* lock for atomic check-and-commit.
|
|
28
|
+
*/
|
|
29
|
+
const podLocks = new Map();
|
|
30
|
+
|
|
31
|
+
function withPodLock(podName, fn) {
|
|
32
|
+
const prev = podLocks.get(podName) || Promise.resolve();
|
|
33
|
+
// Chain onto the previous holder regardless of how it settled.
|
|
34
|
+
const run = prev.then(fn, fn);
|
|
35
|
+
// Store a tail that never rejects so the chain can't wedge on an error.
|
|
36
|
+
const tail = run.then(() => {}, () => {});
|
|
37
|
+
podLocks.set(podName, tail);
|
|
38
|
+
// Opportunistic cleanup so the map doesn't grow unbounded across many pods.
|
|
39
|
+
tail.then(() => {
|
|
40
|
+
if (podLocks.get(podName) === tail) podLocks.delete(podName);
|
|
41
|
+
});
|
|
42
|
+
return run;
|
|
43
|
+
}
|
|
44
|
+
|
|
16
45
|
/**
|
|
17
46
|
* Get quota file path for a pod
|
|
18
47
|
*/
|
|
@@ -168,19 +197,75 @@ export async function checkQuota(podName, additionalBytes, defaultQuota) {
|
|
|
168
197
|
}
|
|
169
198
|
|
|
170
199
|
/**
|
|
171
|
-
*
|
|
200
|
+
* Atomically reserve quota for a pending write: check-and-commit under a
|
|
201
|
+
* per-pod lock so concurrent writers cannot both pass the check and then
|
|
202
|
+
* overshoot the limit. On success the reserved bytes are already recorded in
|
|
203
|
+
* `used`, so callers must NOT also call updateQuotaUsage for the same bytes —
|
|
204
|
+
* instead, release the reservation with `updateQuotaUsage(pod, -bytes)` if the
|
|
205
|
+
* write subsequently fails.
|
|
206
|
+
*
|
|
207
|
+
* This is the authoritative enforcement point and the only one the write path
|
|
208
|
+
* uses. checkQuota remains exported as a lock-free read-only probe for callers
|
|
209
|
+
* that want to inspect headroom without reserving it, but it performs no
|
|
210
|
+
* pre-check for PUT/POST any more — do not go looking for one. Mirrors
|
|
211
|
+
* QuotaPolicy::reserve in the solid-pod-rs parity port.
|
|
212
|
+
*
|
|
213
|
+
* @param {string} podName - The pod name
|
|
214
|
+
* @param {number} additionalBytes - Bytes to reserve (expected >= 0)
|
|
215
|
+
* @param {number} defaultQuota - Default quota limit
|
|
216
|
+
* @returns {Promise<{allowed: boolean, quota: object, error?: string}>}
|
|
217
|
+
*/
|
|
218
|
+
export async function reserveQuota(podName, additionalBytes, defaultQuota) {
|
|
219
|
+
return withPodLock(podName, async () => {
|
|
220
|
+
let quota = await loadQuota(podName);
|
|
221
|
+
|
|
222
|
+
// Initialize limit from the default on first use, preserving any usage
|
|
223
|
+
// reconciled from a recovered corrupt/empty file (see checkQuota).
|
|
224
|
+
if (quota.limit === 0 && defaultQuota > 0) {
|
|
225
|
+
quota = { limit: defaultQuota, used: quota.used };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// No enforcement (and no tracking) when no limit is in effect — matches
|
|
229
|
+
// updateQuotaUsage, which skips uninitialized quotas.
|
|
230
|
+
if (quota.limit === 0) {
|
|
231
|
+
return { allowed: true, quota };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const projectedUsage = quota.used + additionalBytes;
|
|
235
|
+
|
|
236
|
+
if (additionalBytes > 0 && projectedUsage > quota.limit) {
|
|
237
|
+
const usedMB = (quota.used / (1024 * 1024)).toFixed(2);
|
|
238
|
+
const limitMB = (quota.limit / (1024 * 1024)).toFixed(2);
|
|
239
|
+
return {
|
|
240
|
+
allowed: false,
|
|
241
|
+
quota,
|
|
242
|
+
error: `Storage quota exceeded. Used: ${usedMB}MB / ${limitMB}MB`
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Commit the reservation as part of the same locked critical section.
|
|
247
|
+
quota.used = Math.max(0, projectedUsage);
|
|
248
|
+
await saveQuota(podName, quota);
|
|
249
|
+
return { allowed: true, quota };
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Update quota usage after a write (or to release a reservation).
|
|
172
255
|
* @param {string} podName - The pod name
|
|
173
256
|
* @param {number} bytesChange - Bytes added (positive) or removed (negative)
|
|
174
257
|
*/
|
|
175
258
|
export async function updateQuotaUsage(podName, bytesChange) {
|
|
176
|
-
|
|
259
|
+
return withPodLock(podName, async () => {
|
|
260
|
+
const quota = await loadQuota(podName);
|
|
177
261
|
|
|
178
|
-
|
|
179
|
-
|
|
262
|
+
// Skip if no quota initialized
|
|
263
|
+
if (quota.limit === 0) return quota;
|
|
180
264
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
265
|
+
quota.used = Math.max(0, quota.used + bytesChange);
|
|
266
|
+
await saveQuota(podName, quota);
|
|
267
|
+
return quota;
|
|
268
|
+
});
|
|
184
269
|
}
|
|
185
270
|
|
|
186
271
|
/**
|
package/src/wac/parser.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Parses ACL files (JSON-LD or Turtle) into authorization rules
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { turtleToJsonLd } from '../rdf/turtle.js';
|
|
6
|
+
import { turtleToJsonLd, expandUri } from '../rdf/turtle.js';
|
|
7
7
|
import { safeJsonParse } from '../utils/url.js';
|
|
8
8
|
|
|
9
9
|
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
@@ -57,9 +57,17 @@ export async function parseAcl(content, aclUrl) {
|
|
|
57
57
|
// Handle @graph array or single object
|
|
58
58
|
const nodes = Array.isArray(doc) ? doc : (doc['@graph'] || [doc]);
|
|
59
59
|
|
|
60
|
+
// The document's @context (plus any node-level @context) decides what the
|
|
61
|
+
// keys mean. Contexts are merged leniently across the whole document, as
|
|
62
|
+
// jsonLdToTurtle does; remote context URLs are never fetched (#389).
|
|
63
|
+
const docContext = mergeContext({}, Array.isArray(doc) ? undefined : doc['@context']);
|
|
64
|
+
|
|
60
65
|
for (const node of nodes) {
|
|
61
|
-
if (
|
|
62
|
-
|
|
66
|
+
if (!node || typeof node !== 'object') continue;
|
|
67
|
+
const context = mergeContext(docContext, node['@context']);
|
|
68
|
+
const expanded = expandNode(node, context);
|
|
69
|
+
if (isAuthorization(expanded, context)) {
|
|
70
|
+
const auth = parseAuthorization(expanded, context, aclUrl);
|
|
63
71
|
if (auth) {
|
|
64
72
|
authorizations.push(auth);
|
|
65
73
|
}
|
|
@@ -69,18 +77,89 @@ export async function parseAcl(content, aclUrl) {
|
|
|
69
77
|
return authorizations;
|
|
70
78
|
}
|
|
71
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Merge a JSON-LD @context value (object, or array of objects / strings) into
|
|
82
|
+
* an accumulated context object. String entries (remote contexts) are skipped
|
|
83
|
+
* on purpose — JSS never dereferences contexts at parse time (#389).
|
|
84
|
+
*/
|
|
85
|
+
function mergeContext(base, ctx) {
|
|
86
|
+
if (!ctx) return base;
|
|
87
|
+
const entries = Array.isArray(ctx) ? ctx : [ctx];
|
|
88
|
+
let merged = base;
|
|
89
|
+
for (const entry of entries) {
|
|
90
|
+
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
|
|
91
|
+
merged = { ...merged, ...entry };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return merged;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Expand a property key or @type value to a full IRI. Falls back to @vocab
|
|
99
|
+
* for bare terms the context doesn't define.
|
|
100
|
+
*/
|
|
101
|
+
function expandTerm(term, context) {
|
|
102
|
+
if (typeof term !== 'string' || !term) return term;
|
|
103
|
+
const expanded = expandUri(term, context);
|
|
104
|
+
if (expanded === term && !term.includes(':') && typeof context['@vocab'] === 'string') {
|
|
105
|
+
return context['@vocab'] + term;
|
|
106
|
+
}
|
|
107
|
+
return expanded;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Return a view of the node keyed by full predicate IRIs (#631). Keyword
|
|
112
|
+
* entries (`@id`, `@type`, …) are kept as-is. Keys that expand to the same
|
|
113
|
+
* IRI (e.g. `acl:mode` and the expanded form in one node) are concatenated.
|
|
114
|
+
*/
|
|
115
|
+
function expandNode(node, context) {
|
|
116
|
+
const out = {};
|
|
117
|
+
for (const [key, value] of Object.entries(node)) {
|
|
118
|
+
const iri = key.startsWith('@') ? key : expandTerm(key, context);
|
|
119
|
+
if (iri in out && !key.startsWith('@')) {
|
|
120
|
+
out[iri] = [].concat(out[iri], value);
|
|
121
|
+
} else {
|
|
122
|
+
out[iri] = value;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Read an ACL property from an expanded node. The full IRI is what a
|
|
130
|
+
* correctly-expanded key becomes; the `acl:`-prefixed and bare forms are
|
|
131
|
+
* kept as fallbacks for documents without any usable context.
|
|
132
|
+
*/
|
|
133
|
+
function aclProp(node, term) {
|
|
134
|
+
return node[`${ACL}${term}`] ?? node[`acl:${term}`] ?? node[term];
|
|
135
|
+
}
|
|
136
|
+
|
|
72
137
|
/**
|
|
73
138
|
* Check if node is an Authorization
|
|
74
139
|
*/
|
|
75
|
-
function isAuthorization(node) {
|
|
140
|
+
function isAuthorization(node, context = {}) {
|
|
76
141
|
const type = node['@type'];
|
|
77
142
|
if (!type) return false;
|
|
78
143
|
|
|
79
144
|
const types = Array.isArray(type) ? type : [type];
|
|
80
|
-
return types.some(t =>
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
145
|
+
return types.some(t => {
|
|
146
|
+
const full = expandTerm(t, context);
|
|
147
|
+
return full === `${ACL}Authorization` || t === 'Authorization';
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* True when at least one authorization can grant something: it names a mode
|
|
153
|
+
* and an agent, agent class or group. An ACL for which this is false grants
|
|
154
|
+
* nobody access, including the writer, so writes that would leave a resource
|
|
155
|
+
* with such an ACL are refused (#631).
|
|
156
|
+
* @param {Array<Authorization>} authorizations
|
|
157
|
+
* @returns {boolean}
|
|
158
|
+
*/
|
|
159
|
+
export function grantsAccess(authorizations) {
|
|
160
|
+
return authorizations.some(a =>
|
|
161
|
+
a.modes.length > 0 &&
|
|
162
|
+
(a.agents.length > 0 || a.agentClasses.length > 0 || a.agentGroups.length > 0)
|
|
84
163
|
);
|
|
85
164
|
}
|
|
86
165
|
|
|
@@ -123,8 +202,9 @@ function resolveUri(uri, baseUrl) {
|
|
|
123
202
|
/**
|
|
124
203
|
* Parse a single Authorization node
|
|
125
204
|
*/
|
|
126
|
-
function parseAuthorization(node, aclUrl) {
|
|
205
|
+
function parseAuthorization(node, context, aclUrl) {
|
|
127
206
|
const baseUrl = getBaseUrl(aclUrl);
|
|
207
|
+
const uris = term => parseUriArray(aclProp(node, term)).map(u => expandUri(u, context));
|
|
128
208
|
|
|
129
209
|
const auth = {
|
|
130
210
|
id: node['@id'],
|
|
@@ -138,28 +218,25 @@ function parseAuthorization(node, aclUrl) {
|
|
|
138
218
|
};
|
|
139
219
|
|
|
140
220
|
// Parse accessTo - resolve relative URLs
|
|
141
|
-
auth.accessTo =
|
|
142
|
-
.map(uri => resolveUri(uri, baseUrl));
|
|
221
|
+
auth.accessTo = uris('accessTo').map(uri => resolveUri(uri, baseUrl));
|
|
143
222
|
|
|
144
223
|
// Parse default (for containers) - resolve relative URLs
|
|
145
|
-
auth.default =
|
|
146
|
-
.map(uri => resolveUri(uri, baseUrl));
|
|
224
|
+
auth.default = uris('default').map(uri => resolveUri(uri, baseUrl));
|
|
147
225
|
|
|
148
226
|
// Parse agents (WebIDs can be relative too) - resolve against ACL URL
|
|
149
|
-
auth.agents =
|
|
150
|
-
.map(uri => resolveUri(uri, aclUrl));
|
|
227
|
+
auth.agents = uris('agent').map(uri => resolveUri(uri, aclUrl));
|
|
151
228
|
|
|
152
229
|
// Parse agentClass
|
|
153
|
-
auth.agentClasses =
|
|
230
|
+
auth.agentClasses = uris('agentClass');
|
|
154
231
|
|
|
155
232
|
// Parse agentGroup
|
|
156
|
-
auth.agentGroups =
|
|
233
|
+
auth.agentGroups = uris('agentGroup');
|
|
157
234
|
|
|
158
235
|
// Parse modes
|
|
159
|
-
auth.modes =
|
|
236
|
+
auth.modes = uris('mode').map(normalizeMode);
|
|
160
237
|
|
|
161
238
|
// Parse conditions
|
|
162
|
-
auth.conditions = parseConditions(node
|
|
239
|
+
auth.conditions = parseConditions(aclProp(node, 'condition'));
|
|
163
240
|
|
|
164
241
|
return auth;
|
|
165
242
|
}
|
package/src/webledger.js
CHANGED
|
@@ -34,7 +34,11 @@ export function createLedger(options = {}) {
|
|
|
34
34
|
defaultCurrency: options.defaultCurrency ?? 'satoshi',
|
|
35
35
|
created: now,
|
|
36
36
|
updated: now,
|
|
37
|
-
entries: []
|
|
37
|
+
entries: [],
|
|
38
|
+
// Idempotency keys for deposits already absorbed into balances. Seeded
|
|
39
|
+
// here so a freshly created ledger has the same shape readLedger's
|
|
40
|
+
// migration produces for a legacy one.
|
|
41
|
+
credited: []
|
|
38
42
|
};
|
|
39
43
|
}
|
|
40
44
|
|
|
@@ -56,6 +60,11 @@ export async function readLedger(ledgerPath = DEFAULT_PATH) {
|
|
|
56
60
|
if (!ledger.defaultCurrency) ledger.defaultCurrency = 'satoshi';
|
|
57
61
|
if (!ledger.created) ledger.created = Math.floor(Date.now() / 1000);
|
|
58
62
|
if (!ledger.entries) ledger.entries = [];
|
|
63
|
+
// Idempotency keys for deposits already absorbed into balances. Kept in
|
|
64
|
+
// the ledger itself so crediting is crash-safe: the balance and the "this
|
|
65
|
+
// deposit was counted" marker commit together in one writeLedger, instead
|
|
66
|
+
// of the balance landing in one file and the spent-marker in another.
|
|
67
|
+
if (!ledger.credited) ledger.credited = [];
|
|
59
68
|
return ledger;
|
|
60
69
|
} catch {
|
|
61
70
|
return createLedger();
|
|
@@ -164,6 +173,34 @@ export function debit(ledger, uri, amount, currency) {
|
|
|
164
173
|
return { success: true, balance: newBalance };
|
|
165
174
|
}
|
|
166
175
|
|
|
176
|
+
/**
|
|
177
|
+
* Idempotently credit a keyed deposit exactly once.
|
|
178
|
+
*
|
|
179
|
+
* The dedup key (e.g. `${chain}:${txid}:${vout}` for an on-chain UTXO) is
|
|
180
|
+
* recorded in the ledger's own `credited` list, so the balance increment and
|
|
181
|
+
* the "already counted" marker are committed together by a single writeLedger.
|
|
182
|
+
* A crash after that single write can never re-credit the same deposit — which
|
|
183
|
+
* is exactly what happened when the credit and the UTXO-spent record lived in
|
|
184
|
+
* two separate files written one after another.
|
|
185
|
+
*
|
|
186
|
+
* @param {object} ledger - WebLedger object (must be persisted afterwards)
|
|
187
|
+
* @param {string} key - Stable idempotency key for this deposit
|
|
188
|
+
* @param {string} uri - Agent URI
|
|
189
|
+
* @param {number} amount - Amount to add
|
|
190
|
+
* @param {string} [currency] - Currency code
|
|
191
|
+
* @returns {{credited: boolean, balance: number}} `credited` is false when the
|
|
192
|
+
* key was already absorbed (no change made)
|
|
193
|
+
*/
|
|
194
|
+
export function creditOnce(ledger, key, uri, amount, currency) {
|
|
195
|
+
if (!ledger.credited) ledger.credited = [];
|
|
196
|
+
if (ledger.credited.includes(key)) {
|
|
197
|
+
return { credited: false, balance: getBalance(ledger, uri, currency) };
|
|
198
|
+
}
|
|
199
|
+
const balance = credit(ledger, uri, amount, currency);
|
|
200
|
+
ledger.credited.push(key);
|
|
201
|
+
return { credited: true, balance };
|
|
202
|
+
}
|
|
203
|
+
|
|
167
204
|
/**
|
|
168
205
|
* List all entries with non-zero balances
|
|
169
206
|
* @param {object} ledger - WebLedger object
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* --git and plugin-owned git paths (#616): core's git lane must not shadow a
|
|
3
|
+
* plugin that serves git smart-HTTP under its own prefix. With --git on, a
|
|
4
|
+
* request like GET /forge/<owner>/<name>.git/info/refs?service=git-receive-pack
|
|
5
|
+
* used to be grabbed by core, looked up under the pod root, and answered 401
|
|
6
|
+
* before the plugin ran. App plugins own their prefix: git-looking URLs below
|
|
7
|
+
* an app path fall through to the plugin; pod git outside it is unchanged.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, before, after, afterEach } from 'node:test';
|
|
11
|
+
import assert from 'node:assert';
|
|
12
|
+
import fs from 'fs-extra';
|
|
13
|
+
import path from 'path';
|
|
14
|
+
import os from 'os';
|
|
15
|
+
|
|
16
|
+
const TEST_DATA_DIR = './test-data-git-plugin-prefix';
|
|
17
|
+
const FIXTURE_DIR = path.join(os.tmpdir(), 'jss-git-plugin-prefix-fixture');
|
|
18
|
+
|
|
19
|
+
// A plugin that answers every request under its mount, git-shaped or not,
|
|
20
|
+
// and says which URL it saw — the forge's smart-HTTP lane, in miniature.
|
|
21
|
+
const FIXTURE = `
|
|
22
|
+
export async function activate(api) {
|
|
23
|
+
await api.mountApp((req, res) => {
|
|
24
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
25
|
+
res.end(JSON.stringify({ plugin: 'forge', method: req.method, url: req.url }));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
let server;
|
|
31
|
+
let baseUrl;
|
|
32
|
+
let originalDataRoot;
|
|
33
|
+
|
|
34
|
+
async function start() {
|
|
35
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
36
|
+
const { createServer } = await import('../src/server.js');
|
|
37
|
+
server = createServer({
|
|
38
|
+
logger: false,
|
|
39
|
+
forceCloseConnections: true,
|
|
40
|
+
root: TEST_DATA_DIR,
|
|
41
|
+
git: true,
|
|
42
|
+
plugins: [
|
|
43
|
+
{ id: 'forge', module: path.join(FIXTURE_DIR, 'plugin.js'), prefix: '/forge' },
|
|
44
|
+
],
|
|
45
|
+
});
|
|
46
|
+
await server.listen({ port: 0, host: '127.0.0.1' });
|
|
47
|
+
baseUrl = `http://127.0.0.1:${server.server.address().port}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('--git defers to plugin-owned prefixes (#616)', () => {
|
|
51
|
+
before(async () => {
|
|
52
|
+
originalDataRoot = process.env.DATA_ROOT;
|
|
53
|
+
await fs.emptyDir(FIXTURE_DIR);
|
|
54
|
+
await fs.writeFile(path.join(FIXTURE_DIR, 'plugin.js'), FIXTURE);
|
|
55
|
+
});
|
|
56
|
+
after(async () => {
|
|
57
|
+
await fs.remove(FIXTURE_DIR);
|
|
58
|
+
if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
|
|
59
|
+
else process.env.DATA_ROOT = originalDataRoot;
|
|
60
|
+
});
|
|
61
|
+
afterEach(async () => {
|
|
62
|
+
if (server) { await server.close(); server = null; }
|
|
63
|
+
await fs.remove(TEST_DATA_DIR);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('a push discovery under the plugin prefix reaches the plugin, unauthenticated', async () => {
|
|
67
|
+
await start();
|
|
68
|
+
const url = '/forge/alice/repo.git/info/refs?service=git-receive-pack';
|
|
69
|
+
const res = await fetch(baseUrl + url);
|
|
70
|
+
assert.strictEqual(res.status, 200, 'core did not answer 401 for the plugin\'s git URL');
|
|
71
|
+
const body = await res.json();
|
|
72
|
+
assert.strictEqual(body.plugin, 'forge', 'the plugin handled it');
|
|
73
|
+
assert.strictEqual(body.url, url, 'the full git-shaped URL, query included, reached the plugin');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('the pack services under the plugin prefix reach the plugin too', async () => {
|
|
77
|
+
await start();
|
|
78
|
+
for (const svc of ['git-receive-pack', 'git-upload-pack']) {
|
|
79
|
+
const res = await fetch(`${baseUrl}/forge/alice/repo.git/${svc}`, {
|
|
80
|
+
method: 'POST', headers: { 'content-type': `application/x-${svc}-request` }, body: '0000',
|
|
81
|
+
});
|
|
82
|
+
assert.strictEqual(res.status, 200, `${svc} reached the plugin`);
|
|
83
|
+
assert.strictEqual((await res.json()).plugin, 'forge');
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('pod git outside the prefix is still core\'s: a push there is auth-gated as before', async () => {
|
|
88
|
+
await start();
|
|
89
|
+
const res = await fetch(`${baseUrl}/alice/repo.git/info/refs?service=git-receive-pack`);
|
|
90
|
+
assert.strictEqual(res.status, 401, 'core still guards pod repos (write needs auth)');
|
|
91
|
+
const body = await res.json();
|
|
92
|
+
assert.strictEqual(body.error, 'Write access required for push');
|
|
93
|
+
});
|
|
94
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression tests for the quota check-and-commit race.
|
|
3
|
+
*
|
|
4
|
+
* saveQuota is atomic (temp + rename, #309), but check→write→record used to be
|
|
5
|
+
* three separate async steps: two concurrent writers could both pass the check
|
|
6
|
+
* and then overshoot the limit, and the read-modify-write in updateQuotaUsage
|
|
7
|
+
* could lose updates. reserveQuota + a per-pod lock make check-and-commit
|
|
8
|
+
* atomic — mirroring QuotaPolicy::reserve in the solid-pod-rs parity port.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, before, after, beforeEach } from 'node:test';
|
|
12
|
+
import assert from 'node:assert';
|
|
13
|
+
import fs from 'fs-extra';
|
|
14
|
+
import os from 'os';
|
|
15
|
+
import path from 'path';
|
|
16
|
+
import {
|
|
17
|
+
initializeQuota,
|
|
18
|
+
updateQuotaUsage,
|
|
19
|
+
reserveQuota,
|
|
20
|
+
loadQuota
|
|
21
|
+
} from '../src/storage/quota.js';
|
|
22
|
+
|
|
23
|
+
const POD = 'testpod';
|
|
24
|
+
let TEST_ROOT;
|
|
25
|
+
let originalDataRoot;
|
|
26
|
+
|
|
27
|
+
describe('quota — atomic reservation (check-and-commit race)', () => {
|
|
28
|
+
before(async () => {
|
|
29
|
+
originalDataRoot = process.env.DATA_ROOT;
|
|
30
|
+
TEST_ROOT = await fs.mkdtemp(path.join(os.tmpdir(), 'jss-quota-reserve-'));
|
|
31
|
+
process.env.DATA_ROOT = TEST_ROOT;
|
|
32
|
+
await fs.ensureDir(path.join(TEST_ROOT, POD));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
after(async () => {
|
|
36
|
+
if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
|
|
37
|
+
else process.env.DATA_ROOT = originalDataRoot;
|
|
38
|
+
await fs.remove(TEST_ROOT);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
beforeEach(async () => {
|
|
42
|
+
await initializeQuota(POD, 1000);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('concurrent reservations never overshoot the limit', async () => {
|
|
46
|
+
// 40 writers each try to reserve 100 bytes against a 1000-byte limit.
|
|
47
|
+
// Only 10 can be admitted; a non-atomic check would let many more through.
|
|
48
|
+
const N = 40;
|
|
49
|
+
const results = await Promise.all(
|
|
50
|
+
Array.from({ length: N }, () => reserveQuota(POD, 100, 0))
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const admitted = results.filter((r) => r.allowed).length;
|
|
54
|
+
assert.strictEqual(admitted, 10, 'exactly limit/size reservations may be admitted');
|
|
55
|
+
|
|
56
|
+
const final = await loadQuota(POD);
|
|
57
|
+
assert.ok(final.used <= final.limit, `used ${final.used} must not exceed limit ${final.limit}`);
|
|
58
|
+
assert.strictEqual(final.used, 1000, 'committed usage must equal the admitted reservations');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('concurrent updateQuotaUsage does not lose updates', async () => {
|
|
62
|
+
await initializeQuota(POD, 10 * 1024 * 1024);
|
|
63
|
+
const N = 50;
|
|
64
|
+
const each = 100;
|
|
65
|
+
await Promise.all(Array.from({ length: N }, () => updateQuotaUsage(POD, each)));
|
|
66
|
+
|
|
67
|
+
const final = await loadQuota(POD);
|
|
68
|
+
assert.strictEqual(final.used, N * each, 'every increment must be recorded (no lost update)');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('a released reservation frees the space for a later writer', async () => {
|
|
72
|
+
// Fill the quota, release one slot, then a new reservation must succeed.
|
|
73
|
+
const filled = await Promise.all(
|
|
74
|
+
Array.from({ length: 10 }, () => reserveQuota(POD, 100, 0))
|
|
75
|
+
);
|
|
76
|
+
assert.strictEqual(filled.filter((r) => r.allowed).length, 10);
|
|
77
|
+
|
|
78
|
+
const overflow = await reserveQuota(POD, 100, 0);
|
|
79
|
+
assert.strictEqual(overflow.allowed, false, 'quota is full');
|
|
80
|
+
|
|
81
|
+
await updateQuotaUsage(POD, -100); // simulate a failed write releasing its reservation
|
|
82
|
+
const retry = await reserveQuota(POD, 100, 0);
|
|
83
|
+
assert.strictEqual(retry.allowed, true, 'freed space is reusable');
|
|
84
|
+
});
|
|
85
|
+
});
|
package/test/wac.test.js
CHANGED
|
@@ -81,7 +81,7 @@ describe('WAC Parser', () => {
|
|
|
81
81
|
assert.ok(ownerAuth.modes.includes(AccessMode.WRITE));
|
|
82
82
|
assert.ok(ownerAuth.modes.includes(AccessMode.CONTROL));
|
|
83
83
|
// Check public authorization
|
|
84
|
-
const publicAuth = auths.find(a => a.agentClasses.includes('foaf
|
|
84
|
+
const publicAuth = auths.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
85
85
|
assert.ok(publicAuth, 'Should have public authorization');
|
|
86
86
|
assert.ok(publicAuth.modes.includes(AccessMode.READ));
|
|
87
87
|
});
|
|
@@ -101,7 +101,7 @@ describe('WAC Parser', () => {
|
|
|
101
101
|
const auths = await parseAcl(JSON.stringify(acl), 'https://alice.example/public/.acl');
|
|
102
102
|
|
|
103
103
|
assert.strictEqual(auths.length, 1);
|
|
104
|
-
assert.ok(auths[0].agentClasses.includes('foaf
|
|
104
|
+
assert.ok(auths[0].agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
105
105
|
assert.ok(auths[0].modes.includes(AccessMode.READ));
|
|
106
106
|
});
|
|
107
107
|
|
|
@@ -444,8 +444,8 @@ describe('WAC Parser', () => {
|
|
|
444
444
|
const auths1 = await parseAcl(wire, 'http://localhost:4444/.acl');
|
|
445
445
|
const auths2 = await parseAcl(wire, 'http://0.0.0.0:4444/.acl');
|
|
446
446
|
|
|
447
|
-
const pub1 = auths1.find(a => a.agentClasses.includes('foaf
|
|
448
|
-
const pub2 = auths2.find(a => a.agentClasses.includes('foaf
|
|
447
|
+
const pub1 = auths1.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
448
|
+
const pub2 = auths2.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
449
449
|
assert.ok(pub1.accessTo.includes('http://localhost:4444/'),
|
|
450
450
|
`Expected localhost resolution, got: ${JSON.stringify(pub1.accessTo)}`);
|
|
451
451
|
assert.ok(pub2.accessTo.includes('http://0.0.0.0:4444/'),
|
|
@@ -788,3 +788,225 @@ describe('WAC PaymentCondition noDebit (secondary/guard checks must not charge)'
|
|
|
788
788
|
assert.strictEqual(await balanceNow(), 100, 'balance must be unchanged');
|
|
789
789
|
});
|
|
790
790
|
});
|
|
791
|
+
|
|
792
|
+
describe('WAC Parser: JSON-LD expansion (#631)', () => {
|
|
793
|
+
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
794
|
+
const aclUrl = 'http://127.0.0.1:8732/me/public/doc.ttl.acl';
|
|
795
|
+
const webId = 'http://127.0.0.1:8732/me/profile/card.jsonld#me';
|
|
796
|
+
const target = 'http://127.0.0.1:8732/me/public/doc.ttl';
|
|
797
|
+
|
|
798
|
+
function expectOwner(auths) {
|
|
799
|
+
assert.strictEqual(auths.length, 1, `expected one authorization, got ${JSON.stringify(auths)}`);
|
|
800
|
+
assert.deepStrictEqual(auths[0].agents, [webId]);
|
|
801
|
+
assert.deepStrictEqual(auths[0].accessTo, [target]);
|
|
802
|
+
assert.deepStrictEqual(auths[0].modes.sort(), [AccessMode.CONTROL, AccessMode.READ, AccessMode.WRITE].sort());
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
it('reads an ACL in expanded form (full IRIs, no @context)', async () => {
|
|
806
|
+
const acl = [{
|
|
807
|
+
'@id': '#owner',
|
|
808
|
+
'@type': [`${ACL}Authorization`],
|
|
809
|
+
[`${ACL}agent`]: [{ '@id': webId }],
|
|
810
|
+
[`${ACL}accessTo`]: [{ '@id': target }],
|
|
811
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
812
|
+
}];
|
|
813
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
it('reads an ACL that uses a different prefix than acl:', async () => {
|
|
817
|
+
const acl = {
|
|
818
|
+
'@context': { wac: ACL },
|
|
819
|
+
'@graph': [{
|
|
820
|
+
'@id': '#owner',
|
|
821
|
+
'@type': 'wac:Authorization',
|
|
822
|
+
'wac:agent': { '@id': webId },
|
|
823
|
+
'wac:accessTo': { '@id': target },
|
|
824
|
+
'wac:mode': [{ '@id': 'wac:Read' }, { '@id': 'wac:Write' }, { '@id': 'wac:Control' }]
|
|
825
|
+
}]
|
|
826
|
+
};
|
|
827
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
828
|
+
});
|
|
829
|
+
|
|
830
|
+
it('reads an ACL whose @context is an array with a remote entry', async () => {
|
|
831
|
+
const acl = {
|
|
832
|
+
'@context': ['https://www.w3.org/ns/solid/context', { auth: ACL }],
|
|
833
|
+
'@graph': [{
|
|
834
|
+
'@id': '#owner',
|
|
835
|
+
'@type': 'auth:Authorization',
|
|
836
|
+
'auth:agent': { '@id': webId },
|
|
837
|
+
'auth:accessTo': { '@id': target },
|
|
838
|
+
'auth:mode': [{ '@id': 'auth:Read' }, { '@id': 'auth:Write' }, { '@id': 'auth:Control' }]
|
|
839
|
+
}]
|
|
840
|
+
};
|
|
841
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
842
|
+
});
|
|
843
|
+
|
|
844
|
+
it('reads an ACL that relies on @vocab and term definitions', async () => {
|
|
845
|
+
const acl = {
|
|
846
|
+
'@context': {
|
|
847
|
+
'@vocab': ACL,
|
|
848
|
+
agent: { '@id': `${ACL}agent`, '@type': '@id' },
|
|
849
|
+
accessTo: { '@id': `${ACL}accessTo`, '@type': '@id' },
|
|
850
|
+
mode: { '@id': `${ACL}mode`, '@type': '@id' }
|
|
851
|
+
},
|
|
852
|
+
'@id': '#owner',
|
|
853
|
+
'@type': 'Authorization',
|
|
854
|
+
agent: webId,
|
|
855
|
+
accessTo: target,
|
|
856
|
+
mode: ['Read', 'Write', 'Control']
|
|
857
|
+
};
|
|
858
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
859
|
+
});
|
|
860
|
+
|
|
861
|
+
it('reads a Turtle ACL that declares a non-acl prefix', async () => {
|
|
862
|
+
const ttl = `@prefix wac: <${ACL}> .
|
|
863
|
+
<#owner> a wac:Authorization ;
|
|
864
|
+
wac:agent <${webId}> ;
|
|
865
|
+
wac:accessTo <${target}> ;
|
|
866
|
+
wac:mode wac:Read, wac:Write, wac:Control .`;
|
|
867
|
+
expectOwner(await parseAcl(ttl, aclUrl));
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
it('normalises agent classes to full IRIs', async () => {
|
|
871
|
+
const acl = {
|
|
872
|
+
'@context': { wac: ACL, people: 'http://xmlns.com/foaf/0.1/' },
|
|
873
|
+
'@id': '#public',
|
|
874
|
+
'@type': 'wac:Authorization',
|
|
875
|
+
'wac:agentClass': { '@id': 'people:Agent' },
|
|
876
|
+
'wac:accessTo': { '@id': target },
|
|
877
|
+
'wac:mode': { '@id': 'wac:Read' }
|
|
878
|
+
};
|
|
879
|
+
const auths = await parseAcl(JSON.stringify(acl), aclUrl);
|
|
880
|
+
assert.deepStrictEqual(auths[0].agentClasses, ['http://xmlns.com/foaf/0.1/Agent']);
|
|
881
|
+
});
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
describe('WAC Integration: ACL PUT guard (#631)', () => {
|
|
885
|
+
let baseUrl;
|
|
886
|
+
|
|
887
|
+
before(async () => {
|
|
888
|
+
const result = await startTestServer();
|
|
889
|
+
baseUrl = result.baseUrl;
|
|
890
|
+
await createTestPod('aclguard');
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
after(async () => {
|
|
894
|
+
await stopTestServer();
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
898
|
+
|
|
899
|
+
it('accepts an expanded-form ACL and the owner keeps access', async () => {
|
|
900
|
+
const put = await request('/aclguard/public/exp.jsonld', {
|
|
901
|
+
method: 'PUT', auth: 'aclguard',
|
|
902
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
903
|
+
body: JSON.stringify({ '@id': '', 'http://schema.org/name': 'x' })
|
|
904
|
+
});
|
|
905
|
+
assert.ok(put.status === 201 || put.status === 204, `PUT resource: ${put.status}`);
|
|
906
|
+
|
|
907
|
+
const webId = `${baseUrl}/aclguard/profile/card.jsonld#me`;
|
|
908
|
+
const acl = [{
|
|
909
|
+
'@id': '#owner',
|
|
910
|
+
'@type': [`${ACL}Authorization`],
|
|
911
|
+
[`${ACL}agent`]: [{ '@id': webId }],
|
|
912
|
+
[`${ACL}accessTo`]: [{ '@id': `${baseUrl}/aclguard/public/exp.jsonld` }],
|
|
913
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
914
|
+
}];
|
|
915
|
+
const putAcl = await request('/aclguard/public/exp.jsonld.acl', {
|
|
916
|
+
method: 'PUT', auth: 'aclguard',
|
|
917
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
918
|
+
body: JSON.stringify(acl)
|
|
919
|
+
});
|
|
920
|
+
assert.ok(putAcl.status === 201 || putAcl.status === 204, `PUT acl: ${putAcl.status}`);
|
|
921
|
+
|
|
922
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
923
|
+
assertStatus(await request('/aclguard/public/exp.jsonld.acl', { auth: 'aclguard' }), 200);
|
|
924
|
+
// The expanded ACL grants nothing to the public.
|
|
925
|
+
assertStatus(await request('/aclguard/public/exp.jsonld'), 401);
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
it('rejects an ACL document that yields no authorizations', async () => {
|
|
929
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
930
|
+
method: 'PUT', auth: 'aclguard',
|
|
931
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
932
|
+
body: JSON.stringify({ '@context': { acl: ACL }, '@id': '#owner', 'acl:agent': { '@id': 'x' } })
|
|
933
|
+
});
|
|
934
|
+
assertStatus(res, 400);
|
|
935
|
+
const body = await res.json();
|
|
936
|
+
assert.match(body.message, /authorization/i);
|
|
937
|
+
// The previous ACL is still in place.
|
|
938
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
it('rejects an ACL whose authorizations name an agent but no mode', async () => {
|
|
942
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
943
|
+
method: 'PUT', auth: 'aclguard',
|
|
944
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
945
|
+
body: JSON.stringify({
|
|
946
|
+
'@context': { acl: ACL },
|
|
947
|
+
'@id': '#owner',
|
|
948
|
+
'@type': 'acl:Authorization',
|
|
949
|
+
'acl:agent': { '@id': `${baseUrl}/aclguard/profile/card.jsonld#me` },
|
|
950
|
+
'acl:accessTo': { '@id': `${baseUrl}/aclguard/public/exp.jsonld` }
|
|
951
|
+
})
|
|
952
|
+
});
|
|
953
|
+
assertStatus(res, 400);
|
|
954
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
it('rejects an ACL whose authorizations name a mode but no agent', async () => {
|
|
958
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
959
|
+
method: 'PUT', auth: 'aclguard',
|
|
960
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
961
|
+
body: JSON.stringify({
|
|
962
|
+
'@context': { acl: ACL },
|
|
963
|
+
'@id': '#owner',
|
|
964
|
+
'@type': 'acl:Authorization',
|
|
965
|
+
'acl:accessTo': { '@id': `${baseUrl}/aclguard/public/exp.jsonld` },
|
|
966
|
+
'acl:mode': [{ '@id': 'acl:Read' }, { '@id': 'acl:Control' }]
|
|
967
|
+
})
|
|
968
|
+
});
|
|
969
|
+
assertStatus(res, 400);
|
|
970
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
971
|
+
});
|
|
972
|
+
|
|
973
|
+
it('rejects a PATCH that would leave the ACL granting nobody access', async () => {
|
|
974
|
+
const webId = `${baseUrl}/aclguard/profile/card.jsonld#me`;
|
|
975
|
+
// Single expanded node (the N3 patch engine matches full-IRI keys and
|
|
976
|
+
// does not handle top-level arrays), so the delete below is applied.
|
|
977
|
+
const put = await request('/aclguard/public/exp.jsonld.acl', {
|
|
978
|
+
method: 'PUT', auth: 'aclguard',
|
|
979
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
980
|
+
body: JSON.stringify({
|
|
981
|
+
'@id': '#owner',
|
|
982
|
+
'@type': `${ACL}Authorization`,
|
|
983
|
+
[`${ACL}agent`]: { '@id': webId },
|
|
984
|
+
[`${ACL}accessTo`]: { '@id': `${baseUrl}/aclguard/public/exp.jsonld` },
|
|
985
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
986
|
+
})
|
|
987
|
+
});
|
|
988
|
+
assertStatus(put, 204);
|
|
989
|
+
const patch = `
|
|
990
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
991
|
+
@prefix acl: <${ACL}>.
|
|
992
|
+
_:patch a solid:InsertDeletePatch;
|
|
993
|
+
solid:deletes { <#owner> acl:agent <${webId}> }.
|
|
994
|
+
`;
|
|
995
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
996
|
+
method: 'PATCH', auth: 'aclguard',
|
|
997
|
+
headers: { 'Content-Type': 'text/n3' },
|
|
998
|
+
body: patch
|
|
999
|
+
});
|
|
1000
|
+
assertStatus(res, 409);
|
|
1001
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
1002
|
+
});
|
|
1003
|
+
|
|
1004
|
+
it('rejects an ACL body that is not valid JSON', async () => {
|
|
1005
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
1006
|
+
method: 'PUT', auth: 'aclguard',
|
|
1007
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
1008
|
+
body: '{not json'
|
|
1009
|
+
});
|
|
1010
|
+
assertStatus(res, 400);
|
|
1011
|
+
});
|
|
1012
|
+
});
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression tests for the deposit double-credit window.
|
|
3
|
+
*
|
|
4
|
+
* The GET /pay/.balance auto-scanner credited the ledger and then, in a
|
|
5
|
+
* separate write, recorded the UTXO as seen. A crash between the two writes
|
|
6
|
+
* lost the seen-record, and because the scanner re-runs on every balance poll
|
|
7
|
+
* the same on-chain UTXO was credited again — minting balance from nothing.
|
|
8
|
+
*
|
|
9
|
+
* creditOnce records the deposit's idempotency key inside the ledger, so the
|
|
10
|
+
* balance and the "already counted" marker commit together. Replaying the same
|
|
11
|
+
* deposit — the exact effect of the crash-then-rescan — is now a no-op. This
|
|
12
|
+
* mirrors the single atomic state.json commit in the solid-pod-rs parity port.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { describe, it } from 'node:test';
|
|
16
|
+
import assert from 'node:assert';
|
|
17
|
+
import fs from 'fs-extra';
|
|
18
|
+
import os from 'os';
|
|
19
|
+
import path from 'path';
|
|
20
|
+
import { createLedger, creditOnce, getBalance, readLedger, LEDGER_PATH } from '../src/webledger.js';
|
|
21
|
+
import * as storage from '../src/storage/filesystem.js';
|
|
22
|
+
|
|
23
|
+
const DID = 'did:nostr:npub1example';
|
|
24
|
+
const KEY = 'tbtc4:abcd1234:0';
|
|
25
|
+
|
|
26
|
+
describe('webledger — creditOnce idempotency', () => {
|
|
27
|
+
it('credits once and reports the new balance', () => {
|
|
28
|
+
const ledger = createLedger();
|
|
29
|
+
const r = creditOnce(ledger, KEY, DID, 5000, 'tbtc4');
|
|
30
|
+
assert.strictEqual(r.credited, true);
|
|
31
|
+
assert.strictEqual(r.balance, 5000);
|
|
32
|
+
assert.strictEqual(getBalance(ledger, DID, 'tbtc4'), 5000);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('a replayed deposit key is a no-op (no double-credit)', () => {
|
|
36
|
+
const ledger = createLedger();
|
|
37
|
+
creditOnce(ledger, KEY, DID, 5000, 'tbtc4');
|
|
38
|
+
|
|
39
|
+
// Simulate the crash-then-rescan: the very same outpoint is seen again.
|
|
40
|
+
const replay = creditOnce(ledger, KEY, DID, 5000, 'tbtc4');
|
|
41
|
+
assert.strictEqual(replay.credited, false, 'replay must not credit');
|
|
42
|
+
assert.strictEqual(replay.balance, 5000, 'balance unchanged on replay');
|
|
43
|
+
assert.strictEqual(getBalance(ledger, DID, 'tbtc4'), 5000);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('distinct outpoints each credit exactly once', () => {
|
|
47
|
+
const ledger = createLedger();
|
|
48
|
+
creditOnce(ledger, 'tbtc4:aaaa:0', DID, 1000, 'tbtc4');
|
|
49
|
+
creditOnce(ledger, 'tbtc4:bbbb:1', DID, 2000, 'tbtc4');
|
|
50
|
+
creditOnce(ledger, 'tbtc4:aaaa:0', DID, 1000, 'tbtc4'); // replay of the first
|
|
51
|
+
assert.strictEqual(getBalance(ledger, DID, 'tbtc4'), 3000);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('readLedger migrates a legacy ledger to carry a credited array', async () => {
|
|
55
|
+
// A ledger written before creditOnce existed has no `credited` field. The
|
|
56
|
+
// migration in readLedger must add one, otherwise the idempotency guard
|
|
57
|
+
// has nothing to consult for deposits made against pre-existing ledgers.
|
|
58
|
+
// Exercised through real storage so the migration itself is under test —
|
|
59
|
+
// asserting on a hand-built object would only re-test the test.
|
|
60
|
+
const prevRoot = process.env.DATA_ROOT;
|
|
61
|
+
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'jss-webledger-'));
|
|
62
|
+
process.env.DATA_ROOT = tmpRoot;
|
|
63
|
+
try {
|
|
64
|
+
const legacy = { '@context': 'https://w3id.org/webledgers', type: 'WebLedger', entries: [] };
|
|
65
|
+
await storage.write(LEDGER_PATH, Buffer.from(JSON.stringify(legacy)));
|
|
66
|
+
|
|
67
|
+
const migrated = await readLedger();
|
|
68
|
+
// Assert before any creditOnce call: creditOnce self-heals the field, so
|
|
69
|
+
// checking after one would pass even if the migration were deleted.
|
|
70
|
+
assert.ok(Array.isArray(migrated.credited),
|
|
71
|
+
'readLedger must add a credited array to a legacy ledger');
|
|
72
|
+
assert.strictEqual(migrated.credited.length, 0);
|
|
73
|
+
|
|
74
|
+
// And the guard works end-to-end on the migrated ledger.
|
|
75
|
+
assert.strictEqual(creditOnce(migrated, KEY, DID, 100, 'tbtc4').credited, true);
|
|
76
|
+
assert.strictEqual(creditOnce(migrated, KEY, DID, 100, 'tbtc4').credited, false);
|
|
77
|
+
assert.strictEqual(getBalance(migrated, DID, 'tbtc4'), 100);
|
|
78
|
+
} finally {
|
|
79
|
+
if (prevRoot === undefined) delete process.env.DATA_ROOT;
|
|
80
|
+
else process.env.DATA_ROOT = prevRoot;
|
|
81
|
+
await fs.remove(tmpRoot);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('a persisted credited marker survives a write/read round trip', async () => {
|
|
86
|
+
const prevRoot = process.env.DATA_ROOT;
|
|
87
|
+
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'jss-webledger-'));
|
|
88
|
+
process.env.DATA_ROOT = tmpRoot;
|
|
89
|
+
try {
|
|
90
|
+
const ledger = createLedger();
|
|
91
|
+
creditOnce(ledger, KEY, DID, 5000, 'tbtc4');
|
|
92
|
+
await storage.write(LEDGER_PATH, Buffer.from(JSON.stringify(ledger)));
|
|
93
|
+
|
|
94
|
+
// Simulate the crash-then-rescan across a process restart: the marker
|
|
95
|
+
// must come back from disk so the replay is still a no-op.
|
|
96
|
+
const reread = await readLedger();
|
|
97
|
+
assert.ok(reread.credited.includes(KEY), 'credited key must persist');
|
|
98
|
+
assert.strictEqual(creditOnce(reread, KEY, DID, 5000, 'tbtc4').credited, false);
|
|
99
|
+
assert.strictEqual(getBalance(reread, DID, 'tbtc4'), 5000);
|
|
100
|
+
} finally {
|
|
101
|
+
if (prevRoot === undefined) delete process.env.DATA_ROOT;
|
|
102
|
+
else process.env.DATA_ROOT = prevRoot;
|
|
103
|
+
await fs.remove(tmpRoot);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fastify/websocket registration tests (#545)
|
|
3
|
+
*
|
|
4
|
+
* Several features (notifications, nostr relay, webrtc, terminal, tunnel,
|
|
5
|
+
* app plugins) need @fastify/websocket. Each registration adds an 'upgrade'
|
|
6
|
+
* listener to the shared HTTP server; with more than one, every WebSocket
|
|
7
|
+
* upgrade logs N-1 spurious "websocket upgrade failed" warnings. The server
|
|
8
|
+
* must register the plugin exactly once, at the root, whatever is enabled.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it } from 'node:test';
|
|
12
|
+
import assert from 'node:assert';
|
|
13
|
+
import { mkdtempSync } from 'node:fs';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { createServer } from '../src/server.js';
|
|
17
|
+
|
|
18
|
+
async function upgradeListeners(options) {
|
|
19
|
+
const root = mkdtempSync(join(tmpdir(), 'jss-ws-reg-'));
|
|
20
|
+
const fastify = createServer({ root, port: 0, logger: false, ...options });
|
|
21
|
+
await fastify.ready();
|
|
22
|
+
try {
|
|
23
|
+
return fastify.server.listenerCount('upgrade');
|
|
24
|
+
} finally {
|
|
25
|
+
await fastify.close();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('@fastify/websocket registration', () => {
|
|
30
|
+
it('adds no upgrade listener when no WebSocket feature is enabled', async () => {
|
|
31
|
+
assert.strictEqual(await upgradeListeners({}), 0);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('adds exactly one upgrade listener for a single WebSocket feature', async () => {
|
|
35
|
+
assert.strictEqual(await upgradeListeners({ notifications: true }), 1);
|
|
36
|
+
assert.strictEqual(await upgradeListeners({ nostr: true }), 1);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('still adds exactly one upgrade listener with every WebSocket feature enabled', async () => {
|
|
40
|
+
const listeners = await upgradeListeners({
|
|
41
|
+
notifications: true, nostr: true, webrtc: true, tunnel: true, terminal: true,
|
|
42
|
+
});
|
|
43
|
+
assert.strictEqual(listeners, 1);
|
|
44
|
+
});
|
|
45
|
+
});
|