mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-23 14:17:06 +00:00
fix(puter-js): unshare lists refused pairs in failed and rejects when all were refused (#4557)
* fix(puter-js): unshare rejects when every revoke was refused
/share/revoke reports refused pairs in a 200 body, and unshare() only
read `revoked`, so a call where every pair was refused resolved as if it
had worked. It now rejects with the first pair's { message, code }, the
same way share() does; a call where some pairs went through still
resolves with { revoked }.
GUI tests drive the SDK's unshare against a refused body and check that
the share dialogs and Remove from Shared show the error and keep the
row. The unshare docs list the per-pair codes.
* fix(puter-js): unshare and share reject with the first refused pair that names a code
A pair the server could not complete carries no code and a generic message,
so it no longer comes ahead of a refusal that says what happened. Both
operations pick the error through one helper. The unshare docs describe which
pair's error is surfaced and the request-level rejections.
* fix(gui): share modal says how many items a person was removed from when some were refused
After removing someone from several items, the refreshed listing is compared
with the items the removal covered, and the status reports the count that
went through instead of all of them.
* test(gui): unshare fixture swaps XMLHttpRequest per call; alert mock cleared in hooks
* feat(puter-js): unshare resolves with the refused pairs; share is as it was
unshare resolves { revoked, failed }, with one failed entry per refused
recipient/item pair. A pair refused because the recipient or the item is gone
counts as nothing to withdraw: the call rejects only when every pair was
refused and at least one for another reason, with the first such refusal that
names a code. paths and recipients are typed and documented.
share() picks its rejection as before; the error choice lives in unshare.
* fix(gui): sharing dialogs report the items an unshare was refused for
The share modal counts refused items from the unshare result across every
run of a large selection, going on past a run refused whole, for removing a
person and for closing the link on several items. The share window and
Remove from Shared show the refusal when the call resolves with the pair
refused.
* fix(gui): sharing dialogs keep the unshare outcome on screen after the listing refresh
The share modal shows the partial count once its refresh has settled, for
removing a person and for closing the link, so a listing that fails for the
refused item does not replace it. The share window does the same when closing
the link.
* feat(puter-js): an unshare rejected for refused pairs lists them in failed; failed[].path is documented as the absolute path
* test(puter-js): API suite covers unshare's refused pairs
* fix(gui): share modal stops at a revoke request that failed and counts only refused items
---------
Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
This commit is contained in:
1 parent
eefc1f2f2e
commit
2c3b69011f
14 files changed
+684
-25
No files matched your search
@@ -41,21 +41,52 @@ An object with the following properties:
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `path` | `String` | The item. Required when passing options as the only argument. |
|
||||
| `recipient` | `String \| Object` | Whose access to withdraw. |
|
||||
| `path` | `String` | The item. Required when passing options as the only argument, unless `paths` or `uid` names it. |
|
||||
| `paths` | `Array` | Several items to withdraw in one call. |
|
||||
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
|
||||
| `recipient` | `String \| Object \| Array` | Whose access to withdraw. An array withdraws several recipients in one call. |
|
||||
| `recipients` | `String \| Object \| Array` | Alias for `recipient`. |
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that resolves to `{ revoked }`, where `revoked` is how many grants were actually removed. It is `0` when there was nothing to withdraw, which is not an error.
|
||||
A `Promise` that resolves to an object with the following properties:
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| `revoked` | `Number` | How many grants were actually removed. It is `0` when there was nothing to withdraw, which is not an error. |
|
||||
| `failed` | `Array` | The recipient/item pairs that were refused. Empty when none were. |
|
||||
|
||||
Each entry of `failed` has the following properties:
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| `recipient` | `String` | The recipient as the call named it. This is a username, an email address, a team's uid or handle, or `anyone`. |
|
||||
| `path` | `String` | The item's absolute path, when the call named it by path. A relative path comes back resolved against the app's root directory, and a path that starts with `~` comes back under the user's home directory, such as `/username/report.txt`. |
|
||||
| `uid` | `String` | The item's UID as the call passed it, when the call named it by UID. |
|
||||
| `message` | `String` | Why the pair was refused. |
|
||||
| `code` | `String` | One of the codes below. |
|
||||
|
||||
Each recipient/item pair is withdrawn on its own. With several items or recipients, every combination is one pair. A refused pair does not stop the others. The promise resolves, `revoked` counts what the others removed, and `failed` lists the pairs that were refused.
|
||||
|
||||
## Errors
|
||||
|
||||
A rejection carries `{ message, code }`.
|
||||
The promise rejects only when every pair was refused, and at least one of them for a reason other than the recipient or the item being gone. A pair refused with `user_does_not_exist` or `subject_does_not_exist` has nothing left to withdraw, so a call made only of those resolves with `revoked: 0` and the pairs listed in `failed`.
|
||||
|
||||
That rejection carries `{ message, code, failed }`. The `message` and `code` come from the first refused pair that names a code other than those two. The `failed` array lists every refused pair, with the same properties as in the return value.
|
||||
|
||||
A request that fails as a whole also rejects, with the server's error and no `failed`. This happens when a call names no recipient or no item, or names a team by both `team` and `teamHandle` (`bad_request`), when it names more recipients or items than one call allows (`too_many_recipients`, `too_many_items`), and when it's over the [rate limit](/rate-limits-and-quotas/).
|
||||
|
||||
The codes a refused pair carries, in `failed` or on a rejection:
|
||||
|
||||
| `code` | Meaning |
|
||||
| --- | --- |
|
||||
| `team_share` | You tried to leave an item you hold only through a team. That access is the team's grant, not yours to drop; ask whoever shared it with the team, or leave the team. Returned with status `409`. If you also hold a share of your own, leaving drops that one and succeeds. |
|
||||
| `team_share` | You tried to leave an item you hold only through a team. That access is the team's grant, not yours to drop; ask whoever shared it with the team, or leave the team. If you also hold a share of your own, leaving drops that one and succeeds. |
|
||||
| `forbidden` | You may not withdraw shares of this item, or you tried to close its "anyone with the link" share, which only the owner may do, in person rather than through an app. |
|
||||
| `subject_does_not_exist` | No such item, or you cannot see it. It is listed in `failed` and never causes a rejection on its own. |
|
||||
| `user_does_not_exist` | The username has no account. It is listed in `failed` and never causes a rejection on its own. |
|
||||
| `team_not_found` | No team has that uid. |
|
||||
| `cannot_revoke_owner` | The recipient owns the item. |
|
||||
| `unshare_failed` | No refused pair named a code, as when the server could not complete the request. |
|
||||
|
||||
## Who can withdraw what
|
||||
|
||||
@@ -96,6 +127,19 @@ Passing an email address that was **invited** but has not yet joined cancels the
|
||||
</html>
|
||||
```
|
||||
|
||||
### Withdraw several items and see which were refused
|
||||
|
||||
```js
|
||||
const { revoked, failed } = await puter.fs.unshare({
|
||||
paths: ['report.txt', 'budget.txt', 'notes.txt'],
|
||||
recipient: 'friend',
|
||||
});
|
||||
console.log(`Removed ${revoked} share(s)`);
|
||||
for (const pair of failed) {
|
||||
console.log(`${pair.path} was not withdrawn from ${pair.recipient}: ${pair.message} (${pair.code})`);
|
||||
}
|
||||
```
|
||||
|
||||
### Leave a share someone gave you
|
||||
|
||||
```js
|
||||
|
||||
@@ -672,10 +672,30 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
return created;
|
||||
};
|
||||
|
||||
// Same runs as grant_access. Resolves with the refused items, each with
|
||||
// its error, and rejects with the first when every item was refused. A
|
||||
// run that fails otherwise (rate limit, network) ends it there, rejecting
|
||||
// with that error and the count withdrawn before it as `withdrawn`.
|
||||
const revoke_access = async (recipient, paths) => {
|
||||
const failed = [];
|
||||
let attempted = 0;
|
||||
for ( const run of chunk(paths, MAX_ITEMS_PER_REQUEST) ) {
|
||||
await puter.fs.unshare({ paths: run, recipient });
|
||||
try {
|
||||
const result = await puter.fs.unshare({ paths: run, recipient });
|
||||
failed.push(...(result?.failed ?? []));
|
||||
} catch (err) {
|
||||
// Only a rejection for refused pairs lists them.
|
||||
if ( ! Array.isArray(err?.failed) ) {
|
||||
const withdrawn = attempted - failed.length;
|
||||
if ( withdrawn && err && typeof err === 'object' ) err.withdrawn = withdrawn;
|
||||
throw err;
|
||||
}
|
||||
failed.push(...err.failed);
|
||||
}
|
||||
attempted += run.length;
|
||||
}
|
||||
if ( failed.length >= paths.length ) throw failed[0];
|
||||
return failed;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -685,6 +705,8 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
const set_link_access = async (mode, el_control) => {
|
||||
$link_access.prop('disabled', true);
|
||||
$link_mode.prop('disabled', true);
|
||||
// Shown once the refresh settles, so its own notice can't replace it.
|
||||
let outcome_error = null;
|
||||
try {
|
||||
if ( mode ) {
|
||||
const created = await grant_access({ anyone: true }, mode, target_paths);
|
||||
@@ -692,26 +714,37 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
link_state = { access: 'anyone', mode };
|
||||
show_success(i18n(`share_link_on_${mode === 'write' ? 'write' : 'read'}${is_multi ? '_items' : ''}`));
|
||||
} else {
|
||||
await revoke_access({ anyone: true }, target_paths);
|
||||
link_state = { access: 'restricted', mode: null };
|
||||
show_success(i18n(is_multi ? 'share_link_off_items' : 'share_link_off'));
|
||||
const failed = await revoke_access({ anyone: true }, target_paths);
|
||||
if ( failed.length ) {
|
||||
link_state = { access: 'mixed', mode: null };
|
||||
outcome_error = `${i18n('share_link_off_partial', { count: total - failed.length, total })}. ${error_html(failed[0])}`;
|
||||
} else {
|
||||
link_state = { access: 'restricted', mode: null };
|
||||
show_success(i18n(is_multi ? 'share_link_off_items' : 'share_link_off'));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// A plan gate gets the flow that clears it, where the deployment
|
||||
// has one; a refusal is otherwise reported like any other.
|
||||
if ( is_plan_gate_error(err) ) {
|
||||
if ( ! open_upgrade_flow() ) show_error(i18n('share_link_requires_plan'));
|
||||
if ( ! open_upgrade_flow() ) outcome_error = i18n('share_link_requires_plan');
|
||||
} else if ( err?.withdrawn ) {
|
||||
// Runs that landed before the failure closed the link all the same.
|
||||
link_state = { access: 'mixed', mode: null };
|
||||
outcome_error = `${i18n('share_link_off_partial', { count: err.withdrawn, total })}. ${error_html(err)}`;
|
||||
} else {
|
||||
show_error(error_html(err));
|
||||
outcome_error = error_html(err);
|
||||
}
|
||||
} finally {
|
||||
$link_access.prop('disabled', false);
|
||||
$link_mode.prop('disabled', false);
|
||||
}
|
||||
if ( outcome_error ) show_error(outcome_error);
|
||||
// The listings are the truth either way, and they put the control
|
||||
// back; a selection too large to list keeps what was just applied.
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
if ( outcome_error ) show_error(outcome_error);
|
||||
render_link_access();
|
||||
if ( el_control && $(el_control).is(':visible') ) el_control.focus({ preventScroll: true });
|
||||
else focus_dialog();
|
||||
@@ -978,7 +1011,22 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
const revoke_paths = group.pending ? group.pendingPaths : group.directPaths;
|
||||
$(this).closest('.share-modal-row-confirm').find('button').prop('disabled', true);
|
||||
try {
|
||||
await revoke_access(recipient_of(group), revoke_paths);
|
||||
const failed = await revoke_access(recipient_of(group), revoke_paths);
|
||||
// Some items were refused: say how many went through, and stay
|
||||
// open on what the listing now shows.
|
||||
if ( failed.length ) {
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
// After the refresh: a refused item may not list any more,
|
||||
// and that notice must not replace this one.
|
||||
show_error(`${i18n('share_access_removed_partial', {
|
||||
recipient: group.name,
|
||||
count: revoke_paths.length - failed.length,
|
||||
total: revoke_paths.length,
|
||||
})}. ${error_html(failed[0])}`);
|
||||
focus_list_control('.share-modal-row-mode', key) || focus_dialog();
|
||||
return;
|
||||
}
|
||||
// Leaving takes away the access this list is read with, and the
|
||||
// items may leave the listing behind it (the Shared view) too.
|
||||
if ( ! group.teamUid && ! group.pending && group.name === window.user.username ) {
|
||||
|
||||
@@ -43,6 +43,7 @@ globalThis.def = globalThis.def ?? (value => value);
|
||||
globalThis.use = globalThis.use ?? (() => class {});
|
||||
|
||||
const { default: UIShareModal } = await import('./UIShareModal.js');
|
||||
const { unshareAnswering, allRefused, refusing } = await import('../../../tests/fixtures/sdkUnshare.js');
|
||||
|
||||
const settle = async () => {
|
||||
for ( let i = 0; i < 5; i++ ) await new Promise(resolve => setTimeout(resolve, 0));
|
||||
@@ -82,6 +83,126 @@ describe('UIShareModal general access', () => {
|
||||
expect($('.share-modal-link-access').val()).toBe('restricted');
|
||||
});
|
||||
|
||||
it('shows the error when closing the link is refused', async () => {
|
||||
puter.fs.getShares = vi.fn(async () => [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }]);
|
||||
puter.fs.unshare = unshareAnswering(allRefused);
|
||||
UIShareModal({ path: '/alice/a.txt' });
|
||||
await settle();
|
||||
expect($('.share-modal-link-access').val()).toBe('anyone');
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe('Held through a team');
|
||||
expect($('.share-modal-link-access').val()).toBe('anyone');
|
||||
});
|
||||
|
||||
it('says how many items the link was closed on when some were refused', async () => {
|
||||
puter.fs.getShares = vi.fn(async () => [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }]);
|
||||
puter.fs.unshare = unshareAnswering((request) => refusing(
|
||||
request,
|
||||
(path) => path === '/alice/f1.txt',
|
||||
{ code: 'forbidden', message: 'Not allowed' },
|
||||
));
|
||||
UIShareModal({ items: items(3) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe(
|
||||
'Only people with access can open 2 of 3 items now. Not allowed',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the count on screen when a refused item no longer lists, closing the link', async () => {
|
||||
let gone = false;
|
||||
puter.fs.getShares = vi.fn(async (path) => {
|
||||
if ( gone && path === '/alice/f1.txt' ) throw { message: 'Subject does not exist' };
|
||||
return [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }];
|
||||
});
|
||||
puter.fs.unshare = unshareAnswering((request) => refusing(
|
||||
request,
|
||||
(path) => path === '/alice/f1.txt',
|
||||
{ code: 'subject_does_not_exist', message: 'Subject does not exist' },
|
||||
));
|
||||
UIShareModal({ items: items(3) });
|
||||
await settle();
|
||||
gone = true;
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect($('.share-modal-status').text()).toBe(
|
||||
'Only people with access can open 2 of 3 items now. Subject does not exist',
|
||||
);
|
||||
});
|
||||
|
||||
it('goes on past a run that was refused whole, and counts every refused item', async () => {
|
||||
const requests = [];
|
||||
// Runs of 50: the second is refused whole, the third loses one item.
|
||||
puter.fs.unshare = unshareAnswering((request) => {
|
||||
requests.push(request.items.length);
|
||||
const run = requests.length;
|
||||
return refusing(
|
||||
request,
|
||||
(path) => run === 2 || path === '/alice/f119.txt',
|
||||
{ code: 'forbidden', message: 'Not allowed' },
|
||||
);
|
||||
});
|
||||
UIShareModal({ items: items(120) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect(requests).toEqual([50, 50, 20]);
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe(
|
||||
'Only people with access can open 69 of 120 items now. Not allowed',
|
||||
);
|
||||
expect($('.share-modal-link-access')[0].value).toBe('mixed');
|
||||
});
|
||||
|
||||
it('stops at a run the server turned away whole, and counts only what was closed before it', async () => {
|
||||
const requests = [];
|
||||
// Runs of 50: the second is rate limited, so the third is never sent.
|
||||
puter.fs.unshare = unshareAnswering((request, xhr) => {
|
||||
requests.push(request.items.length);
|
||||
if ( requests.length === 2 ) {
|
||||
xhr.status = 429;
|
||||
return { message: 'Too many requests', code: 'too_many_requests' };
|
||||
}
|
||||
return refusing(request, () => false);
|
||||
});
|
||||
UIShareModal({ items: items(120) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect(requests).toEqual([50, 50]);
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe(
|
||||
'Only people with access can open 50 of 120 items now. Too many requests',
|
||||
);
|
||||
expect($('.share-modal-link-access')[0].value).toBe('mixed');
|
||||
});
|
||||
|
||||
it('reports a failed request as it is, with no item counted as refused', async () => {
|
||||
const requests = [];
|
||||
puter.fs.unshare = unshareAnswering((request, xhr) => {
|
||||
requests.push(request.items.length);
|
||||
xhr.status = 429;
|
||||
return { message: 'Too many requests', code: 'too_many_requests' };
|
||||
});
|
||||
UIShareModal({ items: items(120) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-link-access').val('restricted').trigger('change');
|
||||
await settle();
|
||||
expect(requests).toEqual([50]);
|
||||
expect($('.share-modal-status').text()).toBe('Too many requests');
|
||||
expect($('.share-modal-link-access')[0].value).toBe('unchecked');
|
||||
});
|
||||
|
||||
it('shows a listed selection as the listings say', async () => {
|
||||
UIShareModal({ items: items(2) });
|
||||
await settle();
|
||||
@@ -154,6 +275,67 @@ describe('UIShareModal removing access', () => {
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith({ paths: ['/alice/a.txt'], recipient: 'bob' });
|
||||
});
|
||||
|
||||
it('keeps the row and shows the error when the removal is refused', async () => {
|
||||
puter.fs.getShares = vi.fn(async () => [{ holder: 'bob', mode: 'read', issuer: 'alice' }]);
|
||||
puter.fs.unshare = unshareAnswering(allRefused);
|
||||
UIShareModal({ path: '/alice/a.txt' });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-row-mode').val('__remove').trigger('change');
|
||||
$('.share-modal-confirm-remove').trigger('click');
|
||||
await settle();
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe('Held through a team');
|
||||
expect($('.share-modal-row-mode').attr('data-key')).toBeTruthy();
|
||||
expect($('.share-modal-row-mode').val()).toBe('read');
|
||||
});
|
||||
|
||||
it('says how many items a person was removed from when one was refused', async () => {
|
||||
puter.fs.getShares = vi.fn(async () => [{ holder: 'bob', mode: 'read', issuer: 'alice' }]);
|
||||
puter.fs.unshare = unshareAnswering((request) => refusing(
|
||||
request,
|
||||
(path) => path === '/alice/f2.txt',
|
||||
{ code: 'forbidden', message: 'Not allowed' },
|
||||
));
|
||||
UIShareModal({ items: [0, 1, 2].map((i) => ({ path: `/alice/f${i}.txt` })) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-row-mode').val('__remove').trigger('change');
|
||||
$('.share-modal-confirm-remove').trigger('click');
|
||||
await settle();
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe('Removed bob from 2 of 3 items. Not allowed');
|
||||
expect($('.share-modal-row-mode').length).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the count on screen when a refused item no longer lists', async () => {
|
||||
let removed = false;
|
||||
puter.fs.getShares = vi.fn(async (path) => {
|
||||
if ( removed && path === '/alice/f2.txt' ) throw { message: 'Subject does not exist' };
|
||||
return removed ? [] : [{ holder: 'bob', mode: 'read', issuer: 'alice' }];
|
||||
});
|
||||
const answering = unshareAnswering((request) => refusing(
|
||||
request,
|
||||
(path) => path === '/alice/f2.txt',
|
||||
{ code: 'subject_does_not_exist', message: 'Subject does not exist' },
|
||||
));
|
||||
puter.fs.unshare = async (...args) => {
|
||||
removed = true;
|
||||
return answering(...args);
|
||||
};
|
||||
UIShareModal({ items: [0, 1, 2].map((i) => ({ path: `/alice/f${i}.txt` })) });
|
||||
await settle();
|
||||
|
||||
$('.share-modal-row-mode').val('__remove').trigger('change');
|
||||
$('.share-modal-confirm-remove').trigger('click');
|
||||
await settle();
|
||||
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
|
||||
expect($('.share-modal-status').text()).toBe(
|
||||
'Removed bob from 2 of 3 items. Subject does not exist',
|
||||
);
|
||||
expect($('.share-modal-row-mode').length).toBe(0);
|
||||
});
|
||||
|
||||
it('offers cancelling an invitation from its menu', async () => {
|
||||
puter.fs.getShares = vi.fn(async () => [
|
||||
{ holder: null, recipientEmail: 'carol@example.com', pending: true, mode: 'write', issuer: 'alice' },
|
||||
|
||||
@@ -1417,10 +1417,11 @@ async function UIItem (options) {
|
||||
html: i18n('share_remove_from_shared'),
|
||||
onClick: async function () {
|
||||
try {
|
||||
await puter.fs.unshare(
|
||||
const left = await puter.fs.unshare(
|
||||
$(el_item).attr('data-path'),
|
||||
window.user.username,
|
||||
);
|
||||
if ( left?.failed?.length ) throw left.failed[0];
|
||||
// Or mode lookups keep answering for a share we
|
||||
// just walked away from.
|
||||
invalidate_shared_roots();
|
||||
|
||||
@@ -65,10 +65,13 @@ Object.assign(window, {
|
||||
|
||||
const { default: UIItem } = await import('./UIItem.js');
|
||||
const { default: UIContextMenu } = await import('./UIContextMenu.js');
|
||||
const { default: UIAlert } = await import('./UIAlert.js');
|
||||
const { unshareAnswering, allRefused, goneRefused } =
|
||||
await import('../../tests/fixtures/sdkUnshare.js');
|
||||
const { default: refresh_item_container } =
|
||||
await import('../helpers/refreshItemContainer.js');
|
||||
|
||||
const menuLabels = async (options) => {
|
||||
const menuItems = async (options) => {
|
||||
document.body.innerHTML =
|
||||
'<div class="window"><div class="item-container"></div></div>';
|
||||
await UIItem({
|
||||
@@ -87,9 +90,12 @@ const menuLabels = async (options) => {
|
||||
UIContextMenu.mockClear();
|
||||
$('.item').trigger('contextmenu');
|
||||
await vi.waitFor(() => expect(UIContextMenu).toHaveBeenCalled());
|
||||
return UIContextMenu.mock.calls[0][0].items.map((item) => item?.html);
|
||||
return UIContextMenu.mock.calls[0][0].items;
|
||||
};
|
||||
|
||||
const menuLabels = async (options) =>
|
||||
(await menuItems(options)).map((item) => item?.html);
|
||||
|
||||
const removeFromShared = async (options) => {
|
||||
await menuLabels(options);
|
||||
await UIContextMenu.mock.calls[0][0].items
|
||||
@@ -109,6 +115,7 @@ describe('UIItem Remove from Shared', () => {
|
||||
};
|
||||
globalThis.puter = window.puter;
|
||||
refresh_item_container.mockClear();
|
||||
UIAlert.mockClear();
|
||||
});
|
||||
|
||||
it('is offered on an item shared with the user directly', async () => {
|
||||
@@ -121,6 +128,29 @@ describe('UIItem Remove from Shared', () => {
|
||||
expect(labels).not.toContain('share_remove_from_shared');
|
||||
});
|
||||
|
||||
it('keeps the item and shows the error when leaving is refused', async () => {
|
||||
puter.fs.unshare = unshareAnswering(allRefused);
|
||||
const items = await menuItems({});
|
||||
await items
|
||||
.find((item) => item?.html === 'share_remove_from_shared')
|
||||
.onClick();
|
||||
|
||||
expect(UIAlert).toHaveBeenCalledWith({
|
||||
message: 'Held through a team',
|
||||
});
|
||||
expect($('.item').length).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the item and shows why when the unshare resolves with the pair refused', async () => {
|
||||
puter.fs.unshare = unshareAnswering(goneRefused);
|
||||
await removeFromShared({});
|
||||
|
||||
expect(UIAlert).toHaveBeenCalledWith({
|
||||
message: 'Subject does not exist',
|
||||
});
|
||||
expect($('.item').length).toBe(1);
|
||||
});
|
||||
|
||||
it('takes the item away once the user has left it', async () => {
|
||||
await removeFromShared({});
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
|
||||
|
||||
@@ -357,10 +357,11 @@ const generate_file_context_menu = async function (options) {
|
||||
html: i18n('share_remove_from_shared'),
|
||||
onClick: async function () {
|
||||
try {
|
||||
await puter.fs.unshare(
|
||||
const left = await puter.fs.unshare(
|
||||
$(el_item).attr('data-path'),
|
||||
window.user.username,
|
||||
);
|
||||
if ( left?.failed?.length ) throw left.failed[0];
|
||||
// Or mode lookups keep answering for a share we just
|
||||
// walked away from.
|
||||
invalidate_shared_roots();
|
||||
|
||||
@@ -48,6 +48,7 @@ const { default: generate_file_context_menu } =
|
||||
await import('./generateFileContextMenu.js');
|
||||
const { default: launch_app } = await import('./launchApp.js');
|
||||
const { default: UIAlert } = await import('../UI/UIAlert.js');
|
||||
const { unshareAnswering, allRefused, goneRefused } = await import('../../tests/fixtures/sdkUnshare.js');
|
||||
const { can_share } = await import('./sharedAccess.js');
|
||||
const { is_owned_by_me } = await import('./pathOwner.js');
|
||||
|
||||
@@ -195,6 +196,29 @@ describe('Remove from Shared', () => {
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
UIAlert.mockReset();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['is refused', allRefused, 'Held through a team'],
|
||||
['resolves with the pair refused', goneRefused, 'Subject does not exist'],
|
||||
])('keeps the row and shows the error when leaving the share %s', async (_, answer, message) => {
|
||||
const row = sharedRow();
|
||||
document.body.append(row);
|
||||
const onRemovedFromShared = vi.fn();
|
||||
window.user = { username: 'alice' };
|
||||
globalThis.puter = { fs: { unshare: unshareAnswering(answer) } };
|
||||
const items = await generate_file_context_menu({
|
||||
element: row,
|
||||
fsentry: { name: 'notes.txt', path: '/ann/uid-1/notes.txt' },
|
||||
associated_app_name: 'editor',
|
||||
onRemovedFromShared,
|
||||
});
|
||||
await items.find((item) => item.html === 'share_remove_from_shared').onClick();
|
||||
|
||||
expect(UIAlert).toHaveBeenCalledWith({ message });
|
||||
expect(row.isConnected).toBe(true);
|
||||
expect(onRemovedFromShared).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('takes the row away once the user has left it', async () => {
|
||||
|
||||
@@ -568,6 +568,8 @@ const en = {
|
||||
share_access_updated_items:
|
||||
'Updated access for {{recipient}} on {{count}} items',
|
||||
share_access_removed_items: 'Removed {{recipient}} from {{count}} items',
|
||||
share_access_removed_partial:
|
||||
'Removed {{recipient}} from {{count}} of {{total}} items',
|
||||
block: 'Block',
|
||||
unblock: 'Unblock',
|
||||
manage: 'Manage',
|
||||
@@ -614,6 +616,8 @@ const en = {
|
||||
share_link_on_write_items: 'Anyone with the link can now edit these items',
|
||||
share_link_off: 'Only people with access can open this item now',
|
||||
share_link_off_items: 'Only people with access can open these items now',
|
||||
share_link_off_partial:
|
||||
'Only people with access can open {{count}} of {{total}} items now',
|
||||
share_link_requires_plan:
|
||||
'Sharing with anyone who has the link requires a subscription.',
|
||||
share_copy_link: 'Copy link',
|
||||
|
||||
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
// The SDK's own puter.fs.unshare, answering its request with a canned /share/revoke body.
|
||||
import unshare from '../../../puter-js/src/modules/FileSystem/operations/unshare.js';
|
||||
|
||||
const cannedXHR = (answer) => class {
|
||||
_listeners = {};
|
||||
status = 200;
|
||||
open () {}
|
||||
setRequestHeader () {}
|
||||
getResponseHeader (name) {
|
||||
return name.toLowerCase() === 'content-type' ? 'application/json' : null;
|
||||
}
|
||||
addEventListener (type, fn) {
|
||||
(this._listeners[type] ??= []).push(fn);
|
||||
}
|
||||
send (request) {
|
||||
const body = typeof answer === 'function' ? answer(JSON.parse(request), this) : answer;
|
||||
queueMicrotask(() => {
|
||||
this.responseText = JSON.stringify(body);
|
||||
for ( const fn of this._listeners.load ?? [] ) fn.call(this, { target: this });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Record<string, unknown> | ((request: { items: { path?: string }[] }, xhr: { status: number }) => Record<string, unknown>)} answer
|
||||
* what /share/revoke answers with, or how it answers one request; setting
|
||||
* `xhr.status` answers with an HTTP error
|
||||
* @returns {(...args: unknown[]) => Promise<unknown>}
|
||||
*/
|
||||
export const unshareAnswering = (answer) => {
|
||||
const CannedXHR = cannedXHR(answer);
|
||||
const fs = { APIOrigin: 'https://api.test', authToken: 'test-token' };
|
||||
// XMLHttpRequest is swapped for the length of one call only.
|
||||
return async (...args) => {
|
||||
const original = globalThis.XMLHttpRequest;
|
||||
globalThis.XMLHttpRequest = CannedXHR;
|
||||
try {
|
||||
return await unshare.call(fs, ...args);
|
||||
} finally {
|
||||
globalThis.XMLHttpRequest = original;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** Every pair refused, as the backend reports leaving a share held through a team. */
|
||||
export const allRefused = {
|
||||
status: 'aborted',
|
||||
revoked: 0,
|
||||
results: [{ recipient: 'alice', status: 'error', code: 'team_share', message: 'Held through a team' }],
|
||||
};
|
||||
|
||||
/**
|
||||
* A /share/revoke answer for `request` that refuses the items `refuses` picks.
|
||||
*
|
||||
* @param {{ items: { path?: string }[] }} request
|
||||
* @param {(path: string) => boolean} refuses
|
||||
* @param {{ code: string, message: string }} error
|
||||
*/
|
||||
export const refusing = (request, refuses, error) => {
|
||||
const results = request.items.map(({ path }) => (refuses(path)
|
||||
? { recipient: 'bob', path, status: 'error', ...error }
|
||||
: { recipient: 'bob', path, status: 'success' }));
|
||||
const refused = results.filter((result) => result.status === 'error').length;
|
||||
return {
|
||||
status: refused === 0 ? 'success' : (refused === results.length ? 'aborted' : 'mixed'),
|
||||
revoked: results.length - refused,
|
||||
results,
|
||||
};
|
||||
};
|
||||
|
||||
/** One pair refused because the recipient or the item is gone, which unshare resolves. */
|
||||
export const goneRefused = {
|
||||
status: 'aborted',
|
||||
revoked: 0,
|
||||
results: [{ recipient: 'alice', path: '/gone', status: 'error', code: 'subject_does_not_exist', message: 'Subject does not exist' }],
|
||||
};
|
||||
Vendored
+3
@@ -187,7 +187,10 @@ export type {
|
||||
SignResult,
|
||||
SpaceInfo,
|
||||
StatOptions,
|
||||
UnshareError,
|
||||
UnshareFailure,
|
||||
UnshareOptions,
|
||||
UnshareResult,
|
||||
UploadBatchError,
|
||||
UploadItems,
|
||||
UploadOperationResult,
|
||||
|
||||
@@ -599,6 +599,117 @@ describe('stat', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('unshare', () => {
|
||||
const answer = (status, revoked, results) => {
|
||||
FakeXHR.respondWith = () => ({ status, revoked, results });
|
||||
};
|
||||
const refused = (path, code, message = code) => ({
|
||||
recipient: 'me', path, status: 'error', message, ...(code ? { code } : {}),
|
||||
});
|
||||
const failure = (path, code, message = code) => ({ recipient: 'me', path, message, code });
|
||||
|
||||
it('rejects with the first error and every refused pair when all were refused', async () => {
|
||||
answer('aborted', 0, [
|
||||
refused('/a/file.txt', 'team_share', 'Held through a team'),
|
||||
refused('/a/other.txt', 'forbidden', 'Not allowed'),
|
||||
]);
|
||||
const onSuccess = vi.fn();
|
||||
const onError = vi.fn();
|
||||
const expected = {
|
||||
message: 'Held through a team',
|
||||
code: 'team_share',
|
||||
failed: [
|
||||
failure('/a/file.txt', 'team_share', 'Held through a team'),
|
||||
failure('/a/other.txt', 'forbidden', 'Not allowed'),
|
||||
],
|
||||
};
|
||||
await expect(fs.unshare('/a/file.txt', 'me', onSuccess, onError))
|
||||
.rejects.toEqual(expected);
|
||||
expect(onSuccess).not.toHaveBeenCalled();
|
||||
expect(onError).toHaveBeenCalledWith(expected);
|
||||
});
|
||||
|
||||
it('lists the refused pair when others were withdrawn', async () => {
|
||||
answer('mixed', 1, [
|
||||
{ recipient: 'bob', path: '/a/file.txt', status: 'success' },
|
||||
{ recipient: 'me', uid: 'u-2', status: 'error', code: 'forbidden', message: 'Not allowed' },
|
||||
]);
|
||||
await expect(fs.unshare({ path: '/a/file.txt', recipients: ['bob', 'me'] })).resolves.toEqual({
|
||||
revoked: 1,
|
||||
failed: [{ recipient: 'me', uid: 'u-2', message: 'Not allowed', code: 'forbidden' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects with a named refusal ahead of a pair the server could not complete', async () => {
|
||||
answer('aborted', 0, [
|
||||
refused('/a/file.txt', undefined, 'Request failed'),
|
||||
refused('/a/other.txt', 'team_share', 'Held through a team'),
|
||||
]);
|
||||
await expect(fs.unshare({ paths: ['/a/file.txt', '/a/other.txt'], recipient: 'me' }))
|
||||
.rejects.toMatchObject({ message: 'Held through a team', code: 'team_share' });
|
||||
});
|
||||
|
||||
it('rejects with a fallback code when no refused pair names one', async () => {
|
||||
answer('aborted', 0, [refused('/a/file.txt', undefined, 'Request failed')]);
|
||||
await expect(fs.unshare('/a/file.txt', 'me'))
|
||||
.rejects.toMatchObject({ message: 'Request failed', code: 'unshare_failed' });
|
||||
});
|
||||
|
||||
it('resolves, listing the refused pair, next to one with nothing to withdraw', async () => {
|
||||
answer('mixed', 0, [
|
||||
{ recipient: 'me', path: '/a/file.txt', status: 'success' },
|
||||
refused('/a/other.txt', 'team_share', 'Held through a team'),
|
||||
]);
|
||||
const onSuccess = vi.fn();
|
||||
const onError = vi.fn();
|
||||
const expected = {
|
||||
revoked: 0,
|
||||
failed: [failure('/a/other.txt', 'team_share', 'Held through a team')],
|
||||
};
|
||||
await expect(fs.unshare({
|
||||
paths: ['/a/file.txt', '/a/other.txt'], recipient: 'me', success: onSuccess, error: onError,
|
||||
})).resolves.toEqual(expected);
|
||||
expect(onSuccess).toHaveBeenCalledWith(expected);
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves, listing the pair, when the recipient or the item is gone', async () => {
|
||||
for ( const code of ['user_does_not_exist', 'subject_does_not_exist'] ) {
|
||||
answer('aborted', 0, [refused('/a/file.txt', code)]);
|
||||
await expect(fs.unshare('/a/file.txt', 'me'))
|
||||
.resolves.toEqual({ revoked: 0, failed: [failure('/a/file.txt', code)] });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects with the other refusal when a gone pair comes first', async () => {
|
||||
answer('aborted', 0, [
|
||||
refused('/a/file.txt', 'subject_does_not_exist'),
|
||||
refused('/a/other.txt', 'forbidden', 'Not allowed'),
|
||||
]);
|
||||
await expect(fs.unshare({ paths: ['/a/file.txt', '/a/other.txt'], recipient: 'me' }))
|
||||
.rejects.toEqual({
|
||||
message: 'Not allowed',
|
||||
code: 'forbidden',
|
||||
failed: [
|
||||
failure('/a/file.txt', 'subject_does_not_exist'),
|
||||
failure('/a/other.txt', 'forbidden', 'Not allowed'),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects with the server error, and no refused pairs, when the request itself fails', async () => {
|
||||
FakeXHR.status = 429;
|
||||
FakeXHR.respondWith = () => ({ message: 'Too many requests', code: 'too_many_requests' });
|
||||
await expect(fs.unshare('/a/file.txt', 'me'))
|
||||
.rejects.toEqual({ message: 'Too many requests', code: 'too_many_requests' });
|
||||
});
|
||||
|
||||
it('resolves with no refused pairs when there was nothing to withdraw', async () => {
|
||||
answer('success', 0, [{ recipient: 'bob', path: '/a/file.txt', status: 'success' }]);
|
||||
await expect(fs.unshare('/a/file.txt', 'bob')).resolves.toEqual({ revoked: 0, failed: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('readdir', () => {
|
||||
beforeEach(() => {
|
||||
FakeXHR.respondWith = () => [{ uuid: 'u1', name: 'file.txt', path: '/a/file.txt', isDir: false }];
|
||||
|
||||
@@ -4,6 +4,25 @@ import { invalidateShareCache, toShareItems, toShareRecipients } from './shareUt
|
||||
|
||||
/** @typedef {import('../types.js').UnshareOptions} UnshareOptions */
|
||||
/** @typedef {import('../types.js').ShareRecipient} ShareRecipient */
|
||||
/** @typedef {import('../types.js').UnshareResult} UnshareResult */
|
||||
/** @typedef {import('../types.js').UnshareFailure} UnshareFailure */
|
||||
/** @typedef {import('../types.js').UnshareError} UnshareError */
|
||||
|
||||
// The recipient or the item is gone: nothing to withdraw.
|
||||
const GONE_CODES = ['user_does_not_exist', 'subject_does_not_exist'];
|
||||
const UNNAMED_CODE = 'unshare_failed';
|
||||
|
||||
/**
|
||||
* @param {Record<string, unknown>} result a refused pair as the server reports it
|
||||
* @returns {UnshareFailure}
|
||||
*/
|
||||
const toFailure = (result) => ({
|
||||
recipient: String(result.recipient ?? ''),
|
||||
...(result.path ? { path: String(result.path) } : {}),
|
||||
...(result.uid ? { uid: String(result.uid) } : {}),
|
||||
message: String(result.message ?? 'Unshare failed'),
|
||||
code: String(result.code ?? UNNAMED_CODE),
|
||||
});
|
||||
|
||||
/**
|
||||
* Withdraws a user's access to a file or directory.
|
||||
@@ -13,16 +32,19 @@ import { invalidateShareCache, toShareItems, toShareRecipients } from './shareUt
|
||||
* yourself as the recipient to leave a share someone else gave you.
|
||||
*
|
||||
* Resolves with the number of grants actually removed, which is `0` when there
|
||||
* was nothing to withdraw.
|
||||
* was nothing to withdraw, and the recipient/item pairs that were refused. A
|
||||
* refused pair does not fail the others. The promise rejects only when every
|
||||
* pair was refused and at least one for a reason other than the recipient or
|
||||
* the item being gone; that rejection is an `UnshareError`.
|
||||
*
|
||||
* @type {{
|
||||
* (options: UnshareOptions): Promise<{ revoked: number }>,
|
||||
* (options: UnshareOptions): Promise<UnshareResult>,
|
||||
* (
|
||||
* path: string,
|
||||
* recipient: ShareRecipient,
|
||||
* success?: (value: { revoked: number }) => void,
|
||||
* success?: (value: UnshareResult) => void,
|
||||
* error?: (reason: unknown) => void,
|
||||
* ): Promise<{ revoked: number }>,
|
||||
* ): Promise<UnshareResult>,
|
||||
* }}
|
||||
*/
|
||||
const unshare = defineOperation({
|
||||
@@ -37,10 +59,19 @@ const unshare = defineOperation({
|
||||
),
|
||||
items,
|
||||
},
|
||||
transform: (/** @type {{ revoked?: number }} */ response) => {
|
||||
transform: (/** @type {{ revoked?: number, results?: Record<string, unknown>[] }} */ response) => {
|
||||
const results = response.results ?? [];
|
||||
const failed = results.filter((r) => r.status === 'error').map(toFailure);
|
||||
const refusals = failed.filter((f) => ! GONE_CODES.includes(f.code));
|
||||
if ( results.length > 0 && failed.length === results.length && refusals.length > 0 ) {
|
||||
// A pair the server could not complete names no code.
|
||||
const { message, code } =
|
||||
refusals.find((f) => f.code !== UNNAMED_CODE) ?? refusals[0];
|
||||
throw /** @type {UnshareError} */ ({ message, code, failed });
|
||||
}
|
||||
const revoked = Number(response.revoked ?? 0);
|
||||
if ( revoked > 0 ) invalidateShareCache(items);
|
||||
return { revoked };
|
||||
return { revoked, failed };
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -380,12 +380,49 @@
|
||||
* @typedef {Object} UnshareOptionsOwn
|
||||
* @property {string} [path] Item to stop sharing.
|
||||
* @property {string} [uid] Item to stop sharing, by UID.
|
||||
* @property {ShareRecipient} [recipient] Who to withdraw access from. Pass
|
||||
* yourself to leave a share someone else granted you.
|
||||
* @property {string[]} [paths] Several items to stop sharing in one call.
|
||||
* @property {ShareRecipient | ShareRecipient[]} [recipient] Who to withdraw
|
||||
* access from. Pass yourself to leave a share someone else granted you.
|
||||
* @property {ShareRecipient | ShareRecipient[]} [recipients] Alias for
|
||||
* `recipient`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {UnshareOptionsOwn & RequestCallbacks<{ revoked: number }>} UnshareOptions
|
||||
* One recipient/item pair an unshare call was refused for.
|
||||
*
|
||||
* @typedef {Object} UnshareFailure
|
||||
* @property {string} recipient The recipient as the call named it: a
|
||||
* username, an email, a team's uid or handle, or `'anyone'`.
|
||||
* @property {string} [path] The item's absolute path, when the call named
|
||||
* it by path. A relative path comes back resolved against the app's root
|
||||
* directory, and a leading `~` as the user's home directory.
|
||||
* @property {string} [uid] The item's UID as the call passed it, when the
|
||||
* call named it by UID.
|
||||
* @property {string} message Why the pair was refused.
|
||||
* @property {string} code The refusal's code; `unshare_failed` when the
|
||||
* server named none.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} UnshareResult
|
||||
* @property {number} revoked How many grants were removed.
|
||||
* @property {UnshareFailure[]} failed The pairs that were refused; empty when
|
||||
* none were.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The rejection value of `unshare()` when every pair was refused. A request
|
||||
* that failed as a whole rejects with its own error, which has no `failed`.
|
||||
*
|
||||
* @typedef {Object} UnshareError
|
||||
* @property {string} message Why the first refused pair that names a code
|
||||
* other than `user_does_not_exist` or `subject_does_not_exist` was refused.
|
||||
* @property {string} code That pair's code.
|
||||
* @property {UnshareFailure[]} failed Every refused pair.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {UnshareOptionsOwn & RequestCallbacks<UnshareResult>} UnshareOptions
|
||||
*/
|
||||
|
||||
/**
|
||||
|
||||
@@ -352,6 +352,73 @@ export default suite('sharing', {
|
||||
t.assert.equal(result.revoked, 0);
|
||||
},
|
||||
|
||||
'unshare lists a refused pair and still withdraws the others': async (t) => {
|
||||
const path = scratch(t, 'partial');
|
||||
await t.puter.fs.write(path, 'x');
|
||||
await t.puter.fs.share(path, t.env.users.other.username, 'read');
|
||||
|
||||
// The owner can't be removed from their own item. The item is named
|
||||
// from the home directory, and comes back as its absolute path.
|
||||
const result = await t.puter.fs.unshare({
|
||||
path: path.replace(home(t), '~'),
|
||||
recipients: [t.env.users.other.username, t.env.users.user.username],
|
||||
});
|
||||
t.assert.equal(result.revoked, 1);
|
||||
t.assert.equal(result.failed.length, 1);
|
||||
t.assert.equal(result.failed[0].recipient, t.env.users.user.username);
|
||||
t.assert.equal(result.failed[0].path, path);
|
||||
t.assert.equal(result.failed[0].code, 'cannot_revoke_owner');
|
||||
t.assert.equal(typeof result.failed[0].message, 'string');
|
||||
|
||||
const after = await readAsOther(t, path);
|
||||
t.assert.ok(after.status !== 200, `read should fail after unshare (got ${after.status})`);
|
||||
},
|
||||
|
||||
'unshare rejects when every pair was refused': async (t) => {
|
||||
const path = scratch(t, 'refused');
|
||||
const written = await t.puter.fs.write(path, 'x');
|
||||
|
||||
const error = (await t.assert.rejects(() =>
|
||||
t.puter.fs.unshare(path, t.env.users.user.username),
|
||||
)) as { message?: string; code?: string; failed?: Record<string, string>[] };
|
||||
t.assert.equal(error.code, 'cannot_revoke_owner');
|
||||
t.assert.equal(typeof error.message, 'string');
|
||||
t.assert.equal(error.failed?.length, 1);
|
||||
t.assert.equal(error.failed?.[0].path, path);
|
||||
t.assert.equal(error.failed?.[0].code, 'cannot_revoke_owner');
|
||||
|
||||
// Named by UID, the pair carries the UID and no path.
|
||||
const byUid = (await t.assert.rejects(() =>
|
||||
t.puter.fs.unshare({ uid: written.uid, recipient: t.env.users.user.username }),
|
||||
)) as { code?: string; failed?: Record<string, string>[] };
|
||||
t.assert.equal(byUid.code, 'cannot_revoke_owner');
|
||||
t.assert.equal(byUid.failed?.[0].uid, written.uid);
|
||||
t.assert.equal(byUid.failed?.[0].path, undefined);
|
||||
},
|
||||
|
||||
'unshare resolves when the recipient or the item is gone': async (t) => {
|
||||
const path = scratch(t, 'gone');
|
||||
await t.puter.fs.write(path, 'x');
|
||||
|
||||
const noUser = await t.puter.fs.unshare(path, 'no-such-user-zzz');
|
||||
t.assert.equal(noUser.revoked, 0);
|
||||
t.assert.equal(noUser.failed.length, 1);
|
||||
t.assert.equal(noUser.failed[0].recipient, 'no-such-user-zzz');
|
||||
t.assert.equal(noUser.failed[0].code, 'user_does_not_exist');
|
||||
|
||||
// A relative name comes back as the absolute path it resolved to.
|
||||
const name = scratch(t, 'missing').split('/').pop()!;
|
||||
const noItem = await t.puter.fs.unshare(name, t.env.users.other.username);
|
||||
t.assert.equal(noItem.revoked, 0);
|
||||
t.assert.equal(noItem.failed.length, 1);
|
||||
t.assert.equal(noItem.failed[0].code, 'subject_does_not_exist');
|
||||
t.assert.ok(
|
||||
noItem.failed[0].path?.startsWith(`${home(t)}/`) &&
|
||||
noItem.failed[0].path.endsWith(`/${name}`),
|
||||
`path should be absolute (got ${noItem.failed[0].path})`,
|
||||
);
|
||||
},
|
||||
|
||||
'sharing with an unregistered address records an invite': async (t) => {
|
||||
const path = scratch(t, 'invite');
|
||||
await t.puter.fs.write(path, 'x');
|
||||
|
||||
Reference in new issue
Block a user