@yu_robotics/remote-cli-router 1.6.184 → 1.6.189
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/binding/BindingManager.d.ts +21 -59
- package/dist/binding/BindingManager.d.ts.map +1 -1
- package/dist/binding/BindingManager.js +131 -155
- package/dist/binding/BindingManager.js.map +1 -1
- package/dist/binding/ThreadSelectionManager.d.ts +46 -0
- package/dist/binding/ThreadSelectionManager.d.ts.map +1 -0
- package/dist/binding/ThreadSelectionManager.js +130 -0
- package/dist/binding/ThreadSelectionManager.js.map +1 -0
- package/dist/feishu/ApprovalCards.d.ts +1 -1
- package/dist/feishu/ApprovalCards.d.ts.map +1 -1
- package/dist/feishu/ApprovalCards.js +3 -1
- package/dist/feishu/ApprovalCards.js.map +1 -1
- package/dist/feishu/FeishuLongConnHandler.d.ts +17 -10
- package/dist/feishu/FeishuLongConnHandler.d.ts.map +1 -1
- package/dist/feishu/FeishuLongConnHandler.js +142 -64
- package/dist/feishu/FeishuLongConnHandler.js.map +1 -1
- package/dist/server.d.ts +9 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +277 -82
- package/dist/server.js.map +1 -1
- package/dist/storage/JsonStore.d.ts +40 -64
- package/dist/storage/JsonStore.d.ts.map +1 -1
- package/dist/storage/JsonStore.js +380 -178
- package/dist/storage/JsonStore.js.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -7,268 +7,470 @@ exports.JsonStore = void 0;
|
|
|
7
7
|
const promises_1 = __importDefault(require("fs/promises"));
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const os_1 = __importDefault(require("os"));
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
const crypto_1 = require("crypto");
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
function isIdentifier(value) {
|
|
15
|
+
return typeof value === 'string' && value.length > 0;
|
|
16
|
+
}
|
|
17
|
+
function isTimestamp(value) {
|
|
18
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
19
|
+
}
|
|
20
|
+
function isDictionary(value, entry) {
|
|
21
|
+
return isRecord(value) && Object.values(value).every(entry);
|
|
22
|
+
}
|
|
23
|
+
function isBindingCode(value) {
|
|
24
|
+
return isRecord(value) && isIdentifier(value.code) && isIdentifier(value.deviceId)
|
|
25
|
+
&& isTimestamp(value.createdAt) && isTimestamp(value.expiresAt)
|
|
26
|
+
&& (!Object.hasOwn(value, 'devicePublicKey') || isIdentifier(value.devicePublicKey));
|
|
27
|
+
}
|
|
28
|
+
function isLegacyBinding(value) {
|
|
29
|
+
return isRecord(value) && isIdentifier(value.openId) && isIdentifier(value.deviceId)
|
|
30
|
+
&& typeof value.deviceName === 'string' && isTimestamp(value.boundAt) && isTimestamp(value.lastActiveAt)
|
|
31
|
+
&& !Object.hasOwn(value, 'devices');
|
|
32
|
+
}
|
|
33
|
+
function isDeviceBinding(value) {
|
|
34
|
+
return isRecord(value) && isIdentifier(value.deviceId) && typeof value.deviceName === 'string'
|
|
35
|
+
&& isTimestamp(value.boundAt) && isTimestamp(value.lastActiveAt) && typeof value.isActive === 'boolean';
|
|
36
|
+
}
|
|
37
|
+
function isUserBinding(value) {
|
|
38
|
+
return isRecord(value) && isIdentifier(value.openId) && Array.isArray(value.devices)
|
|
39
|
+
&& value.devices.every(isDeviceBinding) && (value.activeDeviceId === null || isIdentifier(value.activeDeviceId))
|
|
40
|
+
&& isTimestamp(value.createdAt) && isTimestamp(value.updatedAt);
|
|
41
|
+
}
|
|
42
|
+
function parseStoreData(content, currentVersion) {
|
|
43
|
+
const value = JSON.parse(content);
|
|
44
|
+
if (isRecord(value) && value.version === currentVersion
|
|
45
|
+
&& isDictionary(value.bindingCodes, isBindingCode) && isDictionary(value.userBindings, isUserBinding)
|
|
46
|
+
&& isDictionary(value.deviceToUserMap, isIdentifier)) {
|
|
47
|
+
return { kind: 'current', data: value };
|
|
48
|
+
}
|
|
49
|
+
if (isRecord(value) && !Object.hasOwn(value, 'version')
|
|
50
|
+
&& isDictionary(value.bindingCodes, isBindingCode) && isDictionary(value.userBindings, isLegacyBinding)
|
|
51
|
+
&& (!Object.hasOwn(value, 'deviceBindings') || isDictionary(value.deviceBindings, isLegacyBinding))
|
|
52
|
+
&& (!Object.hasOwn(value, 'deviceToUserMap') || isDictionary(value.deviceToUserMap, isIdentifier))) {
|
|
53
|
+
return { kind: 'legacy', data: value };
|
|
54
|
+
}
|
|
55
|
+
throw new Error('Unsupported bindings data structure or version.');
|
|
56
|
+
}
|
|
57
|
+
class ReplacementUncertainty extends Error {
|
|
58
|
+
constructor(cause) {
|
|
59
|
+
super('Bindings replacement completed, but durability could not be confirmed.', { cause });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** JSON file-based storage with serialized, durable-before-visible mutations. */
|
|
14
63
|
class JsonStore {
|
|
15
64
|
storePath;
|
|
16
65
|
data;
|
|
17
66
|
saveTimer = null;
|
|
18
|
-
|
|
67
|
+
pendingSaves = [];
|
|
68
|
+
writeTail = Promise.resolve();
|
|
69
|
+
draining;
|
|
70
|
+
uncertainty;
|
|
71
|
+
invalidDataError;
|
|
72
|
+
expiringCodes = new Set();
|
|
19
73
|
SAVE_DELAY;
|
|
20
74
|
static CURRENT_VERSION = 1;
|
|
21
75
|
constructor(storePath, saveDelay = 1000) {
|
|
22
76
|
this.storePath = storePath || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'bindings.json');
|
|
23
77
|
this.SAVE_DELAY = saveDelay;
|
|
24
|
-
this.data =
|
|
25
|
-
version: JsonStore.CURRENT_VERSION,
|
|
26
|
-
bindingCodes: {},
|
|
27
|
-
userBindings: {},
|
|
28
|
-
deviceToUserMap: {},
|
|
29
|
-
};
|
|
78
|
+
this.data = this.emptyData();
|
|
30
79
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
80
|
+
emptyData() {
|
|
81
|
+
return { version: JsonStore.CURRENT_VERSION, bindingCodes: {}, userBindings: {}, deviceToUserMap: {} };
|
|
82
|
+
}
|
|
83
|
+
assertReconciled() {
|
|
84
|
+
if (this.uncertainty)
|
|
85
|
+
throw this.uncertainty;
|
|
86
|
+
if (this.invalidDataError)
|
|
87
|
+
throw this.invalidDataError;
|
|
88
|
+
}
|
|
89
|
+
/** Initialize without replacing an unreadable or damaged existing file. */
|
|
34
90
|
async initialize() {
|
|
91
|
+
this.assertReconciled();
|
|
92
|
+
await promises_1.default.mkdir(path_1.default.dirname(this.storePath), { recursive: true });
|
|
93
|
+
let content;
|
|
35
94
|
try {
|
|
36
|
-
|
|
37
|
-
await promises_1.default.mkdir(path_1.default.dirname(this.storePath), { recursive: true });
|
|
38
|
-
// Try to load existing data
|
|
39
|
-
try {
|
|
40
|
-
const content = await promises_1.default.readFile(this.storePath, 'utf-8');
|
|
41
|
-
const rawData = JSON.parse(content);
|
|
42
|
-
// Check if migration is needed
|
|
43
|
-
if (!rawData.version) {
|
|
44
|
-
await this.migrateFromLegacy(rawData);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
this.data = rawData;
|
|
48
|
-
}
|
|
49
|
-
// Clean up expired binding codes on startup
|
|
50
|
-
this.cleanupExpiredBindingCodes();
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
// File doesn't exist or is invalid, start with empty data
|
|
54
|
-
if (error.code !== 'ENOENT') {
|
|
55
|
-
console.warn('Failed to load bindings data, starting fresh:', error.message);
|
|
56
|
-
}
|
|
57
|
-
await this.save();
|
|
58
|
-
}
|
|
95
|
+
content = await promises_1.default.readFile(this.storePath, 'utf-8');
|
|
59
96
|
}
|
|
60
97
|
catch (error) {
|
|
61
|
-
|
|
62
|
-
|
|
98
|
+
if (error.code !== 'ENOENT')
|
|
99
|
+
throw error;
|
|
100
|
+
await this.commitImmediate(current => current);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = parseStoreData(content, JsonStore.CURRENT_VERSION);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// Parser diagnostics can quote private values from the original input.
|
|
109
|
+
this.invalidDataError = new Error('Bindings data is invalid or unsupported; the existing file was preserved. Correct or restore the file and restart the Router.');
|
|
110
|
+
throw this.invalidDataError;
|
|
63
111
|
}
|
|
112
|
+
if (parsed.kind === 'legacy')
|
|
113
|
+
await this.migrateFromLegacy(parsed.data);
|
|
114
|
+
else
|
|
115
|
+
this.data = parsed.data;
|
|
116
|
+
await this.commitImmediate(current => this.withoutExpiredBindingCodes(current));
|
|
64
117
|
}
|
|
65
|
-
/**
|
|
66
|
-
* Migrate from legacy single-device schema to multi-device schema
|
|
67
|
-
*/
|
|
68
118
|
async migrateFromLegacy(rawData) {
|
|
69
119
|
console.log('[JsonStore] Migrating legacy binding data to multi-device schema...');
|
|
70
|
-
const legacyUserBindings =
|
|
71
|
-
const newUserBindings =
|
|
72
|
-
const deviceToUserMap =
|
|
120
|
+
const legacyUserBindings = rawData.userBindings;
|
|
121
|
+
const newUserBindings = Object.create(null);
|
|
122
|
+
const deviceToUserMap = Object.create(null);
|
|
73
123
|
const now = Date.now();
|
|
74
124
|
for (const [openId, legacy] of Object.entries(legacyUserBindings)) {
|
|
75
125
|
newUserBindings[openId] = {
|
|
76
126
|
openId,
|
|
77
127
|
devices: [{
|
|
78
|
-
deviceId: legacy.deviceId,
|
|
79
|
-
|
|
80
|
-
boundAt: legacy.boundAt,
|
|
81
|
-
lastActiveAt: legacy.lastActiveAt,
|
|
82
|
-
isActive: true,
|
|
128
|
+
deviceId: legacy.deviceId, deviceName: legacy.deviceName, boundAt: legacy.boundAt,
|
|
129
|
+
lastActiveAt: legacy.lastActiveAt, isActive: true,
|
|
83
130
|
}],
|
|
84
|
-
activeDeviceId: legacy.deviceId,
|
|
85
|
-
createdAt: legacy.boundAt,
|
|
86
|
-
updatedAt: now,
|
|
131
|
+
activeDeviceId: legacy.deviceId, createdAt: legacy.boundAt, updatedAt: now,
|
|
87
132
|
};
|
|
88
133
|
deviceToUserMap[legacy.deviceId] = openId;
|
|
89
134
|
}
|
|
90
|
-
|
|
135
|
+
const migrated = {
|
|
91
136
|
version: JsonStore.CURRENT_VERSION,
|
|
92
|
-
bindingCodes: rawData.bindingCodes
|
|
137
|
+
bindingCodes: { ...rawData.bindingCodes },
|
|
93
138
|
userBindings: newUserBindings,
|
|
94
139
|
deviceToUserMap,
|
|
95
140
|
};
|
|
96
|
-
await this.
|
|
141
|
+
await this.commitImmediate(() => migrated);
|
|
97
142
|
console.log(`[JsonStore] Migration complete. Migrated ${Object.keys(newUserBindings).length} user(s).`);
|
|
98
143
|
}
|
|
99
|
-
/**
|
|
100
|
-
* Store binding code with expiration
|
|
101
|
-
*/
|
|
102
144
|
async setBindingCode(code, bindingCode) {
|
|
103
|
-
|
|
104
|
-
await this.scheduleSave();
|
|
145
|
+
const copy = { ...bindingCode };
|
|
146
|
+
await this.scheduleSave(current => ({ ...current, bindingCodes: { ...current.bindingCodes, [code]: copy } }));
|
|
105
147
|
}
|
|
106
|
-
/**
|
|
107
|
-
* Get binding code
|
|
108
|
-
*/
|
|
109
148
|
getBindingCode(code) {
|
|
149
|
+
this.assertReconciled();
|
|
110
150
|
const bindingCode = this.data.bindingCodes[code];
|
|
111
|
-
if (!bindingCode)
|
|
151
|
+
if (!bindingCode)
|
|
112
152
|
return null;
|
|
113
|
-
}
|
|
114
|
-
// Check if expired
|
|
115
153
|
if (Date.now() > bindingCode.expiresAt) {
|
|
116
|
-
|
|
117
|
-
this.scheduleSave();
|
|
154
|
+
this.scheduleExpiry(code);
|
|
118
155
|
return null;
|
|
119
156
|
}
|
|
120
|
-
return bindingCode;
|
|
157
|
+
return { ...bindingCode };
|
|
158
|
+
}
|
|
159
|
+
scheduleExpiry(code) {
|
|
160
|
+
if (this.expiringCodes.has(code))
|
|
161
|
+
return;
|
|
162
|
+
this.expiringCodes.add(code);
|
|
163
|
+
const operation = this.scheduleSave(current => {
|
|
164
|
+
const candidate = current.bindingCodes[code];
|
|
165
|
+
if (!candidate || Date.now() <= candidate.expiresAt)
|
|
166
|
+
return undefined;
|
|
167
|
+
const bindingCodes = { ...current.bindingCodes };
|
|
168
|
+
delete bindingCodes[code];
|
|
169
|
+
return { ...current, bindingCodes };
|
|
170
|
+
});
|
|
171
|
+
const settled = () => { this.expiringCodes.delete(code); };
|
|
172
|
+
void operation.then(settled, settled);
|
|
173
|
+
this.reportBackgroundSave(operation);
|
|
121
174
|
}
|
|
122
|
-
/**
|
|
123
|
-
* Delete binding code
|
|
124
|
-
*/
|
|
125
175
|
async deleteBindingCode(code) {
|
|
126
|
-
|
|
127
|
-
|
|
176
|
+
await this.scheduleSave(current => {
|
|
177
|
+
if (!current.bindingCodes[code])
|
|
178
|
+
return undefined;
|
|
179
|
+
const bindingCodes = { ...current.bindingCodes };
|
|
180
|
+
delete bindingCodes[code];
|
|
181
|
+
return { ...current, bindingCodes };
|
|
182
|
+
});
|
|
128
183
|
}
|
|
129
|
-
/**
|
|
130
|
-
* Set user binding
|
|
131
|
-
*/
|
|
132
184
|
async setUserBinding(openId, binding) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
185
|
+
const copy = { ...binding, devices: binding.devices.map(device => ({ ...device })) };
|
|
186
|
+
await this.scheduleSave(current => {
|
|
187
|
+
const deviceToUserMap = { ...current.deviceToUserMap };
|
|
188
|
+
for (const device of copy.devices)
|
|
189
|
+
deviceToUserMap[device.deviceId] = openId;
|
|
190
|
+
return { ...current, userBindings: { ...current.userBindings, [openId]: copy }, deviceToUserMap };
|
|
191
|
+
});
|
|
139
192
|
}
|
|
140
|
-
/**
|
|
141
|
-
* Get user binding
|
|
142
|
-
*/
|
|
143
193
|
getUserBinding(openId) {
|
|
144
|
-
|
|
194
|
+
this.assertReconciled();
|
|
195
|
+
const binding = this.data.userBindings[openId];
|
|
196
|
+
return binding ? { ...binding, devices: binding.devices.map(device => ({ ...device })) } : null;
|
|
197
|
+
}
|
|
198
|
+
getDeviceThreadSelection(openId, deviceId) {
|
|
199
|
+
this.assertReconciled();
|
|
200
|
+
const device = this.data.userBindings[openId]?.devices.find(item => item.deviceId === deviceId);
|
|
201
|
+
if (!device || !Object.hasOwn(device, 'selectedThreadId'))
|
|
202
|
+
return { status: 'none' };
|
|
203
|
+
const value = device.selectedThreadId;
|
|
204
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 200
|
|
205
|
+
? { status: 'valid', threadId: value }
|
|
206
|
+
: { status: 'invalid' };
|
|
207
|
+
}
|
|
208
|
+
/** Prompt, FIFO preference mutation against the latest committed binding state. */
|
|
209
|
+
async setDeviceThreadSelection(openId, deviceId, threadId, options = {}) {
|
|
210
|
+
if (threadId !== null && (typeof threadId !== 'string' || threadId.length === 0 || threadId.length > 200)) {
|
|
211
|
+
throw new Error('Invalid selected thread ID.');
|
|
212
|
+
}
|
|
213
|
+
let matches = true;
|
|
214
|
+
await this.commitQueued(current => {
|
|
215
|
+
if (options.guard && !options.guard()) {
|
|
216
|
+
matches = false;
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
const binding = current.userBindings[openId];
|
|
220
|
+
const device = binding?.devices.find(item => item.deviceId === deviceId);
|
|
221
|
+
if (!binding || !device)
|
|
222
|
+
throw new Error('Device is no longer bound to this user.');
|
|
223
|
+
if ((options.requireActive && binding.activeDeviceId !== deviceId)
|
|
224
|
+
|| (options.expectedThreadId !== undefined && device.selectedThreadId !== options.expectedThreadId)) {
|
|
225
|
+
matches = false;
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
if (device.selectedThreadId === threadId
|
|
229
|
+
|| (threadId === null && !Object.hasOwn(device, 'selectedThreadId')))
|
|
230
|
+
return undefined;
|
|
231
|
+
const devices = binding.devices.map(item => {
|
|
232
|
+
if (item.deviceId !== deviceId)
|
|
233
|
+
return { ...item };
|
|
234
|
+
if (threadId !== null)
|
|
235
|
+
return { ...item, selectedThreadId: threadId };
|
|
236
|
+
const { selectedThreadId: _removed, ...withoutSelection } = item;
|
|
237
|
+
return withoutSelection;
|
|
238
|
+
});
|
|
239
|
+
return { ...current, userBindings: { ...current.userBindings,
|
|
240
|
+
[openId]: { ...binding, devices, updatedAt: Date.now() } } };
|
|
241
|
+
});
|
|
242
|
+
return matches;
|
|
145
243
|
}
|
|
146
|
-
/** Return a detached snapshot of users with at least one bound device. */
|
|
147
244
|
listBoundUserIds() {
|
|
245
|
+
this.assertReconciled();
|
|
148
246
|
return Object.keys(this.data.userBindings).filter(id => this.data.userBindings[id].devices.length > 0);
|
|
149
247
|
}
|
|
150
|
-
/**
|
|
151
|
-
* Get user openId by device ID (reverse lookup)
|
|
152
|
-
*/
|
|
153
248
|
getUserByDeviceId(deviceId) {
|
|
249
|
+
this.assertReconciled();
|
|
154
250
|
return this.data.deviceToUserMap[deviceId] || null;
|
|
155
251
|
}
|
|
156
|
-
/**
|
|
157
|
-
* Set device-to-user mapping
|
|
158
|
-
*/
|
|
159
252
|
async setDeviceToUserMap(deviceId, openId) {
|
|
160
|
-
this.
|
|
161
|
-
|
|
253
|
+
await this.scheduleSave(current => ({ ...current,
|
|
254
|
+
deviceToUserMap: { ...current.deviceToUserMap, [deviceId]: openId } }));
|
|
162
255
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Remove device-to-user mapping
|
|
165
|
-
*/
|
|
166
256
|
async removeDeviceToUserMap(deviceId) {
|
|
167
|
-
|
|
168
|
-
|
|
257
|
+
await this.scheduleSave(current => {
|
|
258
|
+
if (!current.deviceToUserMap[deviceId])
|
|
259
|
+
return undefined;
|
|
260
|
+
const deviceToUserMap = { ...current.deviceToUserMap };
|
|
261
|
+
delete deviceToUserMap[deviceId];
|
|
262
|
+
return { ...current, deviceToUserMap };
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** Remove both ownership representations and select any replacement active device in one snapshot. */
|
|
266
|
+
async unbindDevice(openId, deviceId) {
|
|
267
|
+
let removed = false;
|
|
268
|
+
await this.scheduleSave(current => {
|
|
269
|
+
const binding = current.userBindings[openId];
|
|
270
|
+
const deviceIndex = binding?.devices.findIndex(device => device.deviceId === deviceId) ?? -1;
|
|
271
|
+
if (!binding || deviceIndex < 0)
|
|
272
|
+
return undefined;
|
|
273
|
+
const devices = binding.devices.filter(device => device.deviceId !== deviceId).map(device => ({ ...device }));
|
|
274
|
+
const deviceToUserMap = { ...current.deviceToUserMap };
|
|
275
|
+
if (deviceToUserMap[deviceId] === openId)
|
|
276
|
+
delete deviceToUserMap[deviceId];
|
|
277
|
+
const userBindings = { ...current.userBindings };
|
|
278
|
+
if (devices.length === 0)
|
|
279
|
+
delete userBindings[openId];
|
|
280
|
+
else {
|
|
281
|
+
let activeDeviceId = binding.activeDeviceId;
|
|
282
|
+
if (activeDeviceId === deviceId) {
|
|
283
|
+
devices[0] = { ...devices[0], isActive: true };
|
|
284
|
+
activeDeviceId = devices[0].deviceId;
|
|
285
|
+
}
|
|
286
|
+
userBindings[openId] = { ...binding, devices, activeDeviceId, updatedAt: Date.now() };
|
|
287
|
+
}
|
|
288
|
+
removed = true;
|
|
289
|
+
return { ...current, userBindings, deviceToUserMap };
|
|
290
|
+
});
|
|
291
|
+
return removed;
|
|
169
292
|
}
|
|
170
|
-
/**
|
|
171
|
-
* Delete user binding and all associated device mappings
|
|
172
|
-
*/
|
|
173
293
|
async deleteUserBinding(openId) {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
294
|
+
await this.scheduleSave(current => {
|
|
295
|
+
const binding = current.userBindings[openId];
|
|
296
|
+
if (!binding)
|
|
297
|
+
return undefined;
|
|
298
|
+
const deviceToUserMap = { ...current.deviceToUserMap };
|
|
177
299
|
for (const device of binding.devices) {
|
|
178
|
-
|
|
300
|
+
if (deviceToUserMap[device.deviceId] === openId)
|
|
301
|
+
delete deviceToUserMap[device.deviceId];
|
|
179
302
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
303
|
+
const userBindings = { ...current.userBindings };
|
|
304
|
+
delete userBindings[openId];
|
|
305
|
+
return { ...current, userBindings, deviceToUserMap };
|
|
306
|
+
});
|
|
183
307
|
}
|
|
184
|
-
/**
|
|
185
|
-
* Update last active time for the active device of a user
|
|
186
|
-
*/
|
|
187
308
|
async updateLastActive(openId) {
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
const
|
|
191
|
-
if (
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
309
|
+
const now = Date.now();
|
|
310
|
+
await this.scheduleSave(current => {
|
|
311
|
+
const binding = current.userBindings[openId];
|
|
312
|
+
if (!binding?.activeDeviceId)
|
|
313
|
+
return undefined;
|
|
314
|
+
const device = binding.devices.find(item => item.deviceId === binding.activeDeviceId);
|
|
315
|
+
if (!device)
|
|
316
|
+
return undefined;
|
|
317
|
+
const updated = { ...binding, updatedAt: now,
|
|
318
|
+
devices: binding.devices.map(item => item.deviceId === device.deviceId ? { ...item, lastActiveAt: now } : { ...item }) };
|
|
319
|
+
return { ...current, userBindings: { ...current.userBindings, [openId]: updated } };
|
|
320
|
+
});
|
|
197
321
|
}
|
|
198
|
-
|
|
199
|
-
* Clean up expired binding codes
|
|
200
|
-
*/
|
|
201
|
-
cleanupExpiredBindingCodes() {
|
|
322
|
+
withoutExpiredBindingCodes(current) {
|
|
202
323
|
const now = Date.now();
|
|
203
|
-
|
|
204
|
-
|
|
324
|
+
const bindingCodes = { ...current.bindingCodes };
|
|
325
|
+
let changed = false;
|
|
326
|
+
for (const [code, bindingCode] of Object.entries(bindingCodes)) {
|
|
205
327
|
if (now > bindingCode.expiresAt) {
|
|
206
|
-
delete
|
|
207
|
-
|
|
328
|
+
delete bindingCodes[code];
|
|
329
|
+
changed = true;
|
|
208
330
|
}
|
|
209
331
|
}
|
|
210
|
-
|
|
211
|
-
this.scheduleSave();
|
|
212
|
-
}
|
|
332
|
+
return changed ? { ...current, bindingCodes } : undefined;
|
|
213
333
|
}
|
|
214
|
-
/**
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
334
|
+
/** Capture inputs at admission, but compute drafts only against prior committed state. */
|
|
335
|
+
scheduleSave(createDraft) {
|
|
336
|
+
if (this.invalidDataError)
|
|
337
|
+
return Promise.reject(this.invalidDataError);
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
this.pendingSaves.push({ createDraft, resolve, reject });
|
|
340
|
+
if (this.saveTimer)
|
|
341
|
+
clearTimeout(this.saveTimer);
|
|
342
|
+
this.saveTimer = setTimeout(() => {
|
|
343
|
+
this.saveTimer = null;
|
|
344
|
+
this.reportBackgroundSave(this.drainSaves());
|
|
345
|
+
}, this.SAVE_DELAY);
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
reportBackgroundSave(operation) {
|
|
349
|
+
void operation.catch(error => console.error('Failed to save bindings data:', error));
|
|
350
|
+
}
|
|
351
|
+
drainSaves() {
|
|
352
|
+
if (this.draining)
|
|
353
|
+
return this.draining;
|
|
354
|
+
const draining = (async () => {
|
|
355
|
+
const errors = [];
|
|
356
|
+
while (this.pendingSaves.length > 0) {
|
|
357
|
+
const writes = this.admitPendingSaves();
|
|
358
|
+
const results = await Promise.allSettled(writes);
|
|
359
|
+
for (const result of results)
|
|
360
|
+
if (result.status === 'rejected')
|
|
361
|
+
errors.push(result.reason);
|
|
362
|
+
}
|
|
363
|
+
await this.writeTail;
|
|
364
|
+
if (errors.length > 0)
|
|
365
|
+
throw errors[0];
|
|
366
|
+
})();
|
|
367
|
+
this.draining = draining;
|
|
368
|
+
const clear = () => { if (this.draining === draining)
|
|
369
|
+
this.draining = undefined; };
|
|
370
|
+
void draining.then(clear, clear);
|
|
371
|
+
return draining;
|
|
372
|
+
}
|
|
373
|
+
/** Move admitted debounced writes into the shared FIFO before an immediate write. */
|
|
374
|
+
admitPendingSaves() {
|
|
375
|
+
const batch = this.pendingSaves.splice(0);
|
|
376
|
+
return batch.map(request => {
|
|
377
|
+
const write = this.enqueueWrite(request.createDraft);
|
|
378
|
+
void write.then(request.resolve, request.reject);
|
|
379
|
+
return write;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
commitImmediate(createDraft) {
|
|
383
|
+
return this.enqueueWrite(createDraft);
|
|
384
|
+
}
|
|
385
|
+
commitQueued(createDraft) {
|
|
220
386
|
if (this.saveTimer) {
|
|
221
387
|
clearTimeout(this.saveTimer);
|
|
388
|
+
this.saveTimer = null;
|
|
222
389
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
390
|
+
this.admitPendingSaves();
|
|
391
|
+
return this.enqueueWrite(createDraft);
|
|
392
|
+
}
|
|
393
|
+
enqueueWrite(createDraft) {
|
|
394
|
+
const write = this.writeTail.then(async () => {
|
|
395
|
+
this.assertReconciled();
|
|
396
|
+
const draft = createDraft(this.data);
|
|
397
|
+
if (!draft)
|
|
398
|
+
return;
|
|
399
|
+
try {
|
|
400
|
+
await this.writeSnapshot(draft);
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
if (error instanceof ReplacementUncertainty) {
|
|
404
|
+
this.uncertainty = new Error('Bindings disk state is uncertain after replacement. Authentication and writes are blocked until a new JsonStore reconciles the file.', { cause: error });
|
|
405
|
+
throw this.uncertainty;
|
|
406
|
+
}
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
// Publication is authoritative only after replacement and required fsyncs succeed.
|
|
410
|
+
this.data = draft;
|
|
232
411
|
});
|
|
412
|
+
this.writeTail = write.catch(() => undefined);
|
|
413
|
+
return write;
|
|
233
414
|
}
|
|
234
|
-
/**
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
415
|
+
/** Atomically replace the file, distinguishing pre-replacement and uncertain failures. */
|
|
416
|
+
async writeSnapshot(snapshot) {
|
|
417
|
+
const temporary = `${this.storePath}.${(0, crypto_1.randomUUID)()}.tmp`;
|
|
418
|
+
let handle;
|
|
419
|
+
let replaced = false;
|
|
238
420
|
try {
|
|
239
|
-
|
|
240
|
-
await
|
|
421
|
+
handle = await promises_1.default.open(temporary, 'wx', 0o600);
|
|
422
|
+
await handle.writeFile(JSON.stringify(snapshot, null, 2), 'utf-8');
|
|
423
|
+
await handle.sync();
|
|
424
|
+
await handle.close();
|
|
425
|
+
handle = undefined;
|
|
426
|
+
await promises_1.default.rename(temporary, this.storePath);
|
|
427
|
+
replaced = true;
|
|
428
|
+
// Windows does not support directory handles/fsync through this portable path.
|
|
429
|
+
if (process.platform !== 'win32') {
|
|
430
|
+
const directory = await promises_1.default.open(path_1.default.dirname(this.storePath), 'r');
|
|
431
|
+
try {
|
|
432
|
+
await directory.sync();
|
|
433
|
+
}
|
|
434
|
+
finally {
|
|
435
|
+
await directory.close();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
241
438
|
}
|
|
242
439
|
catch (error) {
|
|
243
|
-
|
|
440
|
+
if (replaced)
|
|
441
|
+
throw new ReplacementUncertainty(error);
|
|
442
|
+
throw error;
|
|
443
|
+
}
|
|
444
|
+
finally {
|
|
445
|
+
if (handle)
|
|
446
|
+
await handle.close().catch(() => undefined);
|
|
447
|
+
await promises_1.default.rm(temporary, { force: true }).catch(() => undefined);
|
|
244
448
|
}
|
|
245
449
|
}
|
|
246
|
-
/**
|
|
247
|
-
* Force immediate save (for graceful shutdown)
|
|
248
|
-
*/
|
|
450
|
+
/** Drain accepted writes, including writes admitted while an earlier flush waits. */
|
|
249
451
|
async flush() {
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
452
|
+
const blocked = this.uncertainty ?? this.invalidDataError;
|
|
453
|
+
const errors = blocked ? [blocked] : [];
|
|
454
|
+
do {
|
|
455
|
+
if (this.saveTimer) {
|
|
456
|
+
clearTimeout(this.saveTimer);
|
|
457
|
+
this.saveTimer = null;
|
|
458
|
+
}
|
|
459
|
+
try {
|
|
460
|
+
await this.drainSaves();
|
|
461
|
+
}
|
|
462
|
+
catch (error) {
|
|
463
|
+
errors.push(error);
|
|
464
|
+
}
|
|
465
|
+
} while (this.saveTimer || this.pendingSaves.length > 0);
|
|
466
|
+
if (errors.length > 0)
|
|
467
|
+
throw errors[0];
|
|
255
468
|
}
|
|
256
|
-
/**
|
|
257
|
-
* Clear all data
|
|
258
|
-
*/
|
|
259
469
|
async clear() {
|
|
260
|
-
this.
|
|
261
|
-
version: JsonStore.CURRENT_VERSION,
|
|
262
|
-
bindingCodes: {},
|
|
263
|
-
userBindings: {},
|
|
264
|
-
deviceToUserMap: {},
|
|
265
|
-
};
|
|
266
|
-
await this.save();
|
|
470
|
+
await this.scheduleSave(() => this.emptyData());
|
|
267
471
|
}
|
|
268
|
-
/**
|
|
269
|
-
* Get statistics
|
|
270
|
-
*/
|
|
271
472
|
getStats() {
|
|
473
|
+
this.assertReconciled();
|
|
272
474
|
return {
|
|
273
475
|
bindingCodes: Object.keys(this.data.bindingCodes).length,
|
|
274
476
|
userBindings: Object.keys(this.data.userBindings).length,
|