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56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Tests SQLite-backed pairing store lifecycle and account isolation.
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { executeSqliteQuerySync, getNodeSqliteKysely } from "../infra/kysely-sync.js";
import { DEFAULT_ACCOUNT_ID } from "../routing/session-key.js";
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
import {
  closeOpenClawStateDatabaseForTest,
  openOpenClawStateDatabase,
} from "../state/openclaw-state-db.js";

const pairingMocks = vi.hoisted(() => ({
  getPairingAdapter: vi.fn<
    () => { idLabel: string; normalizeAllowEntry?: (entry: string) => string } | null
  >(() => null),
}));

vi.mock("../channels/plugins/pairing.js", () => ({
  getPairingAdapter: pairingMocks.getPairingAdapter,
}));

import {
  readChannelPairingStateSnapshot,
  writeChannelPairingStateSnapshot,
} from "./pairing-store-sqlite.test-helpers.js";
import {
  addChannelAllowFromStoreEntry,
  approveChannelPairingCode,
  approveChannelPairingRequest,
  dismissChannelPairingRequest,
  listChannelPairingRequests,
  readChannelAllowFromStore,
  readChannelAllowFromStoreSync,
  removeChannelAllowFromStoreEntry,
  resolveChannelPairingRequestId,
  upsertChannelPairingRequest,
} from "./pairing-store.js";

type PairingTestDatabase = Pick<
  OpenClawStateKyselyDatabase,
  "channel_pairing_allow_entries" | "channel_pairing_requests"
>;

let fixtureRoot = "";
let caseId = 0;
type RandomIntSync = (minOrMax: number, max?: number) => number;

beforeAll(() => {
  fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-pairing-"));
});

afterAll(() => {
  closeOpenClawStateDatabaseForTest();
  fs.rmSync(fixtureRoot, { recursive: true, force: true });
});

beforeEach(() => {
  vi.useRealTimers();
  vi.restoreAllMocks();
  pairingMocks.getPairingAdapter.mockReset();
});

afterEach(() => {
  vi.useRealTimers();
  vi.restoreAllMocks();
  closeOpenClawStateDatabaseForTest();
});

function createTestEnv(): { stateDir: string; env: NodeJS.ProcessEnv } {
  const stateDir = path.join(fixtureRoot, `case-${caseId++}`);
  fs.mkdirSync(stateDir, { recursive: true });
  return { stateDir, env: { ...process.env, OPENCLAW_STATE_DIR: stateDir } };
}

function requireFirstPairingRequest(
  requests: Awaited<ReturnType<typeof listChannelPairingRequests>>,
) {
  expect(requests).toHaveLength(1);
  const request = requests[0];
  if (!request) {
    throw new Error("expected pairing request");
  }
  return request;
}

async function withMockRandomInt(params: {
  initialValue?: number;
  sequence?: number[];
  fallbackValue?: number;
  run: () => Promise<void>;
}) {
  const spy = vi.spyOn(crypto, "randomInt") as unknown as {
    mockImplementation: (impl: RandomIntSync) => void;
    mockReturnValue: (value: number) => void;
    mockRestore: () => void;
  };
  try {
    if (params.initialValue !== undefined) {
      spy.mockReturnValue(params.initialValue);
    }
    if (params.sequence) {
      let index = 0;
      spy.mockImplementation(() => params.sequence?.[index++] ?? params.fallbackValue ?? 1);
    }
    await params.run();
  } finally {
    spy.mockRestore();
  }
}

function writeAllowFromFixture(params: {
  env: NodeJS.ProcessEnv;
  channel: string;
  accountId?: string;
  allowFrom: string[];
}) {
  const state = readChannelPairingStateSnapshot(params.channel, params.env);
  state.allowFrom ??= {};
  state.allowFrom[params.accountId ?? DEFAULT_ACCOUNT_ID] = params.allowFrom;
  writeChannelPairingStateSnapshot(params.channel, state, params.env);
}

describe("pairing store", () => {
  it("normalizes allowlist entries through channel pairing adapters", async () => {
    const { env } = createTestEnv();
    pairingMocks.getPairingAdapter.mockReturnValue({
      idLabel: "Telegram user",
      normalizeAllowEntry: (entry) => entry.replace(/^telegram:/i, ""),
    });

    await expect(
      addChannelAllowFromStoreEntry({
        channel: "telegram",
        accountId: "yy",
        entry: "telegram:1001",
        env,
      }),
    ).resolves.toEqual({ changed: true, allowFrom: ["1001"] });
    await expect(readChannelAllowFromStore("telegram", env, "yy")).resolves.toEqual(["1001"]);

    const directAdapter = {
      idLabel: "Direct",
      normalizeAllowEntry: (entry: string) => entry.replace(/^direct:/i, ""),
    };
    await expect(
      addChannelAllowFromStoreEntry({
        channel: "external-channel",
        accountId: "main",
        entry: "direct:42",
        env,
        pairingAdapter: directAdapter,
      }),
    ).resolves.toEqual({ changed: true, allowFrom: ["42"] });
  });

  it("skips malformed persisted requests while approving valid codes", async () => {
    const { env } = createTestEnv();
    const database = openOpenClawStateDatabase({ env });
    const db = getNodeSqliteKysely<PairingTestDatabase>(database.db);
    executeSqliteQuerySync(
      database.db,
      db.insertInto("channel_pairing_requests").values([
        {
          channel_key: "telegram",
          account_id: DEFAULT_ACCOUNT_ID,
          request_id: "",
          code: "BADCODE1",
          created_at: "invalid",
          last_seen_at: "invalid",
          meta_json: null,
        },
        {
          channel_key: "telegram",
          account_id: "alpha",
          request_id: "valid-user",
          code: "GOODCODE",
          created_at: new Date().toISOString(),
          last_seen_at: new Date().toISOString(),
          meta_json: JSON.stringify({ accountId: "stale-account" }),
        },
      ]),
    );

    await expect(listChannelPairingRequests("telegram", env, "alpha")).resolves.toHaveLength(1);
    await expect(listChannelPairingRequests("telegram", env, "stale-account")).resolves.toEqual([]);
    await expect(
      approveChannelPairingCode({ channel: "telegram", accountId: "alpha", code: "GOODCODE", env }),
    ).resolves.toMatchObject({ id: "valid-user" });
    await expect(readChannelAllowFromStore("telegram", env, "alpha")).resolves.toEqual([
      "valid-user",
    ]);
    await expect(readChannelAllowFromStore("telegram", env, "stale-account")).resolves.toEqual([]);
  });

  it("handles pending request reuse, expiry, and per-account limits", async () => {
    const { env } = createTestEnv();
    const first = await upsertChannelPairingRequest({
      channel: "demo-a",
      id: "u1",
      accountId: DEFAULT_ACCOUNT_ID,
      env,
    });
    const reused = await upsertChannelPairingRequest({
      channel: "demo-a",
      id: "u1",
      accountId: DEFAULT_ACCOUNT_ID,
      env,
    });
    expect(reused).toEqual({ code: first.code, created: false });

    const expired = await upsertChannelPairingRequest({
      channel: "demo-b",
      id: "expired",
      accountId: DEFAULT_ACCOUNT_ID,
      env,
    });
    expect(expired.created).toBe(true);
    const state = readChannelPairingStateSnapshot("demo-b", env);
    const expiredAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
    state.requests = state.requests.map((request) => ({
      ...request,
      createdAt: expiredAt,
      lastSeenAt: expiredAt,
    }));
    writeChannelPairingStateSnapshot("demo-b", state, env);
    await expect(listChannelPairingRequests("demo-b", env)).resolves.toEqual([]);

    for (const id of ["one", "two", "three"]) {
      await expect(
        upsertChannelPairingRequest({
          channel: "demo-c",
          id,
          accountId: DEFAULT_ACCOUNT_ID,
          env,
        }),
      ).resolves.toMatchObject({ created: true });
    }
    await expect(
      upsertChannelPairingRequest({
        channel: "demo-c",
        id: "four",
        accountId: DEFAULT_ACCOUNT_ID,
        env,
      }),
    ).resolves.toEqual({ code: "", created: false });
  });

  it("persists a channel-derived approval entry from request metadata", async () => {
    const { env } = createTestEnv();
    const request = await upsertChannelPairingRequest({
      channel: "demo-a",
      id: "alice",
      accountId: DEFAULT_ACCOUNT_ID,
      meta: { proofEntry: "fixture-entry" },
      env,
    });
    const pairingAdapter = {
      idLabel: "peer",
      normalizeAllowEntry: (entry: string) => entry,
      resolveApprovalStoreEntry: ({ meta }: { meta?: Record<string, string> }) =>
        meta?.proofEntry ?? null,
    };

    await expect(
      approveChannelPairingCode({
        channel: "demo-a",
        code: request.code,
        env,
        pairingAdapter,
      }),
    ).resolves.toMatchObject({ id: "alice" });
    await expect(readChannelAllowFromStore("demo-a", env)).resolves.toEqual(["fixture-entry"]);
  });

  it("approves and dismisses account-scoped requests by opaque id", async () => {
    const { env } = createTestEnv();
    await upsertChannelPairingRequest({
      channel: "telegram",
      accountId: "alpha",
      id: "shared-sender",
      env,
    });
    await upsertChannelPairingRequest({
      channel: "telegram",
      accountId: "beta",
      id: "shared-sender",
      env,
    });
    const alphaRequest = requireFirstPairingRequest(
      await listChannelPairingRequests("telegram", env, "alpha"),
    );
    const betaRequest = requireFirstPairingRequest(
      await listChannelPairingRequests("telegram", env, "beta"),
    );
    const alphaRequestId = resolveChannelPairingRequestId("telegram", alphaRequest);
    const betaRequestId = resolveChannelPairingRequestId("telegram", betaRequest);

    expect(alphaRequestId).not.toBe(betaRequestId);
    expect(alphaRequestId).not.toContain(alphaRequest.code);
    await expect(
      approveChannelPairingRequest({
        channel: "telegram",
        accountId: "alpha",
        requestId: alphaRequestId,
        env,
      }),
    ).resolves.toMatchObject({ id: "shared-sender" });
    await expect(readChannelAllowFromStore("telegram", env, "alpha")).resolves.toEqual([
      "shared-sender",
    ]);
    await expect(
      approveChannelPairingRequest({
        channel: "telegram",
        accountId: "beta",
        requestId: alphaRequestId,
        env,
      }),
    ).resolves.toBeNull();

    await expect(
      dismissChannelPairingRequest({
        channel: "telegram",
        accountId: "beta",
        requestId: betaRequestId,
        env,
      }),
    ).resolves.toMatchObject({ id: "shared-sender" });
    await expect(readChannelAllowFromStore("telegram", env, "beta")).resolves.toEqual([]);
    await expect(listChannelPairingRequests("telegram", env)).resolves.toEqual([]);
  });

  it("regenerates colliding codes and reports exhaustion without leaking codes", async () => {
    const { env } = createTestEnv();
    await withMockRandomInt({
      initialValue: 0,
      run: async () => {
        const first = await upsertChannelPairingRequest({
          channel: "telegram",
          id: "123",
          accountId: DEFAULT_ACCOUNT_ID,
          env,
        });
        expect(first.code).toBe("AAAAAAAA");

        await withMockRandomInt({
          sequence: Array(8).fill(0).concat(Array(8).fill(1)),
          fallbackValue: 1,
          run: async () => {
            await expect(
              upsertChannelPairingRequest({
                channel: "telegram",
                id: "456",
                accountId: DEFAULT_ACCOUNT_ID,
                env,
              }),
            ).resolves.toMatchObject({ code: "BBBBBBBB" });
          },
        });
      },
    });

    const second = createTestEnv();
    await withMockRandomInt({
      initialValue: 0,
      run: async () => {
        await upsertChannelPairingRequest({
          channel: "telegram",
          id: "123",
          accountId: DEFAULT_ACCOUNT_ID,
          env: second.env,
        });
        await expect(
          upsertChannelPairingRequest({
            channel: "telegram",
            id: "456",
            accountId: DEFAULT_ACCOUNT_ID,
            env: second.env,
          }),
        ).rejects.toThrow(
          "failed to generate unique pairing code after 500 attempts; existing code count: 1",
        );
      },
    });
  });

  it("keeps allowFrom and pending requests isolated by account", async () => {
    const { env } = createTestEnv();
    await addChannelAllowFromStoreEntry({
      channel: "telegram",
      accountId: "alpha",
      entry: "1001",
      env,
    });
    await expect(readChannelAllowFromStore("telegram", env, "alpha")).resolves.toEqual(["1001"]);
    await expect(readChannelAllowFromStore("telegram", env, "beta")).resolves.toEqual([]);

    const alpha = await upsertChannelPairingRequest({
      channel: "telegram",
      accountId: "alpha",
      id: "shared",
      env,
    });
    const beta = await upsertChannelPairingRequest({
      channel: "telegram",
      accountId: "beta",
      id: "shared",
      env,
    });
    expect(beta.code).not.toBe(alpha.code);
    expect(
      requireFirstPairingRequest(await listChannelPairingRequests("telegram", env, "alpha")).code,
    ).toBe(alpha.code);
    expect(
      requireFirstPairingRequest(await listChannelPairingRequests("telegram", env, "beta")).code,
    ).toBe(beta.code);

    await expect(
      approveChannelPairingCode({ channel: "telegram", code: alpha.code, env }),
    ).resolves.toMatchObject({ id: "shared" });
    await expect(readChannelAllowFromStore("telegram", env, "alpha")).resolves.toEqual([
      "1001",
      "shared",
    ]);
    await expect(readChannelAllowFromStore("telegram", env, "beta")).resolves.toEqual([]);

    await expect(
      removeChannelAllowFromStoreEntry({
        channel: "telegram",
        accountId: "alpha",
        entry: "1001",
        env,
      }),
    ).resolves.toEqual({ changed: true, allowFrom: ["shared"] });
  });

  it("reads current SQLite entries without a process-local file cache", async () => {
    const { env } = createTestEnv();
    writeAllowFromFixture({ env, channel: "telegram", accountId: "yy", allowFrom: ["1001"] });
    await expect(readChannelAllowFromStore("telegram", env, "yy")).resolves.toEqual(["1001"]);
    expect(readChannelAllowFromStoreSync("telegram", env, "yy")).toEqual(["1001"]);

    writeAllowFromFixture({ env, channel: "telegram", accountId: "yy", allowFrom: ["10022"] });
    await expect(readChannelAllowFromStore("telegram", env, "yy")).resolves.toEqual(["10022"]);
    expect(readChannelAllowFromStoreSync("telegram", env, "yy")).toEqual(["10022"]);
  });
});