mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-17 11:17:46 +00:00
feat: notification type registry and audience rules (PUT-1665) (#3671)
This commit is contained in:
1 parent
148b930182
commit
5f37817a5c
16 files changed
+857
-93
No files matched your search
@@ -708,12 +708,16 @@ describe('share endpoints over HTTP', () => {
|
||||
);
|
||||
}
|
||||
|
||||
const seen: Array<{ userIds: number[]; payload: Record<string, unknown> }> = [];
|
||||
const seen: Array<{
|
||||
userIds: number[];
|
||||
payload: Record<string, unknown>;
|
||||
type: string;
|
||||
}> = [];
|
||||
const notification = env.server.services.notification;
|
||||
const original = notification.notify.bind(notification);
|
||||
notification.notify = async (userIds, payload) => {
|
||||
seen.push({ userIds, payload });
|
||||
return original(userIds, payload);
|
||||
notification.notify = async (userIds, payload, opts) => {
|
||||
seen.push({ userIds, payload, type: opts.type });
|
||||
return original(userIds, payload, opts);
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -734,8 +738,8 @@ describe('share endpoints over HTTP', () => {
|
||||
|
||||
// Two items, one recipient — one notification carrying the count.
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0].type).toBe('share.received');
|
||||
expect(seen[0].payload).toMatchObject({
|
||||
source: 'sharing',
|
||||
fields: { count: 2 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -578,9 +578,12 @@ describe('WorkerDriver hot reload', () => {
|
||||
expect(notifySpy).toHaveBeenCalledWith(
|
||||
[user.id],
|
||||
expect.objectContaining({
|
||||
source: 'worker',
|
||||
title: `Successfully deployed https://${name}.puter.work`,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: 'app.worker.deployed',
|
||||
appUid: null,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -977,6 +977,8 @@ export class WorkerDriver extends PuterDriver {
|
||||
const workerName = workerFullName.slice(
|
||||
WORKER_SUBDOMAIN_PREFIX.length,
|
||||
);
|
||||
// Null until resolved, and for a worker bound to no app at all.
|
||||
let appUid: string | null = null;
|
||||
|
||||
try {
|
||||
const ownerUser = await this.stores.user.getById(entry.userId);
|
||||
@@ -1007,6 +1009,7 @@ export class WorkerDriver extends PuterDriver {
|
||||
if (appOwnerId) {
|
||||
const app = await this.stores.app.getById(appOwnerId);
|
||||
if (!app) continue; // app gone
|
||||
appUid = String(app.uid);
|
||||
authorization =
|
||||
await this.services.auth.createWorkerAppToken(
|
||||
ownerActor,
|
||||
@@ -1039,16 +1042,23 @@ export class WorkerDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
// Notify the user
|
||||
await this.#notifyUser(entry.userId, workerName, cfResult);
|
||||
await this.#notifyUser(
|
||||
entry.userId,
|
||||
workerName,
|
||||
cfResult,
|
||||
appUid,
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[workers] hot-reload deploy failed for ${workerName}`,
|
||||
err,
|
||||
);
|
||||
await this.#notifyUser(entry.userId, workerName, {
|
||||
success: false,
|
||||
errors: [String(err)],
|
||||
});
|
||||
await this.#notifyUser(
|
||||
entry.userId,
|
||||
workerName,
|
||||
{ success: false, errors: [String(err)] },
|
||||
appUid,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1184,17 +1194,23 @@ export class WorkerDriver extends PuterDriver {
|
||||
userId: number,
|
||||
workerName: string,
|
||||
result: { success?: boolean; errors?: unknown[]; url?: string },
|
||||
appUid: string | null,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const title = result.success
|
||||
? `Successfully deployed https://${workerName}.puter.work`
|
||||
: `Failed to deploy ${workerName}! ${(result.errors ?? []).join(', ')}`;
|
||||
|
||||
await this.services.notification.notify([userId], {
|
||||
source: 'worker',
|
||||
title,
|
||||
template: 'user-requesting-share',
|
||||
});
|
||||
await this.services.notification.notify(
|
||||
[userId],
|
||||
{ title },
|
||||
{
|
||||
type: result.success
|
||||
? 'app.worker.deployed'
|
||||
: 'app.worker.deployFailed',
|
||||
appUid,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn('[workers] notification create failed', err);
|
||||
}
|
||||
|
||||
@@ -85,10 +85,11 @@ describe('NotificationService.notify', () => {
|
||||
const pushed = collect('outer.gui.notif.message');
|
||||
const persisted = collect('outer.gui.notif.persisted');
|
||||
|
||||
const uid = await notifications.notify([a.id, b.id], {
|
||||
source: 'test',
|
||||
title: 'hello',
|
||||
});
|
||||
const uid = await notifications.notify(
|
||||
[a.id, b.id],
|
||||
{ title: 'hello' },
|
||||
{ type: 'share.received' },
|
||||
);
|
||||
|
||||
// One push per recipient, each with a distinct uid — the row uid is
|
||||
// UNIQUE table-wide, so a shared batch uid could never name both rows.
|
||||
@@ -101,8 +102,8 @@ describe('NotificationService.notify', () => {
|
||||
);
|
||||
expect([...byUser.keys()].sort()).toEqual([a.id, b.id].sort());
|
||||
expect(byUser.get(a.id)!.notification).toEqual({
|
||||
source: 'test',
|
||||
title: 'hello',
|
||||
type: 'share.received',
|
||||
});
|
||||
expect(byUser.get(a.id)!.uid).not.toBe(byUser.get(b.id)!.uid);
|
||||
// The returned uid is the first recipient's.
|
||||
@@ -120,7 +121,13 @@ describe('NotificationService.notify', () => {
|
||||
);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].uid).toBe(byUser.get(user.id)!.uid);
|
||||
expect(rows[0].value).toEqual({ source: 'test', title: 'hello' });
|
||||
expect(rows[0].value).toEqual({
|
||||
title: 'hello',
|
||||
type: 'share.received',
|
||||
});
|
||||
expect(rows[0].type).toBe('share.received');
|
||||
expect(rows[0].audience).toBe('account');
|
||||
expect(rows[0].app_uid).toBeNull();
|
||||
}
|
||||
|
||||
pushed.stop();
|
||||
@@ -134,10 +141,11 @@ describe('NotificationService.notify', () => {
|
||||
|
||||
// userId 0 is falsy — NotificationStore.create rejects it. The
|
||||
// remaining user must still be written and still report persisted.
|
||||
await notifications.notify([0, good.id], {
|
||||
source: 'test',
|
||||
title: 'partial',
|
||||
});
|
||||
await notifications.notify(
|
||||
[0, good.id],
|
||||
{ title: 'partial' },
|
||||
{ type: 'share.received' },
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
persisted.seen.some(
|
||||
@@ -157,11 +165,130 @@ describe('NotificationService.notify', () => {
|
||||
|
||||
it('is a no-op push for an empty recipient list', async () => {
|
||||
const pushed = collect('outer.gui.notif.message');
|
||||
const uid = await notifications.notify([], { source: 'test' });
|
||||
const uid = await notifications.notify(
|
||||
[],
|
||||
{},
|
||||
{ type: 'share.received' },
|
||||
);
|
||||
expect(pushed.seen).toEqual([]);
|
||||
expect(uid).toMatch(/^[0-9a-f-]{8}-/);
|
||||
pushed.stop();
|
||||
});
|
||||
|
||||
it('records the audience and app the registry entry declares', async () => {
|
||||
const user = await makeUser();
|
||||
const appUid = `app-${uuidv4()}`;
|
||||
const persisted = collect('outer.gui.notif.persisted');
|
||||
|
||||
await notifications.notify(
|
||||
[user.id],
|
||||
{ title: 'subscription ended' },
|
||||
{ type: 'app.events.ended', appUid },
|
||||
);
|
||||
await waitFor(() => persisted.seen.length === 1);
|
||||
|
||||
const [row] = await server.stores.notification.listByUserId(
|
||||
user.id,
|
||||
{},
|
||||
);
|
||||
expect(row.type).toBe('app.events.ended');
|
||||
expect(row.audience).toBe('developer');
|
||||
expect(row.app_uid).toBe(appUid);
|
||||
persisted.stop();
|
||||
});
|
||||
|
||||
it('writes nothing and pushes nothing for an unregistered type', async () => {
|
||||
const user = await makeUser();
|
||||
const pushed = collect('outer.gui.notif.message');
|
||||
|
||||
await expect(
|
||||
notifications.notify(
|
||||
[user.id],
|
||||
{ title: 'nope' },
|
||||
// Only reachable from an untyped caller; the registry is the
|
||||
// gate either way.
|
||||
{ type: 'account.invented' as 'share.received' },
|
||||
),
|
||||
).rejects.toThrow('not registered');
|
||||
|
||||
expect(pushed.seen).toEqual([]);
|
||||
expect(
|
||||
await server.stores.notification.listByUserId(user.id, {}),
|
||||
).toHaveLength(0);
|
||||
pushed.stop();
|
||||
});
|
||||
|
||||
it('refuses an app uid on an account type and a missing one on an app-scoped type', async () => {
|
||||
const user = await makeUser();
|
||||
const pushed = collect('outer.gui.notif.message');
|
||||
|
||||
await expect(
|
||||
notifications.notify(
|
||||
[user.id],
|
||||
{},
|
||||
{ type: 'share.received', appUid: `app-${uuidv4()}` },
|
||||
),
|
||||
).rejects.toThrow('cannot name an app');
|
||||
|
||||
await expect(
|
||||
notifications.notify([user.id], {}, { type: 'app.events.ended' }),
|
||||
).rejects.toThrow('requires an app uid');
|
||||
|
||||
expect(pushed.seen).toEqual([]);
|
||||
expect(
|
||||
await server.stores.notification.listByUserId(user.id, {}),
|
||||
).toHaveLength(0);
|
||||
pushed.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationService.notifyUpdate', () => {
|
||||
it('rewrites an open row and keeps its type on the payload', async () => {
|
||||
const user = await makeUser();
|
||||
const persisted = collect('outer.gui.notif.persisted');
|
||||
const uid = await notifications.notify(
|
||||
[user.id],
|
||||
{ title: 'one share' },
|
||||
{ type: 'share.received' },
|
||||
);
|
||||
await waitFor(() => persisted.seen.length === 1);
|
||||
persisted.stop();
|
||||
|
||||
const pushed = collect('outer.gui.notif.message');
|
||||
expect(
|
||||
await notifications.notifyUpdate(
|
||||
uid,
|
||||
user.id,
|
||||
{ title: 'two shares' },
|
||||
{ type: 'share.received' },
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
expect(pushed.seen).toHaveLength(1);
|
||||
expect((pushed.seen[0] as NotifPush).response.notification).toEqual({
|
||||
title: 'two shares',
|
||||
type: 'share.received',
|
||||
});
|
||||
const row = await server.stores.notification.getByUid(uid, {
|
||||
userId: user.id,
|
||||
});
|
||||
// The scope columns belong to the original row and do not move.
|
||||
expect(row?.type).toBe('share.received');
|
||||
expect(row?.audience).toBe('account');
|
||||
pushed.stop();
|
||||
});
|
||||
|
||||
it('refuses to fold a type that does not group', async () => {
|
||||
const user = await makeUser();
|
||||
await expect(
|
||||
notifications.notifyUpdate(
|
||||
'no-such-uid',
|
||||
user.id,
|
||||
{},
|
||||
{ type: 'share.claimed' },
|
||||
),
|
||||
).rejects.toThrow('not groupable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationService.markAcknowledged / markShown', () => {
|
||||
@@ -316,10 +443,11 @@ describe('NotificationService — unread delivery on connect', () => {
|
||||
describe('NotificationService — delivery receipts', () => {
|
||||
it('marks a notification shown once the socket fan-out reports delivery', async () => {
|
||||
const user = await makeUser();
|
||||
const uid = await notifications.notify([user.id], {
|
||||
source: 'test',
|
||||
title: 'receipt',
|
||||
});
|
||||
const uid = await notifications.notify(
|
||||
[user.id],
|
||||
{ title: 'receipt' },
|
||||
{ type: 'share.received' },
|
||||
);
|
||||
|
||||
// What SocketService emits after pushing `notif.message` to a room.
|
||||
server.clients.event.emit(
|
||||
|
||||
@@ -19,6 +19,22 @@
|
||||
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PuterService } from '../types.js';
|
||||
import {
|
||||
findNotificationType,
|
||||
resolveNotificationWrite,
|
||||
} from './notificationTypes.js';
|
||||
import type { NotificationTypeName } from './notificationTypes.js';
|
||||
|
||||
export {
|
||||
NOTIFICATION_TYPES,
|
||||
findNotificationType,
|
||||
} from './notificationTypes.js';
|
||||
export type {
|
||||
NotificationAudience,
|
||||
NotificationType,
|
||||
NotificationTypeName,
|
||||
} from './notificationTypes.js';
|
||||
export { canViewNotification } from './notificationAudience.js';
|
||||
|
||||
/**
|
||||
* Notification orchestration — glues the NotificationStore (DB) to the event
|
||||
@@ -94,17 +110,29 @@ export class NotificationService extends PuterService {
|
||||
* look, but nothing interrupts them now. For callers that budget how often
|
||||
* they may interrupt someone and must still keep the record straight.
|
||||
*
|
||||
* `type` names a registry entry and decides the row's audience; an
|
||||
* unregistered one, or an app uid the entry does not allow, throws before
|
||||
* anything is written or pushed. The type rides along in the payload too,
|
||||
* so a client reading only the socket message can tell what it received.
|
||||
*
|
||||
* @param userIds Target user ids
|
||||
* @param notification Payload — { source, title, text?, icon?, template?,
|
||||
* fields? }
|
||||
* @param opts `{ silent }` to skip the socket push.
|
||||
* @param notification Payload — { title, text?, icon?, fields? }
|
||||
* @param opts `{ type }` from the registry, `{ appUid }` for a row about an
|
||||
* app, `{ silent }` to skip the socket push.
|
||||
* @returns The uid of the first recipient's notification.
|
||||
*/
|
||||
async notify(
|
||||
userIds: number[],
|
||||
notification: Record<string, unknown>,
|
||||
opts: { silent?: boolean } = {},
|
||||
opts: {
|
||||
type: NotificationTypeName;
|
||||
appUid?: string | null;
|
||||
silent?: boolean;
|
||||
},
|
||||
): Promise<string> {
|
||||
const appUid = opts.appUid ?? null;
|
||||
const registered = resolveNotificationWrite(opts.type, appUid);
|
||||
const payload = { ...notification, type: registered.type };
|
||||
const uidByIndex = userIds.map(() => uuidv4());
|
||||
|
||||
// Immediate socket push (before DB write completes)
|
||||
@@ -114,7 +142,10 @@ export class NotificationService extends PuterService {
|
||||
'outer.gui.notif.message',
|
||||
{
|
||||
user_id_list: [userId],
|
||||
response: { uid: uidByIndex[i], notification },
|
||||
response: {
|
||||
uid: uidByIndex[i],
|
||||
notification: payload,
|
||||
},
|
||||
},
|
||||
{},
|
||||
);
|
||||
@@ -128,8 +159,11 @@ export class NotificationService extends PuterService {
|
||||
try {
|
||||
await this.stores.notification.create({
|
||||
userId,
|
||||
value: notification,
|
||||
value: payload,
|
||||
uid,
|
||||
type: registered.type,
|
||||
audience: registered.audience,
|
||||
appUid,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
@@ -162,7 +196,8 @@ export class NotificationService extends PuterService {
|
||||
/**
|
||||
* Rewrite a notification the recipient hasn't dismissed and deliver it
|
||||
* again — for a story that grows rather than repeats, where a second
|
||||
* notification would just be noise.
|
||||
* notification would just be noise. Only a `groupable` type may be folded
|
||||
* this way; the scope columns are the original row's and don't move.
|
||||
*
|
||||
* False when there was nothing to rewrite (dismissed in between), which is
|
||||
* the caller's signal to send a fresh one.
|
||||
@@ -171,12 +206,17 @@ export class NotificationService extends PuterService {
|
||||
uid: string,
|
||||
userId: number,
|
||||
notification: Record<string, unknown>,
|
||||
opts: { silent?: boolean } = {},
|
||||
opts: { type: NotificationTypeName; silent?: boolean },
|
||||
): Promise<boolean> {
|
||||
const registered = findNotificationType(opts.type);
|
||||
if (!registered?.groupable) {
|
||||
throw new Error(`notification type is not groupable: ${opts.type}`);
|
||||
}
|
||||
const payload = { ...notification, type: registered.type };
|
||||
const updated = await this.stores.notification.updateValue(
|
||||
uid,
|
||||
userId,
|
||||
notification,
|
||||
payload,
|
||||
);
|
||||
if (!updated) return false;
|
||||
|
||||
@@ -187,7 +227,7 @@ export class NotificationService extends PuterService {
|
||||
'outer.gui.notif.message',
|
||||
{
|
||||
user_id_list: [userId],
|
||||
response: { uid, notification },
|
||||
response: { uid, notification: payload },
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { makeActor } from '../../core/actor.js';
|
||||
import type { Actor } from '../../core/actor.js';
|
||||
import { canViewNotification } from './notificationAudience.js';
|
||||
|
||||
const OWN_APP = 'app-11111111-1111-4111-8111-111111111111';
|
||||
const OTHER_APP = 'app-22222222-2222-4222-8222-222222222222';
|
||||
|
||||
const user = { uuid: 'user-uuid', username: 'holder', id: 7 };
|
||||
|
||||
/** A plain web session: no app anywhere in the chain. */
|
||||
const session = makeActor({ user });
|
||||
|
||||
/** An app-under-user token. */
|
||||
const appUnderUser = makeActor({ user, app: { uid: OWN_APP, id: 1 } });
|
||||
|
||||
/** An access token an app minted: its app arrives through the issuer. */
|
||||
const appIssuedToken = makeActor({
|
||||
user,
|
||||
accessToken: { uid: 'tok-app', issuer: appUnderUser },
|
||||
});
|
||||
|
||||
/** An access token a plain session minted: still no app. */
|
||||
const userIssuedToken = makeActor({
|
||||
user,
|
||||
accessToken: { uid: 'tok-user', issuer: session },
|
||||
});
|
||||
|
||||
/** Never went through `makeActor`, so `effectiveApp` was never derived. */
|
||||
const unresolved = { user } as Actor;
|
||||
|
||||
const owns = { recipientOwnsApp: true };
|
||||
|
||||
describe('canViewNotification — account rows', () => {
|
||||
const account = { audience: 'account', appUid: null };
|
||||
|
||||
it('reaches a session and a token that session issued', () => {
|
||||
expect(canViewNotification(account, session)).toBe(true);
|
||||
expect(canViewNotification(account, userIssuedToken)).toBe(true);
|
||||
});
|
||||
|
||||
it('never reaches an actor acting as an app', () => {
|
||||
expect(canViewNotification(account, appUnderUser)).toBe(false);
|
||||
// The access token carries no `app` of its own — the app it acts as
|
||||
// arrives through the issuer chain, and reading `app` would let it
|
||||
// through.
|
||||
expect(appIssuedToken.app).toBeUndefined();
|
||||
expect(appIssuedToken.effectiveApp?.uid).toBe(OWN_APP);
|
||||
expect(canViewNotification(account, appIssuedToken)).toBe(false);
|
||||
});
|
||||
|
||||
it('is not overridable by ownership', () => {
|
||||
expect(canViewNotification(account, appUnderUser, owns)).toBe(false);
|
||||
});
|
||||
|
||||
it('denies an actor whose app was never resolved', () => {
|
||||
expect(canViewNotification(account, unresolved)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canViewNotification — developer rows', () => {
|
||||
const own = { audience: 'developer', appUid: OWN_APP };
|
||||
|
||||
it('reaches the owner session and the app itself', () => {
|
||||
expect(canViewNotification(own, session, owns)).toBe(true);
|
||||
expect(canViewNotification(own, appUnderUser, owns)).toBe(true);
|
||||
expect(canViewNotification(own, appIssuedToken, owns)).toBe(true);
|
||||
});
|
||||
|
||||
it('is empty rather than an error for a holder who does not own the app', () => {
|
||||
expect(canViewNotification(own, session)).toBe(false);
|
||||
expect(canViewNotification(own, appUnderUser)).toBe(false);
|
||||
expect(canViewNotification(own, appIssuedToken)).toBe(false);
|
||||
});
|
||||
|
||||
it('never crosses to another app', () => {
|
||||
const other = { audience: 'developer', appUid: OTHER_APP };
|
||||
expect(canViewNotification(other, appUnderUser, owns)).toBe(false);
|
||||
expect(canViewNotification(other, appIssuedToken, owns)).toBe(false);
|
||||
// The owning user still sees it from a session.
|
||||
expect(canViewNotification(other, session, owns)).toBe(true);
|
||||
});
|
||||
|
||||
it('treats a row naming no app as the recipient own', () => {
|
||||
const unattributed = { audience: 'developer', appUid: null };
|
||||
expect(canViewNotification(unattributed, session)).toBe(true);
|
||||
expect(canViewNotification(unattributed, userIssuedToken)).toBe(true);
|
||||
expect(canViewNotification(unattributed, appUnderUser, owns)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(canViewNotification(unattributed, appIssuedToken, owns)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('denies an actor whose app was never resolved', () => {
|
||||
expect(canViewNotification(own, unresolved, owns)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canViewNotification — app-user rows', () => {
|
||||
const own = { audience: 'app-user', appUid: OWN_APP };
|
||||
|
||||
it('reaches the user session and the app it is about, ownership aside', () => {
|
||||
expect(canViewNotification(own, session)).toBe(true);
|
||||
expect(canViewNotification(own, appUnderUser)).toBe(true);
|
||||
expect(canViewNotification(own, appIssuedToken)).toBe(true);
|
||||
});
|
||||
|
||||
it('never crosses to another app', () => {
|
||||
const other = { audience: 'app-user', appUid: OTHER_APP };
|
||||
expect(canViewNotification(other, appUnderUser)).toBe(false);
|
||||
expect(canViewNotification(other, appIssuedToken)).toBe(false);
|
||||
expect(canViewNotification(other, session)).toBe(true);
|
||||
});
|
||||
|
||||
it('denies an actor whose app was never resolved', () => {
|
||||
expect(canViewNotification(own, unresolved)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canViewNotification — unknown audiences', () => {
|
||||
it('denies an audience nothing registers', () => {
|
||||
for (const actor of [session, appUnderUser, appIssuedToken]) {
|
||||
expect(
|
||||
canViewNotification(
|
||||
{ audience: 'everyone', appUid: null },
|
||||
actor,
|
||||
owns,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
canViewNotification({ audience: '', appUid: OWN_APP }, actor, owns),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type { Actor } from '../../core/actor.js';
|
||||
|
||||
/** The scope columns of a `notification` row. */
|
||||
export interface NotificationRowScope {
|
||||
audience: string;
|
||||
appUid: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationVisibilityFacts {
|
||||
/**
|
||||
* Whether the row's recipient owns the app it names — the `developer`
|
||||
* audience is the app owner's, so nothing else may read it. Absent denies,
|
||||
* so a caller that cannot answer it gets no developer rows.
|
||||
*/
|
||||
recipientOwnsApp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an actor may see one row of a recipient's mailbox. Scoping to the
|
||||
* recipient is the caller's job; this decides audience only.
|
||||
*
|
||||
* Default-deny by audience rather than a filter applied afterwards: an
|
||||
* `account` row — email changed, card verified, an abuse block — must never
|
||||
* reach an actor acting as an app, and no grant overrides that. `developer`
|
||||
* rows are the app owner's; an ordinary app token asking for them gets nothing
|
||||
* back rather than a refusal, because the app roster is not an oracle.
|
||||
*
|
||||
* Reads `effectiveApp`, so an access token issued by an app is treated as that
|
||||
* app; `undefined` means the actor never went through `makeActor` and is denied
|
||||
* rather than read as "no app".
|
||||
*/
|
||||
export const canViewNotification = (
|
||||
scope: NotificationRowScope,
|
||||
actor: Pick<Actor, 'effectiveApp'>,
|
||||
facts: NotificationVisibilityFacts = {},
|
||||
): boolean => {
|
||||
if (actor.effectiveApp === undefined) return false;
|
||||
const viewingApp = actor.effectiveApp?.uid ?? null;
|
||||
|
||||
if (scope.audience === 'account') return viewingApp === null;
|
||||
if (scope.audience !== 'developer' && scope.audience !== 'app-user') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// An app-scoped audience on a row naming no app: legacy worker rows, and
|
||||
// deploys of a worker bound to no app. It is the recipient's, and no
|
||||
// app's.
|
||||
if (!scope.appUid) return viewingApp === null;
|
||||
|
||||
if (viewingApp !== null && viewingApp !== scope.appUid) return false;
|
||||
return scope.audience === 'app-user' || facts.recipientOwnsApp === true;
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
NOTIFICATION_TYPES,
|
||||
findNotificationType,
|
||||
resolveNotificationWrite,
|
||||
} from './notificationTypes.js';
|
||||
|
||||
describe('NOTIFICATION_TYPES', () => {
|
||||
it('names every type exactly once', () => {
|
||||
const names = NOTIFICATION_TYPES.map((entry) => entry.type);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
it('keeps account rows off apps entirely', () => {
|
||||
for (const entry of NOTIFICATION_TYPES) {
|
||||
if (entry.audience !== 'account') continue;
|
||||
expect(entry.appScoped).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('only app-scoped audiences may require an app', () => {
|
||||
for (const entry of NOTIFICATION_TYPES) {
|
||||
if (!entry.appScoped) continue;
|
||||
expect(['developer', 'app-user']).toContain(entry.audience);
|
||||
}
|
||||
});
|
||||
|
||||
it('carries the types the events work will emit', () => {
|
||||
for (const type of ['app.events.ended', 'app.events.suspended']) {
|
||||
const entry = findNotificationType(type);
|
||||
expect(entry).toMatchObject({
|
||||
audience: 'developer',
|
||||
appScoped: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('projects a subject naming the app, or the recipient when there is none', () => {
|
||||
const account = findNotificationType('share.received')!;
|
||||
expect(
|
||||
account.subject({ userUuid: 'user-uuid', appUid: null }),
|
||||
).toBe('notif:user-uuid:account');
|
||||
|
||||
const developer = findNotificationType('app.events.ended')!;
|
||||
expect(
|
||||
developer.subject({ userUuid: 'user-uuid', appUid: 'app-1' }),
|
||||
).toBe('notif:app-1:developer');
|
||||
|
||||
// A worker bound to no app has no app to name.
|
||||
const worker = findNotificationType('app.worker.deployed')!;
|
||||
expect(worker.subject({ userUuid: 'user-uuid', appUid: null })).toBe(
|
||||
'notif:user-uuid:developer',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveNotificationWrite', () => {
|
||||
it('returns the entry for a legal write', () => {
|
||||
expect(resolveNotificationWrite('share.received', null).audience).toBe(
|
||||
'account',
|
||||
);
|
||||
expect(
|
||||
resolveNotificationWrite('app.events.suspended', 'app-1').audience,
|
||||
).toBe('developer');
|
||||
// Not app-scoped, but carries the app where one is known.
|
||||
expect(
|
||||
resolveNotificationWrite('app.worker.deployed', 'app-1').audience,
|
||||
).toBe('developer');
|
||||
expect(
|
||||
resolveNotificationWrite('app.worker.deployed', null).audience,
|
||||
).toBe('developer');
|
||||
});
|
||||
|
||||
it('rejects an unregistered type', () => {
|
||||
expect(() => resolveNotificationWrite('share.invented', null)).toThrow(
|
||||
'not registered',
|
||||
);
|
||||
expect(() => resolveNotificationWrite('', null)).toThrow(
|
||||
'not registered',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an app uid on an account type', () => {
|
||||
expect(() =>
|
||||
resolveNotificationWrite('share.received', 'app-1'),
|
||||
).toThrow('cannot name an app');
|
||||
});
|
||||
|
||||
it('rejects an app-scoped type with no app uid', () => {
|
||||
expect(() => resolveNotificationWrite('app.events.ended', null)).toThrow(
|
||||
'requires an app uid',
|
||||
);
|
||||
expect(() => resolveNotificationWrite('app.events.ended', '')).toThrow(
|
||||
'requires an app uid',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/** Who the recipient is in relation to the notification. */
|
||||
export type NotificationAudience = 'account' | 'developer' | 'app-user';
|
||||
|
||||
/** What a subject is built from: the recipient, and the app the row is about. */
|
||||
export interface NotificationSubjectRef {
|
||||
userUuid: string;
|
||||
appUid: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationType {
|
||||
/** Stable wire name, stored in `notification`.`type`. */
|
||||
type: string;
|
||||
audience: NotificationAudience;
|
||||
/**
|
||||
* Whether a row of this type must name an app. `account` types never may; a
|
||||
* `developer` type that is not app-scoped still carries one where the app
|
||||
* is known.
|
||||
*/
|
||||
appScoped: boolean;
|
||||
/** Whether `notifyUpdate` may fold a later one into an open row. */
|
||||
groupable: boolean;
|
||||
/** Where a delivery of this type publishes. */
|
||||
subject: (ref: NotificationSubjectRef) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `notif:<appUid>:<audience>`, falling back to the recipient when the row names
|
||||
* no app — which is every `account` row, and the worker rows whose app is
|
||||
* optional.
|
||||
*/
|
||||
const subjectFor =
|
||||
(audience: NotificationAudience) =>
|
||||
(ref: NotificationSubjectRef): string =>
|
||||
`notif:${ref.appUid ?? ref.userUuid}:${audience}`;
|
||||
|
||||
/**
|
||||
* The catalog. Every write goes through it, so a type that is not here cannot
|
||||
* reach the table.
|
||||
*
|
||||
* `audience` is not derivable from `app_uid`: "your worker failed to deploy"
|
||||
* and "your background job finished" both name an app, but the first must never
|
||||
* reach a _user_ of that app.
|
||||
*/
|
||||
export const NOTIFICATION_TYPES = [
|
||||
{
|
||||
type: 'share.received',
|
||||
audience: 'account',
|
||||
appScoped: false,
|
||||
groupable: true,
|
||||
subject: subjectFor('account'),
|
||||
},
|
||||
{
|
||||
type: 'share.claimed',
|
||||
audience: 'account',
|
||||
appScoped: false,
|
||||
groupable: false,
|
||||
subject: subjectFor('account'),
|
||||
},
|
||||
// A worker need not be bound to an app — `#resolveWorkerAppBinding`
|
||||
// returns null for a user-scoped one — so these carry an app only when
|
||||
// there is one to carry.
|
||||
{
|
||||
type: 'app.worker.deployed',
|
||||
audience: 'developer',
|
||||
appScoped: false,
|
||||
groupable: false,
|
||||
subject: subjectFor('developer'),
|
||||
},
|
||||
{
|
||||
type: 'app.worker.deployFailed',
|
||||
audience: 'developer',
|
||||
appScoped: false,
|
||||
groupable: false,
|
||||
subject: subjectFor('developer'),
|
||||
},
|
||||
{
|
||||
type: 'app.events.ended',
|
||||
audience: 'developer',
|
||||
appScoped: true,
|
||||
groupable: false,
|
||||
subject: subjectFor('developer'),
|
||||
},
|
||||
{
|
||||
type: 'app.events.suspended',
|
||||
audience: 'developer',
|
||||
appScoped: true,
|
||||
groupable: false,
|
||||
subject: subjectFor('developer'),
|
||||
},
|
||||
] as const satisfies readonly NotificationType[];
|
||||
|
||||
/** Every registered type name; what `notify` accepts. */
|
||||
export type NotificationTypeName = (typeof NOTIFICATION_TYPES)[number]['type'];
|
||||
|
||||
const BY_NAME = new Map<string, NotificationType>(
|
||||
NOTIFICATION_TYPES.map((entry) => [entry.type, entry]),
|
||||
);
|
||||
|
||||
export const findNotificationType = (
|
||||
type: string,
|
||||
): NotificationType | undefined => BY_NAME.get(type);
|
||||
|
||||
/**
|
||||
* The registry entry for a write, or a throw. `account` rows never name an app;
|
||||
* app-scoped rows always do.
|
||||
*/
|
||||
export const resolveNotificationWrite = (
|
||||
type: string,
|
||||
appUid: string | null,
|
||||
): NotificationType => {
|
||||
const entry = BY_NAME.get(type);
|
||||
if (!entry) {
|
||||
throw new Error(`notification type is not registered: ${type}`);
|
||||
}
|
||||
if (entry.audience === 'account' && appUid !== null) {
|
||||
throw new Error(
|
||||
`notification type ${type} is account-audience and cannot name an app`,
|
||||
);
|
||||
}
|
||||
if (entry.appScoped && !appUid) {
|
||||
throw new Error(`notification type ${type} requires an app uid`);
|
||||
}
|
||||
return entry;
|
||||
};
|
||||
@@ -81,15 +81,21 @@ describe('ShareNotificationService', () => {
|
||||
const calls: Array<{
|
||||
userIds: number[];
|
||||
payload: Record<string, unknown>;
|
||||
type: string;
|
||||
silent: boolean;
|
||||
}> = [];
|
||||
vi.spyOn(server.services.notification, 'notify').mockImplementation(
|
||||
async (
|
||||
userIds: number[],
|
||||
payload: Record<string, unknown>,
|
||||
opts: { silent?: boolean } = {},
|
||||
opts: { type: string; silent?: boolean },
|
||||
) => {
|
||||
calls.push({ userIds, payload, silent: Boolean(opts.silent) });
|
||||
calls.push({
|
||||
userIds,
|
||||
payload,
|
||||
type: opts.type,
|
||||
silent: Boolean(opts.silent),
|
||||
});
|
||||
return 'stub-uid';
|
||||
},
|
||||
);
|
||||
@@ -102,8 +108,7 @@ describe('ShareNotificationService', () => {
|
||||
filter: 'unacknowledged',
|
||||
});
|
||||
return rows.filter(
|
||||
(row: { value?: { template?: string } }) =>
|
||||
row.value?.template === 'file-shared-with-you',
|
||||
(row: { type?: string }) => row.type === 'share.received',
|
||||
);
|
||||
};
|
||||
|
||||
@@ -127,7 +132,7 @@ describe('ShareNotificationService', () => {
|
||||
const byUser = new Map(calls.map((c) => [c.userIds[0], c.payload]));
|
||||
expect(byUser.get(alice.id)?.fields).toMatchObject({ count: 3 });
|
||||
expect(byUser.get(bob.id)?.fields).toMatchObject({ count: 2 });
|
||||
expect(byUser.get(alice.id)?.source).toBe('sharing');
|
||||
expect(calls.every((c) => c.type === 'share.received')).toBe(true);
|
||||
});
|
||||
|
||||
it('says "an item" for one and "items" for several', async () => {
|
||||
|
||||
@@ -102,10 +102,14 @@ const HOUR_MS = 60 * 60_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
/** Notifications this service folds shares into. */
|
||||
const SHARE_TEMPLATE = 'file-shared-with-you';
|
||||
const SHARE_TYPE = 'share.received';
|
||||
|
||||
/** Kept distinct from `SHARE_TEMPLATE` so grouping never rewrites it. */
|
||||
const CLAIM_TEMPLATE = 'file-shared-before-you-joined';
|
||||
/**
|
||||
* The `template` marker `SHARE_TYPE` rows carried before the type registry.
|
||||
* Still matched when looking for an open group, so a notification written by
|
||||
* the previous release still absorbs today's shares.
|
||||
*/
|
||||
const LEGACY_SHARE_TEMPLATE = 'file-shared-with-you';
|
||||
|
||||
/** A budget: a key, how many are allowed, and over what window. */
|
||||
type Budget = [key: string, limit: number, windowMs: number];
|
||||
@@ -350,7 +354,7 @@ export class ShareNotificationService extends PuterService {
|
||||
open.uid,
|
||||
holderId,
|
||||
folded,
|
||||
{ silent },
|
||||
{ type: SHARE_TYPE, silent },
|
||||
)
|
||||
) {
|
||||
return;
|
||||
@@ -367,7 +371,7 @@ export class ShareNotificationService extends PuterService {
|
||||
Date.now() + this.#limits().pairWindowSeconds * 1000,
|
||||
count === 1 ? target : null,
|
||||
),
|
||||
{ silent },
|
||||
{ type: SHARE_TYPE, silent },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -384,9 +388,7 @@ export class ShareNotificationService extends PuterService {
|
||||
target: ShareNotificationTarget | null,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
source: 'sharing',
|
||||
title: shareNotifyTitle(senders),
|
||||
template: SHARE_TEMPLATE,
|
||||
// `username` and `count` are the pre-grouping shape, kept for
|
||||
// anything still reading it; `senders` is what the title is from.
|
||||
fields: {
|
||||
@@ -416,7 +418,10 @@ export class ShareNotificationService extends PuterService {
|
||||
template?: unknown;
|
||||
fields?: { groupUntil?: unknown };
|
||||
};
|
||||
if (value.template !== SHARE_TEMPLATE || !row?.uid) continue;
|
||||
const isOpenShare =
|
||||
row?.type === SHARE_TYPE ||
|
||||
value.template === LEGACY_SHARE_TEMPLATE;
|
||||
if (!isOpenShare || !row?.uid) continue;
|
||||
|
||||
// Newest first, so the first share notification is the only
|
||||
// candidate: if its group has closed, every older one's has too.
|
||||
@@ -929,12 +934,14 @@ export class ShareNotificationService extends PuterService {
|
||||
if (shares.length === 0) return;
|
||||
try {
|
||||
const count = shares.length;
|
||||
await this.services.notification.notify([holderId], {
|
||||
source: 'sharing',
|
||||
title: `${count === 1 ? 'An item was' : `${count} items were`} shared with you before you joined`,
|
||||
template: CLAIM_TEMPLATE,
|
||||
fields: { count },
|
||||
});
|
||||
await this.services.notification.notify(
|
||||
[holderId],
|
||||
{
|
||||
title: `${count === 1 ? 'An item was' : `${count} items were`} shared with you before you joined`,
|
||||
fields: { count },
|
||||
},
|
||||
{ type: 'share.claimed' },
|
||||
);
|
||||
} catch {
|
||||
// Best-effort by design; see the class comment.
|
||||
}
|
||||
|
||||
@@ -106,8 +106,14 @@ export class NotificationStore extends PuterStore {
|
||||
* notification service is what decides which combinations are legal, and
|
||||
* the empty `type` written by a caller that names none reads as legacy.
|
||||
*
|
||||
* @param {{ userId: number; value: unknown; uid?: string; type?: string;
|
||||
* audience?: string; appUid?: string | null }} args
|
||||
* @param {{
|
||||
* userId: number;
|
||||
* value: unknown;
|
||||
* uid?: string;
|
||||
* type?: string;
|
||||
* audience?: string;
|
||||
* appUid?: string | null;
|
||||
* }} args
|
||||
*/
|
||||
async create({
|
||||
userId,
|
||||
|
||||
@@ -82,7 +82,7 @@ const toastIconFor = (notification) => {
|
||||
? window.icons[iconName]
|
||||
: null;
|
||||
if ( named ) return named;
|
||||
const color = notification?.source === 'sharing' ? '#2563eb' : '#64748b';
|
||||
const color = glyphKey(notification) === 'sharing' ? '#2563eb' : '#64748b';
|
||||
// Loaded as an image rather than inlined, the SVG needs its namespace.
|
||||
const svg = glyphFor(notification)
|
||||
.replace('<svg ', '<svg xmlns="http://www.w3.org/2000/svg" ')
|
||||
@@ -251,7 +251,8 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
|
||||
const rowHtml = (entry) => {
|
||||
const { notification } = entry;
|
||||
const source = typeof notification.source === 'string' ? notification.source.replace(/[^a-z0-9_-]/gi, '') : 'default';
|
||||
// A closed set, so it needs no sanitising on the way into the class.
|
||||
const glyph = glyphKey(notification);
|
||||
const text = textFor(notification);
|
||||
const time = entry.createdAt === null ? '' : `
|
||||
<time class="dashboard-notification-time" datetime="${new Date(entry.createdAt).toISOString()}"
|
||||
@@ -270,7 +271,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
return `
|
||||
<li class="${classes}" data-uid="${html_encode(entry.uid)}">
|
||||
<${mainTag} class="dashboard-notification-main${actionable ? ' is-actionable' : ''}">
|
||||
<span class="dashboard-notification-icon dashboard-notification-icon-${html_encode(source)}">${glyphFor(notification)}<span class="dashboard-notification-unread-dot" aria-hidden="true"></span></span>
|
||||
<span class="dashboard-notification-icon dashboard-notification-icon-${glyph}">${glyphFor(notification)}<span class="dashboard-notification-unread-dot" aria-hidden="true"></span></span>
|
||||
<span class="dashboard-notification-content">
|
||||
<span class="dashboard-notification-title">${unread ? `<span class="dashboard-notification-sr">${i18n('notification_unread')}: </span>` : ''}${html_encode(title)}</span>
|
||||
${text ? `<span class="dashboard-notification-text">${html_encode(text)}</span>` : ''}
|
||||
|
||||
@@ -25,11 +25,12 @@
|
||||
|
||||
/**
|
||||
* @typedef {Object} NotificationPayload
|
||||
* @property {string} [source] - Who sent it: `sharing`, `worker`, …
|
||||
* @property {string} [type] - What it is, from the server's registry
|
||||
* @property {string} [source] - Legacy sender marker: `sharing`, `worker`, …
|
||||
* @property {string} [title]
|
||||
* @property {string} [text]
|
||||
* @property {string} [icon] - A `window.icons` key
|
||||
* @property {string} [template]
|
||||
* @property {string} [template] - Legacy marker, superseded by `type`
|
||||
* @property {Object} [fields]
|
||||
*/
|
||||
|
||||
@@ -42,14 +43,36 @@
|
||||
* @property {number} receivedAt - When this client first saw it (epoch ms)
|
||||
*/
|
||||
|
||||
/** Notifications announcing a share; the two templates the backend writes. */
|
||||
const SHARE_TEMPLATES = new Set(['file-shared-with-you', 'file-shared-before-you-joined']);
|
||||
/** Notifications announcing a share. */
|
||||
const SHARE_TYPES = new Set(['share.received', 'share.claimed']);
|
||||
|
||||
/**
|
||||
* Senders the notification center leaves out entirely — a worker's deploy
|
||||
* The `source` / `template` markers share and worker notifications carried
|
||||
* before the server sent a `type`. Kept so rows written by the previous
|
||||
* release still read correctly.
|
||||
*/
|
||||
const LEGACY_SHARE_TEMPLATES = new Set(['file-shared-with-you', 'file-shared-before-you-joined']);
|
||||
const LEGACY_HIDDEN_SOURCES = new Set(['worker']);
|
||||
|
||||
/**
|
||||
* Notifications the center leaves out entirely — a worker's deploy
|
||||
* confirmations are noise next to things that need the user.
|
||||
*/
|
||||
const HIDDEN_SOURCES = new Set(['worker']);
|
||||
const HIDDEN_TYPES = new Set(['app.worker.deployed', 'app.worker.deployFailed']);
|
||||
|
||||
/**
|
||||
* Whether a notification announces a share, by either the server's `type` or
|
||||
* the markers that preceded it.
|
||||
*
|
||||
* @param {NotificationPayload} notification
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const isShareNotification = (notification) => {
|
||||
if ( ! notification || typeof notification !== 'object' ) return false;
|
||||
return SHARE_TYPES.has(notification.type)
|
||||
|| notification.source === 'sharing'
|
||||
|| LEGACY_SHARE_TEMPLATES.has(notification.template);
|
||||
};
|
||||
|
||||
// SQLite's CURRENT_TIMESTAMP: UTC with no zone marker, which `Date.parse`
|
||||
// would otherwise read as local time.
|
||||
@@ -99,7 +122,8 @@ export const toEntry = (raw, now) => {
|
||||
if ( typeof uid !== 'string' || uid === '' ) return null;
|
||||
const payload = raw.notification ?? raw.value;
|
||||
const notification = payload && typeof payload === 'object' ? payload : {};
|
||||
if ( HIDDEN_SOURCES.has(notification.source) ) return null;
|
||||
if ( HIDDEN_TYPES.has(notification.type) ) return null;
|
||||
if ( LEGACY_HIDDEN_SOURCES.has(notification.source) ) return null;
|
||||
const createdAt = parseCreatedAt(raw.created_at);
|
||||
return {
|
||||
uid,
|
||||
@@ -209,18 +233,15 @@ export const isUnread = (entry) => entry.readAt === null;
|
||||
*/
|
||||
export const unreadCount = (entries) => entries.filter(isUnread).length;
|
||||
|
||||
/** The senders that have a glyph of their own; anything else gets the bell. */
|
||||
const GLYPH_SOURCES = new Set(['sharing']);
|
||||
|
||||
/**
|
||||
* Which glyph an entry shows, by who sent it. A plain property lookup
|
||||
* would let a `source` like `constructor` reach into the prototype.
|
||||
* Which glyph an entry shows. Shares have one of their own; anything else
|
||||
* gets the bell.
|
||||
*
|
||||
* @param {NotificationPayload} notification
|
||||
* @returns {'sharing'|'default'}
|
||||
*/
|
||||
export const glyphKey = (notification) => (
|
||||
GLYPH_SOURCES.has(notification?.source) ? notification.source : 'default'
|
||||
isShareNotification(notification) ? 'sharing' : 'default'
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -236,9 +257,7 @@ export const glyphKey = (notification) => (
|
||||
* @returns {NotificationTarget}
|
||||
*/
|
||||
export const notificationTarget = (notification) => {
|
||||
if ( ! notification || typeof notification !== 'object' ) return null;
|
||||
const isShare = notification.source === 'sharing' || SHARE_TEMPLATES.has(notification.template);
|
||||
if ( ! isShare ) return null;
|
||||
if ( ! isShareNotification(notification) ) return null;
|
||||
const path = notification.fields?.target?.path;
|
||||
if ( typeof path === 'string' && path.startsWith('/') ) {
|
||||
return { kind: 'shared-item', path };
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
formatAbsoluteTime,
|
||||
formatRelativeTime,
|
||||
glyphKey,
|
||||
isShareNotification,
|
||||
isUnread,
|
||||
mergeEntries,
|
||||
notificationTarget,
|
||||
@@ -124,6 +125,14 @@ describe('toEntry', () => {
|
||||
});
|
||||
|
||||
it('leaves out worker notifications, listed or pushed', () => {
|
||||
const worker = { title: 'Successfully deployed https://x.puter.work', type: 'app.worker.deployed' };
|
||||
expect(toEntry({ uid: 'a', value: worker, created_at: '2026-08-27 12:00:00' }, NOW)).toBeNull();
|
||||
expect(toEntry({ uid: 'b', notification: worker }, NOW)).toBeNull();
|
||||
expect(toEntry({ uid: 'c', notification: { title: 'Failed to deploy x!', type: 'app.worker.deployFailed' } }, NOW)).toBeNull();
|
||||
expect(toEntry({ uid: 'd', notification: { type: 'share.received' } }, NOW)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('still leaves out worker notifications written before the type registry', () => {
|
||||
const worker = { title: 'Successfully deployed https://x.puter.work', source: 'worker', template: 'user-requesting-share' };
|
||||
expect(toEntry({ uid: 'a', value: worker, created_at: '2026-08-27 12:00:00' }, NOW)).toBeNull();
|
||||
expect(toEntry({ uid: 'b', notification: worker }, NOW)).toBeNull();
|
||||
@@ -258,33 +267,63 @@ describe('unreadCount', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('isShareNotification', () => {
|
||||
it('accepts the server type and the markers that preceded it', () => {
|
||||
expect(isShareNotification({ type: 'share.received' })).toBe(true);
|
||||
expect(isShareNotification({ type: 'share.claimed' })).toBe(true);
|
||||
expect(isShareNotification({ source: 'sharing' })).toBe(true);
|
||||
expect(isShareNotification({ template: 'file-shared-with-you' })).toBe(true);
|
||||
expect(isShareNotification({ template: 'file-shared-before-you-joined' })).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses anything else', () => {
|
||||
expect(isShareNotification({ type: 'app.worker.deployed' })).toBe(false);
|
||||
expect(isShareNotification({ source: 'worker' })).toBe(false);
|
||||
expect(isShareNotification({})).toBe(false);
|
||||
expect(isShareNotification(null)).toBe(false);
|
||||
expect(isShareNotification('text')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('notificationTarget', () => {
|
||||
it('points a single share at its item', () => {
|
||||
expect(notificationTarget({
|
||||
source: 'sharing',
|
||||
template: 'file-shared-with-you',
|
||||
type: 'share.received',
|
||||
fields: { target: { path: '/alice/0b1c2d3e-0000-4000-8000-000000000000/report.txt', name: 'report.txt' } },
|
||||
})).toEqual({ kind: 'shared-item', path: '/alice/0b1c2d3e-0000-4000-8000-000000000000/report.txt' });
|
||||
});
|
||||
|
||||
it('points a grouped share at Shared', () => {
|
||||
expect(notificationTarget({ source: 'sharing', template: 'file-shared-with-you', fields: { count: 3 } }))
|
||||
expect(notificationTarget({ type: 'share.received', fields: { count: 3 } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
});
|
||||
|
||||
it('points a share claimed after signup at Shared', () => {
|
||||
expect(notificationTarget({ source: 'sharing', template: 'file-shared-before-you-joined', fields: { count: 1 } }))
|
||||
expect(notificationTarget({ type: 'share.claimed', fields: { count: 1 } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
});
|
||||
|
||||
it('still reads shares written before the type registry', () => {
|
||||
expect(notificationTarget({
|
||||
source: 'sharing',
|
||||
template: 'file-shared-with-you',
|
||||
fields: { target: { path: '/alice/0b1c2d3e-0000-4000-8000-000000000000/report.txt' } },
|
||||
})).toEqual({ kind: 'shared-item', path: '/alice/0b1c2d3e-0000-4000-8000-000000000000/report.txt' });
|
||||
expect(notificationTarget({ source: 'sharing', template: 'file-shared-with-you', fields: { count: 3 } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
expect(notificationTarget({ template: 'file-shared-before-you-joined', fields: { count: 1 } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
});
|
||||
|
||||
it('refuses a target that is not an absolute path', () => {
|
||||
expect(notificationTarget({ source: 'sharing', fields: { target: { path: 'https://evil' } } }))
|
||||
expect(notificationTarget({ type: 'share.received', fields: { target: { path: 'https://evil' } } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
expect(notificationTarget({ source: 'sharing', fields: { target: { path: 42 } } }))
|
||||
expect(notificationTarget({ type: 'share.received', fields: { target: { path: 42 } } }))
|
||||
.toEqual({ kind: 'shared' });
|
||||
});
|
||||
|
||||
it('has nowhere to go for other notifications', () => {
|
||||
expect(notificationTarget({ type: 'app.worker.deployed', title: 'Deployed' })).toBeNull();
|
||||
expect(notificationTarget({ source: 'worker', title: 'Deployed' })).toBeNull();
|
||||
expect(notificationTarget({})).toBeNull();
|
||||
expect(notificationTarget(null)).toBeNull();
|
||||
@@ -293,11 +332,15 @@ describe('notificationTarget', () => {
|
||||
});
|
||||
|
||||
describe('glyphKey', () => {
|
||||
it('names the glyph for known senders', () => {
|
||||
it('names the glyph for shares, by type or legacy marker', () => {
|
||||
expect(glyphKey({ type: 'share.received' })).toBe('sharing');
|
||||
expect(glyphKey({ type: 'share.claimed' })).toBe('sharing');
|
||||
expect(glyphKey({ source: 'sharing' })).toBe('sharing');
|
||||
expect(glyphKey({ template: 'file-shared-with-you' })).toBe('sharing');
|
||||
});
|
||||
|
||||
it('falls back to the bell for anything else', () => {
|
||||
expect(glyphKey({ type: 'app.worker.deployed' })).toBe('default');
|
||||
expect(glyphKey({ source: 'billing' })).toBe('default');
|
||||
expect(glyphKey({})).toBe('default');
|
||||
expect(glyphKey(null)).toBe('default');
|
||||
@@ -305,9 +348,10 @@ describe('glyphKey', () => {
|
||||
});
|
||||
|
||||
it('never reaches into the prototype', () => {
|
||||
expect(glyphKey({ type: '__proto__' })).toBe('default');
|
||||
expect(glyphKey({ source: '__proto__' })).toBe('default');
|
||||
expect(glyphKey({ source: 'constructor' })).toBe('default');
|
||||
expect(glyphKey({ source: 'toString' })).toBe('default');
|
||||
expect(glyphKey({ template: 'toString' })).toBe('default');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import item_icon from '../helpers/itemIcon.js';
|
||||
import { SHARED_PATH_PARAM, clear_shared_param } from '../helpers/parseSharedPath.js';
|
||||
import resolve_shared_item from '../helpers/resolveSharedItem.js';
|
||||
import { markNotificationAcknowledged } from '../helpers/notificationApi.js';
|
||||
import { notificationTarget } from './Dashboard/notificationCenter.js';
|
||||
import apply_item_added_to_containers from '../helpers/applyItemAddedToContainers.js';
|
||||
import UIWindowSearch from './UIWindowSearch.js';
|
||||
|
||||
@@ -211,11 +212,15 @@ async function UIDesktop (options) {
|
||||
}
|
||||
});
|
||||
|
||||
/** Clicking a share notification opens the item, or Shared if grouped. */
|
||||
/**
|
||||
* Clicking a share notification opens the item, or Shared if grouped.
|
||||
* Shares the notification center's predicate so a toast and a list entry
|
||||
* never disagree about where a click goes.
|
||||
*/
|
||||
const share_notification_click = (notification) => {
|
||||
if ( notification?.source !== 'sharing' ) return undefined;
|
||||
const target = notification?.fields?.target;
|
||||
if ( target?.path ) {
|
||||
const target = notificationTarget(notification);
|
||||
if ( target === null ) return undefined;
|
||||
if ( target.kind === 'shared-item' ) {
|
||||
return () => {
|
||||
open_shared_item(target.path);
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user