Skip to content

Commit 64d22bf

Browse files
committed
test(service-messaging): pin the push device registry over sys_user_device (red)
Claude-Session: https://claude.ai/code/session_01ADHkmRD9KKqvTU3THnute6 Co-authored-by: Claude <noreply@anthropic.com>
1 parent ff827bc commit 64d22bf

2 files changed

Lines changed: 267 additions & 0 deletions

File tree

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The push device registry (ADR-0012 §6): `MessagingService`'s four
5+
* `INotificationService` device members over `sys_user_device`, pinned on a
6+
* real `ObjectQL` over `SqlDriver` (better-sqlite3) with the real `sys_user`.
7+
*
8+
* What the contract (`@objectstack/spec/contracts` `INotificationService`)
9+
* and spec's three rules (`system/push-device.zod.ts`) owe, one case each:
10+
*
11+
* - register, then refresh the same `deviceId`: one row, token and
12+
* `last_seen_at` moved;
13+
* - a registration without `deviceId` mints one; the same user registering
14+
* the same token again without it gets the SAME id back, never a second row;
15+
* - a second user registering the token takes it over, and the first user's
16+
* row for it is removed (rule b);
17+
* - unregister by another user answers `NOT_FOUND` (404) and the row
18+
* survives; the owner's unregister removes it;
19+
* - `invalidateDeviceToken` keeps the row, disabled with its time (rule c);
20+
* a later registration of the same device re-enables it and clears the
21+
* time; a token nobody holds is a no-op;
22+
* - the vendor derives from the platform, and a `web` registration without
23+
* one is refused `VALIDATION_FAILED` at `vendor`, storing nothing;
24+
* - `listDevices` answers only the caller's devices, newest first;
25+
* - the database refuses a second holder of a token (the unique index), and
26+
* two concurrent registrations of one token end with one row.
27+
*
28+
* Refusals assert `code` AND `status` (ADR-0112).
29+
*/
30+
31+
import { describe, it, expect, afterEach } from 'vitest';
32+
import { ObjectQL } from '@objectstack/objectql';
33+
import { SqlDriver } from '@objectstack/driver-sql';
34+
import { SysUser } from '@objectstack/platform-objects';
35+
import { validationFailureDetails } from '@objectstack/types';
36+
import { UserDevice } from './objects/user-device.object.js';
37+
import { MessagingService } from './messaging-service.js';
38+
import { USER_DEVICE_OBJECT } from './device-registry.js';
39+
import { installDefaultOrganization } from './default-organization.testkit.js';
40+
41+
const SYS = { context: { isSystem: true } } as any;
42+
const silent: any = { debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } };
43+
44+
let engine: ObjectQL | undefined;
45+
46+
afterEach(async () => {
47+
try { await engine?.destroy(); } catch { /* noop */ }
48+
engine = undefined;
49+
});
50+
51+
/** A clock the test moves, so `last_seen_at` ordering is not a race. */
52+
function clock() {
53+
let t = Date.parse('2026-11-02T10:00:00.000Z');
54+
return { now: () => new Date(t).toISOString(), tick: (ms = 60_000) => { t += ms; } };
55+
}
56+
57+
async function boot() {
58+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
59+
const ql = new ObjectQL({ logger: silent });
60+
ql.registerDriver(driver, true);
61+
await ql.init();
62+
ql.registry.registerObject(SysUser as any, '@objectstack/plugin-auth');
63+
ql.registry.registerObject(UserDevice as any, '@objectstack/service-messaging');
64+
await ql.syncSchemas();
65+
await installDefaultOrganization(ql as any);
66+
engine = ql;
67+
const time = clock();
68+
const service = new MessagingService({ logger: silent, getData: () => ql as any, now: time.now });
69+
const alice = String((await ql.insert('sys_user', { name: 'Alice', email: 'alice@device.test' }, SYS)).id);
70+
const bob = String((await ql.insert('sys_user', { name: 'Bob', email: 'bob@device.test' }, SYS)).id);
71+
const rows = async (where: Record<string, unknown> = {}) =>
72+
(await ql.find(USER_DEVICE_OBJECT, { where }, SYS)) as Array<Record<string, any>>;
73+
return { ql, service, time, alice, bob, rows };
74+
}
75+
76+
async function thrown(p: Promise<unknown>): Promise<any> {
77+
try {
78+
await p;
79+
} catch (e) {
80+
return e;
81+
}
82+
throw new Error('the call resolved; a refusal was expected');
83+
}
84+
85+
describe('push device registry: INotificationService device members over sys_user_device', () => {
86+
it('register, then refresh the same deviceId: one row, token and last_seen_at updated', async () => {
87+
const { service, time, alice, rows } = await boot();
88+
const first = await service.registerDevice(alice, { token: 'tok-1', platform: 'ios', deviceId: 'dev-a', name: 'iPhone' });
89+
expect(first).toEqual({ deviceId: 'dev-a', success: true });
90+
const [before] = await rows({ user_id: alice });
91+
92+
time.tick();
93+
const again = await service.registerDevice(alice, { token: 'tok-2', platform: 'ios', deviceId: 'dev-a', locale: 'zh-CN' });
94+
expect(again).toEqual({ deviceId: 'dev-a', success: true });
95+
96+
const after = await rows({ user_id: alice });
97+
expect(after).toHaveLength(1);
98+
expect(after[0].id).toBe(before.id);
99+
expect(after[0].token).toBe('tok-2');
100+
expect(after[0].locale).toBe('zh-CN');
101+
expect(new Date(after[0].last_seen_at).getTime()).toBeGreaterThan(new Date(before.last_seen_at).getTime());
102+
});
103+
104+
it('mints a deviceId when absent, and answers the same id for the same token without one', async () => {
105+
const { service, alice, rows } = await boot();
106+
const minted = await service.registerDevice(alice, { token: 'tok-m', platform: 'android' });
107+
expect(minted.success).toBe(true);
108+
expect(minted.deviceId).toMatch(/\S/);
109+
110+
const cleared = await service.registerDevice(alice, { token: 'tok-m', platform: 'android' });
111+
expect(cleared.deviceId).toBe(minted.deviceId);
112+
expect(await rows({ token: 'tok-m' })).toHaveLength(1);
113+
});
114+
115+
it('a second user registering the token takes it over; the first user\'s row for it is removed', async () => {
116+
const { service, alice, bob, rows } = await boot();
117+
await service.registerDevice(alice, { token: 'tok-shared', platform: 'ios', deviceId: 'alice-phone' });
118+
await service.registerDevice(alice, { token: 'tok-other', platform: 'ios', deviceId: 'alice-tablet' });
119+
120+
const taken = await service.registerDevice(bob, { token: 'tok-shared', platform: 'ios', deviceId: 'bob-phone' });
121+
expect(taken).toEqual({ deviceId: 'bob-phone', success: true });
122+
123+
const holders = await rows({ token: 'tok-shared' });
124+
expect(holders).toHaveLength(1);
125+
expect(String(holders[0].user_id)).toBe(bob);
126+
expect((await rows({ user_id: alice })).map((r) => r.device_id)).toEqual(['alice-tablet']);
127+
expect((await service.listDevices(alice)).map((d) => d.deviceId)).toEqual(['alice-tablet']);
128+
});
129+
130+
it('a token this user holds under another deviceId moves to the named device; the stale row goes', async () => {
131+
const { service, alice, rows } = await boot();
132+
await service.registerDevice(alice, { token: 'tok-x', platform: 'ios', deviceId: 'old-install' });
133+
await service.registerDevice(alice, { token: 'tok-x', platform: 'ios', deviceId: 'new-install' });
134+
expect((await rows({ user_id: alice })).map((r) => r.device_id)).toEqual(['new-install']);
135+
});
136+
137+
it('unregister by a non-owner is NOT_FOUND (404) and the row survives; the owner removes it', async () => {
138+
const { service, alice, bob, rows } = await boot();
139+
await service.registerDevice(alice, { token: 'tok-u', platform: 'android', deviceId: 'alice-dev' });
140+
141+
const refused = await thrown(service.unregisterDevice(bob, 'alice-dev'));
142+
expect(refused.code).toBe('NOT_FOUND');
143+
expect(refused.status).toBe(404);
144+
expect(await rows({ device_id: 'alice-dev' })).toHaveLength(1);
145+
146+
const unknown = await thrown(service.unregisterDevice(alice, 'no-such-device'));
147+
expect(unknown.code).toBe('NOT_FOUND');
148+
expect(unknown.status).toBe(404);
149+
150+
expect(await service.unregisterDevice(alice, 'alice-dev')).toEqual({ success: true });
151+
expect(await rows({ device_id: 'alice-dev' })).toHaveLength(0);
152+
});
153+
154+
it('invalidateDeviceToken keeps the row disabled with its time; re-registration re-enables and clears it', async () => {
155+
const { service, time, alice, rows } = await boot();
156+
await service.registerDevice(alice, { token: 'tok-dead', platform: 'ios', deviceId: 'dev-d' });
157+
158+
time.tick();
159+
await service.invalidateDeviceToken('tok-dead');
160+
const [dead] = await rows({ device_id: 'dev-d' });
161+
expect(dead.enabled).toBe(false);
162+
expect(dead.invalidated_at).toBeTruthy();
163+
const [listed] = await service.listDevices(alice);
164+
expect(listed.enabled).toBe(false);
165+
expect(listed.invalidatedAt).toBe(time.now());
166+
167+
// A token nobody holds is a no-op.
168+
await expect(service.invalidateDeviceToken('tok-nobody')).resolves.toBeUndefined();
169+
170+
time.tick();
171+
await service.registerDevice(alice, { token: 'tok-dead', platform: 'ios', deviceId: 'dev-d' });
172+
const [revived] = await rows({ device_id: 'dev-d' });
173+
expect(revived.id).toBe(dead.id);
174+
expect(revived.enabled).toBe(true);
175+
expect(revived.invalidated_at ?? null).toBeNull();
176+
const [relisted] = await service.listDevices(alice);
177+
expect(relisted.enabled).toBe(true);
178+
expect(relisted).not.toHaveProperty('invalidatedAt');
179+
});
180+
181+
it('derives the vendor from the platform, and refuses a web registration without one', async () => {
182+
const { service, alice, rows } = await boot();
183+
await service.registerDevice(alice, { token: 'tok-ios', platform: 'ios' });
184+
await service.registerDevice(alice, { token: 'tok-and', platform: 'android' });
185+
await service.registerDevice(alice, { token: 'tok-web', platform: 'web', vendor: 'fcm' });
186+
const vendorOf = async (token: string) => (await rows({ token }))[0]?.vendor;
187+
expect(await vendorOf('tok-ios')).toBe('apns');
188+
expect(await vendorOf('tok-and')).toBe('fcm');
189+
expect(await vendorOf('tok-web')).toBe('fcm');
190+
191+
const refused = await thrown(service.registerDevice(alice, { token: 'tok-web-2', platform: 'web' }));
192+
const details = validationFailureDetails(refused);
193+
expect(details?.code).toBe('VALIDATION_FAILED');
194+
expect(details?.fields).toEqual([expect.objectContaining({ field: 'vendor', code: 'required' })]);
195+
expect(await rows({ token: 'tok-web-2' })).toHaveLength(0);
196+
});
197+
198+
it('listDevices answers only the caller\'s devices, newest last_seen_at first', async () => {
199+
const { service, time, alice, bob } = await boot();
200+
await service.registerDevice(alice, { token: 't1', platform: 'ios', deviceId: 'older' });
201+
time.tick();
202+
await service.registerDevice(alice, { token: 't2', platform: 'android', deviceId: 'newer', appId: 'ai.objectos.app' });
203+
await service.registerDevice(bob, { token: 't3', platform: 'ios', deviceId: 'bobs' });
204+
205+
const mine = await service.listDevices(alice);
206+
expect(mine.map((d) => d.deviceId)).toEqual(['newer', 'older']);
207+
expect(mine[0]).toMatchObject({ userId: alice, vendor: 'fcm', token: 't2', platform: 'android', appId: 'ai.objectos.app', enabled: true });
208+
expect(mine.every((d) => d.userId === alice)).toBe(true);
209+
});
210+
211+
it('the database refuses a second holder of a token, and concurrent registrations end with one row', async () => {
212+
const { ql, service, alice, bob, rows } = await boot();
213+
await service.registerDevice(alice, { token: 'tok-race', platform: 'ios', deviceId: 'a1' });
214+
215+
// The unique index itself: a direct second holder is refused.
216+
const direct = await thrown(ql.insert(USER_DEVICE_OBJECT, {
217+
id: 'manual', user_id: bob, device_id: 'b-manual', token: 'tok-race', vendor: 'apns', platform: 'ios', enabled: true,
218+
}, SYS));
219+
expect(String(direct?.message ?? direct)).toMatch(/unique|duplicate/i);
220+
221+
await Promise.all([
222+
service.registerDevice(bob, { token: 'tok-race', platform: 'ios', deviceId: 'b1' }),
223+
service.registerDevice(alice, { token: 'tok-race', platform: 'ios', deviceId: 'a2' }),
224+
service.registerDevice(bob, { token: 'tok-race', platform: 'ios', deviceId: 'b2' }),
225+
]);
226+
expect(await rows({ token: 'tok-race' })).toHaveLength(1);
227+
});
228+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `sys_user_device`'s declaration (ADR-0012 §6): system-owned and closed to
5+
* the generic data API, no organization column (spec rule a), and the same
6+
* platform vocabulary as the registration it stores.
7+
*/
8+
9+
import { describe, it, expect } from 'vitest';
10+
import { RegisterDeviceRequestSchema } from '@objectstack/spec/api';
11+
import { UserDeviceSchema } from '@objectstack/spec/system';
12+
import { UserDevice } from './user-device.object.js';
13+
14+
describe('sys_user_device declaration', () => {
15+
it('is closed to the generic data API: no method is exposed', () => {
16+
expect(UserDevice.enable?.apiEnabled).toBe(false);
17+
expect(UserDevice.enable?.apiMethods).toEqual([]);
18+
expect(UserDevice.managedBy).toBe('engine-owned');
19+
});
20+
21+
it('has no organization column and opts out of tenancy (a device belongs to a user)', () => {
22+
expect(Object.keys(UserDevice.fields)).not.toContain('organization_id');
23+
expect(UserDevice.tenancy).toEqual({ enabled: false });
24+
});
25+
26+
it('stores the platform vocabulary the registration admits, no more and no less', () => {
27+
const declared = (UserDevice.fields.platform as any).options.map((o: any) => (typeof o === 'string' ? o : o.value));
28+
const admitted = (RegisterDeviceRequestSchema as any).shape.platform.options;
29+
expect([...declared].sort()).toEqual([...admitted].sort());
30+
expect((UserDeviceSchema as any).shape.platform.options.slice().sort()).toEqual([...admitted].sort());
31+
});
32+
33+
it('carries the two unique indexes the registry relies on', () => {
34+
expect(UserDevice.indexes).toEqual(expect.arrayContaining([
35+
expect.objectContaining({ fields: ['user_id', 'device_id'], unique: 'global' }),
36+
expect.objectContaining({ fields: ['token'], unique: 'global' }),
37+
]));
38+
});
39+
});

0 commit comments

Comments
 (0)