@napuketto/kernel 0.16.4 → 0.18.0

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/dist/index.d.mts CHANGED
@@ -1310,6 +1310,8 @@ type CanonicalElement = {
1310
1310
  } | {
1311
1311
  type: "reply";
1312
1312
  messageId: string;
1313
+ senderUid?: string;
1314
+ senderUin?: string;
1313
1315
  } | {
1314
1316
  type: "forward";
1315
1317
  messageIds: string[];
@@ -1640,7 +1642,8 @@ export declare class FlashTransferApi {
1640
1642
  /** 好友条目(uid + 昵称/备注,昵称由 buddy service 缓存补全)。 */
1641
1643
  interface Friend {
1642
1644
  uid: string;
1643
- uin: string;
1645
+ /** QQ 号。无法解析时为空,uid 始终单独保留。 */
1646
+ uin: string | null;
1644
1647
  nickname: string;
1645
1648
  remark: string;
1646
1649
  }
@@ -1672,7 +1675,7 @@ interface DoubtFriendRequestInfo {
1672
1675
  }
1673
1676
  /** FriendApi 构造选项。 */
1674
1677
  interface FriendApiOptions {
1675
- /** uid→uin 转换器(通常注入 GroupApi.uidToUin);缺省 uin 退化为 uid。 */
1678
+ /** uid→uin 转换器(通常注入 GroupApi.uidToUin);只补缺少 UIN 的项。 */
1676
1679
  uidToUin?: ((uids: string[]) => Promise<Map<string, string>>) | undefined;
1677
1680
  }
1678
1681
  /** 好友 API:从 session 拿 buddy service,包装成语义化方法。 */
@@ -1682,6 +1685,7 @@ export declare class FriendApi {
1682
1685
  constructor(session: NodeIQQNTWrapperSession, opts?: FriendApiOptions);
1683
1686
  /** 好友列表(分类拍平为 Friend[];昵称/备注从 service 缓存读取)。 */
1684
1687
  getFriendList(): Promise<Friend[]>;
1688
+ private friendsFromCategories;
1685
1689
  /** 带分类的好友列表(get_friends_with_category,分类保留)。 */
1686
1690
  getFriendCategories(): Promise<FriendCategory[]>;
1687
1691
  /** 原始分类(getBuddyListV2 / 缓存)。 */
@@ -1698,8 +1702,6 @@ export declare class FriendApi {
1698
1702
  deleteFriend(uid: string, tempBlock?: boolean, tempBothDel?: boolean): Promise<void>;
1699
1703
  /** 可疑好友申请列表(get_doubt_friends_add_request;uin 经 uidToUin 转换)。 */
1700
1704
  getDoubtFriendRequest(count: number): Promise<DoubtFriendRequestInfo[]>;
1701
- /** 单项转换:DoubtBuddyReq → OB11 结构(可选字段条件赋值,exactOptionalPropertyTypes)。 */
1702
- private toDoubtFriendRequestInfo;
1703
1705
  /** 处理可疑好友申请(set_doubt_friends_add_request;uid=flag)。 */
1704
1706
  handleDoubtFriendRequest(uid: string): void;
1705
1707
  }
@@ -1792,16 +1794,51 @@ export declare class GroupApi {
1792
1794
  remainAtAllCountForGroup: number;
1793
1795
  }>;
1794
1796
  }
1797
+ declare const requestTypes: {
1798
+ readonly invitation: 1;
1799
+ readonly invited_join_request: 5;
1800
+ readonly join_request: 7;
1801
+ };
1802
+ type GroupRequestKind = keyof typeof requestTypes;
1803
+ interface GroupRequestRef {
1804
+ seq: string;
1805
+ groupCode: string;
1806
+ kind: GroupRequestKind;
1807
+ doubt: boolean;
1808
+ }
1809
+ interface PendingGroupRequest {
1810
+ request: GroupRequestRef;
1811
+ initiatorUid?: string;
1812
+ targetUid?: string;
1813
+ comment?: string;
1814
+ }
1815
+ /** 仅接受有完整审批标识的未处理群通知。 */
1816
+ export declare function toPendingGroupRequest(notify: GroupNotify, doubt: boolean): PendingGroupRequest | undefined;
1817
+ /** 兼容按序号审批的协议。指定队列时只读取该队列。 */
1818
+ export declare function findPendingGroupRequest(api: Pick<GroupNotifyApi, "getSingleScreenNotifies">, filter: {
1819
+ seq: string;
1820
+ doubt?: boolean | undefined;
1821
+ groupCode?: string;
1822
+ kind?: GroupRequestKind | readonly GroupRequestKind[] | undefined;
1823
+ }, count: number): Promise<{
1824
+ request: GroupRequestRef;
1825
+ notify: GroupNotify;
1826
+ }>;
1795
1827
  /** 群通知 API:从 session 拿 group service,包装成语义化方法。 */
1796
1828
  export declare class GroupNotifyApi {
1797
1829
  private readonly service;
1798
1830
  constructor(session: NodeIQQNTWrapperSession);
1799
1831
  /** 单屏通知列表(get_group_system_msg / set_group_add_request 共用)。 */
1800
1832
  getSingleScreenNotifies(doubt: boolean, count: number): Promise<GroupNotify[]>;
1833
+ /** 从实时通知提取可供 IPC 消费的请求。 */
1834
+ getPendingGroupRequests(doubt: boolean, notifies: unknown): PendingGroupRequest[];
1835
+ /** 处理同一登录会话发出的请求引用。QQ 负责权限与请求有效性判定。 */
1836
+ respondToRequest(request: GroupRequestRef, approve: boolean, reason?: string): Promise<void>;
1801
1837
  /** 禁言成员列表(get_group_shut_list)。 */
1802
1838
  getGroupShutUpMemberList(groupCode: string): Promise<GroupMember[]>;
1803
1839
  /** 处理群请求(set_group_add_request 应答;approve=true 同意 / false 拒绝)。 */
1804
1840
  handleGroupRequest(doubt: boolean, notify: GroupNotify, operateType: NTGroupRequestOperateTypes, reason: string): Promise<void>;
1841
+ private operateRequest;
1805
1842
  }
1806
1843
  /** Listener 接口形状(宽约束;精确签名由实例化时的具体接口保证)。 */
1807
1844
  type ListenerShape = Record<string, unknown>;
@@ -3251,11 +3288,14 @@ interface CoreLoginOptions {
3251
3288
  * (qrFallback 可接)。底层 promise 无法取消:超时后悬挂丢弃。
3252
3289
  */
3253
3290
  quickLoginTimeoutMs?: number | undefined;
3254
- /** 快速登录失败时回退 QR 登录(二维码写缓存目录),默认 false。 */
3291
+ /** 快速登录失败时回退 QR 登录(二维码写账号 cache/qr 临时目录),默认 false。 */
3255
3292
  qrFallback?: boolean | undefined;
3256
3293
  /** 强制扫码:跳过快速登录,直接走 QR 登录(koishi 强制扫码 / 切账号)。默认 false。 */
3257
3294
  qrOnly?: boolean | undefined;
3258
- /** QR 二维码图片保存路径(默认缓存目录 qrcode.png)。 */
3295
+ /**
3296
+ * QR 二维码图片保存路径(显式指定时由调用方接管生命周期;默认
3297
+ * `<账号目录>/cache/qr/qrcode.png`,登录结束删除)。
3298
+ */
3259
3299
  qrCodePath?: string | undefined;
3260
3300
  /** 登录进度回调(QR 阶段:二维码数据 + 状态变化)。子进程 IPC 模式转发用。 */
3261
3301
  onLoginProgress?: ((progress: LoginProgress) => void) | undefined;
@@ -3275,6 +3315,8 @@ export declare class NapukettoCore {
3275
3315
  readonly ctx: CoreContext;
3276
3316
  /** QR 登录会话句柄(登录期间非空;登录终态后清空)。refreshQr() 据此可达。 */
3277
3317
  private qrSession;
3318
+ /** 本次登录默认落盘的临时二维码路径(显式 qrCodePath 不纳入自动清理)。 */
3319
+ private ephemeralQrCodePath;
3278
3320
  /** 由 createRuntime() 装配的运行时服务集合(stop/dispose 时统一清理)。 */
3279
3321
  private runtime;
3280
3322
  /** stop 幂等标记。 */
@@ -3345,7 +3387,7 @@ export declare class NapukettoCore {
3345
3387
  * koishi 前端「刷新二维码」按钮经 loader IPC `login.refreshQr` 动作直达。
3346
3388
  */
3347
3389
  refreshQr(): boolean;
3348
- /** QR 登录:QrLoginSession 状态机 + 二维码写缓存目录(无 UI,cli 可打印路径)。 */
3390
+ /** QR 登录:QrLoginSession 状态机 + 二维码写独占缓存目录(无 UI,cli 可打印路径)。 */
3349
3391
  private loginByQr;
3350
3392
  /** 订阅 QR 进度:二维码写盘 + 状态机经 onLoginProgress 转发。 */
3351
3393
  private subscribeQrProgress;
@@ -3356,6 +3398,8 @@ export declare class NapukettoCore {
3356
3398
  * 重复调用直接返回(宿主关停钩子可能同时触发多次)。
3357
3399
  */
3358
3400
  stop(): void;
3401
+ /** 删除本次登录默认落盘的临时二维码(显式 qrCodePath 不删)。幂等。 */
3402
+ private cleanupEphemeralQrCode;
3359
3403
  /** 显式释放(`using` / 手动调用的统一入口;等价 stop)。 */
3360
3404
  dispose(): void;
3361
3405
  /** `using core = ...` 自动释放。 */
@@ -3603,4 +3647,4 @@ interface QqVersionInfo {
3603
3647
  }
3604
3648
  /** @deprecated 使用 `QqVersionInfo`(缩写大小写统一为 `Qq`)。 */
3605
3649
  type QQVersionInfo = QqVersionInfo;
3606
- export { type BootEnv, type BuddyCacheEventChannel, type BuddyCacheListener, type BuddyCacheOptions, type BuddyCategory, type BuddyCoreInfo, type BuddyEventChannel, type BuddyListEntry, type BuddyListener, type BuddyProfileLikeResult, type BuddyReq, type CanonicalElement, type ConfigFormat, type ConfigOptions, type ConfigPathOptions, type ConfigSchema, type ConsoleFormatStreamOptions, type CoreContext, type CoreContextOptions, type CoreLoginOptions, type DesktopPathConfig, type DeviceInfo, type DoubtBuddyReq, type DoubtFriendRequestInfo, type EnginInitDesktopConfig, type EssenceAddedItem, type EssenceCacheEntry, type EssenceDiffResult, type EssenceListSyncDeps, type EssenceMsgItem, type FaceElement, type FileElement, type FlashTransferFileSet, type FlashTransferFileStatus, type FlashTransferPermission, type FlashTransferTarget, type FlashTransferTaskInfo, type FlashTransferUploadListener, type FlashTransferUploadOptions, type FlashTransferUploadResult, type ForceFetchClientKeyRetType, type Friend, type FriendApiOptions, type FriendCategory, type GeneralCallResult, type GetFileListParam, type GrayTipElement, type GrayTipRevokeElement, type Group, type GroupBulletin, type GroupCacheOptions, type GroupDetailInfo, type GroupEventChannel, type GroupFileItemInfo, type GroupFileListItem, type GroupFileSystemInfo, type GroupFolderInfo, type GroupHonorWebInfo, type GroupListener, type GroupMember, type GroupMemberListChange, type GroupNotify, type GroupRemainAtTimes, type GroupSpaceInfo, type HonorListItem, type IKernelLoginListener, type KernelErrorCode, type KernelLoginListener, type KernelRuntime, type KernelRuntimeOptions, type KickMemberInfo, type KickMemberV2Req, type ListenerEvents, type ListenerRecordEvent, type ListenerRecordingResult, type LogConfig, type LogEnvSource, type LogFileConfig, type LogFormat, type LogLevel, type LogModuleName, type LoggerOptions, type LoginAccountInfo, type LoginEventChannel, type LoginListItem, type LoginListener, type LoginProgress, type LoginResult, type LoginState, type MsgEventChannel, type MsgListener, type MsgReadReportItem, type MsgReceipt, type NapukettoCoreOptions, type NodeIDependsAdapter, type NodeIDispatcherAdapter, type NodeIGlobalAdapter, type NodeIKernelBuddyService, type NodeIKernelGroupService, type NodeIKernelLoginService, type NodeIKernelMsgService, type NodeIKernelProfileLikeService, type NodeIKernelProfileService, type NodeIKernelRecentContactService, type NodeIKernelRichMediaService, type NodeIKernelSessionListener, type NodeIKernelTicketService, type NodeIQQNTStartupSessionWrapper, type NodeIQQNTWrapperEngine, type NodeIQQNTWrapperSession, type NodeQQNTWrapperUtil, type NudgeParam, type PathOptions, type Peer, type PicElement, type PinnedContact, type PlatformType, type PttElement, type QQVersionContext, type QQVersionInfo, type QqDataRootOptions, type QqVersionContext, type QqVersionInfo, type QrCodeData, type QuickLoginOptions, type RDeliveryConfig, type RawElement, type RawMessage, type RecentContact, type RecentContactEventChannel, type RecentContactFetchParam, type RecentContactListChanged, type RecentContactListener, type ReplyElement, type SelfInfo, type SendMessageElement, type SessionConfigOptions, type SessionListenerOptions, type ShutUpGroupMember, type StartNapukettoOptions, type StrangerInfo, type TextElement, type TimestampMode, type TipAioOpGrayTipElement, type TipGroupElement, type UserDetailInfoByUin, type VendorType, type VideoElement, type WrapperContext, type WrapperNodeApi, type WrapperSessionInitConfig, createSessionListener as createLifecycleSessionListener };
3650
+ export { type BootEnv, type BuddyCacheEventChannel, type BuddyCacheListener, type BuddyCacheOptions, type BuddyCategory, type BuddyCoreInfo, type BuddyEventChannel, type BuddyListEntry, type BuddyListener, type BuddyProfileLikeResult, type BuddyReq, type CanonicalElement, type ConfigFormat, type ConfigOptions, type ConfigPathOptions, type ConfigSchema, type ConsoleFormatStreamOptions, type CoreContext, type CoreContextOptions, type CoreLoginOptions, type DesktopPathConfig, type DeviceInfo, type DoubtBuddyReq, type DoubtFriendRequestInfo, type EnginInitDesktopConfig, type EssenceAddedItem, type EssenceCacheEntry, type EssenceDiffResult, type EssenceListSyncDeps, type EssenceMsgItem, type FaceElement, type FileElement, type FlashTransferFileSet, type FlashTransferFileStatus, type FlashTransferPermission, type FlashTransferTarget, type FlashTransferTaskInfo, type FlashTransferUploadListener, type FlashTransferUploadOptions, type FlashTransferUploadResult, type ForceFetchClientKeyRetType, type Friend, type FriendApiOptions, type FriendCategory, type GeneralCallResult, type GetFileListParam, type GrayTipElement, type GrayTipRevokeElement, type Group, type GroupBulletin, type GroupCacheOptions, type GroupDetailInfo, type GroupEventChannel, type GroupFileItemInfo, type GroupFileListItem, type GroupFileSystemInfo, type GroupFolderInfo, type GroupHonorWebInfo, type GroupListener, type GroupMember, type GroupMemberListChange, type GroupNotify, type GroupRemainAtTimes, type GroupRequestKind, type GroupRequestRef, type GroupSpaceInfo, type HonorListItem, type IKernelLoginListener, type KernelErrorCode, type KernelLoginListener, type KernelRuntime, type KernelRuntimeOptions, type KickMemberInfo, type KickMemberV2Req, type ListenerEvents, type ListenerRecordEvent, type ListenerRecordingResult, type LogConfig, type LogEnvSource, type LogFileConfig, type LogFormat, type LogLevel, type LogModuleName, type LoggerOptions, type LoginAccountInfo, type LoginEventChannel, type LoginListItem, type LoginListener, type LoginProgress, type LoginResult, type LoginState, type MsgEventChannel, type MsgListener, type MsgReadReportItem, type MsgReceipt, type NapukettoCoreOptions, type NodeIDependsAdapter, type NodeIDispatcherAdapter, type NodeIGlobalAdapter, type NodeIKernelBuddyService, type NodeIKernelGroupService, type NodeIKernelLoginService, type NodeIKernelMsgService, type NodeIKernelProfileLikeService, type NodeIKernelProfileService, type NodeIKernelRecentContactService, type NodeIKernelRichMediaService, type NodeIKernelSessionListener, type NodeIKernelTicketService, type NodeIQQNTStartupSessionWrapper, type NodeIQQNTWrapperEngine, type NodeIQQNTWrapperSession, type NodeQQNTWrapperUtil, type NudgeParam, type PathOptions, type Peer, type PendingGroupRequest, type PicElement, type PinnedContact, type PlatformType, type PttElement, type QQVersionContext, type QQVersionInfo, type QqDataRootOptions, type QqVersionContext, type QqVersionInfo, type QrCodeData, type QuickLoginOptions, type RDeliveryConfig, type RawElement, type RawMessage, type RecentContact, type RecentContactEventChannel, type RecentContactFetchParam, type RecentContactListChanged, type RecentContactListener, type ReplyElement, type SelfInfo, type SendMessageElement, type SessionConfigOptions, type SessionListenerOptions, type ShutUpGroupMember, type StartNapukettoOptions, type StrangerInfo, type TextElement, type TimestampMode, type TipAioOpGrayTipElement, type TipGroupElement, type UserDetailInfoByUin, type VendorType, type VideoElement, type WrapperContext, type WrapperNodeApi, type WrapperSessionInitConfig, createSessionListener as createLifecycleSessionListener };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { open, readFile, rename, rm, stat } from "node:fs/promises";
4
4
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import process from "node:process";
@@ -750,7 +750,10 @@ const SENSITIVE_FIELDS = /* @__PURE__ */ new Set([
750
750
  "skey",
751
751
  "p_skey",
752
752
  "csrf_token",
753
- "bkn"
753
+ "bkn",
754
+ "qrcodeurl",
755
+ "qr_code_url",
756
+ "qrcode_url"
754
757
  ]);
755
758
  /** 只遍历刚解析的 JSON 树;不会触碰业务对象、getter、toJSON 或循环引用。 */
756
759
  function redactFields(record) {
@@ -1292,6 +1295,7 @@ function clearTimer(timer) {
1292
1295
  * (getBuddyReq / approvalFriendRequest / setBuddyRemark / delBuddy /
1293
1296
  * getDoubtBuddyReq / approvalDoubtBuddyReq)。
1294
1297
  */
1298
+ const QQ_NUMBER = /^[1-9]\d*$/;
1295
1299
  /** 好友 API:从 session 拿 buddy service,包装成语义化方法。 */
1296
1300
  var FriendApi = class {
1297
1301
  service;
@@ -1302,34 +1306,30 @@ var FriendApi = class {
1302
1306
  }
1303
1307
  /** 好友列表(分类拍平为 Friend[];昵称/备注从 service 缓存读取)。 */
1304
1308
  async getFriendList() {
1305
- let categories;
1306
- try {
1307
- categories = await this.service.getBuddyListFromCache(0);
1308
- } catch {
1309
- const raw = await this.service.getBuddyListV2("cli", true, 0);
1310
- if (raw.result !== 0) throw kernelError(`getBuddyListV2 失败: ${raw.errMsg}`, "UNKNOWN");
1311
- categories = raw.data;
1312
- }
1313
- const uids = categories.flatMap((cat) => cat.buddyList?.map((b) => b.uid) ?? cat.buddyUids ?? []);
1314
- let uinMap = /* @__PURE__ */ new Map();
1315
- if (this.uidToUin !== void 0) uinMap = await this.uidToUin(uids);
1316
- const out = [];
1317
- for (const uid of uids) out.push({
1318
- uid,
1319
- uin: uinMap.get(uid) ?? uid,
1320
- nickname: this.service.getBuddyNick(uid),
1321
- remark: this.service.getBuddyRemark(uid)
1309
+ return this.friendsFromCategories(await this.getBuddyCategories());
1310
+ }
1311
+ async friendsFromCategories(categories) {
1312
+ const entries = categories.flatMap(buddyEntries);
1313
+ const unresolved = new Set(entries.filter((entry) => buddyUin(entry) === null).map(({ uid }) => uid));
1314
+ const uinMap = unresolved.size > 0 ? await this.uidToUin?.([...unresolved]) : void 0;
1315
+ return entries.map((entry) => {
1316
+ const { uid, coreInfo } = entry;
1317
+ return {
1318
+ uid,
1319
+ uin: buddyUin(entry) ?? validUin(uinMap?.get(uid)),
1320
+ nickname: coreInfo?.nick ?? this.service.getBuddyNick(uid),
1321
+ remark: coreInfo?.remark ?? this.service.getBuddyRemark(uid)
1322
+ };
1322
1323
  });
1323
- return out;
1324
1324
  }
1325
1325
  /** 带分类的好友列表(get_friends_with_category,分类保留)。 */
1326
1326
  async getFriendCategories() {
1327
1327
  const categories = await this.getBuddyCategories();
1328
1328
  const friendMap = /* @__PURE__ */ new Map();
1329
- for (const friend of await this.getFriendList()) friendMap.set(friend.uid, friend);
1329
+ for (const friend of await this.friendsFromCategories(categories)) friendMap.set(friend.uid, friend);
1330
1330
  return categories.map((cat) => {
1331
1331
  const buddies = [];
1332
- for (const uid of cat.buddyList?.map((b) => b.uid) ?? cat.buddyUids ?? []) {
1332
+ for (const { uid } of buddyEntries(cat)) {
1333
1333
  const friend = friendMap.get(uid);
1334
1334
  if (friend !== void 0) buddies.push(friend);
1335
1335
  }
@@ -1394,19 +1394,22 @@ var FriendApi = class {
1394
1394
  const list = raw.doubtList ?? [];
1395
1395
  let uinMap = /* @__PURE__ */ new Map();
1396
1396
  if (this.uidToUin !== void 0 && list.length > 0) uinMap = await this.uidToUin(list.map((item) => item.uid));
1397
- const out = [];
1398
- for (const item of list) out.push(this.toDoubtFriendRequestInfo(item, uinMap));
1399
- return out;
1400
- }
1401
- /** 单项转换:DoubtBuddyReq → OB11 结构(可选字段条件赋值,exactOptionalPropertyTypes)。 */
1402
- toDoubtFriendRequestInfo(item, uinMap) {
1403
- return toDoubtFriendRequestInfo(item, uinMap);
1397
+ return list.map((item) => toDoubtFriendRequestInfo(item, uinMap));
1404
1398
  }
1405
1399
  /** 处理可疑好友申请(set_doubt_friends_add_request;uid=flag)。 */
1406
1400
  handleDoubtFriendRequest(uid) {
1407
1401
  this.service.approvalDoubtBuddyReq(uid, "", "");
1408
1402
  }
1409
1403
  };
1404
+ function buddyEntries(category) {
1405
+ return category.buddyList ?? category.buddyUids?.map((uid) => ({ uid })) ?? [];
1406
+ }
1407
+ function buddyUin(entry) {
1408
+ return validUin(entry.uin) ?? validUin(entry.coreInfo?.uin);
1409
+ }
1410
+ function validUin(value) {
1411
+ return typeof value === "string" && QQ_NUMBER.test(value) ? value : null;
1412
+ }
1410
1413
  /** 可选字段条件赋值(undefined 跳过,兼容 exactOptionalPropertyTypes)。 */
1411
1414
  function assignOptional(info, key, value) {
1412
1415
  if (value !== void 0) info[key] = value;
@@ -1418,7 +1421,7 @@ function assignOptional(info, key, value) {
1418
1421
  * 经 JSON.stringify 变 null。这里只接受正安全整数(QQ 号),其余交给调用方省略字段。
1419
1422
  */
1420
1423
  function resolveDoubtUin(uid, uinMap) {
1421
- const value = Number(uinMap.get(uid) ?? uid);
1424
+ const value = Number(validUin(uinMap.get(uid)));
1422
1425
  return Number.isSafeInteger(value) && value > 0 ? value : void 0;
1423
1426
  }
1424
1427
  /** 单项转换:DoubtBuddyReq → OB11 结构(导出供单测,friend.test.ts)。 */
@@ -1599,10 +1602,10 @@ function textToCanonical(textEl) {
1599
1602
  type: "at",
1600
1603
  target: "all"
1601
1604
  };
1602
- if (atType === AtType.ONE || atType === AtType.ME) {
1605
+ if ((atType === AtType.ONE || atType === AtType.ME) && atUid != null && atUid.trim() !== "") {
1603
1606
  const base = {
1604
1607
  type: "at",
1605
- target: atUid ?? content
1608
+ target: atUid
1606
1609
  };
1607
1610
  const display = content.startsWith("@") ? content.slice(1) : content;
1608
1611
  if (display === "") return base;
@@ -1742,9 +1745,13 @@ function replyToCanonical(reply) {
1742
1745
  type: "reply",
1743
1746
  messageId: ""
1744
1747
  };
1748
+ const senderUid = emptyToUndefined(reply.senderUid);
1749
+ const senderUin = emptyToUndefined(reply.senderUin);
1745
1750
  return {
1746
1751
  type: "reply",
1747
- messageId: reply.replayMsgId ?? ""
1752
+ messageId: reply.replayMsgId ?? "",
1753
+ ...senderUid !== void 0 ? { senderUid } : {},
1754
+ ...senderUin !== void 0 ? { senderUin } : {}
1748
1755
  };
1749
1756
  }
1750
1757
  /**
@@ -2020,6 +2027,7 @@ var GroupApi = class {
2020
2027
  */
2021
2028
  async setMemberShutUp(groupCode, members) {
2022
2029
  if (members.length === 0) throw kernelError("setMemberShutUp 需要至少一个成员", "INVALID_PARAM");
2030
+ if (members.some(({ duration }) => !Number.isSafeInteger(duration) || duration < 0)) throw kernelError("禁言时长必须是非负整数秒,0 表示解除", "INVALID_PARAM");
2023
2031
  const raw = await this.service.setMemberShutUp(groupCode, members.map((m) => ({
2024
2032
  uid: m.uid,
2025
2033
  timeStamp: m.duration
@@ -2249,6 +2257,66 @@ function extractGroupDetail(result, raw) {
2249
2257
  return isGroupDetailInfo(candidate) ? candidate : null;
2250
2258
  }
2251
2259
  // src/apis/group-notify.ts
2260
+ /**
2261
+ * GroupNotifyApi:群通知/禁言列表语义化 API(ADR-009 统一错误语义,P2-13)
2262
+ *
2263
+ * get_group_system_msg / set_group_add_request / get_group_shut_list 共用。
2264
+ * getSingleScreenNotifies / getGroupShutUpMemberList 的列表可能走 listener 回调,
2265
+ * 直接调用返回形状待探测校准:兼容 result 数组 / 字段 / Map。
2266
+ *
2267
+ * 列表提取一律走元素级类型守卫(`isGroupNotify` / `isGroupMember`):
2268
+ * 原生返回数组里混入 null / 字符串 / 残缺对象时逐项丢弃,而不是整数组强转。
2269
+ */
2270
+ const requestTypes = {
2271
+ invitation: GroupNotifyMsgType.INVITED_BY_MEMBER,
2272
+ invited_join_request: GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS,
2273
+ join_request: GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS
2274
+ };
2275
+ const GROUP_CODE = /^[1-9]\d*$/;
2276
+ /** 仅接受有完整审批标识的未处理群通知。 */
2277
+ function toPendingGroupRequest(notify, doubt) {
2278
+ const { status, type, seq, group, user1, user2, postscript } = notify;
2279
+ const groupCode = group?.groupCode;
2280
+ if (status !== GroupNotifyMsgStatus.KUNHANDLE || typeof seq !== "string" || seq.trim() === "" || typeof groupCode !== "string" || !GROUP_CODE.test(groupCode)) return;
2281
+ const kind = requestKinds.find((key) => requestTypes[key] === type);
2282
+ if (kind === void 0) return;
2283
+ return {
2284
+ request: {
2285
+ seq,
2286
+ groupCode,
2287
+ kind,
2288
+ doubt
2289
+ },
2290
+ ...typeof user1?.uid === "string" && user1.uid !== "" ? { initiatorUid: user1.uid } : {},
2291
+ ...typeof user2?.uid === "string" && user2.uid !== "" ? { targetUid: user2.uid } : {},
2292
+ ...typeof postscript === "string" ? { comment: postscript } : {}
2293
+ };
2294
+ }
2295
+ const requestKinds = [
2296
+ "invitation",
2297
+ "invited_join_request",
2298
+ "join_request"
2299
+ ];
2300
+ /** 兼容按序号审批的协议。指定队列时只读取该队列。 */
2301
+ async function findPendingGroupRequest(api, filter, count) {
2302
+ const queues = filter.doubt === void 0 ? [false, true] : [filter.doubt];
2303
+ const kinds = typeof filter.kind === "string" ? [filter.kind] : filter.kind;
2304
+ const matches = /* @__PURE__ */ new Map();
2305
+ for (const doubt of queues) {
2306
+ const notifies = await api.getSingleScreenNotifies(doubt, count);
2307
+ for (const notify of notifies.filter(({ seq }) => seq === filter.seq)) {
2308
+ const request = toPendingGroupRequest(notify, doubt)?.request;
2309
+ if (request !== void 0 && request.groupCode === (filter.groupCode ?? request.groupCode) && kinds?.includes(request.kind) !== false) matches.set(JSON.stringify(request), {
2310
+ request,
2311
+ notify
2312
+ });
2313
+ }
2314
+ }
2315
+ if (matches.size > 1) throw kernelError("群请求标识有多个匹配,请指定队列、群号和类型", "INVALID_PARAM");
2316
+ const match = matches.values().next().value;
2317
+ if (match === void 0) throw kernelError("未找到待处理群请求", "NOT_FOUND");
2318
+ return match;
2319
+ }
2252
2320
  /** 群通知 API:从 session 拿 group service,包装成语义化方法。 */
2253
2321
  var GroupNotifyApi = class {
2254
2322
  service;
@@ -2258,7 +2326,27 @@ var GroupNotifyApi = class {
2258
2326
  /** 单屏通知列表(get_group_system_msg / set_group_add_request 共用)。 */
2259
2327
  async getSingleScreenNotifies(doubt, count) {
2260
2328
  const raw = await this.service.getSingleScreenNotifies(doubt, "", count);
2261
- return extractNotifyList(isRecord(raw) ? raw["result"] : void 0);
2329
+ checkLooseResult("getSingleScreenNotifies", raw);
2330
+ const result = isRecord(raw) ? raw["result"] : void 0;
2331
+ return extractNotifyList(result !== null && typeof result === "object" ? result : raw);
2332
+ }
2333
+ /** 从实时通知提取可供 IPC 消费的请求。 */
2334
+ getPendingGroupRequests(doubt, notifies) {
2335
+ return extractNotifyList(notifies).flatMap((notify) => {
2336
+ const pending = toPendingGroupRequest(notify, doubt);
2337
+ return pending === void 0 ? [] : [pending];
2338
+ });
2339
+ }
2340
+ /** 处理同一登录会话发出的请求引用。QQ 负责权限与请求有效性判定。 */
2341
+ async respondToRequest(request, approve, reason = "") {
2342
+ const { seq, groupCode, kind, doubt } = request;
2343
+ if (!requestKinds.includes(kind) || seq.trim() === "" || !GROUP_CODE.test(groupCode)) throw kernelError("群请求引用无效", "INVALID_PARAM");
2344
+ await this.operateRequest(doubt, {
2345
+ seq,
2346
+ type: requestTypes[kind],
2347
+ groupCode,
2348
+ postscript: reason || " "
2349
+ }, approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE);
2262
2350
  }
2263
2351
  /** 禁言成员列表(get_group_shut_list)。 */
2264
2352
  async getGroupShutUpMemberList(groupCode) {
@@ -2274,15 +2362,18 @@ var GroupNotifyApi = class {
2274
2362
  if (group !== void 0) ({groupCode} = group);
2275
2363
  let postscript = reason;
2276
2364
  if (postscript === "") postscript = " ";
2277
- await this.service.operateSysNotify(doubt, {
2365
+ await this.operateRequest(doubt, {
2366
+ seq,
2367
+ type,
2368
+ groupCode,
2369
+ postscript
2370
+ }, operateType);
2371
+ }
2372
+ async operateRequest(doubt, targetMsg, operateType) {
2373
+ checkLooseResult("operateSysNotify", await this.service.operateSysNotify(doubt, {
2278
2374
  operateType,
2279
- targetMsg: {
2280
- seq,
2281
- type,
2282
- groupCode,
2283
- postscript
2284
- }
2285
- });
2375
+ targetMsg
2376
+ }));
2286
2377
  }
2287
2378
  };
2288
2379
  /** 群通知项形状判定(seq 字符串 + type 数字是 GroupNotify 的必备标识)。 */
@@ -5849,6 +5940,8 @@ var NapukettoCore = class NapukettoCore {
5849
5940
  ctx;
5850
5941
  /** QR 登录会话句柄(登录期间非空;登录终态后清空)。refreshQr() 据此可达。 */
5851
5942
  qrSession = null;
5943
+ /** 本次登录默认落盘的临时二维码路径(显式 qrCodePath 不纳入自动清理)。 */
5944
+ ephemeralQrCodePath = null;
5852
5945
  /** 由 createRuntime() 装配的运行时服务集合(stop/dispose 时统一清理)。 */
5853
5946
  runtime = null;
5854
5947
  /** stop 幂等标记。 */
@@ -6019,13 +6112,15 @@ var NapukettoCore = class NapukettoCore {
6019
6112
  this.qrSession.refresh();
6020
6113
  return true;
6021
6114
  }
6022
- /** QR 登录:QrLoginSession 状态机 + 二维码写缓存目录(无 UI,cli 可打印路径)。 */
6115
+ /** QR 登录:QrLoginSession 状态机 + 二维码写独占缓存目录(无 UI,cli 可打印路径)。 */
6023
6116
  async loginByQr(opts) {
6024
6117
  const { wrapper } = this.ctx;
6025
6118
  if (wrapper === null || wrapper.loginService === null) throw kernelError("wrapper/loginService 不可用,无法 QR 登录", "INVALID_STATE");
6026
6119
  const session = new QrLoginSession(wrapper.loginService);
6027
6120
  this.qrSession = session;
6028
- const qrPath = opts.qrCodePath ?? this.ctx.paths.file("cache", "qrcode.png");
6121
+ const explicitPath = opts.qrCodePath;
6122
+ const qrPath = explicitPath ?? this.ctx.paths.file("cache", QR_CODE_DIR, QR_CODE_FILENAME);
6123
+ this.ephemeralQrCodePath = explicitPath === void 0 ? qrPath : null;
6029
6124
  this.subscribeQrProgress(session, opts, qrPath);
6030
6125
  try {
6031
6126
  session.start();
@@ -6039,12 +6134,13 @@ var NapukettoCore = class NapukettoCore {
6039
6134
  } finally {
6040
6135
  session.stop();
6041
6136
  this.qrSession = null;
6137
+ this.cleanupEphemeralQrCode();
6042
6138
  }
6043
6139
  }
6044
6140
  /** 订阅 QR 进度:二维码写盘 + 状态机经 onLoginProgress 转发。 */
6045
6141
  subscribeQrProgress(session, opts, qrPath) {
6046
6142
  session.onQrCode((qr) => {
6047
- this.ctx.logger.warn(`请扫描二维码登录(保存: ${qrPath} | URL: ${qr.qrcodeUrl})`);
6143
+ this.ctx.logger.warn(`请扫描二维码登录(图片: ${qrPath})`);
6048
6144
  if (qr.pngBase64 !== "") writeQrCodePng(qrPath, qr.pngBase64);
6049
6145
  opts.onLoginProgress?.({
6050
6146
  state: "waiting_scan",
@@ -6070,10 +6166,17 @@ var NapukettoCore = class NapukettoCore {
6070
6166
  this.stopped = true;
6071
6167
  this.qrSession?.stop();
6072
6168
  this.qrSession = null;
6169
+ this.cleanupEphemeralQrCode();
6073
6170
  this.runtime?.dispose();
6074
6171
  this.runtime = null;
6075
6172
  this.ctx.logger.info("NapukettoCore 停止");
6076
6173
  }
6174
+ /** 删除本次登录默认落盘的临时二维码(显式 qrCodePath 不删)。幂等。 */
6175
+ cleanupEphemeralQrCode() {
6176
+ const path = this.ephemeralQrCodePath;
6177
+ this.ephemeralQrCodePath = null;
6178
+ if (path !== null) removeQrCodePng(path);
6179
+ }
6077
6180
  /** 显式释放(`using` / 手动调用的统一入口;等价 stop)。 */
6078
6181
  dispose() {
6079
6182
  this.stop();
@@ -6121,11 +6224,33 @@ function resolveSessionAccountPath(ctx, wrapper) {
6121
6224
  function hasInitConfig(val) {
6122
6225
  return typeof val["initConfig"] === "function";
6123
6226
  }
6124
- /** 写二维码 png 到磁盘(base64 解码,供 cli/用户扫码)。 */
6227
+ /** 二维码 png 默认落盘目录(账号 cache 下的独占子目录)。 */
6228
+ const QR_CODE_DIR = "qr";
6229
+ /** 二维码 png 默认文件名。 */
6230
+ const QR_CODE_FILENAME = "qrcode.png";
6231
+ /**
6232
+ * 写二维码 png 到磁盘(base64 解码,供 cli/用户扫码)。
6233
+ *
6234
+ * 安全边界:目录按 0o700 创建、文件按 0o600 写入;写入前拒绝符号链接,避免被
6235
+ * 预置链接引到其他文件。失败不阻塞登录(cli 仍可打印 URL / 终端渲染)。
6236
+ */
6125
6237
  function writeQrCodePng(filePath, pngBase64) {
6126
6238
  try {
6127
- mkdirSync(dirname(filePath), { recursive: true });
6128
- writeFileSync(filePath, Buffer.from(pngBase64, "base64"));
6239
+ mkdirSync(dirname(filePath), {
6240
+ recursive: true,
6241
+ mode: 448
6242
+ });
6243
+ try {
6244
+ if (lstatSync(filePath).isSymbolicLink()) return;
6245
+ } catch {}
6246
+ writeFileSync(filePath, Buffer.from(pngBase64, "base64"), { mode: 384 });
6247
+ chmodSync(filePath, 384);
6248
+ } catch {}
6249
+ }
6250
+ /** 删除默认落盘的二维码文件(不存在 / 权限失败静默)。 */
6251
+ function removeQrCodePng(filePath) {
6252
+ try {
6253
+ unlinkSync(filePath);
6129
6254
  } catch {}
6130
6255
  }
6131
6256
  /** CoreLoginOptions → quickLogin 参数(仅取快速登录相关两键,QR 键不透传)。 */
@@ -7030,4 +7155,4 @@ function listQQVersions(installDir) {
7030
7155
  return statSync(full).isDirectory() && existsSync(join(full, "resources", "app", "wrapper.node"));
7031
7156
  }).sort().reverse();
7032
7157
  }
7033
- export { BuddyCache, CONFIG_FILE_MODE, ChatType, ConfigBase, ConfigError, DEFAULT_DATA_ROOT_NAME, DependsAdapter, DispatcherAdapter, EXIT_CONFIG_INVALID, ElementType, EssenceListSync, FlashTransferApi, FriendApi, FriendBridge, GlobalAdapter, GrayTipSubType, GroupApi, GroupBridge, GroupCache, GroupListUpdateType, GroupMemberDataSource, GroupNotifyApi, GroupNotifyMsgStatus, GroupNotifyMsgType, KERNEL_ERROR_CODES, KernelError, LoginBridge, MAIN_CONFIG_FILE, MsgApi, MsgBridge, NTEventChannel, NTGroupMemberRole, NTGroupRequestOperateTypes, NapukettoCore, PathWrapper, ProfileApi, ProfileLikeApi, QrLoginSession, RecentContactApi, RecentContactBridge, RichMediaApi, TicketApi, TipGroupElementType, VIDEO_THUMB_KEY, WebApi, WebHonorType, activateO3MiscService, buildEngineConfig, buildLoginConfig, buildSessionConfig, configError, createConsoleFormatStream, createCoreContext, createKernelRuntime, createSessionListener as createLifecycleSessionListener, createSessionListener, createLogger, createLoginListener, createRecordingListener, createSession, createWrapper, diffEssenceList, dlopenWrapper, electronProcessType, errorMessage, getErrorCode, getErrorMessage, getExistingSession, getMainSession, getOwnProp, hasBooleanProp, hasCallableProp, hasFunctionProp, hasMethodSurface, hasNumberProp, hasStaticCreator, hasStaticGetter, hasStringProp, initAndStartSession, initEngine, initSession, isCallable, isKernelError, isPromiseLike, isRecord, kernelError, listLoginAccounts, listQQVersions, narrowBuddyCategories, narrowEssenceGroupArg, parseAppidFromMajor, parseJsonWithGuard, parseLogConfig, parseToml, probeRuntime, quickLogin, readMachineGuid, requireKernelService, resolveAppidQua, resolveConfigPath, resolveDataRoot, resolveQQVersion, resolveQqGlobalPath, resolveQqUserDataRoot, resolveSandboxWritePath, resolveWrapperPath, sleep, startListenerRecording, startNapuketto, startSession, stringifyToml, toCanonicalElements, toSendElements, waitFor, waitForNetworkConnection, waitSessionReady };
7158
+ export { BuddyCache, CONFIG_FILE_MODE, ChatType, ConfigBase, ConfigError, DEFAULT_DATA_ROOT_NAME, DependsAdapter, DispatcherAdapter, EXIT_CONFIG_INVALID, ElementType, EssenceListSync, FlashTransferApi, FriendApi, FriendBridge, GlobalAdapter, GrayTipSubType, GroupApi, GroupBridge, GroupCache, GroupListUpdateType, GroupMemberDataSource, GroupNotifyApi, GroupNotifyMsgStatus, GroupNotifyMsgType, KERNEL_ERROR_CODES, KernelError, LoginBridge, MAIN_CONFIG_FILE, MsgApi, MsgBridge, NTEventChannel, NTGroupMemberRole, NTGroupRequestOperateTypes, NapukettoCore, PathWrapper, ProfileApi, ProfileLikeApi, QrLoginSession, RecentContactApi, RecentContactBridge, RichMediaApi, TicketApi, TipGroupElementType, VIDEO_THUMB_KEY, WebApi, WebHonorType, activateO3MiscService, buildEngineConfig, buildLoginConfig, buildSessionConfig, configError, createConsoleFormatStream, createCoreContext, createKernelRuntime, createSessionListener as createLifecycleSessionListener, createSessionListener, createLogger, createLoginListener, createRecordingListener, createSession, createWrapper, diffEssenceList, dlopenWrapper, electronProcessType, errorMessage, findPendingGroupRequest, getErrorCode, getErrorMessage, getExistingSession, getMainSession, getOwnProp, hasBooleanProp, hasCallableProp, hasFunctionProp, hasMethodSurface, hasNumberProp, hasStaticCreator, hasStaticGetter, hasStringProp, initAndStartSession, initEngine, initSession, isCallable, isKernelError, isPromiseLike, isRecord, kernelError, listLoginAccounts, listQQVersions, narrowBuddyCategories, narrowEssenceGroupArg, parseAppidFromMajor, parseJsonWithGuard, parseLogConfig, parseToml, probeRuntime, quickLogin, readMachineGuid, requireKernelService, resolveAppidQua, resolveConfigPath, resolveDataRoot, resolveQQVersion, resolveQqGlobalPath, resolveQqUserDataRoot, resolveSandboxWritePath, resolveWrapperPath, sleep, startListenerRecording, startNapuketto, startSession, stringifyToml, toCanonicalElements, toPendingGroupRequest, toSendElements, waitFor, waitForNetworkConnection, waitSessionReady };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/kernel",
4
- "version": "0.16.4",
4
+ "version": "0.18.0",
5
5
  "type": "module",
6
6
  "description": "Core runtime kernel of NapukettoQQ",
7
7
  "keywords": [