@serviceme/devtools-core 2.0.0 → 2.0.2
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/auth-Bzss8zOv.mjs +995 -0
- package/dist/auth-Bzss8zOv.mjs.map +1 -0
- package/dist/auth-DXam3c4S.js +1078 -0
- package/dist/auth-DXam3c4S.js.map +1 -0
- package/dist/auth.d.mts +2 -2
- package/dist/auth.d.ts +2 -2
- package/dist/auth.js +14 -1029
- package/dist/auth.mjs +2 -991
- package/dist/device-CDDcwDY6.mjs +758 -0
- package/dist/device-CDDcwDY6.mjs.map +1 -0
- package/dist/device-DuAYH8bk.js +839 -0
- package/dist/device-DuAYH8bk.js.map +1 -0
- package/dist/device.d.mts +2 -455
- package/dist/device.d.ts +2 -455
- package/dist/device.js +15 -728
- package/dist/device.mjs +2 -679
- package/dist/index-2rX86yMq.d.mts +331 -0
- package/dist/index-BI11AfMH.d.mts +377 -0
- package/dist/index-BI11AfMH.d.ts +377 -0
- package/dist/index-CoA6y0MP.d.mts +498 -0
- package/dist/index-CoA6y0MP.d.ts +498 -0
- package/dist/index-DaW7IYA-.d.mts +185 -0
- package/dist/index-DaW7IYA-.d.ts +185 -0
- package/dist/index-Dp6FwWKh.d.ts +331 -0
- package/dist/index.d.mts +2340 -2101
- package/dist/index.d.ts +2340 -2101
- package/dist/index.js +8117 -10538
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7895 -10318
- package/dist/index.mjs.map +1 -1
- package/dist/rolldown-runtime-VH7oDXx4.js +28 -0
- package/dist/skill-linker.d.mts +82 -81
- package/dist/skill-linker.d.ts +82 -81
- package/dist/skill-linker.js +359 -402
- package/dist/skill-linker.js.map +1 -1
- package/dist/skill-linker.mjs +345 -357
- package/dist/skill-linker.mjs.map +1 -1
- package/dist/skill-store-Bym2yinU.mjs +388 -0
- package/dist/skill-store-Bym2yinU.mjs.map +1 -0
- package/dist/skill-store-CJdYyyxu.js +408 -0
- package/dist/skill-store-CJdYyyxu.js.map +1 -0
- package/dist/skill-store.d.mts +41 -42
- package/dist/skill-store.d.ts +41 -42
- package/dist/skill-store.js +5 -338
- package/dist/skill-store.mjs +2 -301
- package/dist/submit-Cg7wSa3x.mjs +84 -0
- package/dist/submit-Cg7wSa3x.mjs.map +1 -0
- package/dist/submit-CltE6YOZ.js +98 -0
- package/dist/submit-CltE6YOZ.js.map +1 -0
- package/dist/submit.d.mts +2 -3
- package/dist/submit.d.ts +2 -3
- package/dist/submit.js +4 -166
- package/dist/submit.mjs +2 -130
- package/dist/toolbox-CbfxpNg-.mjs +540 -0
- package/dist/toolbox-CbfxpNg-.mjs.map +1 -0
- package/dist/toolbox-CxnOr-FY.js +614 -0
- package/dist/toolbox-CxnOr-FY.js.map +1 -0
- package/dist/toolbox.d.mts +2 -244
- package/dist/toolbox.d.ts +2 -244
- package/dist/toolbox.js +14 -584
- package/dist/toolbox.mjs +2 -536
- package/dist/{types-B9gk3dXH.d.ts → types-BCV3IedE.d.mts} +25 -23
- package/dist/{types-B9gk3dXH.d.mts → types-BCV3IedE.d.ts} +25 -23
- package/dist/userHome-BquDeFVE.js +526 -0
- package/dist/userHome-BquDeFVE.js.map +1 -0
- package/dist/userHome-CcnAQPG1.mjs +212 -0
- package/dist/userHome-CcnAQPG1.mjs.map +1 -0
- package/package.json +10 -10
- package/dist/auth.js.map +0 -1
- package/dist/auth.mjs.map +0 -1
- package/dist/device.js.map +0 -1
- package/dist/device.mjs.map +0 -1
- package/dist/index-BMk4tqIT.d.mts +0 -328
- package/dist/index-CymN0x9Z.d.ts +0 -328
- package/dist/index-PD135hlB.d.mts +0 -626
- package/dist/index-PD135hlB.d.ts +0 -626
- package/dist/skill-store.js.map +0 -1
- package/dist/skill-store.mjs.map +0 -1
- package/dist/submit.js.map +0 -1
- package/dist/submit.mjs.map +0 -1
- package/dist/toolbox.js.map +0 -1
- package/dist/toolbox.mjs.map +0 -1
package/dist/auth.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/AccessControl.ts","../src/logger.ts","../src/auth/AuthStateManager.ts","../src/auth/ProviderRegistry.ts","../src/auth/AuthCore.ts","../src/auth/KeychainAuthTokenStore.ts","../src/auth/utils/githubUserEmail.ts","../src/auth/providers/GitHubAuthProvider.ts","../src/auth/providers/MicrosoftAuthProvider.ts"],"sourcesContent":["/**\n * AccessControl — Pure logic for org-membership gating.\n *\n * Ported from `apps/extension/src/services/auth/AccessControlService.ts`\n * but stripped of all VSCode dependencies:\n * - No `vscode.window.showWarningMessage` — callers render the notice.\n * - No `vscode.context.globalState` — callers inject a `KeyValueStore`.\n * - No `vscode.Event` — uses a plain `onDidChange` callback.\n *\n * The class is generic over the membership-fetcher function so it can\n * run identically with the CLI's `@serviceme/devtools-shared` `getGitHubOrgMembership`\n * or with the Extension's bundled copy. ADL-003 forbids Core from\n * importing `@serviceme/devtools-shared` directly, so the org membership\n * result type is defined locally and the runtime adapter wraps the\n * shared helper at the boundary (Phase 5.3+).\n *\n * Refs:\n * - 4.功能规划.md §2.1 — `AccessControl.ts 从 AccessControlService 改写`\n * - ADL-003 — `@serviceme/devtools-shared` boundary (Core MUST NOT import shared)\n */\n\nimport type { AuthAccountMeta, AuthProvider } from \"@serviceme/devtools-protocol\";\n\n/** Core-local mirror of `GitHubOrgMembershipCheckResult` (defined in `@serviceme/devtools-shared`). */\nexport interface CoreOrgMembershipResult {\n\tstatus: \"active\" | \"pending\" | \"not_member\" | \"unknown\";\n\thttpStatus?: number;\n\trole?: string;\n\tdirectMembership?: boolean;\n}\n\n/**\n * Upstream org-membership fetcher. CLI / Extension adapters wrap\n * `getGitHubOrgMembership` (or the local extension copy) to match\n * this signature.\n */\nexport type OrgMembershipFetcher = (token: string, org: string) => Promise<CoreOrgMembershipResult>;\n\n/** Pluggable key/value store. Extension injects `globalState`-backed impl; CLI injects a file-backed impl. */\nexport interface KeyValueStore {\n\tget<T>(key: string): T | undefined;\n\tupdate<T>(key: string, value: T): Promise<void>;\n}\n\nexport interface AccessCheckResult {\n\tallowed: boolean;\n\treason?: \"not_authenticated\" | \"not_member\";\n\tusername?: string;\n}\n\nexport interface AccessControlOptions {\n\torg: string;\n\t/** Domains that auto-qualify Microsoft users without a GitHub link. */\n\tmicrosoftEmailDomains?: readonly string[];\n\t/** TTL for in-memory membership cache (ms). */\n\tcacheTtlMs?: number;\n\t/** TTL for persisted membership cache (ms). */\n\tpersistentCacheTtlMs?: number;\n\t/** Tokens whose bearer can be supplied to `OrgMembershipFetcher`. */\n\ttokenFetcher: (provider: AuthProvider) => Promise<string | null>;\n\t/** Upstream org-membership fetcher (typically `getGitHubOrgMembership` from `@serviceme/devtools-shared`). */\n\torgFetcher: OrgMembershipFetcher;\n\t/** Clock seam for tests. */\n\tnow?: () => number;\n}\n\nconst DEFAULT_CACHE_TTL_MS = 10 * 60 * 1000;\nconst DEFAULT_PERSISTENT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;\nconst KEY_GRANTED_USERS = \"msDevTools.accessControl.grantedUsers\";\nconst KEY_MEMBERSHIP_CACHE = \"msDevTools.accessControl.membershipCache\";\nconst KEY_SERVER_IN_ORG = \"msDevTools.accessControl.serverInOrg\";\n\ninterface CacheEntry {\n\tisMember: boolean;\n\tat: number;\n}\n\ninterface PersistentCache {\n\t[username: string]: CacheEntry;\n}\n\nexport class AccessControl {\n\tprivate readonly memCache = new Map<string, CacheEntry>();\n\tprivate readonly serverInOrgMem = new Map<string, boolean>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly opts: Required<\n\t\tOmit<AccessControlOptions, \"now\" | \"tokenFetcher\" | \"microsoftEmailDomains\" | \"orgFetcher\">\n\t> & {\n\t\ttokenFetcher: AccessControlOptions[\"tokenFetcher\"];\n\t\torgFetcher: OrgMembershipFetcher;\n\t\tmicrosoftEmailDomains: readonly string[];\n\t\tnow: () => number;\n\t};\n\n\tconstructor(\n\t\tprivate readonly kv: KeyValueStore,\n\t\toptions: AccessControlOptions\n\t) {\n\t\tthis.opts = {\n\t\t\torg: options.org,\n\t\t\ttokenFetcher: options.tokenFetcher,\n\t\t\torgFetcher: options.orgFetcher,\n\t\t\tmicrosoftEmailDomains: options.microsoftEmailDomains ?? [],\n\t\t\tcacheTtlMs: options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS,\n\t\t\tpersistentCacheTtlMs: options.persistentCacheTtlMs ?? DEFAULT_PERSISTENT_CACHE_TTL_MS,\n\t\t\tnow: options.now ?? (() => Date.now()),\n\t\t};\n\t\t// Hydrate `serverInOrg` from persistent storage so the gate can run instantly on restart.\n\t\tconst persistedServerInOrg = this.kv.get<Record<string, boolean>>(KEY_SERVER_IN_ORG);\n\t\tif (persistedServerInOrg) {\n\t\t\tfor (const [key, value] of Object.entries(persistedServerInOrg)) {\n\t\t\t\tthis.serverInOrgMem.set(key, value);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Subscribe to inOrg changes (used by extension to refresh access-gated UI). */\n\tonDidChange(listener: () => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/** Full check: requires authentication + org membership / admin grant. */\n\tasync checkAccess(user: AuthAccountMeta | null): Promise<AccessCheckResult> {\n\t\tif (!user) {\n\t\t\treturn { allowed: false, reason: \"not_authenticated\" };\n\t\t}\n\n\t\t// Microsoft users: server-confirmed inOrg takes priority over GitHub link.\n\t\tif (user.provider === \"microsoft\" && user.login) {\n\t\t\tconst inOrg = this.serverInOrgMem.get(user.login.toLowerCase());\n\t\t\tif (inOrg === true) return { allowed: true };\n\t\t\tif (inOrg === false) {\n\t\t\t\treturn { allowed: false, reason: \"not_member\", username: user.login };\n\t\t\t}\n\t\t}\n\n\t\t// Find a GitHub account if available (linked for Microsoft users).\n\t\tconst githubAccount = user.provider === \"github\" ? user : null;\n\t\tif (!githubAccount && user.provider === \"microsoft\" && user.login) {\n\t\t\tconst [, domain = \"\"] = user.login.split(\"@\");\n\t\t\tconst isDomainMember =\n\t\t\t\tdomain.length > 0 && this.opts.microsoftEmailDomains.includes(domain.toLowerCase());\n\t\t\tif (isDomainMember) return { allowed: true };\n\t\t\t// No GitHub link + unknown domain — deny until the next server-confirmed claim.\n\t\t\treturn { allowed: false, reason: \"not_member\", username: user.login };\n\t\t}\n\t\tif (!githubAccount) {\n\t\t\t// No identity at all — treat as authenticated for now (caller may have other gating).\n\t\t\treturn { allowed: true };\n\t\t}\n\n\t\tconst accessUsername = githubAccount.login ?? user.login ?? \"\";\n\t\tif (accessUsername.length === 0) {\n\t\t\treturn { allowed: false, reason: \"not_member\", username: \"\" };\n\t\t}\n\n\t\t// Admin-granted users bypass the org check.\n\t\tconst granted = this.getGrantedUsers();\n\t\tif (granted.includes(accessUsername.toLowerCase())) {\n\t\t\treturn { allowed: true };\n\t\t}\n\n\t\tconst isMember = await this.checkOrgMembership(accessUsername);\n\t\treturn isMember\n\t\t\t? { allowed: true }\n\t\t\t: { allowed: false, reason: \"not_member\", username: accessUsername };\n\t}\n\n\t/** Admin: grant access to a GitHub username (bypasses org check). */\n\tasync grantAccess(username: string): Promise<void> {\n\t\tconst list = this.getGrantedUsers();\n\t\tconst key = username.toLowerCase();\n\t\tif (!list.includes(key)) {\n\t\t\tlist.push(key);\n\t\t\tawait this.kv.update(KEY_GRANTED_USERS, list);\n\t\t}\n\t}\n\n\t/** Admin: revoke a previously granted access. */\n\tasync revokeAccess(username: string): Promise<void> {\n\t\tconst updated = this.getGrantedUsers().filter((u) => u !== username.toLowerCase());\n\t\tawait this.kv.update(KEY_GRANTED_USERS, updated);\n\t}\n\n\t/** Snapshot of all admin-granted usernames (lowercased). */\n\tgetGrantedUsers(): string[] {\n\t\treturn this.kv.get<string[]>(KEY_GRANTED_USERS) ?? [];\n\t}\n\n\t/** Cached membership lookup with both in-memory + persistent layers. */\n\tasync checkOrgMembership(username: string): Promise<boolean> {\n\t\tconst now = this.opts.now();\n\n\t\t// 1. In-memory cache.\n\t\tconst inMem = this.memCache.get(username);\n\t\tif (inMem && now - inMem.at < this.opts.cacheTtlMs) {\n\t\t\treturn inMem.isMember;\n\t\t}\n\n\t\t// 2. Persistent cache.\n\t\tconst persistent = this.kv.get<PersistentCache>(KEY_MEMBERSHIP_CACHE) ?? {};\n\t\tconst persistentEntry = persistent[username];\n\t\tif (persistentEntry && now - persistentEntry.at < this.opts.persistentCacheTtlMs) {\n\t\t\tthis.memCache.set(username, persistentEntry);\n\t\t\treturn persistentEntry.isMember;\n\t\t}\n\n\t\t// 3. Hit upstream GitHub API via the injected fetcher.\n\t\tconst token = await this.opts.tokenFetcher(\"github\");\n\t\tif (!token) return false;\n\n\t\ttry {\n\t\t\tconst result = await this.opts.orgFetcher(token, this.opts.org);\n\t\t\tconst decision = this.resolveDecision(username, result);\n\t\t\tif (typeof decision === \"boolean\") {\n\t\t\t\tthis.updateCache(username, decision);\n\t\t\t\treturn decision;\n\t\t\t}\n\t\t\t// Indeterminate — fail-open.\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// Fail-open on transient network errors.\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/** Server-confirmed inOrg status (set by device claim flow). */\n\tsetServerInOrg(username: string, inOrg: boolean): void {\n\t\tconst key = username.toLowerCase();\n\t\tthis.serverInOrgMem.set(key, inOrg);\n\t\tconst persisted = this.kv.get<Record<string, boolean>>(KEY_SERVER_IN_ORG) ?? {};\n\t\tpersisted[key] = inOrg;\n\t\tvoid this.kv.update(KEY_SERVER_IN_ORG, persisted);\n\t\tthis.notifyListeners();\n\t}\n\n\t/** Inspect server-confirmed inOrg for a username; returns undefined when unknown. */\n\tgetServerInOrg(username: string): boolean | undefined {\n\t\treturn this.serverInOrgMem.get(username.toLowerCase());\n\t}\n\n\tprivate resolveDecision(\n\t\t_username: string,\n\t\tmembership: CoreOrgMembershipResult\n\t): boolean | undefined {\n\t\tif (membership.status === \"active\" || membership.status === \"pending\") return true;\n\t\tif (membership.status === \"not_member\") return false;\n\t\treturn undefined;\n\t}\n\n\tprivate updateCache(username: string, isMember: boolean): void {\n\t\tconst at = this.opts.now();\n\t\tthis.memCache.set(username, { isMember, at });\n\t\tconst persistent = this.kv.get<PersistentCache>(KEY_MEMBERSHIP_CACHE) ?? {};\n\t\tpersistent[username] = { isMember, at };\n\t\tvoid this.kv.update(KEY_MEMBERSHIP_CACHE, persistent);\n\t}\n\n\tprivate notifyListeners(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t// listener errors must not propagate; AccessControl is best-effort.\n\t\t\t}\n\t\t}\n\t}\n}\n","export interface ServiceMeLogger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\nexport const noopLogger: ServiceMeLogger = {\n\tdebug() {},\n\tinfo() {},\n\twarn() {},\n\terror() {},\n};\n\nfunction formatArgs(args: unknown[]): string {\n\treturn args\n\t\t.map((arg) => {\n\t\t\tif (typeof arg === \"string\") {\n\t\t\t\treturn arg;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(arg);\n\t\t\t} catch {\n\t\t\t\treturn String(arg);\n\t\t\t}\n\t\t})\n\t\t.join(\" \");\n}\n\nexport function createConsoleLogger(prefix = \"serviceme\"): ServiceMeLogger {\n\treturn {\n\t\tdebug(message: string, ...args: unknown[]) {\n\t\t\tprocess.stderr.write(`[${prefix}] DEBUG ${message} ${formatArgs(args)}\\n`);\n\t\t},\n\t\tinfo(message: string, ...args: unknown[]) {\n\t\t\tprocess.stderr.write(`[${prefix}] INFO ${message} ${formatArgs(args)}\\n`);\n\t\t},\n\t\twarn(message: string, ...args: unknown[]) {\n\t\t\tprocess.stderr.write(`[${prefix}] WARN ${message} ${formatArgs(args)}\\n`);\n\t\t},\n\t\terror(message: string, ...args: unknown[]) {\n\t\t\tprocess.stderr.write(`[${prefix}] ERROR ${message} ${formatArgs(args)}\\n`);\n\t\t},\n\t};\n}\n","/**\n * AuthStateManager — In-memory mirror of the persisted auth state.\n *\n * Holds the multi-account map (provider + accountId keyed) plus the\n * \"active\" provider/account pair. Emits change events via Node's\n * built-in `events.EventEmitter` so listeners stay decoupled.\n *\n * Important: this class does NOT touch `vscode.SecretStorage` or any\n * file — it only keeps the metadata (`AuthAccountMeta`) and the\n * `activeProvider` selection. Token bytes are looked up via the\n * `KeychainAuthTokenStore` on demand. This separation is what lets\n * `AuthCore` run identically in CLI + Extension.\n *\n * Refs:\n * - 4.功能规划.md §2.1 — `AuthStateManager.ts events.EventEmitter, NO VSCode dep`\n * - ADL-004 — token bytes never enter Core state\n */\n\nimport { EventEmitter } from \"node:events\";\n\nimport type { AuthAccountMeta, AuthProvider, AuthStatus } from \"@serviceme/devtools-protocol\";\n\nexport interface AuthStateManagerEvents {\n\tchange: () => void;\n}\n\nexport interface AuthStateManagerOptions {\n\t/** EventEmitter listener cap; defaults to 32 (Node default) but raised for hot test paths. */\n\tmaxListeners?: number;\n}\n\nexport class AuthStateManager {\n\tprivate readonly emitter = new EventEmitter();\n\tprivate accounts: AuthAccountMeta[] = [];\n\tprivate activeProvider: AuthProvider | null = null;\n\tprivate activeAccountId: string | null = null;\n\tprivate lastError: string | null = null;\n\n\tconstructor(opts: AuthStateManagerOptions = {}) {\n\t\tif (opts.maxListeners !== undefined) {\n\t\t\tthis.emitter.setMaxListeners(opts.maxListeners);\n\t\t}\n\t}\n\n\t/** Subscribe to state-change events. Returns a disposer. */\n\tonDidChange(listener: () => void): () => void {\n\t\tthis.emitter.on(\"change\", listener);\n\t\treturn () => this.emitter.off(\"change\", listener);\n\t}\n\n\t/** Snapshot of all known accounts (immutable copy). */\n\tlistAccounts(): AuthAccountMeta[] {\n\t\treturn [...this.accounts];\n\t}\n\n\t/** Find an account by `(provider, accountId)` tuple; returns `null` when absent. */\n\tfindAccount(provider: AuthProvider, accountId: string): AuthAccountMeta | null {\n\t\treturn this.accounts.find((a) => a.provider === provider && a.id === accountId) ?? null;\n\t}\n\n\t/** First account for the requested provider — used for \"switch to GitHub\" UX. */\n\tfindFirstForProvider(provider: AuthProvider): AuthAccountMeta | null {\n\t\treturn this.accounts.find((a) => a.provider === provider) ?? null;\n\t}\n\n\t/** Insert or update an account entry. New accounts land at the head of the list. */\n\tupsertAccount(meta: AuthAccountMeta): void {\n\t\tconst idx = this.accounts.findIndex((a) => a.provider === meta.provider && a.id === meta.id);\n\t\tif (idx >= 0) {\n\t\t\tthis.accounts[idx] = meta;\n\t\t} else {\n\t\t\tthis.accounts.unshift(meta);\n\t\t}\n\t\tthis.fire();\n\t}\n\n\t/** Remove an account entry. Returns `true` when an entry was removed. */\n\tremoveAccount(provider: AuthProvider, accountId: string): boolean {\n\t\tconst before = this.accounts.length;\n\t\tthis.accounts = this.accounts.filter((a) => !(a.provider === provider && a.id === accountId));\n\t\tconst removed = this.accounts.length !== before;\n\t\t// If we removed the active provider's account, clear the active marker.\n\t\tif (removed && this.activeProvider === provider && this.activeAccountId === accountId) {\n\t\t\tconst stillHasSameProvider = this.accounts.some((a) => a.provider === provider);\n\t\t\tif (!stillHasSameProvider) {\n\t\t\t\tthis.activeProvider = null;\n\t\t\t\tthis.activeAccountId = null;\n\t\t\t} else {\n\t\t\t\tconst next = this.accounts.find((a) => a.provider === provider);\n\t\t\t\tif (next) {\n\t\t\t\t\tthis.activeAccountId = next.id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (removed) this.fire();\n\t\treturn removed;\n\t}\n\n\t/** Set the active provider. When `accountId` is omitted, picks the first account for that provider. */\n\tsetActive(provider: AuthProvider, accountId?: string): boolean {\n\t\tconst match =\n\t\t\taccountId !== undefined\n\t\t\t\t? this.accounts.find((a) => a.provider === provider && a.id === accountId)\n\t\t\t\t: this.accounts.find((a) => a.provider === provider);\n\t\tif (!match) return false;\n\t\tthis.activeProvider = provider;\n\t\tthis.activeAccountId = match.id;\n\t\tthis.fire();\n\t\treturn true;\n\t}\n\n\t/** Currently active provider — `null` when no session is active. */\n\tgetActiveProvider(): AuthProvider | null {\n\t\treturn this.activeProvider;\n\t}\n\n\t/** Currently active account metadata — `null` when none. */\n\tgetActiveAccount(): AuthAccountMeta | null {\n\t\tif (!this.activeProvider || !this.activeAccountId) return null;\n\t\treturn (\n\t\t\tthis.accounts.find(\n\t\t\t\t(a) => a.provider === this.activeProvider && a.id === this.activeAccountId\n\t\t\t) ?? null\n\t\t);\n\t}\n\n\t/** True when at least one provider has an account entry. */\n\thasAnySession(): boolean {\n\t\treturn this.accounts.length > 0 && this.activeProvider !== null;\n\t}\n\n\t/** Snapshot of the state for `auth.status` and bridge serialization. */\n\tgetStatus(): AuthStatus {\n\t\tconst grouped: Partial<Record<AuthProvider, AuthAccountMeta>> = {};\n\t\tfor (const account of this.accounts) {\n\t\t\tgrouped[account.provider] = account;\n\t\t}\n\t\treturn {\n\t\t\tactiveProvider: this.activeProvider,\n\t\t\taccounts: grouped,\n\t\t\thasAnySession: this.hasAnySession(),\n\t\t\tlastError: this.lastError ?? undefined,\n\t\t};\n\t}\n\n\t/** Record a non-fatal error from the last login/refresh attempt. */\n\trecordError(message: string): void {\n\t\tthis.lastError = message;\n\t\tthis.fire();\n\t}\n\n\t/** Clear the recorded error (e.g. after a successful login). */\n\tclearError(): void {\n\t\tif (this.lastError === null) return;\n\t\tthis.lastError = null;\n\t\tthis.fire();\n\t}\n\n\t/** Drop every account — used by `auth.logout` with no provider. */\n\tclearAll(): void {\n\t\tthis.accounts = [];\n\t\tthis.activeProvider = null;\n\t\tthis.activeAccountId = null;\n\t\tthis.lastError = null;\n\t\tthis.fire();\n\t}\n\n\tprivate fire(): void {\n\t\tthis.emitter.emit(\"change\");\n\t}\n}\n","/**\n * ProviderRegistry — Maps `AuthProvider` ids to `IAuthProvider` instances.\n *\n * `AuthCore` looks up providers by `AuthProvider` enum (string union\n * per the protocol). The registry is mutable so that callers can\n * replace a provider (e.g. swap a real keyring-backed implementation\n * in tests), but providers must be registered before `AuthCore.login()`\n * is called.\n *\n * Refs:\n * - 4.功能规划.md §2.1 — `ProviderRegistry.ts`\n */\n\nimport type { AuthProvider } from \"@serviceme/devtools-protocol\";\n\nimport type { IAuthProvider } from \"./providers/IAuthProvider\";\n\nexport class ProviderRegistry {\n\tprivate readonly providers = new Map<AuthProvider, IAuthProvider>();\n\n\t/** Register or replace a provider implementation. */\n\tregister(provider: IAuthProvider): void {\n\t\tthis.providers.set(provider.providerId, provider);\n\t}\n\n\t/** Look up a registered provider by id; throws when missing. */\n\tget(providerId: AuthProvider): IAuthProvider {\n\t\tconst p = this.providers.get(providerId);\n\t\tif (!p) {\n\t\t\tthrow new Error(`Auth provider not registered: ${providerId}`);\n\t\t}\n\t\treturn p;\n\t}\n\n\t/** Non-throwing lookup; returns `undefined` when the provider is unknown. */\n\ttryGet(providerId: AuthProvider): IAuthProvider | undefined {\n\t\treturn this.providers.get(providerId);\n\t}\n\n\t/** Return all registered provider ids — used by `auth.status` and bridge capability hints. */\n\tlist(): AuthProvider[] {\n\t\treturn [...this.providers.keys()];\n\t}\n\n\t/** True when a provider has been registered for this id. */\n\thas(providerId: AuthProvider): boolean {\n\t\treturn this.providers.has(providerId);\n\t}\n}\n","/**\n * AuthCore — Main entry for the auth domain.\n *\n * Owns the `ProviderRegistry` + `AuthStateManager` + `KeychainAuthTokenStore`.\n * Provides a small, side-effectful surface that CLI / Extension / Bridge\n * handlers can call:\n *\n * - `login(provider)` → drives Device Flow, persists token via store.\n * - `logout(provider?)` → clears the active session (and token bytes).\n * - `status()` → snapshot for `auth.status`.\n * - `whoami()` → minimal identity for `auth.whoami`.\n * - `switchProvider(p)` → flip the active provider (multi-account).\n *\n * Core NEVER holds token bytes past the `KeychainAuthTokenStore.set()`\n * boundary — callers pass the token to the store immediately, then\n * drop the local reference. Per ADL-004 the token bytes only live in\n * (a) SecretStorage / (b) keyring / (c) HTTP Authorization header.\n *\n * Refs:\n * - 4.功能规划.md §2.1 — `AuthCore.ts 主入口`\n * - ADL-002 — Device Flow OAuth\n * - ADL-004 — Auth token storage\n */\n\nimport type {\n\tAuthAccountMeta,\n\tAuthLoginResult,\n\tAuthProvider,\n\tAuthStatus,\n\tAuthSwitchResult,\n\tAuthWhoamiResult,\n} from \"@serviceme/devtools-protocol\";\nimport { noopLogger, type ServiceMeLogger } from \"../logger\";\nimport type { AccessCheckResult, AccessControl } from \"./AccessControl\";\nimport { AuthStateManager } from \"./AuthStateManager\";\nimport type { KeychainAuthTokenStore } from \"./KeychainAuthTokenStore\";\nimport { ProviderRegistry } from \"./ProviderRegistry\";\nimport type { IAuthProvider, IAuthProviderSession } from \"./providers/IAuthProvider\";\n\nexport interface AuthCoreOptions {\n\tproviders: IAuthProvider[];\n\ttokenStore: KeychainAuthTokenStore;\n\taccessControl?: AccessControl;\n\tstateManager?: AuthStateManager;\n\t/** Diagnostic logger for login/logout lifecycle events (never receives token bytes). */\n\tlogger?: ServiceMeLogger;\n}\n\n/**\n * Callback invoked once the user finishes the device-flow handshake but\n * BEFORE the token is written to the keychain. Lets the caller display\n * the `userCode` + `verificationUrl` to the user (Phase 5.3 CLI prints to\n * stdout; Phase 5.5 Extension pops a webview notification).\n */\nexport type DeviceFlowUiCallback = (result: AuthLoginResult) => void | Promise<void>;\n\n/**\n * Optional cancellation handle — when `shouldContinue()` returns false,\n * the polling loop exits with a clear error so callers can render\n * \"Login cancelled\" UX.\n */\nexport type CancellationCheck = () => boolean;\n\nexport class AuthCore {\n\tprivate readonly registry: ProviderRegistry;\n\tprivate readonly state: AuthStateManager;\n\tprivate readonly tokenStore: KeychainAuthTokenStore;\n\tprivate readonly accessControl?: AccessControl;\n\tprivate readonly logger: ServiceMeLogger;\n\n\tconstructor(opts: AuthCoreOptions) {\n\t\tthis.registry = new ProviderRegistry();\n\t\tfor (const provider of opts.providers) {\n\t\t\tthis.registry.register(provider);\n\t\t}\n\t\tthis.state = opts.stateManager ?? new AuthStateManager();\n\t\tthis.tokenStore = opts.tokenStore;\n\t\tthis.accessControl = opts.accessControl;\n\t\tthis.logger = opts.logger ?? noopLogger;\n\t}\n\n\t/** Snapshot of every account, the active provider, and the last error. */\n\tstatus(): AuthStatus {\n\t\treturn this.state.getStatus();\n\t}\n\n\t/** List accounts (immutable copy). */\n\tlistAccounts(): AuthAccountMeta[] {\n\t\treturn this.state.listAccounts();\n\t}\n\n\t/**\n\t * Drive the device-flow login for `provider`.\n\t *\n\t * Sequence:\n\t * 1. Ask the provider for the user code + verification URL.\n\t * 2. Surface the code to the user (via `ui`).\n\t * 3. Poll until the user authorizes (or `shouldContinue` aborts).\n\t * 4. Persist the token via `KeychainAuthTokenStore.set()`.\n\t * 5. Insert the resulting `AuthAccountMeta` into state and mark active.\n\t */\n\tasync login(\n\t\tprovider: AuthProvider,\n\t\tui: DeviceFlowUiCallback,\n\t\tshouldContinue?: CancellationCheck\n\t): Promise<AuthLoginResult> {\n\t\tconst providerImpl = this.registry.get(provider);\n\t\tthis.logger.info(\"[AuthCore] Starting device-flow login\", { provider });\n\t\ttry {\n\t\t\tconst initial = await providerImpl.requestDeviceFlow();\n\t\t\tawait ui(initial);\n\t\t\tif (!initial.deviceCode) {\n\t\t\t\tthis.logger.error(\"[AuthCore] Provider did not return deviceCode\", provider);\n\t\t\t\tthrow new Error(\"Auth provider did not return deviceCode for device flow completion\");\n\t\t\t}\n\t\t\tconst session = await providerImpl.completeDeviceFlow(\n\t\t\t\tinitial.deviceCode,\n\t\t\t\tshouldContinue,\n\t\t\t\tinitial.pollIntervalMs\n\t\t\t);\n\t\t\tconst result = await this.persistSession(providerImpl, session);\n\t\t\tthis.logger.info(\"[AuthCore] Device-flow login completed\", { provider });\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthis.logger.error(\"[AuthCore] Device-flow login failed\", message, {\n\t\t\t\tprovider,\n\t\t\t});\n\t\t\tthis.state.recordError(message);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/**\n\t * Complete the device-flow handshake given a pre-fetched user code.\n\t * Useful when the caller (Phase 5.3 CLI) wants to fetch the code,\n\t * print the URL, and then poll on a subsequent invocation.\n\t */\n\tasync completeLogin(\n\t\tprovider: AuthProvider,\n\t\tdeviceCode: string,\n\t\tshouldContinue?: CancellationCheck\n\t): Promise<AuthLoginResult> {\n\t\tconst providerImpl = this.registry.get(provider);\n\t\ttry {\n\t\t\tconst session = await providerImpl.completeDeviceFlow(deviceCode, shouldContinue);\n\t\t\treturn await this.persistSession(providerImpl, session);\n\t\t} catch (err) {\n\t\t\tthis.state.recordError(err instanceof Error ? err.message : String(err));\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Resolve the provider + token for the active session; returns null when no session is active. */\n\tasync resolveActiveToken(): Promise<{\n\t\tprovider: AuthProvider;\n\t\taccount: AuthAccountMeta;\n\t\ttoken: string;\n\t} | null> {\n\t\tconst provider = this.state.getActiveProvider();\n\t\tif (!provider) return null;\n\t\tconst account = this.state.getActiveAccount();\n\t\tif (!account) return null;\n\t\tconst envelope = await this.tokenStore.get({\n\t\t\tprovider,\n\t\t\taccountId: account.id,\n\t\t});\n\t\tif (!envelope) return null;\n\t\treturn { provider, account, token: envelope.token };\n\t}\n\n\t/**\n\t * Logout: removes the token bytes from the keychain + drops the\n\t * account entry from state. When `provider` is omitted, clears\n\t * every account.\n\t */\n\tasync logout(\n\t\tprovider?: AuthProvider\n\t): Promise<{ provider: AuthProvider | null; success: boolean }> {\n\t\tthis.logger.info(\"[AuthCore] Logout requested\", {\n\t\t\tprovider: provider ?? \"all\",\n\t\t});\n\t\tif (!provider) {\n\t\t\t// Clear every account's token bytes + metadata.\n\t\t\tfor (const account of this.state.listAccounts()) {\n\t\t\t\tawait this.tokenStore.delete({\n\t\t\t\t\tprovider: account.provider,\n\t\t\t\t\taccountId: account.id,\n\t\t\t\t});\n\t\t\t\tthis.state.removeAccount(account.provider, account.id);\n\t\t\t}\n\t\t\tthis.state.clearAll();\n\t\t\treturn { provider: null, success: true };\n\t\t}\n\n\t\tconst accountsForProvider = this.state.listAccounts().filter((a) => a.provider === provider);\n\t\tlet removed = false;\n\t\tfor (const account of accountsForProvider) {\n\t\t\tawait this.tokenStore.delete({ provider, accountId: account.id });\n\t\t\tconst didRemove = this.state.removeAccount(provider, account.id);\n\t\t\tremoved = removed || didRemove;\n\t\t}\n\t\tif (this.state.getActiveProvider() === provider) {\n\t\t\t// Reset active if we just removed the active provider's account.\n\t\t\tconst firstRemaining = this.state.listAccounts()[0];\n\t\t\tif (firstRemaining) {\n\t\t\t\tthis.state.setActive(firstRemaining.provider);\n\t\t\t}\n\t\t}\n\t\treturn { provider, success: removed };\n\t}\n\n\t/** Minimal identity for `auth.whoami`. */\n\tasync whoami(): Promise<AuthWhoamiResult> {\n\t\tconst provider = this.state.getActiveProvider();\n\t\tconst account = this.state.getActiveAccount();\n\t\tif (!provider || !account) {\n\t\t\treturn { provider: null };\n\t\t}\n\t\treturn {\n\t\t\tprovider,\n\t\t\tlogin: account.login,\n\t\t\tname: account.displayName,\n\t\t\tavatarUrl: account.avatarUrl,\n\t\t\temail: account.email,\n\t\t};\n\t}\n\n\t/** Switch the active provider. Returns the resulting active account. */\n\tswitchProvider(provider: AuthProvider, accountId?: string): AuthSwitchResult {\n\t\tconst ok = this.state.setActive(provider, accountId);\n\t\tconst account = this.state.getActiveAccount();\n\t\treturn {\n\t\t\tactiveProvider: ok ? provider : this.state.getActiveProvider(),\n\t\t\taccount,\n\t\t};\n\t}\n\n\t/** Run the access-control check against the active account (optional, requires AccessControl). */\n\tasync checkAccess(): Promise<AccessCheckResult | null> {\n\t\tif (!this.accessControl) return null;\n\t\tconst account = this.state.getActiveAccount();\n\t\treturn this.accessControl.checkAccess(account);\n\t}\n\n\t/** Expose the state manager for test inspection (not for mutation). */\n\tgetStateManager(): AuthStateManager {\n\t\treturn this.state;\n\t}\n\n\t/** Expose the provider registry for test inspection. */\n\tgetProviderRegistry(): ProviderRegistry {\n\t\treturn this.registry;\n\t}\n\n\t/** Expose the access control (or undefined when not configured). */\n\tgetAccessControl(): AccessControl | undefined {\n\t\treturn this.accessControl;\n\t}\n\n\tprivate async persistSession(\n\t\tproviderImpl: IAuthProvider,\n\t\tsession: IAuthProviderSession\n\t): Promise<AuthLoginResult> {\n\t\tconst expiresAt = session.expiresIn ? Date.now() + session.expiresIn * 1000 : null;\n\t\tconst meta = await providerImpl.fetchAccountMeta(session.token);\n\t\tconst accountMeta: AuthAccountMeta = {\n\t\t\tid: meta.id,\n\t\t\tprovider: meta.provider,\n\t\t\tdisplayName: meta.displayName,\n\t\t\tlogin: meta.login,\n\t\t\temail: meta.email,\n\t\t\tavatarUrl: meta.avatarUrl,\n\t\t\texpiresAt: meta.expiresAt ?? expiresAt,\n\t\t};\n\t\tthis.logger.debug(\"[AuthCore] Persisting session\", {\n\t\t\tprovider: meta.provider,\n\t\t\taccountId: meta.id,\n\t\t});\n\n\t\tawait this.tokenStore.set({ provider: meta.provider, accountId: meta.id }, session.token, {\n\t\t\texpiresAt,\n\t\t});\n\t\tthis.state.upsertAccount(accountMeta);\n\t\tthis.state.setActive(meta.provider, meta.id);\n\t\tthis.state.clearError();\n\t\treturn {\n\t\t\tprovider: meta.provider,\n\t\t\tmessage: `Logged in as ${meta.login ?? meta.id}`,\n\t\t};\n\t}\n}\n","/**\n * KeychainAuthTokenStore — abstract adapter for token byte persistence.\n *\n * Per ADL-004 the OAuth token bytes live in one of three places:\n * (a) VSCode `SecretStorage` (Extension process)\n * (b) `@napi-rs/keyring` Entry (CLI process)\n * (c) HTTP request `Authorization` header\n *\n * `AuthCore` MUST NOT call any of these directly. Instead it receives\n * a `KeychainAuthTokenStore` via DI; CLI provides a `@napi-rs/keyring`\n * adapter, Extension provides a `SecretStorage` adapter. This keeps\n * Core free of native-binding concerns and lets the same business\n * logic power both runtimes.\n *\n * Implementations:\n * - CLI: `apps/serviceme-cli/src/.../KeyringTokenStore.ts` (Phase 5.3)\n * - Extension: `apps/extension/src/.../SecretStorageTokenStore.ts` (Phase 5.5)\n *\n * Failure semantics — `get()` returns `null` when no token is stored\n * (cold-start), throws when the underlying keychain is unavailable\n * (rare on Linux without libsecret). Callers should surface the throw\n * as `AUTH_KEYRING_UNAVAILABLE` rather than silently falling back to\n * in-memory storage (per ADL-004 §不变量).\n *\n * Refs:\n * - ADL-004 — CLI 端 Auth Token 存储选型\n * - 4.功能规划.md §2.1 — \"Core MUST NOT directly depend on `@napi-rs/keyring`\"\n */\n\n/** Opaque account identifier (provider + upstream user id). */\nexport interface KeychainAccountKey {\n\tprovider: string;\n\taccountId: string;\n}\n\n/** Non-secret metadata returned alongside a `get()` so callers can audit. */\nexport interface KeychainTokenMetadata {\n\tprovider: string;\n\taccountId: string;\n\texpiresAt?: number | null;\n\tstoredAt?: number;\n}\n\n/**\n * Result envelope — callers receive the token bytes (for immediate use\n * in an HTTP `Authorization` header) plus optional non-secret metadata.\n *\n * IMPORTANT: the `token` field is plain `string` here, not the\n * `SecretToken` brand. The provider -> store -> HTTP-header pipeline\n * runs inside a single trust boundary; crossing that boundary requires\n * `KeychainTokenEnvelope<SecretToken>` and the `auth.tokenRead`\n * capability gate (see ADL-004 §不变量).\n */\nexport interface KeychainTokenEnvelope {\n\ttoken: string;\n\tmetadata: KeychainTokenMetadata;\n}\n\n/**\n * Abstract token-storage adapter. All methods are async because the\n * keyring / SecretStorage backends are async-by-nature.\n *\n * Thread-safety: implementations MUST be safe for concurrent calls;\n * `AuthCore` will multiplex over multiple providers on the same\n * runtime.\n */\nexport interface KeychainAuthTokenStore {\n\t/** Persist token bytes for the given provider + account pair. */\n\tset(key: KeychainAccountKey, token: string, opts?: { expiresAt?: number | null }): Promise<void>;\n\n\t/** Fetch the token bytes; returns `null` when none is stored. */\n\tget(key: KeychainAccountKey): Promise<KeychainTokenEnvelope | null>;\n\n\t/** Remove the token entry. Idempotent — removing a missing entry is not an error. */\n\tdelete(key: KeychainAccountKey): Promise<void>;\n\n\t/**\n\t * List all stored token keys (metadata only — never the token bytes).\n\t * Useful for multi-account enumeration and bridge `auth.status`.\n\t */\n\tlist(): Promise<KeychainAccountKey[]>;\n\n\t/**\n\t * Health probe — returns `false` when the keychain is unreachable\n\t * (e.g. Linux without libsecret). Callers SHOULD probe on first\n\t * use and surface `AUTH_KEYRING_UNAVAILABLE` rather than degrade.\n\t */\n\tisAvailable(): Promise<boolean>;\n}\n\n/**\n * Sentinel error thrown by `KeychainAuthTokenStore.get()` / `.set()`\n * when the underlying keychain is unavailable. Callers map this to\n * `AUTH_KEYRING_UNAVAILABLE` (Phase 5.3 error code).\n */\nexport class KeychainUnavailableError extends Error {\n\tconstructor(message: string, cause?: unknown) {\n\t\t// Use the native ES2022 `Error` two-arg form instead of redeclaring\n\t\t// `cause` as a class field — a field redeclaration shadows the\n\t\t// inherited member and requires an `override` modifier under\n\t\t// `noImplicitOverride` (downstream consumers like the Extension),\n\t\t// which in turn fails THIS package's own build if its `lib` doesn't\n\t\t// also include `cause` on `Error`. Relying on the built-in\n\t\t// constructor option avoids the mismatch entirely (this package's\n\t\t// `tsconfig.json` targets `lib: [\"ES2022\", \"DOM\"]`, so `cause` is\n\t\t// recognized here too).\n\t\tsuper(message, cause !== undefined ? { cause } : undefined);\n\t\tthis.name = \"KeychainUnavailableError\";\n\t}\n}\n\n/**\n * In-memory `KeychainAuthTokenStore` — test/dev fallback. NEVER use\n * in production: tokens live in process memory and disappear on exit.\n * Production wiring is `KeyringTokenStore` (CLI) / `SecretStorageTokenStore`\n * (Extension).\n */\nexport class InMemoryKeychainAuthTokenStore implements KeychainAuthTokenStore {\n\tprivate readonly entries = new Map<\n\t\tstring,\n\t\t{ token: string; expiresAt: number | null; storedAt: number }\n\t>();\n\n\tprivate compositeKey(key: KeychainAccountKey): string {\n\t\treturn `${key.provider}:${key.accountId}`;\n\t}\n\n\tasync set(\n\t\tkey: KeychainAccountKey,\n\t\ttoken: string,\n\t\topts?: { expiresAt?: number | null }\n\t): Promise<void> {\n\t\tthis.entries.set(this.compositeKey(key), {\n\t\t\ttoken,\n\t\t\texpiresAt: opts?.expiresAt ?? null,\n\t\t\tstoredAt: Date.now(),\n\t\t});\n\t}\n\n\tasync get(key: KeychainAccountKey): Promise<KeychainTokenEnvelope | null> {\n\t\tconst entry = this.entries.get(this.compositeKey(key));\n\t\tif (!entry) return null;\n\t\treturn {\n\t\t\ttoken: entry.token,\n\t\t\tmetadata: {\n\t\t\t\tprovider: key.provider,\n\t\t\t\taccountId: key.accountId,\n\t\t\t\texpiresAt: entry.expiresAt,\n\t\t\t\tstoredAt: entry.storedAt,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync delete(key: KeychainAccountKey): Promise<void> {\n\t\tthis.entries.delete(this.compositeKey(key));\n\t}\n\n\tasync list(): Promise<KeychainAccountKey[]> {\n\t\tconst out: KeychainAccountKey[] = [];\n\t\tfor (const composite of this.entries.keys()) {\n\t\t\tconst sepIdx = composite.indexOf(\":\");\n\t\t\tif (sepIdx <= 0) continue;\n\t\t\tout.push({\n\t\t\t\tprovider: composite.slice(0, sepIdx),\n\t\t\t\taccountId: composite.slice(sepIdx + 1),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync isAvailable(): Promise<boolean> {\n\t\treturn true;\n\t}\n}\n","/**\n * AuthCore — Pure local utilities for GitHub local email handling.\n *\n * Copied verbatim from `@serviceme/devtools-shared/src/github-user-email.ts` (15 LOC)\n * because ADL-003 forbids Core from depending on `@serviceme/devtools-shared`. These\n * helpers are pure functions with zero side effects, so the duplication is\n * trivial to keep in sync.\n *\n * Refs:\n * - 4.功能规划.md §2.1 — \"utils/githubUserEmail.ts 纯函数,直接搬\"\n * - ADL-003 — `@serviceme/devtools-shared` boundary decision\n */\n\n/**\n * Returns true when the supplied address is a synthetic GitHub \"local\" email\n * (suffixed with `@github.local`). Real GitHub OAuth clients often return\n * `null` for `email` (user kept it private) and the application substitutes\n * `<login>@github.local` to keep the field non-null.\n */\nexport function isGitHubLocalEmail(email: string | null | undefined): boolean {\n\treturn typeof email === \"string\" && email.trim().toLowerCase().endsWith(\"@github.local\");\n}\n\n/** Build a synthetic `<login>@github.local` address. */\nexport function buildGitHubLocalEmail(login: string): string {\n\treturn `${login}@github.local`;\n}\n\n/**\n * Resolve the user's primary email address — falling back to the synthetic\n * `<login>@github.local` form when the upstream email is missing or blank.\n */\nexport function resolvePrimaryEmail(login: string, email: string | null | undefined): string {\n\tconst normalizedEmail = email?.trim();\n\treturn normalizedEmail || buildGitHubLocalEmail(login);\n}\n","/**\n * GitHubAuthProvider — Device Flow OAuth implementation.\n *\n * Implements the GitHub OAuth Device Flow per the official spec\n * (https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow).\n *\n * Per ADL-002 the device flow is the locked authentication strategy for\n * SERVICEME — no localhost callback server, no PAT. This class is a\n * pure HTTP client (uses native `fetch`, no vscode dependency) that\n * returns the token bytes for the caller's `KeychainAuthTokenStore` to\n * persist immediately.\n *\n * Token bytes NEVER enter logs / errors / debug output. The provider\n * exposes only the user-visible code + verification URL during the\n * device-flow handshake.\n *\n * Refs:\n * - ADL-002 — Device Flow OAuth (locked)\n * - 4.功能规划.md §2.1 — `providers/GitHubAuthProvider.ts`\n */\n\nimport type { AuthAccountMeta, AuthLoginResult, AuthProvider } from \"@serviceme/devtools-protocol\";\nimport { noopLogger, type ServiceMeLogger } from \"../../logger\";\nimport { buildGitHubLocalEmail } from \"../utils/githubUserEmail\";\nimport type { IAuthProvider, IAuthProviderSession } from \"./IAuthProvider\";\n\nconst DEFAULT_DEVICE_CODE_URL = \"https://github.com/login/device/code\";\nconst DEFAULT_TOKEN_URL = \"https://github.com/login/oauth/access_token\";\nconst DEFAULT_USER_URL = \"https://api.github.com/user\";\nconst DEFAULT_SCOPE = \"read:user user:email\";\n\n/** Attempts for the one-shot device-code request before surfacing a network error. */\nconst DEVICE_CODE_MAX_ATTEMPTS = 3;\nconst DEFAULT_DEVICE_CODE_RETRY_BASE_DELAY_MS = 500;\n\n/**\n * `fetch` (both browser and Node's undici) rejects with a `TypeError`\n * (e.g. \"fetch failed\") when the underlying connection never completes —\n * DNS failure, TLS handshake reset, ECONNRESET, etc. These are transient\n * network hiccups, distinct from a well-formed non-2xx HTTP response, and\n * should be retried rather than immediately failing the whole login.\n */\nfunction isTransientNetworkError(error: unknown): boolean {\n\treturn error instanceof TypeError;\n}\n\n/** Tunable provider config — exposed for tests + forks. */\nexport interface GitHubAuthProviderConfig {\n\tclientId: string;\n\tdeviceCodeUrl?: string;\n\ttokenUrl?: string;\n\tuserUrl?: string;\n\tscope?: string;\n\t/** Polling interval (ms) floor. The device-flow response's `interval` wins when larger. */\n\tminPollIntervalMs?: number;\n\t/**\n\t * Maximum poll interval after back-off. Must stay generous — GitHub's\n\t * `slow_down` response requires adding a fixed step to the interval each\n\t * time it occurs (see `completeDeviceFlow`), and capping this too low\n\t * prevents the interval from ever satisfying GitHub's actual requirement,\n\t * causing a permanent `slow_down` loop that never clears even after the\n\t * user authorizes.\n\t */\n\tmaxPollIntervalMs?: number;\n\t/** Fetch override (for tests + DI). */\n\tfetchImpl?: typeof fetch;\n\t/** Poll-delay override (for tests + DI). Defaults to a real timer-based sleep. */\n\tsleepImpl?: (ms: number) => Promise<void>;\n\t/** Maximum wall-clock time to wait for the user before giving up (ms). Defaults to `expires_in * 1000`. */\n\tmaxWaitMs?: number;\n\t/** Base delay (ms) before retrying the device-code request after a transient network error. */\n\tdeviceCodeRetryBaseDelayMs?: number;\n\t/**\n\t * Diagnostic logger — never receives token bytes or the raw `device_code`,\n\t * only user-facing codes, HTTP statuses, and poll-loop timing so callers\n\t * can troubleshoot a stuck / slow device-flow login.\n\t */\n\tlogger?: ServiceMeLogger;\n}\n\ninterface DeviceCodeResponse {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval: number;\n}\n\ninterface TokenPollResponse {\n\taccess_token?: string;\n\trefresh_token?: string;\n\texpires_in?: number;\n\ttoken_type?: string;\n\tscope?: string;\n\terror?: string;\n\terror_description?: string;\n\terror_uri?: string;\n}\n\ninterface GitHubUserResponse {\n\tid: number;\n\tlogin: string;\n\tname?: string | null;\n\temail?: string | null;\n\tavatar_url?: string | null;\n}\n\nexport class GitHubAuthProvider implements IAuthProvider {\n\treadonly providerId: AuthProvider = \"github\";\n\tprivate readonly cfg: Required<\n\t\tOmit<GitHubAuthProviderConfig, \"maxWaitMs\" | \"fetchImpl\" | \"logger\" | \"sleepImpl\">\n\t> & {\n\t\tmaxWaitMs?: number;\n\t\tfetchImpl: typeof fetch;\n\t};\n\tprivate readonly logger: ServiceMeLogger;\n\tprivate readonly sleepImpl: (ms: number) => Promise<void>;\n\n\tconstructor(config: GitHubAuthProviderConfig) {\n\t\tif (!config.clientId || config.clientId.length === 0) {\n\t\t\tthrow new Error(\"GitHubAuthProvider requires a non-empty `clientId`\");\n\t\t}\n\t\tthis.cfg = {\n\t\t\tclientId: config.clientId,\n\t\t\tdeviceCodeUrl: config.deviceCodeUrl ?? DEFAULT_DEVICE_CODE_URL,\n\t\t\ttokenUrl: config.tokenUrl ?? DEFAULT_TOKEN_URL,\n\t\t\tuserUrl: config.userUrl ?? DEFAULT_USER_URL,\n\t\t\tscope: config.scope ?? DEFAULT_SCOPE,\n\t\t\tminPollIntervalMs: config.minPollIntervalMs ?? 1000,\n\t\t\tmaxPollIntervalMs: config.maxPollIntervalMs ?? 60000,\n\t\t\tmaxWaitMs: config.maxWaitMs,\n\t\t\tfetchImpl: config.fetchImpl ?? fetch,\n\t\t\tdeviceCodeRetryBaseDelayMs:\n\t\t\t\tconfig.deviceCodeRetryBaseDelayMs ?? DEFAULT_DEVICE_CODE_RETRY_BASE_DELAY_MS,\n\t\t};\n\t\tthis.logger = config.logger ?? noopLogger;\n\t\tthis.sleepImpl = config.sleepImpl ?? sleep;\n\t}\n\n\tasync requestDeviceFlow(opts?: { scope?: string }): Promise<AuthLoginResult> {\n\t\tconst body = JSON.stringify({\n\t\t\tclient_id: this.cfg.clientId,\n\t\t\tscope: opts?.scope ?? this.cfg.scope,\n\t\t});\n\n\t\tlet lastNetworkError: unknown;\n\t\tfor (let attempt = 1; attempt <= DEVICE_CODE_MAX_ATTEMPTS; attempt++) {\n\t\t\tthis.logger.debug(\"[GitHubAuthProvider] Requesting device code\", {\n\t\t\t\tattempt,\n\t\t\t\tmaxAttempts: DEVICE_CODE_MAX_ATTEMPTS,\n\t\t\t});\n\t\t\tlet resp: Response;\n\t\t\ttry {\n\t\t\t\tresp = await this.cfg.fetchImpl(this.cfg.deviceCodeUrl, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t\t\t},\n\t\t\t\t\tbody,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (!isTransientNetworkError(error) || attempt === DEVICE_CODE_MAX_ATTEMPTS) {\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[GitHubAuthProvider] Device-code request failed (non-retryable)\",\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t{ attempt }\n\t\t\t\t\t);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tconst delayMs = this.cfg.deviceCodeRetryBaseDelayMs * 2 ** (attempt - 1);\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\"[GitHubAuthProvider] Transient network error requesting device code, retrying\",\n\t\t\t\t\t{\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\tlastNetworkError = error;\n\t\t\t\tawait this.sleepImpl(delayMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!resp.ok) {\n\t\t\t\tthis.logger.error(\n\t\t\t\t\t\"[GitHubAuthProvider] Device-code request rejected by GitHub\",\n\t\t\t\t\t`HTTP ${resp.status}`\n\t\t\t\t);\n\t\t\t\tthrow new Error(`GitHub device-code request failed: HTTP ${resp.status}`);\n\t\t\t}\n\t\t\tconst data = (await resp.json()) as DeviceCodeResponse;\n\t\t\tif (!data.device_code || !data.user_code || !data.verification_uri) {\n\t\t\t\tthis.logger.error(\n\t\t\t\t\t\"[GitHubAuthProvider] Device-code response missing required fields\",\n\t\t\t\t\tJSON.stringify(Object.keys(data))\n\t\t\t\t);\n\t\t\t\tthrow new Error(\"GitHub device-code response missing required fields\");\n\t\t\t}\n\t\t\tthis.logger.info(\"[GitHubAuthProvider] Device code obtained\", {\n\t\t\t\tuserCode: data.user_code,\n\t\t\t\tverificationUri: data.verification_uri,\n\t\t\t\texpiresInSec: data.expires_in,\n\t\t\t\tpollIntervalSec: data.interval,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tprovider: this.providerId,\n\t\t\t\tdeviceCode: data.device_code,\n\t\t\t\tuserCode: data.user_code,\n\t\t\t\tverificationUrl: data.verification_uri,\n\t\t\t\texpiresAt: Date.now() + data.expires_in * 1000,\n\t\t\t\tpollIntervalMs: data.interval * 1000,\n\t\t\t\tmessage: `Open ${data.verification_uri} and enter ${data.user_code}`,\n\t\t\t};\n\t\t}\n\t\t// Unreachable in practice — the loop always returns or throws — but keeps\n\t\t// the type checker happy and surfaces the last transient error if hit.\n\t\tthrow lastNetworkError ?? new Error(\"GitHub device-code request failed\");\n\t}\n\n\tasync completeDeviceFlow(\n\t\tdeviceCode: string,\n\t\tshouldContinue?: () => boolean,\n\t\tinitialPollIntervalMs?: number\n\t): Promise<IAuthProviderSession> {\n\t\tconst start = Date.now();\n\t\t// Honor GitHub's declared `interval` (from the matching `requestDeviceFlow()`\n\t\t// response) as the starting rate — polling faster than this can put the\n\t\t// device code into a `slow_down` state that never clears (see class docs).\n\t\tlet pollIntervalMs = Math.max(this.cfg.minPollIntervalMs, initialPollIntervalMs ?? 0);\n\t\tlet consecutiveSlowDown = 0;\n\t\tlet pollCount = 0;\n\t\tthis.logger.info(\"[GitHubAuthProvider] Starting device-flow polling\", {\n\t\t\tinitialPollIntervalMs: pollIntervalMs,\n\t\t\tmaxWaitMs: this.cfg.maxWaitMs,\n\t\t});\n\n\t\twhile (true) {\n\t\t\tif (shouldContinue && !shouldContinue()) {\n\t\t\t\tthis.logger.info(\"[GitHubAuthProvider] Device flow cancelled by caller\", {\n\t\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\t\tpollCount,\n\t\t\t\t});\n\t\t\t\tthrow new Error(\"GitHub device flow cancelled by caller\");\n\t\t\t}\n\t\t\tconst elapsed = Date.now() - start;\n\t\t\tif (this.cfg.maxWaitMs !== undefined && elapsed > this.cfg.maxWaitMs) {\n\t\t\t\tthis.logger.warn(\"[GitHubAuthProvider] Device flow exceeded max wait time\", {\n\t\t\t\t\telapsedMs: elapsed,\n\t\t\t\t\tmaxWaitMs: this.cfg.maxWaitMs,\n\t\t\t\t\tpollCount,\n\t\t\t\t});\n\t\t\t\tthrow new Error(\"GitHub device flow exceeded max wait time\");\n\t\t\t}\n\t\t\tawait this.sleepImpl(pollIntervalMs);\n\t\t\tif (shouldContinue && !shouldContinue()) {\n\t\t\t\tthis.logger.info(\"[GitHubAuthProvider] Device flow cancelled by caller\", {\n\t\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\t\tpollCount,\n\t\t\t\t});\n\t\t\t\tthrow new Error(\"GitHub device flow cancelled by caller\");\n\t\t\t}\n\n\t\t\tpollCount++;\n\t\t\tthis.logger.debug(\"[GitHubAuthProvider] Polling for authorization\", {\n\t\t\t\tpollCount,\n\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\tpollIntervalMs,\n\t\t\t});\n\t\t\tlet resp: Response;\n\t\t\ttry {\n\t\t\t\tresp = await this.cfg.fetchImpl(this.cfg.tokenUrl, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tclient_id: this.cfg.clientId,\n\t\t\t\t\t\tdevice_code: deviceCode,\n\t\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (!isTransientNetworkError(error)) {\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[GitHubAuthProvider] Non-retryable error while polling token endpoint\",\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t{ pollCount }\n\t\t\t\t\t);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\t// Transient network failure (DNS/TLS/reset) — back off and retry\n\t\t\t\t// polling until the user acts, same as a non-2xx HTTP response.\n\t\t\t\tconst nextPollIntervalMs = Math.min(\n\t\t\t\t\tMath.round(pollIntervalMs * 1.5),\n\t\t\t\t\tthis.cfg.maxPollIntervalMs\n\t\t\t\t);\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\"[GitHubAuthProvider] Transient network error while polling, backing off\",\n\t\t\t\t\t{\n\t\t\t\t\t\tpollCount,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tpreviousPollIntervalMs: pollIntervalMs,\n\t\t\t\t\t\tnextPollIntervalMs,\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\tpollIntervalMs = nextPollIntervalMs;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!resp.ok) {\n\t\t\t\t// Transient HTTP failure — back off and retry until the user acts.\n\t\t\t\tconst nextPollIntervalMs = Math.min(\n\t\t\t\t\tMath.round(pollIntervalMs * 1.5),\n\t\t\t\t\tthis.cfg.maxPollIntervalMs\n\t\t\t\t);\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\"[GitHubAuthProvider] Token endpoint returned non-OK status, backing off\",\n\t\t\t\t\t{\n\t\t\t\t\t\tpollCount,\n\t\t\t\t\t\tstatus: resp.status,\n\t\t\t\t\t\tpreviousPollIntervalMs: pollIntervalMs,\n\t\t\t\t\t\tnextPollIntervalMs,\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\tpollIntervalMs = nextPollIntervalMs;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst data = (await resp.json()) as TokenPollResponse;\n\t\t\tif (data.access_token) {\n\t\t\t\tthis.logger.info(\"[GitHubAuthProvider] Authorization granted, fetching user profile\", {\n\t\t\t\t\tpollCount,\n\t\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\t});\n\t\t\t\tconst rawUser = await this.fetchGitHubUser(data.access_token);\n\t\t\t\tconst email = await this.resolveEmail(data.access_token, rawUser);\n\t\t\t\tthis.logger.info(\"[GitHubAuthProvider] Device-flow login completed\", {\n\t\t\t\t\tpollCount,\n\t\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\t\tlogin: rawUser.login,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\ttoken: data.access_token,\n\t\t\t\t\trefreshToken: data.refresh_token,\n\t\t\t\t\texpiresIn: data.expires_in,\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: String(rawUser.id),\n\t\t\t\t\t\tlogin: rawUser.login,\n\t\t\t\t\t\tname: rawUser.name ?? undefined,\n\t\t\t\t\t\temail: email ?? null,\n\t\t\t\t\t\tavatarUrl: rawUser.avatar_url ?? undefined,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (data.error === \"authorization_pending\") {\n\t\t\t\t// User hasn't acted yet — keep polling without back-off inflation.\n\t\t\t\tthis.logger.debug(\"[GitHubAuthProvider] Authorization still pending\", {\n\t\t\t\t\tpollCount,\n\t\t\t\t\telapsedMs: Date.now() - start,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (data.error === \"slow_down\") {\n\t\t\t\tconsecutiveSlowDown++;\n\t\t\t\t// Per the OAuth Device Flow spec: on `slow_down`, add a fixed 5\n\t\t\t\t// seconds to the polling interval (not a multiplicative back-off).\n\t\t\t\t// Repeatedly under-shooting this requirement is what causes a\n\t\t\t\t// device code to get stuck returning `slow_down` forever.\n\t\t\t\tconst nextPollIntervalMs = Math.min(pollIntervalMs + 5000, this.cfg.maxPollIntervalMs);\n\t\t\t\tthis.logger.warn(\"[GitHubAuthProvider] GitHub requested slower polling (slow_down)\", {\n\t\t\t\t\tpollCount,\n\t\t\t\t\tconsecutiveSlowDown,\n\t\t\t\t\tpreviousPollIntervalMs: pollIntervalMs,\n\t\t\t\t\tnextPollIntervalMs,\n\t\t\t\t});\n\t\t\t\tpollIntervalMs = nextPollIntervalMs;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (data.error === \"access_denied\") {\n\t\t\t\tthis.logger.warn(\"[GitHubAuthProvider] User denied authorization\", {\n\t\t\t\t\tpollCount,\n\t\t\t\t});\n\t\t\t\tthrow new Error(\"User denied authorization\");\n\t\t\t}\n\t\t\tif (data.error === \"expired_token\") {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\"[GitHubAuthProvider] Device code expired before authorization completed\",\n\t\t\t\t\t{ pollCount, elapsedMs: Date.now() - start }\n\t\t\t\t);\n\t\t\t\tthrow new Error(\"GitHub device code expired — restart the flow\");\n\t\t\t}\n\t\t\tthis.logger.error(\n\t\t\t\t\"[GitHubAuthProvider] Unexpected device-flow error from token endpoint\",\n\t\t\t\tdata.error ?? \"unknown\",\n\t\t\t\t{ pollCount }\n\t\t\t);\n\t\t\tthrow new Error(`GitHub device flow error: ${data.error ?? \"unknown\"}`);\n\t\t}\n\t}\n\n\tasync refreshAccessToken(refreshToken: string): Promise<IAuthProviderSession> {\n\t\tif (!refreshToken) {\n\t\t\tthrow new Error(\"refreshAccessToken requires a non-empty refresh token\");\n\t\t}\n\t\tconst resp = await this.cfg.fetchImpl(this.cfg.tokenUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tclient_id: this.cfg.clientId,\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t}),\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`GitHub refresh failed: HTTP ${resp.status}`);\n\t\t}\n\t\tconst data = (await resp.json()) as TokenPollResponse;\n\t\tif (!data.access_token) {\n\t\t\tthrow new Error(`GitHub refresh failed: ${data.error ?? \"no_access_token\"}`);\n\t\t}\n\t\tconst rawUser = await this.fetchGitHubUser(data.access_token);\n\t\tconst email = await this.resolveEmail(data.access_token, rawUser);\n\t\treturn {\n\t\t\ttoken: data.access_token,\n\t\t\trefreshToken: data.refresh_token ?? refreshToken,\n\t\t\texpiresIn: data.expires_in,\n\t\t\tuser: {\n\t\t\t\tid: String(rawUser.id),\n\t\t\t\tlogin: rawUser.login,\n\t\t\t\tname: rawUser.name ?? undefined,\n\t\t\t\temail: email ?? null,\n\t\t\t\tavatarUrl: rawUser.avatar_url ?? undefined,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync validateToken(token: string): Promise<boolean> {\n\t\ttry {\n\t\t\tconst resp = await this.cfg.fetchImpl(this.cfg.userUrl, {\n\t\t\t\theaders: {\n\t\t\t\t\tAccept: \"application/vnd.github+json\",\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (resp.status === 401) return false;\n\t\t\tif (!resp.ok) {\n\t\t\t\tthrow new Error(`GitHub /user returned HTTP ${resp.status}`);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\t// Network / parse errors are surfaced; only 401 means invalid.\n\t\t\tif (err instanceof Error && err.message.includes(\"401\")) return false;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync fetchAccountMeta(token: string): Promise<AuthAccountMeta> {\n\t\tconst user = await this.fetchGitHubUser(token);\n\t\tconst email = await this.resolveEmail(token, user);\n\t\treturn {\n\t\t\tid: String(user.id),\n\t\t\tprovider: this.providerId,\n\t\t\tdisplayName: user.name ?? user.login,\n\t\t\tlogin: user.login,\n\t\t\temail: email ?? buildGitHubLocalEmail(user.login),\n\t\t\tavatarUrl: user.avatar_url ?? undefined,\n\t\t\texpiresAt: null,\n\t\t};\n\t}\n\n\tprivate async fetchGitHubUser(token: string): Promise<GitHubUserResponse> {\n\t\tconst resp = await this.cfg.fetchImpl(this.cfg.userUrl, {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/vnd.github+json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t},\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`GitHub /user failed: HTTP ${resp.status}`);\n\t\t}\n\t\treturn (await resp.json()) as GitHubUserResponse;\n\t}\n\n\t/**\n\t * GitHub's `/user` endpoint returns `null` when the user kept their\n\t * email private. The `/user/emails` endpoint reveals verified emails;\n\t * we pick the primary one, falling back to the synthetic\n\t * `<login>@github.local` form so the account is never email-less.\n\t */\n\tprivate async resolveEmail(token: string, user: GitHubUserResponse): Promise<string | null> {\n\t\tif (user.email) return user.email;\n\t\tconst emailsResp = await this.cfg.fetchImpl(\"https://api.github.com/user/emails\", {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/vnd.github+json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\"User-Agent\": \"serviceme-core\",\n\t\t\t},\n\t\t});\n\t\tif (!emailsResp.ok) {\n\t\t\treturn null;\n\t\t}\n\t\tconst emails = (await emailsResp.json()) as Array<{\n\t\t\temail: string;\n\t\t\tprimary: boolean;\n\t\t\tvisibility: string | null;\n\t\t\tverified: boolean;\n\t\t}>;\n\t\tconst primary = emails.find((e) => e.primary && e.verified);\n\t\treturn primary?.email ?? null;\n\t}\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * MicrosoftAuthProvider — Microsoft Account (MSA) OAuth Device Flow stub.\n *\n * The Extension's existing `MicrosoftAuthProvider` (`apps/extension/src/services/auth/providers/MicrosoftAuthProvider.ts`)\n * delegates to VSCode's built-in `vscode.authentication.getSession()` API\n * — there's no direct Microsoft device-flow endpoint exposed for\n * first-party apps. To keep Core usable from the CLI without VSCode,\n * we expose a minimal stub that throws \"not implemented in Core\" so\n * callers can detect and route back to the Extension adapter.\n *\n * The reason this lives in Core at all (instead of being purely\n * Extension-side) is the cross-runtime registry: `AuthCore` needs to\n * know which providers it MIGHT support, even if only the Extension\n * process can actually fulfil the Microsoft login.\n *\n * Refs:\n * - 4.功能规划.md §2.1 — `providers/MicrosoftAuthProvider.ts 从 extension 整体迁移`\n * - ADL-002 — Device Flow OAuth (locked, GitHub-only)\n */\n\nimport type { AuthAccountMeta, AuthLoginResult, AuthProvider } from \"@serviceme/devtools-protocol\";\n\nimport type { IAuthProvider, IAuthProviderSession } from \"./IAuthProvider\";\n\n/**\n * Error thrown when callers invoke Microsoft auth from a non-Extension\n * runtime (CLI / Bridge). The CLI maps this to `AUTH_PROVIDER_REQUIRES_HOST`\n * so the user is prompted to retry inside VSCode.\n */\nexport class MicrosoftProviderNotHostedError extends Error {\n\tconstructor(\n\t\tmessage = \"Microsoft auth requires the VSCode host; CLI does not yet implement MSA device flow\"\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MicrosoftProviderNotHostedError\";\n\t}\n}\n\nexport class MicrosoftAuthProvider implements IAuthProvider {\n\treadonly providerId: AuthProvider = \"microsoft\";\n\n\tasync requestDeviceFlow(): Promise<AuthLoginResult> {\n\t\tthrow new MicrosoftProviderNotHostedError();\n\t}\n\n\tasync completeDeviceFlow(\n\t\t_deviceCode: string,\n\t\t_shouldContinue?: () => boolean\n\t): Promise<IAuthProviderSession> {\n\t\tthrow new MicrosoftProviderNotHostedError();\n\t}\n\n\tasync refreshAccessToken(_refreshToken: string): Promise<IAuthProviderSession> {\n\t\tthrow new MicrosoftProviderNotHostedError();\n\t}\n\n\tasync validateToken(_token: string): Promise<boolean> {\n\t\tthrow new MicrosoftProviderNotHostedError();\n\t}\n\n\tasync fetchAccountMeta(_token: string): Promise<AuthAccountMeta> {\n\t\tthrow new MicrosoftProviderNotHostedError();\n\t}\n}\n"],"mappings":";AAkEA,IAAM,uBAAuB,KAAK,KAAK;AACvC,IAAM,kCAAkC,KAAK,KAAK,KAAK;AACvD,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB;AAWnB,IAAM,gBAAN,MAAoB;AAAA,EAa1B,YACkB,IACjB,SACC;AAFgB;AAblB,SAAiB,WAAW,oBAAI,IAAwB;AACxD,SAAiB,iBAAiB,oBAAI,IAAqB;AAC3D,SAAiB,YAAY,oBAAI,IAAgB;AAchD,SAAK,OAAO;AAAA,MACX,KAAK,QAAQ;AAAA,MACb,cAAc,QAAQ;AAAA,MACtB,YAAY,QAAQ;AAAA,MACpB,uBAAuB,QAAQ,yBAAyB,CAAC;AAAA,MACzD,YAAY,QAAQ,cAAc;AAAA,MAClC,sBAAsB,QAAQ,wBAAwB;AAAA,MACtD,KAAK,QAAQ,QAAQ,MAAM,KAAK,IAAI;AAAA,IACrC;AAEA,UAAM,uBAAuB,KAAK,GAAG,IAA6B,iBAAiB;AACnF,QAAI,sBAAsB;AACzB,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,oBAAoB,GAAG;AAChE,aAAK,eAAe,IAAI,KAAK,KAAK;AAAA,MACnC;AAAA,IACD;AAAA,EACD;AAAA;AAAA,EAGA,YAAY,UAAkC;AAC7C,SAAK,UAAU,IAAI,QAAQ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,WAAW,EAAE,QAAQ;AAC1D,WAAO,SAAS,SAAS;AAAA,EAC1B;AACD;AAEA,SAAS,MAAM,IAA2B;AACzC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACxD;;;AC5eO,IAAM,kCAAN,cAA8C,MAAM;AAAA,EAC1D,YACC,UAAU,uFACT;AACD,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACb;AACD;AAEO,IAAM,wBAAN,MAAqD;AAAA,EAArD;AACN,SAAS,aAA2B;AAAA;AAAA,EAEpC,MAAM,oBAA8C;AACnD,UAAM,IAAI,gCAAgC;AAAA,EAC3C;AAAA,EAEA,MAAM,mBACL,aACA,iBACgC;AAChC,UAAM,IAAI,gCAAgC;AAAA,EAC3C;AAAA,EAEA,MAAM,mBAAmB,eAAsD;AAC9E,UAAM,IAAI,gCAAgC;AAAA,EAC3C;AAAA,EAEA,MAAM,cAAc,QAAkC;AACrD,UAAM,IAAI,gCAAgC;AAAA,EAC3C;AAAA,EAEA,MAAM,iBAAiB,QAA0C;AAChE,UAAM,IAAI,gCAAgC;AAAA,EAC3C;AACD;","names":[]}
|
package/dist/device.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/device/index.ts","../src/device/deviceAuth.ts","../src/device/Enroller.ts","../src/device/InstallationId.ts","../src/device/IdentityStore.ts","../src/paths/userHome.ts","../src/device/types.ts","../src/device/DeviceCore.ts"],"sourcesContent":["/**\n * device barrel — Phase 5.2 public surface.\n *\n * Consumers import from `@serviceme/devtools-core/device` (subpath\n * added in `package.json` `exports` map). The subpath keeps the\n * device namespace from colliding with the Phase 5b auth/toolbox\n * siblings at the type level.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `device/index.ts`\n */\n\nexport { DeviceCore, type DeviceCoreOptions } from \"./DeviceCore\";\nexport {\n\ttype BuildSignedHeadersParams,\n\tbuildSignedHeaders,\n\tcreateDeviceRequestSignature,\n\tDeviceAuthHeaders,\n\ttype DeviceRequestSignatureParams,\n\ttype DeviceSignedHeaders,\n} from \"./deviceAuth\";\nexport {\n\tDeviceReenrollRequiresAuthError,\n\tDeviceSecretVersionMismatchError,\n\tEnroller,\n\ttype EnrollerOptions,\n\ttype EnrollRequestFn,\n\ttype EnrollResponse,\n} from \"./Enroller\";\nexport {\n\tFsIdentityFileBackend,\n\ttype IdentityFileBackend,\n\tIdentityStore,\n\ttype IdentityStoreOptions,\n} from \"./IdentityStore\";\nexport {\n\tderiveInstallationId,\n\tfingerprintSource,\n\trandomInstallationId,\n} from \"./InstallationId\";\nexport {\n\ttype AtomicWriteResult,\n\tDEVICE_JSON_SCHEMA_VERSION,\n\ttype IdentityStoreHooks,\n\ttype PersistedDeviceIdentity,\n} from \"./types\";\n","/**\n * deviceAuth — Pure HMAC-SHA-256 signing helpers for device auth headers.\n *\n * **Boundary exception copy.** The single source of truth for the\n * `x-ms-device-*` header names + the signature algorithm now lives in\n * `@serviceme/devtools-shared` (`device-auth.ts`), consumed by the\n * extension signer and the server verifier. ADL-003 forbids\n * core → shared (and shared → core), so this module keeps a\n * byte-for-byte copy as the documented exception. Keep it in lock-step\n * with `packages/serviceme-shared/src/device-auth.ts`.\n *\n * See `docs/architecture/phase-5-device-header-spec.md` §5 for the wire\n * format. The basis is `METHOD\\nPATH\\nTIMESTAMP\\nBODY\\nSECRET`\n * (LF-joined, NOT JSON). Output is lowercase hex SHA-256.\n */\n\nimport { createHash } from \"node:crypto\";\n\n/** Canonical header names — MUST match `@serviceme/devtools-shared`'s `DeviceAuthHeaders`. */\nexport const DeviceAuthHeaders = {\n\tdeviceId: \"x-ms-device-id\",\n\tdeviceSecret: \"x-ms-device-secret\",\n\tsignature: \"x-ms-device-signature\",\n\ttimestamp: \"x-ms-device-timestamp\",\n\tsecretVersion: \"x-ms-device-secret-version\",\n} as const;\n\nexport interface DeviceRequestSignatureParams {\n\tmethod: string;\n\tpath: string;\n\ttimestamp: number;\n\tbody: string;\n\tsecret: string;\n}\n\n/**\n * Compute the HMAC-SHA-256 hex digest of the canonical basis.\n *\n * Server contract (`apps/server/src/lib/auth/device-signature-guard.ts:46-62`)\n * is line-for-line identical: same LF-joined basis, same lowercase\n * hex output. Any divergence breaks `device-signature-guard.test.ts`.\n */\nexport function createDeviceRequestSignature(params: DeviceRequestSignatureParams): string {\n\tconst basis = [\n\t\tparams.method.toUpperCase(),\n\t\tparams.path,\n\t\tString(params.timestamp),\n\t\tparams.body,\n\t\tparams.secret,\n\t].join(\"\\n\");\n\treturn createHash(\"sha256\").update(basis).digest(\"hex\");\n}\n\n/** 5-header map consumed by `fetch()` callers (CLI bridge, Extension). */\nexport interface DeviceSignedHeaders {\n\t[DeviceAuthHeaders.deviceId]: string;\n\t[DeviceAuthHeaders.deviceSecret]: string;\n\t[DeviceAuthHeaders.signature]: string;\n\t[DeviceAuthHeaders.timestamp]: string;\n\t[DeviceAuthHeaders.secretVersion]: string;\n}\n\nexport interface BuildSignedHeadersParams {\n\tmethod: string;\n\tpath: string;\n\tbody: string;\n\tpublicId: string;\n\tdeviceSecret: string;\n\tsecretVersion: number;\n\t/** Override for deterministic tests. */\n\ttimestamp?: number;\n}\n\n/**\n * Build the canonical 5-header map. The `body` parameter MUST be the\n * exact byte sequence sent on the wire (no whitespace re-canonicalization\n * between client serialization and signature basis construction).\n */\nexport function buildSignedHeaders(params: BuildSignedHeadersParams): DeviceSignedHeaders {\n\tconst timestamp = params.timestamp ?? Date.now();\n\tconst signature = createDeviceRequestSignature({\n\t\tmethod: params.method,\n\t\tpath: params.path,\n\t\ttimestamp,\n\t\tbody: params.body,\n\t\tsecret: params.deviceSecret,\n\t});\n\treturn {\n\t\t[DeviceAuthHeaders.deviceId]: params.publicId,\n\t\t[DeviceAuthHeaders.deviceSecret]: params.deviceSecret,\n\t\t[DeviceAuthHeaders.signature]: signature,\n\t\t[DeviceAuthHeaders.timestamp]: String(timestamp),\n\t\t[DeviceAuthHeaders.secretVersion]: String(params.secretVersion),\n\t};\n}\n","/**\n * Enroller — State machine for `device.enroll` and `device.rotate-secret`.\n *\n * States per `2.需求澄清.md` §1.2:\n * anonymous → pending → claimed → expired\n *\n * - `anonymous` (initial): no device has ever enrolled. Server returns\n * a fresh `publicId` + secret.\n * - `pending`: enrollment HTTP call has been issued but the server\n * hasn't confirmed yet. In-flight state — never persisted.\n * - `claimed`: user has linked this device to their account (via\n * `/api/v1/devices/claim`). Sticky binding locks future re-enrolls\n * to the same `userId` (server-side matrix).\n * - `expired`: server returned a device-expiry error. Forces a fresh\n * enroll on next call.\n *\n * `--force` semantics: any non-anonymous state can be force-reset to\n * `anonymous` by wiping the local identity file. The next enroll will\n * be treated as a brand-new install by the server (no sticky binding).\n *\n * The Enroller is the **state machine**; the actual HTTP I/O is the\n * caller's responsibility (the `DeviceSyncClient` in Phase 5.4 wires\n * the server). This split keeps the Enroller unit-testable without\n * a live server.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `Enroller.ts anonymous → pending → claimed → expired`\n * - `2.需求澄清.md` §1.2 — binding-state machine\n */\n\nimport { randomBytes } from \"node:crypto\";\n\nimport type { DeviceBindingState, DeviceEnrollResult } from \"@serviceme/devtools-protocol\";\nimport type { IdentityStore } from \"./IdentityStore\";\nimport { deriveInstallationId } from \"./InstallationId\";\nimport type { PersistedDeviceIdentity } from \"./types\";\n\n/** 32 bytes of HMAC secret material — matches the server's `device-registration.ts:73-80` generator. */\nconst SECRET_BYTES = 32;\n/** Server returns `publicId` as 32-char hex (16 bytes). Match the wire length. */\nconst PUBLIC_ID_BYTES = 16;\n\ntype RandomBytesFn = (size: number) => Buffer;\n\nconst defaultRandomBytes: RandomBytesFn = (size) => {\n\treturn randomBytes(size);\n};\n\nexport interface EnrollerOptions {\n\tidentityStore: IdentityStore;\n\t/** Injectable clock for deterministic tests. */\n\tnow?: () => Date;\n\t/** Override the random source (tests). */\n\trandomBytes?: (size: number) => Buffer;\n\t/** Caller-supplied enroll HTTP function. Phase 5.4 wires the real one. */\n\tenrollRequest?: EnrollRequestFn;\n}\n\nexport type EnrollRequestFn = (input: {\n\tinstallationId: string;\n\tmachineId: string;\n\tplatform: string;\n\texisting: PersistedDeviceIdentity | null;\n\tforce: boolean;\n\trequireAuth: boolean;\n}) => Promise<EnrollResponse>;\n\nexport interface EnrollResponse {\n\tpublicId: string;\n\tdeviceSecret: string;\n\tsecretVersion: number;\n\tbindingState: DeviceBindingState;\n\texpiresAt?: string;\n}\n\n/** Sentinel error — re-enroll on a claimed device without auth. */\nexport class DeviceReenrollRequiresAuthError extends Error {\n\tconstructor(\n\t\tmessage = \"Re-enroll on a claimed device requires current device credentials or the bound user\"\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"DeviceReenrollRequiresAuthError\";\n\t}\n}\n\n/** Sentinel error — server returned a 410 / version-mismatch after rotation. */\nexport class DeviceSecretVersionMismatchError extends Error {\n\tconstructor(message = \"Device secret version mismatch — server has rotated past the local copy\") {\n\t\tsuper(message);\n\t\tthis.name = \"DeviceSecretVersionMismatchError\";\n\t}\n}\n\nexport class Enroller {\n\tprivate readonly identity: IdentityStore;\n\tprivate readonly now: () => Date;\n\tprivate readonly random: (size: number) => Buffer;\n\tprivate readonly enrollRequest?: EnrollRequestFn;\n\tprivate inflight: Promise<DeviceEnrollResult> | null = null;\n\n\tconstructor(opts: EnrollerOptions) {\n\t\tthis.identity = opts.identityStore;\n\t\tthis.now = opts.now ?? (() => new Date());\n\t\tthis.random = opts.randomBytes ?? defaultRandomBytes;\n\t\tthis.enrollRequest = opts.enrollRequest;\n\t}\n\n\t/**\n\t * Read the current binding state without touching the disk.\n\t * Returns `anonymous` when no identity is stored.\n\t */\n\tasync currentState(): Promise<DeviceBindingState> {\n\t\tconst stored = await this.identity.read();\n\t\treturn stored?.bindingState ?? \"anonymous\";\n\t}\n\n\t/**\n\t * Drive the enrollment flow.\n\t *\n\t * @param force when true, drop the local identity and start fresh\n\t * (server treats this as a brand-new install).\n\t * @param requireAuth when true, refuse to silently re-enroll an\n\t * existing claimed device — throw\n\t * `DeviceReenrollRequiresAuthError` instead.\n\t */\n\t/**\n\t * Resolve when any in-flight enrollment completes. Returns immediately\n\t * when no enrollment is in progress. Allows callers (e.g. the extension's\n\t * `buildDeviceAuthHeaders`) to wait for a concurrent `syncDeviceInfo()`\n\t * enrollment before attempting to read the identity from the store.\n\t */\n\tasync waitForEnrollment(): Promise<void> {\n\t\tif (this.inflight) {\n\t\t\tawait this.inflight;\n\t\t}\n\t}\n\n\tasync enroll(opts: { force?: boolean; requireAuth?: boolean } = {}): Promise<DeviceEnrollResult> {\n\t\t// Concurrency guard — multiple in-flight calls share the same promise.\n\t\tif (this.inflight) {\n\t\t\treturn this.inflight;\n\t\t}\n\t\tconst promise = this.runEnroll(opts);\n\t\tthis.inflight = promise;\n\t\ttry {\n\t\t\treturn await promise;\n\t\t} finally {\n\t\t\tif (this.inflight === promise) this.inflight = null;\n\t\t}\n\t}\n\n\t/** Test seam — surface the underlying identity store. */\n\tgetIdentityStore(): IdentityStore {\n\t\treturn this.identity;\n\t}\n\n\t/** True when an enrollment is currently in-flight. Used by callers (e.g. the extension's `buildDeviceAuthHeaders`) to skip triggering a competing enrollment. */\n\tisEnrolling(): boolean {\n\t\treturn this.inflight !== null;\n\t}\n\n\tprivate async runEnroll(opts: {\n\t\tforce?: boolean;\n\t\trequireAuth?: boolean;\n\t}): Promise<DeviceEnrollResult> {\n\t\tconst { written } = await this.identity.mutate(async (current) => {\n\t\t\tconst existing = opts.force ? null : current;\n\n\t\t\tif (!opts.force && current) {\n\t\t\t\tif (current.bindingState === \"expired\") {\n\t\t\t\t\t// Expired identities are forced to re-enroll as if they were new.\n\t\t\t\t} else if (\n\t\t\t\t\topts.requireAuth &&\n\t\t\t\t\t(current.bindingState === \"claimed\" || current.bindingState === \"pending\")\n\t\t\t\t) {\n\t\t\t\t\t// Caller asserted the device must be claimed, but local state\n\t\t\t\t\t// shows it's still in flight. This is a CLI-only guard — the\n\t\t\t\t\t// server is the final arbiter.\n\t\t\t\t\tthrow new DeviceReenrollRequiresAuthError();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst installationId = current?.installationId ?? deriveInstallationId();\n\t\t\tconst machineId = current?.machineId ?? \"unknown\";\n\t\t\tconst platform = current?.platform ?? \"unknown\";\n\n\t\t\tlet response: EnrollResponse;\n\t\t\tif (this.enrollRequest) {\n\t\t\t\tresponse = await this.enrollRequest({\n\t\t\t\t\tinstallationId,\n\t\t\t\t\tmachineId,\n\t\t\t\t\tplatform,\n\t\t\t\t\texisting,\n\t\t\t\t\tforce: Boolean(opts.force),\n\t\t\t\t\trequireAuth: Boolean(opts.requireAuth),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Test path / no live HTTP — synthesize a fresh identity. This\n\t\t\t\t// branch is what unit tests exercise; production wires\n\t\t\t\t// `enrollRequest` in Phase 5.4.\n\t\t\t\tresponse = synthesizeEnrollResponse(this.random, existing);\n\t\t\t}\n\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\tversion: current?.version ?? 1,\n\t\t\t\tinstallationId,\n\t\t\t\tmachineId,\n\t\t\t\tplatform,\n\t\t\t\thostname: current?.hostname,\n\t\t\t\tpublicId: response.publicId,\n\t\t\t\tsecretVersion: response.secretVersion,\n\t\t\t\tbindingState: response.bindingState,\n\t\t\t\tdeviceSecret: response.deviceSecret,\n\t\t\t\tpreviousDeviceSecret: existing?.deviceSecret,\n\t\t\t\tpreviousSecretExpiresAt:\n\t\t\t\t\topts.force || response.secretVersion === (existing?.secretVersion ?? 0) + 1\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: existing?.previousSecretExpiresAt,\n\t\t\t\tlastEnrollAt: this.now().toISOString(),\n\t\t\t\tlastSyncAt: existing?.lastSyncAt,\n\t\t\t\tlastSyncError: undefined,\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\n\t\treturn {\n\t\t\tpublicId: written.publicId,\n\t\t\tbindingState: written.bindingState,\n\t\t\texpiresAt: deriveExpiresAt(written, this.now),\n\t\t};\n\t}\n\n\t/**\n\t * Rotate the HMAC secret. Keeps the previous secret for the grace\n\t * window (default 7 days per `2.需求澄清.md` §1.2) — the\n\t * `previousSecretExpiresAt` is stamped on the persisted identity.\n\t */\n\tasync rotateSecret(\n\t\topts: { gracePeriodDays?: number } = {}\n\t): Promise<{ publicId: string; secretVersion: number; gracePeriodDays: number }> {\n\t\tconst gracePeriodDays = opts.gracePeriodDays ?? 7;\n\t\tconst now = this.now();\n\t\tconst newSecret = this.random(SECRET_BYTES).toString(\"hex\");\n\n\t\tconst { written } = await this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\tthrow new Error(\"Cannot rotate-secret without a prior enrollment\");\n\t\t\t}\n\t\t\tconst graceExpiresAt = new Date(now.getTime() + gracePeriodDays * 24 * 60 * 60 * 1000);\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\t...current,\n\t\t\t\tdeviceSecret: newSecret,\n\t\t\t\tpreviousDeviceSecret: current.deviceSecret,\n\t\t\t\tpreviousSecretExpiresAt: graceExpiresAt.toISOString(),\n\t\t\t\tsecretVersion: current.secretVersion + 1,\n\t\t\t\tlastEnrollAt: now.toISOString(),\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\n\t\treturn {\n\t\t\tpublicId: written.publicId,\n\t\t\tsecretVersion: written.secretVersion,\n\t\t\tgracePeriodDays,\n\t\t};\n\t}\n\n\t/**\n\t * Mark the device as `expired`. Used when the server returns a\n\t * device-expiry response; the next `enroll()` call forces a fresh\n\t * round-trip.\n\t */\n\tasync markExpired(): Promise<void> {\n\t\tawait this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\t// Nothing to expire.\n\t\t\t\treturn { next: current ?? (await emptyIdentity(this.random)), result: undefined };\n\t\t\t}\n\t\t\tconst next: PersistedDeviceIdentity = { ...current, bindingState: \"expired\" };\n\t\t\treturn { next };\n\t\t});\n\t}\n\n\t/**\n\t * Mark the device as `claimed`. Called by the bridge after a\n\t * successful `device.claim` server response.\n\t */\n\tasync markClaimed(): Promise<void> {\n\t\tawait this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\tthrow new Error(\"Cannot mark-claimed without a prior enrollment\");\n\t\t\t}\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\t...current,\n\t\t\t\tbindingState: \"claimed\",\n\t\t\t\tlastSyncAt: this.now().toISOString(),\n\t\t\t\tlastSyncError: undefined,\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\t}\n}\n\nfunction deriveExpiresAt(_identity: PersistedDeviceIdentity, _now: () => Date): string | undefined {\n\t// No explicit expiry on the server today (per phase-5-device-header-spec.md\n\t// §9 #1: 7-day grace is rotation-only). The shape is here for forward\n\t// compatibility — when the server adds a per-device expiry, this\n\t// pulls the value from the response without changing the call site.\n\treturn undefined;\n}\n\nfunction synthesizeEnrollResponse(\n\trandom: RandomBytesFn,\n\texisting: PersistedDeviceIdentity | null\n): EnrollResponse {\n\tconst publicId = existing?.publicId ?? random(PUBLIC_ID_BYTES).toString(\"hex\");\n\tconst secretVersion = (existing?.secretVersion ?? 0) + 1;\n\treturn {\n\t\tpublicId,\n\t\tdeviceSecret: random(SECRET_BYTES).toString(\"hex\"),\n\t\tsecretVersion,\n\t\tbindingState: existing?.bindingState === \"claimed\" ? \"claimed\" : \"anonymous\",\n\t};\n}\n\nasync function emptyIdentity(random: RandomBytesFn): Promise<PersistedDeviceIdentity> {\n\treturn {\n\t\tversion: 1,\n\t\tinstallationId: deriveInstallationId(),\n\t\tmachineId: \"unknown\",\n\t\tplatform: \"unknown\",\n\t\tpublicId: random(PUBLIC_ID_BYTES).toString(\"hex\"),\n\t\tsecretVersion: 1,\n\t\tbindingState: \"anonymous\",\n\t\tdeviceSecret: random(SECRET_BYTES).toString(\"hex\"),\n\t\tlastEnrollAt: new Date().toISOString(),\n\t};\n}\n","/**\n * InstallationId — Derive a stable per-machine identifier from\n * `os.hostname()` + `os.userInfo()`.\n *\n * Per `docs/architecture/phase-5-auth-device-toolbox.md § P5-2 (并入本文时对应 § P5-2 拆分)` B2,\n * `installationId` MUST survive Extension re-installs but vary across\n * machines. We compute a UUID v5-style hash over hostname + username +\n * platform so the result is:\n * - deterministic (same machine → same id)\n * - collision-resistant (SHA-256, 128-bit truncated)\n * - browser-safe (no PII survives — username never enters output)\n *\n * Note: this intentionally differs from `vscode.env.machineId`, which\n * is per-Extension-install and uses a different algorithm. The two\n * coexist: `installationId` is what gets sent to the server, while\n * `machineId` (raw `os.hostname()`) is for diagnostics.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `InstallationId.ts os.hostname() + os.userInfo() 哈希生成`\n * - 3.功能拆分.md B2 — installationId semantics\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport * as os from \"node:os\";\n\n/** Hex-encoded SHA-256 input. Format: `<hostname>|<username>|<platform>|<nodeVersion>`. */\nfunction fingerprintMaterial(): string {\n\t// `os.userInfo()` is undefined-ish on Windows in some sandboxes; fall\n\t// back to a process env user, then to a constant placeholder. We never\n\t// emit the raw username to the caller — it only enters the hash.\n\tlet username = \"unknown\";\n\ttry {\n\t\tusername = os.userInfo().username;\n\t} catch {\n\t\tusername = process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n\t}\n\treturn [\n\t\tos.hostname(),\n\t\tusername,\n\t\tos.platform(),\n\t\tos.arch(),\n\t\tprocess.versions.node ?? \"unknown\",\n\t].join(\"|\");\n}\n\n/**\n * Returns a deterministic installation id for the current machine.\n * Use this when you need an id that survives Extension reinstalls\n * but stays stable across restarts on the same machine.\n */\nexport function deriveInstallationId(): string {\n\tconst material = fingerprintMaterial();\n\tconst digest = createHash(\"sha256\").update(material).digest(\"hex\");\n\t// Take the first 32 hex chars (128 bits) and reformat as UUID v4-shape\n\t// so the output looks like a UUID to downstream consumers while\n\t// remaining a pure SHA-256 truncation.\n\treturn formatAsV4(digest.slice(0, 32));\n}\n\n/**\n * Returns a random installation id (UUID v4). Use this for fresh\n * installs when no fingerprint input is available (e.g. containerized\n * CI runners where `os.hostname()` is meaningless).\n */\nexport function randomInstallationId(): string {\n\treturn randomUUID();\n}\n\n/** SHA-256 fingerprint material exposed for tests + diagnostics. */\nexport function fingerprintSource(): string {\n\treturn fingerprintMaterial();\n}\n\nfunction formatAsV4(hex32: string): string {\n\t// Stamp version 4 + variant bits per RFC 4122 §4.4. The bits are\n\t// cosmetic — the underlying entropy is still SHA-256.\n\tconst chars = hex32.split(\"\");\n\t// Version nibble (position 12 in canonical UUID, index 13 of the 32-char string).\n\tconst versionIdx = 12;\n\tconst variantIdx = 16;\n\tconst versionChar = (parseInt(chars[versionIdx] ?? \"8\", 16) & 0x0) | 0x4;\n\tchars[versionIdx] = versionChar.toString(16);\n\t// Variant nibble: 10xx → first hex char of the 17th position.\n\tconst variantChar = (parseInt(chars[variantIdx] ?? \"8\", 16) & 0x3) | 0x8;\n\tchars[variantIdx] = variantChar.toString(16);\n\tconst formatted = chars.join(\"\");\n\treturn `${formatted.slice(0, 8)}-${formatted.slice(8, 12)}-${formatted.slice(12, 16)}-${formatted.slice(16, 20)}-${formatted.slice(20, 32)}`;\n}\n","/**\n * IdentityStore — Atomic JSON persistence for the device identity file.\n *\n * Stores the `PersistedDeviceIdentity` (incl. the HMAC secret cleartext)\n * at `~/.serviceme/device.json` (per `phase-5-device-header-spec.md`\n * §3.1). Writes are atomic via `write-tmp + fsync + rename`, matching\n * the `SkillStore` / `ToolboxStore` precedent. Concurrent writes are\n * serialized with a mkdir-based file lock (POSIX-atomic) — proper\n * cross-process locking is deferred to Phase 6+ per the open spec.\n *\n * The file mode is `0600` (owner read/write only) so the cleartext\n * secret stays safe at rest. On Windows the mode hint is a no-op\n * (Windows uses ACLs) but `writeFile` still succeeds.\n *\n * Migration — IdentityStore auto-detects a v0-shape (pre-Phase-5.2)\n * file written by the Extension's old `globalState` blob:\n * { version: 1, claimed: false, publicKeyFingerprint: null }\n * In that case the file is migrated forward to the v1 schema on the\n * next write (the data fields are empty and a fresh enroll is required).\n * The full Extension `globalState` → JSON migration happens in the\n * Phase 5.5 adapter (`apps/extension/.../DeviceService.ts`) since the\n * adapter holds the live `globalState` access.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `IdentityStore.ts 持久化到 ~/.config/serviceme/device.json, 原子写`\n * - `docs/architecture/phase-5-device-header-spec.md` §3.1, §2.5\n */\n\nimport * as fsp from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { getDeviceJsonPath, getServicemeHome } from \"../paths/userHome\";\n\nimport {\n\ttype AtomicWriteResult,\n\tDEVICE_JSON_SCHEMA_VERSION,\n\ttype IdentityStoreHooks,\n\ttype PersistedDeviceIdentity,\n} from \"./types\";\n\nconst FILE_MODE = 0o600;\nconst LOCK_DIR_MODE = 0o700;\nconst DEFAULT_LOCK_TIMEOUT_MS = 5000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\n// `mkdir` (lock acquisition) and writing the pid file are two separate\n// syscalls, so there's a brief window where the lock dir exists but the\n// pid file doesn't yet. A grace period keeps a concurrent acquirer from\n// mistaking that window for an abandoned lock (see `isStaleLock`).\nconst LOCK_STALE_GRACE_MS = 200;\nconst TMP_SUFFIX = \".tmp\";\n\n/**\n * Minimal interface for reading + writing the persisted identity file.\n * Default impl uses `getDeviceJsonPath()` (which honors `SERVICEME_HOME`),\n * but tests can substitute a custom path for isolation.\n */\nexport interface IdentityFileBackend {\n\tread(filePath: string): Promise<PersistedDeviceIdentity | null>;\n\twrite(filePath: string, payload: PersistedDeviceIdentity): Promise<AtomicWriteResult>;\n\texists(filePath: string): Promise<boolean>;\n\tdelete(filePath: string): Promise<void>;\n\tlistDir?(dir: string): Promise<string[]>;\n}\n\nexport interface IdentityStoreOptions {\n\tfilePath?: string;\n\thooks?: IdentityStoreHooks;\n\tlockTimeoutMs?: number;\n\tlockRetryMs?: number;\n\t/** Injectable clock for deterministic tests. */\n\tnow?: () => Date;\n\tbackend?: IdentityFileBackend;\n}\n\n/**\n * Default file backend — uses `node:fs/promises` with the canonical\n * tmp-then-rename atomic-write pattern.\n */\nexport class FsIdentityFileBackend implements IdentityFileBackend {\n\tasync exists(filePath: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait fsp.access(filePath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync read(filePath: string): Promise<PersistedDeviceIdentity | null> {\n\t\ttry {\n\t\t\tconst buf = await fsp.readFile(filePath, \"utf8\");\n\t\t\tconst parsed = JSON.parse(buf) as unknown;\n\t\t\treturn migratePersistedIdentity(parsed);\n\t\t} catch (err) {\n\t\t\tif (isNodeError(err) && err.code === \"ENOENT\") return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync write(filePath: string, payload: PersistedDeviceIdentity): Promise<AtomicWriteResult> {\n\t\tawait fsp.mkdir(path.dirname(filePath), { recursive: true });\n\t\tconst tmpPath = `${filePath}${TMP_SUFFIX}`;\n\t\tconst bytes = Buffer.from(JSON.stringify(payload, null, \"\\t\"), \"utf8\");\n\t\t// Ensure tmp is fresh (in case a previous run died mid-write).\n\t\tawait fsp.rm(tmpPath, { force: true });\n\t\tconst handle = await fsp.open(tmpPath, \"w\", FILE_MODE);\n\t\ttry {\n\t\t\tawait handle.writeFile(bytes);\n\t\t\tawait handle.sync();\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tawait fsp.rename(tmpPath, filePath);\n\t\t// Best-effort chmod for filesystems that ignore mode on create (Windows).\n\t\tawait fsp.chmod(filePath, FILE_MODE).catch(() => undefined);\n\t\treturn { bytesWritten: bytes.byteLength, tmpPath };\n\t}\n\n\tasync delete(filePath: string): Promise<void> {\n\t\tawait fsp.rm(filePath, { force: true });\n\t}\n}\n\n/**\n * Reconcile an unknown on-disk shape into the current `PersistedDeviceIdentity`.\n *\n * - v1 IdentityStore files (current shape) pass through unchanged.\n * - v0 bootstrap files (`{ version: 1, claimed: false, publicKeyFingerprint: null }`)\n * are recognized by their placeholder keys and discarded; the next\n * enroll writes a fresh identity.\n * - Anything else throws — refuse to silently drop user data.\n */\nfunction migratePersistedIdentity(parsed: unknown): PersistedDeviceIdentity | null {\n\tif (!isRecord(parsed)) {\n\t\tthrow new Error(\"device.json: top-level must be an object\");\n\t}\n\tconst version = parsed.version;\n\tif (version === DEVICE_JSON_SCHEMA_VERSION) {\n\t\t// Pre-Phase-5.2 placeholder shape carries `claimed` /\n\t\t// `publicKeyFingerprint` but no real device fields. Recognize\n\t\t// the marker and return null so the next enroll writes fresh data.\n\t\tif (\n\t\t\tparsed.publicId === undefined &&\n\t\t\tparsed.deviceSecret === undefined &&\n\t\t\t(\"claimed\" in parsed || \"publicKeyFingerprint\" in parsed)\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\t// Trust the schema — the writer is also us.\n\t\treturn parsed as unknown as PersistedDeviceIdentity;\n\t}\n\tif (typeof version === \"number\" && version < DEVICE_JSON_SCHEMA_VERSION) {\n\t\t// Pre-Phase-5.2 bootstrap shape — the file is empty placeholder\n\t\t// data; nothing to migrate. Return null to signal \"no identity\".\n\t\treturn null;\n\t}\n\tthrow new Error(`device.json: unsupported schema version ${String(version)}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isNodeError(value: unknown): value is NodeJS.ErrnoException {\n\treturn value instanceof Error && typeof (value as { code?: unknown }).code === \"string\";\n}\n\nconst LOCK_PID_FILE = \"pid\";\n\n/**\n * Check whether a process is still alive (best-effort, cross-platform).\n * Returns `false` for any PID we cannot verify as alive.\n */\nfunction isProcessAlive(pid: number): boolean {\n\ttry {\n\t\t// signal 0 — permission check only, never actually sent\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * mkdir-based advisory file lock with stale-lock recovery.\n *\n * POSIX mkdir is atomic; on Windows modern filesystems (NTFS) it's also\n * atomic at the API level. Sufficient for single-host, single-user\n * scenarios (which is the SERVICEME threat model).\n *\n * Stale lock recovery: a `pid` file inside the lock directory records the\n * owner's PID. On `EEXIST`, if the recorded PID is no longer alive, the\n * lock directory is forcibly removed and acquisition retried immediately.\n * This prevents permanent lockout when a process crashes without calling\n * `release()`.\n */\nclass FileLock {\n\tprivate readonly dirPath: string;\n\tprivate readonly pidFilePath: string;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly retryMs: number;\n\tprivate acquired = false;\n\n\tconstructor(filePath: string, timeoutMs: number, retryMs: number) {\n\t\tthis.dirPath = `${filePath}.lock`;\n\t\tthis.pidFilePath = path.join(this.dirPath, LOCK_PID_FILE);\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.retryMs = retryMs;\n\t}\n\n\tasync acquire(): Promise<void> {\n\t\tconst start = Date.now();\n\t\twhile (true) {\n\t\t\ttry {\n\t\t\t\tawait fsp.mkdir(this.dirPath, { mode: LOCK_DIR_MODE });\n\t\t\t\t// Write PID so a future acquirer can detect if we crash.\n\t\t\t\tawait fsp.writeFile(this.pidFilePath, String(process.pid), \"utf8\").catch(() => undefined);\n\t\t\t\tthis.acquired = true;\n\t\t\t\treturn;\n\t\t\t} catch (err) {\n\t\t\t\tif (!isNodeError(err) || err.code !== \"EEXIST\") {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\t// Lock directory exists — check for stale owner.\n\t\t\t\tconst stale = await this.isStaleLock();\n\t\t\t\tif (stale) {\n\t\t\t\t\tawait fsp.rm(this.dirPath, { recursive: true, force: true });\n\t\t\t\t\t// Retry immediately without counting this iteration against timeout.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (Date.now() - start >= this.timeoutMs) {\n\t\t\t\t\tthrow new Error(`IdentityStore lock acquisition timed out for ${this.dirPath}`);\n\t\t\t\t}\n\t\t\t\tawait delay(this.retryMs);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async isStaleLock(): Promise<boolean> {\n\t\tlet pidStr: string;\n\t\ttry {\n\t\t\tpidStr = await fsp.readFile(this.pidFilePath, \"utf8\");\n\t\t} catch {\n\t\t\t// The pid file may not exist yet because another acquirer just\n\t\t\t// created the lock dir and hasn't finished writing its pid file\n\t\t\t// (mkdir + writeFile is not atomic). Give it a short grace window\n\t\t\t// before concluding the owner crashed between mkdir and writeFile.\n\t\t\ttry {\n\t\t\t\tconst stat = await fsp.stat(this.dirPath);\n\t\t\t\treturn Date.now() - stat.mtimeMs > LOCK_STALE_GRACE_MS;\n\t\t\t} catch {\n\t\t\t\t// Lock dir disappeared concurrently (e.g. released mid-check) —\n\t\t\t\t// not stale, just gone; the caller's next mkdir will succeed.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tconst pid = Number.parseInt(pidStr.trim(), 10);\n\t\tif (!Number.isFinite(pid) || pid <= 0) return true; // malformed pid file → treat as stale\n\t\treturn !isProcessAlive(pid);\n\t}\n\n\tasync release(): Promise<void> {\n\t\tif (!this.acquired) return;\n\t\tthis.acquired = false;\n\t\tawait fsp.rm(this.dirPath, { recursive: true, force: true });\n\t}\n}\n\nexport class IdentityStore {\n\tprivate readonly filePath: string;\n\tprivate readonly backend: IdentityFileBackend;\n\tprivate readonly hooks: IdentityStoreHooks;\n\tprivate readonly lockTimeoutMs: number;\n\tprivate readonly lockRetryMs: number;\n\n\tconstructor(opts: IdentityStoreOptions = {}) {\n\t\tthis.filePath = opts.filePath ?? getDeviceJsonPath();\n\t\tthis.backend = opts.backend ?? new FsIdentityFileBackend();\n\t\tthis.hooks = opts.hooks ?? {};\n\t\tthis.lockTimeoutMs = opts.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;\n\t\tthis.lockRetryMs = opts.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS;\n\t}\n\n\t/** Absolute path to the underlying JSON file (test seam). */\n\tgetFilePath(): string {\n\t\treturn this.filePath;\n\t}\n\n\t/** True when the JSON file already exists on disk. */\n\tasync exists(): Promise<boolean> {\n\t\treturn this.backend.exists(this.filePath);\n\t}\n\n\t/** Read the persisted identity; returns `null` when no identity is stored. */\n\tasync read(): Promise<PersistedDeviceIdentity | null> {\n\t\treturn this.backend.read(this.filePath);\n\t}\n\n\t/**\n\t * Atomically write the given identity. Concurrent writers are\n\t * serialized via the file lock; the read-modify-write happens\n\t * inside the lock so callers can't see a partial state.\n\t */\n\tasync write(next: PersistedDeviceIdentity): Promise<AtomicWriteResult> {\n\t\tawait this.hooks.beforeWrite?.(next);\n\t\tconst lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);\n\t\tawait lock.acquire();\n\t\ttry {\n\t\t\tconst stamped: PersistedDeviceIdentity = {\n\t\t\t\t...next,\n\t\t\t\tversion: DEVICE_JSON_SCHEMA_VERSION,\n\t\t\t};\n\t\t\tconst result = await this.backend.write(this.filePath, stamped);\n\t\t\tawait this.hooks.afterWrite?.(stamped);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tawait lock.release();\n\t\t}\n\t}\n\n\t/**\n\t * Read-modify-write under the same lock. The mutator receives the\n\t * current identity (or `null` on first call) and returns the\n\t * replacement. Throwing inside the mutator aborts the write.\n\t */\n\tasync mutate<T>(\n\t\tmutator: (\n\t\t\tcurrent: PersistedDeviceIdentity | null\n\t\t) => Promise<{ next: PersistedDeviceIdentity; result?: T }>\n\t): Promise<{ result: T | undefined; written: PersistedDeviceIdentity }> {\n\t\tconst lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);\n\t\tawait lock.acquire();\n\t\ttry {\n\t\t\tconst current = await this.backend.read(this.filePath);\n\t\t\tconst { next, result } = await mutator(current);\n\t\t\tconst stamped: PersistedDeviceIdentity = {\n\t\t\t\t...next,\n\t\t\t\tversion: DEVICE_JSON_SCHEMA_VERSION,\n\t\t\t};\n\t\t\tawait this.hooks.beforeWrite?.(stamped);\n\t\t\tawait this.backend.write(this.filePath, stamped);\n\t\t\tawait this.hooks.afterWrite?.(stamped);\n\t\t\treturn { result, written: stamped };\n\t\t} finally {\n\t\t\tawait lock.release();\n\t\t}\n\t}\n\n\t/** Wipe the persisted identity (used by `device.enroll --force`). */\n\tasync clear(): Promise<void> {\n\t\tawait this.backend.delete(this.filePath);\n\t}\n\n\t/**\n\t * Resolve the installation metadata for the current machine.\n\t * Pure helper — no I/O, just `os.*` calls.\n\t */\n\tresolveInstallationMetadata(): Pick<\n\t\tPersistedDeviceIdentity,\n\t\t\"installationId\" | \"machineId\" | \"platform\"\n\t> {\n\t\tconst machineId = os.hostname();\n\t\tconst platform = os.platform();\n\t\t// installationId is derived by `InstallationId.ts` — pass the\n\t\t// caller's already-computed value via `material` so we don't\n\t\t// recompute the SHA twice in a row.\n\t\treturn {\n\t\t\tinstallationId: \"\", // intentionally empty; caller fills via deriveInstallationId()\n\t\t\tmachineId,\n\t\t\tplatform,\n\t\t};\n\t}\n\n\t/**\n\t * Ensure the parent directory exists (`~/.serviceme/`). Idempotent.\n\t * Useful when the bootstrap phase5 placeholder wasn't run yet.\n\t */\n\tasync ensureHome(): Promise<void> {\n\t\tawait fsp.mkdir(getServicemeHome(), { recursive: true });\n\t\tawait fsp.mkdir(path.dirname(this.filePath), { recursive: true });\n\t}\n}\n","import * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n/**\n * SERVICEME user home directory helpers.\n *\n * All paths resolve under {@link getServicemeHome}, which is either the\n * `SERVICEME_HOME` environment variable (when set and non-empty) or\n * `$HOME/.serviceme` on POSIX / `%USERPROFILE%\\.serviceme` on Windows.\n *\n * Tests inject `homeDir` and `servicemeHomeEnv` overrides via\n * {@link setUserHomeOverrides} / {@link resetUserHomeOverrides} so they can\n * exercise the path logic without touching the real user environment.\n */\n\n/** Layout constants — kept in one place so other modules can reuse them. */\nexport const SERVICEME_DIR_NAME = \".serviceme\";\nexport const REPOS_SUBDIR = \"repos\";\nexport const CACHE_SUBDIR = \"cache\";\nexport const DRAFTS_SUBDIR = \"drafts\";\nexport const SKILL_DRAFTS_SUBDIR = \"skills\";\nexport const AGENT_DRAFTS_SUBDIR = \"agents\";\nexport const REPOS_CONFIG_FILENAME = \"repos.json\";\nexport const WORKSPACES_SUBDIR = \"workspaces\";\nexport const WORKSPACE_CONTENT_STATE_FILENAME = \"copilot-content-state.json\";\n\n/** rev.20 — r7 BYOM Server Proxy toggle self-state (read by ext + CLI + server). */\nexport const SERVER_PROXY_GLOBAL_FILENAME = \"server-proxy.json\";\n\n/**\n * Repo id regex — used to validate any `repoId` argument before it is joined\n * into a filesystem path. Keeps path traversal attempts out and gives us a\n * predictable on-disk shape.\n */\nexport const SAFE_REPO_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\n\n/** Environment variable that overrides the user-home root directory. */\nexport const SERVICEME_HOME_ENV = \"SERVICEME_HOME\";\n\n/**\n * Test seam: lets unit tests inject deterministic values for `os.homedir()`\n * and the `SERVICEME_HOME` env override without actually mutating\n * `process.env` (which would leak into other tests).\n */\ninterface UserHomeOverrides {\n\thomeDir?: string | undefined;\n\tservicemeHomeEnv?: string | undefined;\n\tplatform?: NodeJS.Platform | undefined;\n}\n\nlet activeOverrides: UserHomeOverrides = {};\n\nexport function setUserHomeOverrides(overrides: UserHomeOverrides): void {\n\tactiveOverrides = { ...overrides };\n}\n\nexport function resetUserHomeOverrides(): void {\n\tactiveOverrides = {};\n}\n\nfunction resolveHomeDir(): string {\n\tconst injected = activeOverrides.homeDir;\n\tif (injected !== undefined) {\n\t\treturn injected;\n\t}\n\treturn os.homedir();\n}\n\nfunction resolveServicemeHomeEnv(): string | undefined {\n\tconst injected = activeOverrides.servicemeHomeEnv;\n\tif (injected !== undefined) {\n\t\t// Treat empty string as \"not set\" — `process.env` always returns a string\n\t\t// but tests may deliberately pass \"\" to opt out.\n\t\treturn injected.length > 0 ? injected : undefined;\n\t}\n\tconst envValue = process.env[SERVICEME_HOME_ENV];\n\treturn envValue && envValue.length > 0 ? envValue : undefined;\n}\n\nfunction resolvePlatform(): NodeJS.Platform {\n\treturn activeOverrides.platform ?? process.platform;\n}\n\nexport function assertSafeRepoId(repoId: string): string {\n\tif (typeof repoId !== \"string\" || repoId.length === 0 || !SAFE_REPO_ID_PATTERN.test(repoId)) {\n\t\tthrow new Error(\n\t\t\t`Invalid repo id: ${JSON.stringify(repoId)}. ` +\n\t\t\t\t`Must match ${SAFE_REPO_ID_PATTERN} (alphanumeric start, then ` +\n\t\t\t\t`alphanumerics / underscores / hyphens, ≤ 64 chars).`\n\t\t);\n\t}\n\treturn repoId;\n}\n\n/**\n * The raw OS home directory (`os.homedir()`), honoring test overrides\n * ({@link setUserHomeOverrides}). Exported for callers that need a\n * home-relative path *outside* of `~/.serviceme` — e.g. the\n * `~/.agents/{skills,agents}` convention used by `SkillLinker` for\n * user-scope links.\n */\nexport function getHomeDir(): string {\n\treturn resolveHomeDir();\n}\n\n/**\n * Root directory for all SERVICEME user-level state. Resolves to\n * `${SERVICEME_HOME}` when that env var is set, otherwise `${HOME}/.serviceme`\n * (POSIX) or `%USERPROFILE%\\.serviceme` (Windows via `os.homedir`).\n */\nexport function getServicemeHome(): string {\n\tconst override = resolveServicemeHomeEnv();\n\tif (override !== undefined) {\n\t\treturn path.resolve(override);\n\t}\n\treturn path.join(resolveHomeDir(), SERVICEME_DIR_NAME);\n}\n\n/** `$HOME/.serviceme/repos` (or `${SERVICEME_HOME}/repos`). */\nexport function getReposDir(): string {\n\treturn path.join(getServicemeHome(), REPOS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/repos/<repoId>` — validates `repoId` first. */\nexport function getRepoDir(repoId: string): string {\n\treturn path.join(getReposDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/cache` — generic per-user cache. */\nexport function getCacheDir(): string {\n\treturn path.join(getServicemeHome(), CACHE_SUBDIR);\n}\n\n/** `$HOME/.serviceme/cache/<repoId>` — per-repo sync state lives here. */\nexport function getRepoCacheDir(repoId: string): string {\n\treturn path.join(getCacheDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/drafts` — local edits not yet pushed upstream. */\nexport function getDraftsDir(): string {\n\treturn path.join(getServicemeHome(), DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/skills` — local skill drafts. */\nexport function getSkillDraftsDir(): string {\n\treturn path.join(getDraftsDir(), SKILL_DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/agents` — local agent drafts. */\nexport function getAgentDraftsDir(): string {\n\treturn path.join(getDraftsDir(), AGENT_DRAFTS_SUBDIR);\n}\n\n/**\n * `$HOME/.serviceme/repos.json` — the single config entry point for repo\n * metadata. Always under the resolved home root (i.e. follows\n * `SERVICEME_HOME` overrides too).\n */\nexport function getReposConfigPath(): string {\n\treturn path.join(getServicemeHome(), REPOS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/workspaces` — machine-local per-workspace state root. */\nexport function getWorkspacesDir(): string {\n\treturn path.join(getServicemeHome(), WORKSPACES_SUBDIR);\n}\n\n/**\n * Convenience helper for callers that need to switch behaviour on platform\n * (e.g. `SkillLinker` chooses symlink vs junction). Exported mostly so tests\n * can pin the value without touching `process.platform` directly.\n */\nexport function getHomePlatform(): NodeJS.Platform {\n\treturn resolvePlatform();\n}\n\n// ─── Scheduled Tasks paths (added by M1.5.3) ───────────────────────────────\n\n/** Layout constants for scheduled-tasks files. Kept here so other modules\n * can reuse them and the names stay in sync with the design doc. */\nexport const SCHEDULED_TASKS_CONFIG_FILENAME = \"scheduled-tasks.json\";\nexport const SCHEDULED_TASKS_LOG_FILENAME = \"scheduled-tasks-log.json\";\nexport const SCHEDULER_PID_FILENAME = \"scheduler.pid\";\nexport const SCHEDULER_LOCK_FILENAME = \"scheduler.lock\";\nexport const SCHEDULER_LOG_FILENAME = \"scheduler.log\";\nexport const MIGRATION_FAILURES_FILENAME = \"migration-failures.json\";\nexport const KNOWN_WORKSPACES_FILENAME = \"known-workspaces.json\";\n\n/** `~/.serviceme/scheduled-tasks.json` — the global v2 task list. */\nexport function getScheduledTasksConfigPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/scheduled-tasks-log.json` — the global execution log (200 LRU). */\nexport function getScheduledTasksLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_LOG_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.pid` — global daemon PID file. */\nexport function getSchedulerPidPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_PID_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.lock` — global daemon startup flock. */\nexport function getSchedulerLockPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOCK_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.log` — global daemon log (daemon lifecycle, not task execution). */\nexport function getSchedulerLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOG_FILENAME);\n}\n\n/** `~/.serviceme/migration-failures.json` — diagnostics for failed v1→v2 imports. */\nexport function getMigrationFailuresPath(): string {\n\treturn path.join(getServicemeHome(), MIGRATION_FAILURES_FILENAME);\n}\n\n/** `~/.serviceme/known-workspaces.json` — workspace list the extension has seen. */\nexport function getKnownWorkspacesPath(): string {\n\treturn path.join(getServicemeHome(), KNOWN_WORKSPACES_FILENAME);\n}\n\n// ─── r7 BYOM Server Proxy (rev.20) ─────────────────────────────────────────\n\n/**\n * `~/.serviceme/server-proxy.json` — r7 BYOM Server Proxy toggle\n * self-state. Written by the extension's `ProxyConfigService`, readable\n * by the CLI / Server so they can decide whether to route traffic\n * through the corporate proxy without booting VS Code.\n *\n * Lives under user-level `~/.serviceme/` (not under a workspace) because\n * the toggle is a *user preference* — the same human enabling it on\n * machine A should be able to rely on it on machine B after sync, not\n * have it disappear when they switch repos.\n */\nexport function getServerProxyGlobalPath(): string {\n\treturn path.join(getServicemeHome(), SERVER_PROXY_GLOBAL_FILENAME);\n}\n\n// ─── Phase 5 (auth + device + toolbox) placeholders (Spec §11.12) ────────\n\n/** Layout constants for the Phase 5 client-side state files. The server\n * already has the corresponding routes (`/api/v1/auth/...`,\n * `/api/v1/device/...`, etc.) — the client just needs the on-disk\n * file paths + a first-run bootstrap so the auth/device/toolbox\n * services can open + read them without a per-call existence check. */\nexport const CREDENTIALS_CONFIG_FILENAME = \"credentials.json\";\nexport const DEVICE_JSON_FILENAME = \"device.json\";\nexport const TOOLBOX_JSON_FILENAME = \"toolbox.json\";\nexport const MACHINE_ID_FILENAME = \"machine-id\";\nexport const PROFILES_JSON_FILENAME = \"profiles.json\";\n\n/** `~/.serviceme/credentials.json` — better-auth session tokens + refresh state (client-side cache). */\nexport function getCredentialsConfigPath(): string {\n\treturn path.join(getServicemeHome(), CREDENTIALS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/device.json` — device enrollment payload (id, public key fingerprint, claimed-by). */\nexport function getDeviceJsonPath(): string {\n\treturn path.join(getServicemeHome(), DEVICE_JSON_FILENAME);\n}\n\n/** `~/.serviceme/toolbox.json` — local toolbox state (installed tool refs, per-user prefs). */\nexport function getToolboxJsonPath(): string {\n\treturn path.join(getServicemeHome(), TOOLBOX_JSON_FILENAME);\n}\n\n/** `~/.serviceme/machine-id` — opaque stable per-install id (uuid v4 string, no JSON wrapper). */\nexport function getMachineIdPath(): string {\n\treturn path.join(getServicemeHome(), MACHINE_ID_FILENAME);\n}\n\n/** `~/.serviceme/profiles.json` — cached projection of server-side profile rows; refresh on demand. */\nexport function getProfilesJsonPath(): string {\n\treturn path.join(getServicemeHome(), PROFILES_JSON_FILENAME);\n}\n","/**\n * Internal types for the device domain.\n *\n * These types are NOT re-exported from the protocol package — they are\n * implementation details of the IdentityStore + Enroller. Public data\n * models (the bridge wire shape) live in `@serviceme/devtools-protocol`'s\n * `device.ts`.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `device/types.ts`\n */\n\nimport type { DeviceBindingState } from \"@serviceme/devtools-protocol\";\n\n/**\n * Schema version of the on-disk `device.json` file. Bumped when the\n * shape changes incompatibly. IdentityStore checks this on read and\n * either migrates (versions ≤ 1) or refuses (versions > supported).\n */\nexport const DEVICE_JSON_SCHEMA_VERSION = 1;\n\n/** Internal representation of the persisted identity file. */\nexport interface PersistedDeviceIdentity {\n\tversion: number;\n\t/** Stable per-machine id (UUID v4 shape) — survives secret rotates. */\n\tinstallationId: string;\n\t/** Raw `os.hostname()` for diagnostics. */\n\tmachineId: string;\n\t/** Platform string (e.g. \"darwin\"). */\n\tplatform: string;\n\t/** Optional hostname override for environments where `os.hostname()` is unstable. */\n\thostname?: string;\n\t/** Public, non-secret id returned by the server. 32-char hex. */\n\tpublicId: string;\n\t/** Monotonic secret version counter, starts at 1 after first enroll. */\n\tsecretVersion: number;\n\t/** Current binding state — drives the re-enroll matrix. */\n\tbindingState: DeviceBindingState;\n\t/** HMAC secret (32 bytes hex-encoded = 64 chars). Persisted per `device-header-spec.md` §3.1. */\n\tdeviceSecret: string;\n\t/** Optional: previous secret retained during the grace window (rotation). */\n\tpreviousDeviceSecret?: string;\n\t/** Optional: ISO timestamp at which the previous secret stops being accepted. */\n\tpreviousSecretExpiresAt?: string;\n\t/** ISO timestamp of the most recent successful enroll / rotate. */\n\tlastEnrollAt: string;\n\t/** Optional ISO timestamp of the most recent server sync. */\n\tlastSyncAt?: string;\n\t/** Optional human-readable message for the last sync error. */\n\tlastSyncError?: string;\n}\n\n/** Result of a single atomic write. */\nexport interface AtomicWriteResult {\n\tbytesWritten: number;\n\t/** Path to the temp file (post-rename it no longer exists; useful for diagnostics). */\n\ttmpPath: string;\n}\n\n/** Hook called before/after every identity write — used by tests to assert concurrency safety. */\nexport interface IdentityStoreHooks {\n\tbeforeWrite?: (next: PersistedDeviceIdentity) => void | Promise<void>;\n\tafterWrite?: (next: PersistedDeviceIdentity) => void | Promise<void>;\n}\n","/**\n * DeviceCore — Main entry for the device domain.\n *\n * Aggregates `IdentityStore` + `Enroller` + signer helpers into a single\n * surface that the CLI / Extension / Bridge can call. Pure orchestration\n * — no HTTP of its own (the actual `POST /api/v1/devices/enroll` lives\n * behind `EnrollerOptions.enrollRequest`, wired in Phase 5.4).\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `DeviceCore.ts 主入口`\n * - ADL-003 — data model in `@serviceme/devtools-protocol`\n * - `docs/architecture/phase-5-device-header-spec.md` §3.1\n */\n\nimport type {\n\tDeviceEnrollResult,\n\tDeviceIdentityState,\n\tDeviceMetadata,\n\tDeviceRotateSecretResult,\n\tDeviceStatus,\n} from \"@serviceme/devtools-protocol\";\nimport { buildSignedHeaders, DeviceAuthHeaders, type DeviceSignedHeaders } from \"./deviceAuth\";\nimport { Enroller, type EnrollRequestFn } from \"./Enroller\";\nimport { IdentityStore } from \"./IdentityStore\";\nimport { deriveInstallationId } from \"./InstallationId\";\nimport type { PersistedDeviceIdentity } from \"./types\";\n\nexport interface DeviceCoreOptions {\n\tidentityStore?: IdentityStore;\n\tenrollRequest?: EnrollRequestFn;\n\tnow?: () => Date;\n\t/** Optional override for `deriveInstallationId` (used by tests for determinism). */\n\tresolveInstallationId?: () => string;\n}\n\nexport class DeviceCore {\n\tprivate readonly identity: IdentityStore;\n\tprivate readonly enroller: Enroller;\n\tprivate readonly resolveInstallationId: () => string;\n\n\tconstructor(opts: DeviceCoreOptions = {}) {\n\t\tthis.identity = opts.identityStore ?? new IdentityStore();\n\t\tthis.enroller = new Enroller({\n\t\t\tidentityStore: this.identity,\n\t\t\tenrollRequest: opts.enrollRequest,\n\t\t\tnow: opts.now,\n\t\t});\n\t\tthis.resolveInstallationId = opts.resolveInstallationId ?? deriveInstallationId;\n\t}\n\n\t/** Read-only snapshot of the device status (matches `device.status` wire shape). */\n\tasync status(): Promise<DeviceStatus> {\n\t\tconst stored = await this.identity.read();\n\t\treturn stored\n\t\t\t? {\n\t\t\t\t\tbindingState: stored.bindingState,\n\t\t\t\t\tidentity: projectIdentity(stored),\n\t\t\t\t\tmetadata: projectMetadata(stored),\n\t\t\t\t\tlastSyncAt: stored.lastSyncAt,\n\t\t\t\t\tlastSyncError: stored.lastSyncError,\n\t\t\t\t}\n\t\t\t: { bindingState: \"anonymous\" };\n\t}\n\n\t/** Enroll (or re-enroll) the device. */\n\tasync enroll(opts: { force?: boolean; requireAuth?: boolean } = {}): Promise<DeviceEnrollResult> {\n\t\treturn this.enroller.enroll(opts);\n\t}\n\n\t/** Wait for any in-flight enrollment to finish. Use before `buildSignedHeaders` so that a concurrent `syncDeviceInfo` enrollment has time to write the identity to the store. */\n\tasync waitForEnrollment(): Promise<void> {\n\t\tawait this.enroller.waitForEnrollment();\n\t}\n\n\t/** True when an enrollment is currently in-flight. Used by callers to skip triggering a competing enrollment. */\n\tisEnrolling(): boolean {\n\t\treturn this.enroller.isEnrolling();\n\t}\n\n\t/** Rotate the HMAC secret while keeping the previous one for the grace window. */\n\tasync rotateSecret(opts: { gracePeriodDays?: number } = {}): Promise<DeviceRotateSecretResult> {\n\t\tconst result = await this.enroller.rotateSecret(opts);\n\t\tconst stored = await this.identity.read();\n\t\treturn {\n\t\t\t...result,\n\t\t\tgracePeriodEndsAt: stored?.previousSecretExpiresAt,\n\t\t};\n\t}\n\n\t/** Build the canonical 5-header map for an outbound signed request. */\n\tasync buildSignedHeaders(input: {\n\t\tmethod: string;\n\t\tpath: string;\n\t\tbody: string;\n\t}): Promise<DeviceSignedHeaders | null> {\n\t\tconst stored = await this.identity.read();\n\t\tif (!stored) return null;\n\t\treturn buildSignedHeaders({\n\t\t\tmethod: input.method,\n\t\t\tpath: input.path,\n\t\t\tbody: input.body,\n\t\t\tpublicId: stored.publicId,\n\t\t\tdeviceSecret: stored.deviceSecret,\n\t\t\tsecretVersion: stored.secretVersion,\n\t\t});\n\t}\n\n\t/** Raw stored identity (CLI/extension internal use). Test seam too. */\n\tasync readIdentity(): Promise<PersistedDeviceIdentity | null> {\n\t\treturn this.identity.read();\n\t}\n\n\t/** Wipe the local identity (the `--force` path before re-enroll). */\n\tasync clear(): Promise<void> {\n\t\tawait this.identity.clear();\n\t}\n\n\t/** Mark the device as claimed (called by the bridge after a successful claim). */\n\tasync markClaimed(): Promise<void> {\n\t\tawait this.enroller.markClaimed();\n\t}\n\n\t/** Mark the device as expired (server returned an expiry response). */\n\tasync markExpired(): Promise<void> {\n\t\tawait this.enroller.markExpired();\n\t}\n\n\t/** Expose the identity store (CLI uses it for direct file access in tests). */\n\tgetIdentityStore(): IdentityStore {\n\t\treturn this.identity;\n\t}\n\n\t/** Expose the enroller (CLI uses it for state inspection). */\n\tgetEnroller(): Enroller {\n\t\treturn this.enroller;\n\t}\n\n\t/** Header name constants — re-exported from `deviceAuth.ts`. */\n\tgetHeaderNames(): typeof DeviceAuthHeaders {\n\t\treturn DeviceAuthHeaders;\n\t}\n\n\t/** Compute the installation id for the current machine. */\n\tgetInstallationId(): string {\n\t\treturn this.resolveInstallationId();\n\t}\n}\n\nfunction projectIdentity(stored: PersistedDeviceIdentity): DeviceIdentityState {\n\treturn {\n\t\tpublicId: stored.publicId,\n\t\tsecretVersion: stored.secretVersion,\n\t\tbindingState: stored.bindingState,\n\t};\n}\n\nfunction projectMetadata(stored: PersistedDeviceIdentity): DeviceMetadata {\n\treturn {\n\t\tinstallationId: stored.installationId,\n\t\tmachineId: stored.machineId,\n\t\tplatform: stored.platform,\n\t\thostname: stored.hostname,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgBA,yBAA2B;AAGpB,IAAM,oBAAoB;AAAA,EAChC,UAAU;AAAA,EACV,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,eAAe;AAChB;AAiBO,SAAS,6BAA6B,QAA8C;AAC1F,QAAM,QAAQ;AAAA,IACb,OAAO,OAAO,YAAY;AAAA,IAC1B,OAAO;AAAA,IACP,OAAO,OAAO,SAAS;AAAA,IACvB,OAAO;AAAA,IACP,OAAO;AAAA,EACR,E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AAK;AACxC,QAAI,CAAC,OAAQ,QAAO;AACpB,WAAO,mBAAmB;AAAA,MACzB,QAAQ,MAAM;AAAA,MACd,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM;AAAA,MACZ,UAAU,OAAO;AAAA,MACjB,cAAc,OAAO;AAAA,MACrB,eAAe,OAAO;AAAA,IACvB,CAAC;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,eAAwD;AAC7D,WAAO,KAAK,SAAS,KAAK;AAAA,EAC3B;AAAA;AAAA,EAGA,MAAM,QAAuB;AAC5B,UAAM,KAAK,SAAS,MAAM;AAAA,EAC3B;AAAA;AAAA,EAGA,MAAM,cAA6B;AAClC,UAAM,KAAK,SAAS,YAAY;AAAA,EACjC;AAAA;AAAA,EAGA,MAAM,cAA6B;AAClC,UAAM,KAAK,SAAS,YAAY;AAAA,EACjC;AAAA;AAAA,EAGA,mBAAkC;AACjC,WAAO,KAAK;AAAA,EACb;AAAA;AAAA,EAGA,cAAwB;AACvB,WAAO,KAAK;AAAA,EACb;AAAA;AAAA,EAGA,iBAA2C;AAC1C,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,oBAA4B;AAC3B,WAAO,KAAK,sBAAsB;AAAA,EACnC;AACD;AAEA,SAAS,gBAAgB,QAAsD;AAC9E,SAAO;AAAA,IACN,UAAU,OAAO;AAAA,IACjB,eAAe,OAAO;AAAA,IACtB,cAAc,OAAO;AAAA,EACtB;AACD;AAEA,SAAS,gBAAgB,QAAiD;AACzE,SAAO;AAAA,IACN,gBAAgB,OAAO;AAAA,IACvB,WAAW,OAAO;AAAA,IAClB,UAAU,OAAO;AAAA,IACjB,UAAU,OAAO;AAAA,EAClB;AACD;","names":["import_node_crypto","import_node_crypto","platform","os","path","os","delay","stat","platform"]}
|
package/dist/device.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/device/deviceAuth.ts","../src/device/Enroller.ts","../src/device/InstallationId.ts","../src/device/IdentityStore.ts","../src/paths/userHome.ts","../src/device/types.ts","../src/device/DeviceCore.ts"],"sourcesContent":["/**\n * deviceAuth — Pure HMAC-SHA-256 signing helpers for device auth headers.\n *\n * **Boundary exception copy.** The single source of truth for the\n * `x-ms-device-*` header names + the signature algorithm now lives in\n * `@serviceme/devtools-shared` (`device-auth.ts`), consumed by the\n * extension signer and the server verifier. ADL-003 forbids\n * core → shared (and shared → core), so this module keeps a\n * byte-for-byte copy as the documented exception. Keep it in lock-step\n * with `packages/serviceme-shared/src/device-auth.ts`.\n *\n * See `docs/architecture/phase-5-device-header-spec.md` §5 for the wire\n * format. The basis is `METHOD\\nPATH\\nTIMESTAMP\\nBODY\\nSECRET`\n * (LF-joined, NOT JSON). Output is lowercase hex SHA-256.\n */\n\nimport { createHash } from \"node:crypto\";\n\n/** Canonical header names — MUST match `@serviceme/devtools-shared`'s `DeviceAuthHeaders`. */\nexport const DeviceAuthHeaders = {\n\tdeviceId: \"x-ms-device-id\",\n\tdeviceSecret: \"x-ms-device-secret\",\n\tsignature: \"x-ms-device-signature\",\n\ttimestamp: \"x-ms-device-timestamp\",\n\tsecretVersion: \"x-ms-device-secret-version\",\n} as const;\n\nexport interface DeviceRequestSignatureParams {\n\tmethod: string;\n\tpath: string;\n\ttimestamp: number;\n\tbody: string;\n\tsecret: string;\n}\n\n/**\n * Compute the HMAC-SHA-256 hex digest of the canonical basis.\n *\n * Server contract (`apps/server/src/lib/auth/device-signature-guard.ts:46-62`)\n * is line-for-line identical: same LF-joined basis, same lowercase\n * hex output. Any divergence breaks `device-signature-guard.test.ts`.\n */\nexport function createDeviceRequestSignature(params: DeviceRequestSignatureParams): string {\n\tconst basis = [\n\t\tparams.method.toUpperCase(),\n\t\tparams.path,\n\t\tString(params.timestamp),\n\t\tparams.body,\n\t\tparams.secret,\n\t].join(\"\\n\");\n\treturn createHash(\"sha256\").update(basis).digest(\"hex\");\n}\n\n/** 5-header map consumed by `fetch()` callers (CLI bridge, Extension). */\nexport interface DeviceSignedHeaders {\n\t[DeviceAuthHeaders.deviceId]: string;\n\t[DeviceAuthHeaders.deviceSecret]: string;\n\t[DeviceAuthHeaders.signature]: string;\n\t[DeviceAuthHeaders.timestamp]: string;\n\t[DeviceAuthHeaders.secretVersion]: string;\n}\n\nexport interface BuildSignedHeadersParams {\n\tmethod: string;\n\tpath: string;\n\tbody: string;\n\tpublicId: string;\n\tdeviceSecret: string;\n\tsecretVersion: number;\n\t/** Override for deterministic tests. */\n\ttimestamp?: number;\n}\n\n/**\n * Build the canonical 5-header map. The `body` parameter MUST be the\n * exact byte sequence sent on the wire (no whitespace re-canonicalization\n * between client serialization and signature basis construction).\n */\nexport function buildSignedHeaders(params: BuildSignedHeadersParams): DeviceSignedHeaders {\n\tconst timestamp = params.timestamp ?? Date.now();\n\tconst signature = createDeviceRequestSignature({\n\t\tmethod: params.method,\n\t\tpath: params.path,\n\t\ttimestamp,\n\t\tbody: params.body,\n\t\tsecret: params.deviceSecret,\n\t});\n\treturn {\n\t\t[DeviceAuthHeaders.deviceId]: params.publicId,\n\t\t[DeviceAuthHeaders.deviceSecret]: params.deviceSecret,\n\t\t[DeviceAuthHeaders.signature]: signature,\n\t\t[DeviceAuthHeaders.timestamp]: String(timestamp),\n\t\t[DeviceAuthHeaders.secretVersion]: String(params.secretVersion),\n\t};\n}\n","/**\n * Enroller — State machine for `device.enroll` and `device.rotate-secret`.\n *\n * States per `2.需求澄清.md` §1.2:\n * anonymous → pending → claimed → expired\n *\n * - `anonymous` (initial): no device has ever enrolled. Server returns\n * a fresh `publicId` + secret.\n * - `pending`: enrollment HTTP call has been issued but the server\n * hasn't confirmed yet. In-flight state — never persisted.\n * - `claimed`: user has linked this device to their account (via\n * `/api/v1/devices/claim`). Sticky binding locks future re-enrolls\n * to the same `userId` (server-side matrix).\n * - `expired`: server returned a device-expiry error. Forces a fresh\n * enroll on next call.\n *\n * `--force` semantics: any non-anonymous state can be force-reset to\n * `anonymous` by wiping the local identity file. The next enroll will\n * be treated as a brand-new install by the server (no sticky binding).\n *\n * The Enroller is the **state machine**; the actual HTTP I/O is the\n * caller's responsibility (the `DeviceSyncClient` in Phase 5.4 wires\n * the server). This split keeps the Enroller unit-testable without\n * a live server.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `Enroller.ts anonymous → pending → claimed → expired`\n * - `2.需求澄清.md` §1.2 — binding-state machine\n */\n\nimport { randomBytes } from \"node:crypto\";\n\nimport type { DeviceBindingState, DeviceEnrollResult } from \"@serviceme/devtools-protocol\";\nimport type { IdentityStore } from \"./IdentityStore\";\nimport { deriveInstallationId } from \"./InstallationId\";\nimport type { PersistedDeviceIdentity } from \"./types\";\n\n/** 32 bytes of HMAC secret material — matches the server's `device-registration.ts:73-80` generator. */\nconst SECRET_BYTES = 32;\n/** Server returns `publicId` as 32-char hex (16 bytes). Match the wire length. */\nconst PUBLIC_ID_BYTES = 16;\n\ntype RandomBytesFn = (size: number) => Buffer;\n\nconst defaultRandomBytes: RandomBytesFn = (size) => {\n\treturn randomBytes(size);\n};\n\nexport interface EnrollerOptions {\n\tidentityStore: IdentityStore;\n\t/** Injectable clock for deterministic tests. */\n\tnow?: () => Date;\n\t/** Override the random source (tests). */\n\trandomBytes?: (size: number) => Buffer;\n\t/** Caller-supplied enroll HTTP function. Phase 5.4 wires the real one. */\n\tenrollRequest?: EnrollRequestFn;\n}\n\nexport type EnrollRequestFn = (input: {\n\tinstallationId: string;\n\tmachineId: string;\n\tplatform: string;\n\texisting: PersistedDeviceIdentity | null;\n\tforce: boolean;\n\trequireAuth: boolean;\n}) => Promise<EnrollResponse>;\n\nexport interface EnrollResponse {\n\tpublicId: string;\n\tdeviceSecret: string;\n\tsecretVersion: number;\n\tbindingState: DeviceBindingState;\n\texpiresAt?: string;\n}\n\n/** Sentinel error — re-enroll on a claimed device without auth. */\nexport class DeviceReenrollRequiresAuthError extends Error {\n\tconstructor(\n\t\tmessage = \"Re-enroll on a claimed device requires current device credentials or the bound user\"\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"DeviceReenrollRequiresAuthError\";\n\t}\n}\n\n/** Sentinel error — server returned a 410 / version-mismatch after rotation. */\nexport class DeviceSecretVersionMismatchError extends Error {\n\tconstructor(message = \"Device secret version mismatch — server has rotated past the local copy\") {\n\t\tsuper(message);\n\t\tthis.name = \"DeviceSecretVersionMismatchError\";\n\t}\n}\n\nexport class Enroller {\n\tprivate readonly identity: IdentityStore;\n\tprivate readonly now: () => Date;\n\tprivate readonly random: (size: number) => Buffer;\n\tprivate readonly enrollRequest?: EnrollRequestFn;\n\tprivate inflight: Promise<DeviceEnrollResult> | null = null;\n\n\tconstructor(opts: EnrollerOptions) {\n\t\tthis.identity = opts.identityStore;\n\t\tthis.now = opts.now ?? (() => new Date());\n\t\tthis.random = opts.randomBytes ?? defaultRandomBytes;\n\t\tthis.enrollRequest = opts.enrollRequest;\n\t}\n\n\t/**\n\t * Read the current binding state without touching the disk.\n\t * Returns `anonymous` when no identity is stored.\n\t */\n\tasync currentState(): Promise<DeviceBindingState> {\n\t\tconst stored = await this.identity.read();\n\t\treturn stored?.bindingState ?? \"anonymous\";\n\t}\n\n\t/**\n\t * Drive the enrollment flow.\n\t *\n\t * @param force when true, drop the local identity and start fresh\n\t * (server treats this as a brand-new install).\n\t * @param requireAuth when true, refuse to silently re-enroll an\n\t * existing claimed device — throw\n\t * `DeviceReenrollRequiresAuthError` instead.\n\t */\n\t/**\n\t * Resolve when any in-flight enrollment completes. Returns immediately\n\t * when no enrollment is in progress. Allows callers (e.g. the extension's\n\t * `buildDeviceAuthHeaders`) to wait for a concurrent `syncDeviceInfo()`\n\t * enrollment before attempting to read the identity from the store.\n\t */\n\tasync waitForEnrollment(): Promise<void> {\n\t\tif (this.inflight) {\n\t\t\tawait this.inflight;\n\t\t}\n\t}\n\n\tasync enroll(opts: { force?: boolean; requireAuth?: boolean } = {}): Promise<DeviceEnrollResult> {\n\t\t// Concurrency guard — multiple in-flight calls share the same promise.\n\t\tif (this.inflight) {\n\t\t\treturn this.inflight;\n\t\t}\n\t\tconst promise = this.runEnroll(opts);\n\t\tthis.inflight = promise;\n\t\ttry {\n\t\t\treturn await promise;\n\t\t} finally {\n\t\t\tif (this.inflight === promise) this.inflight = null;\n\t\t}\n\t}\n\n\t/** Test seam — surface the underlying identity store. */\n\tgetIdentityStore(): IdentityStore {\n\t\treturn this.identity;\n\t}\n\n\t/** True when an enrollment is currently in-flight. Used by callers (e.g. the extension's `buildDeviceAuthHeaders`) to skip triggering a competing enrollment. */\n\tisEnrolling(): boolean {\n\t\treturn this.inflight !== null;\n\t}\n\n\tprivate async runEnroll(opts: {\n\t\tforce?: boolean;\n\t\trequireAuth?: boolean;\n\t}): Promise<DeviceEnrollResult> {\n\t\tconst { written } = await this.identity.mutate(async (current) => {\n\t\t\tconst existing = opts.force ? null : current;\n\n\t\t\tif (!opts.force && current) {\n\t\t\t\tif (current.bindingState === \"expired\") {\n\t\t\t\t\t// Expired identities are forced to re-enroll as if they were new.\n\t\t\t\t} else if (\n\t\t\t\t\topts.requireAuth &&\n\t\t\t\t\t(current.bindingState === \"claimed\" || current.bindingState === \"pending\")\n\t\t\t\t) {\n\t\t\t\t\t// Caller asserted the device must be claimed, but local state\n\t\t\t\t\t// shows it's still in flight. This is a CLI-only guard — the\n\t\t\t\t\t// server is the final arbiter.\n\t\t\t\t\tthrow new DeviceReenrollRequiresAuthError();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst installationId = current?.installationId ?? deriveInstallationId();\n\t\t\tconst machineId = current?.machineId ?? \"unknown\";\n\t\t\tconst platform = current?.platform ?? \"unknown\";\n\n\t\t\tlet response: EnrollResponse;\n\t\t\tif (this.enrollRequest) {\n\t\t\t\tresponse = await this.enrollRequest({\n\t\t\t\t\tinstallationId,\n\t\t\t\t\tmachineId,\n\t\t\t\t\tplatform,\n\t\t\t\t\texisting,\n\t\t\t\t\tforce: Boolean(opts.force),\n\t\t\t\t\trequireAuth: Boolean(opts.requireAuth),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Test path / no live HTTP — synthesize a fresh identity. This\n\t\t\t\t// branch is what unit tests exercise; production wires\n\t\t\t\t// `enrollRequest` in Phase 5.4.\n\t\t\t\tresponse = synthesizeEnrollResponse(this.random, existing);\n\t\t\t}\n\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\tversion: current?.version ?? 1,\n\t\t\t\tinstallationId,\n\t\t\t\tmachineId,\n\t\t\t\tplatform,\n\t\t\t\thostname: current?.hostname,\n\t\t\t\tpublicId: response.publicId,\n\t\t\t\tsecretVersion: response.secretVersion,\n\t\t\t\tbindingState: response.bindingState,\n\t\t\t\tdeviceSecret: response.deviceSecret,\n\t\t\t\tpreviousDeviceSecret: existing?.deviceSecret,\n\t\t\t\tpreviousSecretExpiresAt:\n\t\t\t\t\topts.force || response.secretVersion === (existing?.secretVersion ?? 0) + 1\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: existing?.previousSecretExpiresAt,\n\t\t\t\tlastEnrollAt: this.now().toISOString(),\n\t\t\t\tlastSyncAt: existing?.lastSyncAt,\n\t\t\t\tlastSyncError: undefined,\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\n\t\treturn {\n\t\t\tpublicId: written.publicId,\n\t\t\tbindingState: written.bindingState,\n\t\t\texpiresAt: deriveExpiresAt(written, this.now),\n\t\t};\n\t}\n\n\t/**\n\t * Rotate the HMAC secret. Keeps the previous secret for the grace\n\t * window (default 7 days per `2.需求澄清.md` §1.2) — the\n\t * `previousSecretExpiresAt` is stamped on the persisted identity.\n\t */\n\tasync rotateSecret(\n\t\topts: { gracePeriodDays?: number } = {}\n\t): Promise<{ publicId: string; secretVersion: number; gracePeriodDays: number }> {\n\t\tconst gracePeriodDays = opts.gracePeriodDays ?? 7;\n\t\tconst now = this.now();\n\t\tconst newSecret = this.random(SECRET_BYTES).toString(\"hex\");\n\n\t\tconst { written } = await this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\tthrow new Error(\"Cannot rotate-secret without a prior enrollment\");\n\t\t\t}\n\t\t\tconst graceExpiresAt = new Date(now.getTime() + gracePeriodDays * 24 * 60 * 60 * 1000);\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\t...current,\n\t\t\t\tdeviceSecret: newSecret,\n\t\t\t\tpreviousDeviceSecret: current.deviceSecret,\n\t\t\t\tpreviousSecretExpiresAt: graceExpiresAt.toISOString(),\n\t\t\t\tsecretVersion: current.secretVersion + 1,\n\t\t\t\tlastEnrollAt: now.toISOString(),\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\n\t\treturn {\n\t\t\tpublicId: written.publicId,\n\t\t\tsecretVersion: written.secretVersion,\n\t\t\tgracePeriodDays,\n\t\t};\n\t}\n\n\t/**\n\t * Mark the device as `expired`. Used when the server returns a\n\t * device-expiry response; the next `enroll()` call forces a fresh\n\t * round-trip.\n\t */\n\tasync markExpired(): Promise<void> {\n\t\tawait this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\t// Nothing to expire.\n\t\t\t\treturn { next: current ?? (await emptyIdentity(this.random)), result: undefined };\n\t\t\t}\n\t\t\tconst next: PersistedDeviceIdentity = { ...current, bindingState: \"expired\" };\n\t\t\treturn { next };\n\t\t});\n\t}\n\n\t/**\n\t * Mark the device as `claimed`. Called by the bridge after a\n\t * successful `device.claim` server response.\n\t */\n\tasync markClaimed(): Promise<void> {\n\t\tawait this.identity.mutate(async (current) => {\n\t\t\tif (!current) {\n\t\t\t\tthrow new Error(\"Cannot mark-claimed without a prior enrollment\");\n\t\t\t}\n\t\t\tconst next: PersistedDeviceIdentity = {\n\t\t\t\t...current,\n\t\t\t\tbindingState: \"claimed\",\n\t\t\t\tlastSyncAt: this.now().toISOString(),\n\t\t\t\tlastSyncError: undefined,\n\t\t\t};\n\t\t\treturn { next };\n\t\t});\n\t}\n}\n\nfunction deriveExpiresAt(_identity: PersistedDeviceIdentity, _now: () => Date): string | undefined {\n\t// No explicit expiry on the server today (per phase-5-device-header-spec.md\n\t// §9 #1: 7-day grace is rotation-only). The shape is here for forward\n\t// compatibility — when the server adds a per-device expiry, this\n\t// pulls the value from the response without changing the call site.\n\treturn undefined;\n}\n\nfunction synthesizeEnrollResponse(\n\trandom: RandomBytesFn,\n\texisting: PersistedDeviceIdentity | null\n): EnrollResponse {\n\tconst publicId = existing?.publicId ?? random(PUBLIC_ID_BYTES).toString(\"hex\");\n\tconst secretVersion = (existing?.secretVersion ?? 0) + 1;\n\treturn {\n\t\tpublicId,\n\t\tdeviceSecret: random(SECRET_BYTES).toString(\"hex\"),\n\t\tsecretVersion,\n\t\tbindingState: existing?.bindingState === \"claimed\" ? \"claimed\" : \"anonymous\",\n\t};\n}\n\nasync function emptyIdentity(random: RandomBytesFn): Promise<PersistedDeviceIdentity> {\n\treturn {\n\t\tversion: 1,\n\t\tinstallationId: deriveInstallationId(),\n\t\tmachineId: \"unknown\",\n\t\tplatform: \"unknown\",\n\t\tpublicId: random(PUBLIC_ID_BYTES).toString(\"hex\"),\n\t\tsecretVersion: 1,\n\t\tbindingState: \"anonymous\",\n\t\tdeviceSecret: random(SECRET_BYTES).toString(\"hex\"),\n\t\tlastEnrollAt: new Date().toISOString(),\n\t};\n}\n","/**\n * InstallationId — Derive a stable per-machine identifier from\n * `os.hostname()` + `os.userInfo()`.\n *\n * Per `docs/architecture/phase-5-auth-device-toolbox.md § P5-2 (并入本文时对应 § P5-2 拆分)` B2,\n * `installationId` MUST survive Extension re-installs but vary across\n * machines. We compute a UUID v5-style hash over hostname + username +\n * platform so the result is:\n * - deterministic (same machine → same id)\n * - collision-resistant (SHA-256, 128-bit truncated)\n * - browser-safe (no PII survives — username never enters output)\n *\n * Note: this intentionally differs from `vscode.env.machineId`, which\n * is per-Extension-install and uses a different algorithm. The two\n * coexist: `installationId` is what gets sent to the server, while\n * `machineId` (raw `os.hostname()`) is for diagnostics.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `InstallationId.ts os.hostname() + os.userInfo() 哈希生成`\n * - 3.功能拆分.md B2 — installationId semantics\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport * as os from \"node:os\";\n\n/** Hex-encoded SHA-256 input. Format: `<hostname>|<username>|<platform>|<nodeVersion>`. */\nfunction fingerprintMaterial(): string {\n\t// `os.userInfo()` is undefined-ish on Windows in some sandboxes; fall\n\t// back to a process env user, then to a constant placeholder. We never\n\t// emit the raw username to the caller — it only enters the hash.\n\tlet username = \"unknown\";\n\ttry {\n\t\tusername = os.userInfo().username;\n\t} catch {\n\t\tusername = process.env.USER ?? process.env.USERNAME ?? \"unknown\";\n\t}\n\treturn [\n\t\tos.hostname(),\n\t\tusername,\n\t\tos.platform(),\n\t\tos.arch(),\n\t\tprocess.versions.node ?? \"unknown\",\n\t].join(\"|\");\n}\n\n/**\n * Returns a deterministic installation id for the current machine.\n * Use this when you need an id that survives Extension reinstalls\n * but stays stable across restarts on the same machine.\n */\nexport function deriveInstallationId(): string {\n\tconst material = fingerprintMaterial();\n\tconst digest = createHash(\"sha256\").update(material).digest(\"hex\");\n\t// Take the first 32 hex chars (128 bits) and reformat as UUID v4-shape\n\t// so the output looks like a UUID to downstream consumers while\n\t// remaining a pure SHA-256 truncation.\n\treturn formatAsV4(digest.slice(0, 32));\n}\n\n/**\n * Returns a random installation id (UUID v4). Use this for fresh\n * installs when no fingerprint input is available (e.g. containerized\n * CI runners where `os.hostname()` is meaningless).\n */\nexport function randomInstallationId(): string {\n\treturn randomUUID();\n}\n\n/** SHA-256 fingerprint material exposed for tests + diagnostics. */\nexport function fingerprintSource(): string {\n\treturn fingerprintMaterial();\n}\n\nfunction formatAsV4(hex32: string): string {\n\t// Stamp version 4 + variant bits per RFC 4122 §4.4. The bits are\n\t// cosmetic — the underlying entropy is still SHA-256.\n\tconst chars = hex32.split(\"\");\n\t// Version nibble (position 12 in canonical UUID, index 13 of the 32-char string).\n\tconst versionIdx = 12;\n\tconst variantIdx = 16;\n\tconst versionChar = (parseInt(chars[versionIdx] ?? \"8\", 16) & 0x0) | 0x4;\n\tchars[versionIdx] = versionChar.toString(16);\n\t// Variant nibble: 10xx → first hex char of the 17th position.\n\tconst variantChar = (parseInt(chars[variantIdx] ?? \"8\", 16) & 0x3) | 0x8;\n\tchars[variantIdx] = variantChar.toString(16);\n\tconst formatted = chars.join(\"\");\n\treturn `${formatted.slice(0, 8)}-${formatted.slice(8, 12)}-${formatted.slice(12, 16)}-${formatted.slice(16, 20)}-${formatted.slice(20, 32)}`;\n}\n","/**\n * IdentityStore — Atomic JSON persistence for the device identity file.\n *\n * Stores the `PersistedDeviceIdentity` (incl. the HMAC secret cleartext)\n * at `~/.serviceme/device.json` (per `phase-5-device-header-spec.md`\n * §3.1). Writes are atomic via `write-tmp + fsync + rename`, matching\n * the `SkillStore` / `ToolboxStore` precedent. Concurrent writes are\n * serialized with a mkdir-based file lock (POSIX-atomic) — proper\n * cross-process locking is deferred to Phase 6+ per the open spec.\n *\n * The file mode is `0600` (owner read/write only) so the cleartext\n * secret stays safe at rest. On Windows the mode hint is a no-op\n * (Windows uses ACLs) but `writeFile` still succeeds.\n *\n * Migration — IdentityStore auto-detects a v0-shape (pre-Phase-5.2)\n * file written by the Extension's old `globalState` blob:\n * { version: 1, claimed: false, publicKeyFingerprint: null }\n * In that case the file is migrated forward to the v1 schema on the\n * next write (the data fields are empty and a fresh enroll is required).\n * The full Extension `globalState` → JSON migration happens in the\n * Phase 5.5 adapter (`apps/extension/.../DeviceService.ts`) since the\n * adapter holds the live `globalState` access.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `IdentityStore.ts 持久化到 ~/.config/serviceme/device.json, 原子写`\n * - `docs/architecture/phase-5-device-header-spec.md` §3.1, §2.5\n */\n\nimport * as fsp from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { getDeviceJsonPath, getServicemeHome } from \"../paths/userHome\";\n\nimport {\n\ttype AtomicWriteResult,\n\tDEVICE_JSON_SCHEMA_VERSION,\n\ttype IdentityStoreHooks,\n\ttype PersistedDeviceIdentity,\n} from \"./types\";\n\nconst FILE_MODE = 0o600;\nconst LOCK_DIR_MODE = 0o700;\nconst DEFAULT_LOCK_TIMEOUT_MS = 5000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\n// `mkdir` (lock acquisition) and writing the pid file are two separate\n// syscalls, so there's a brief window where the lock dir exists but the\n// pid file doesn't yet. A grace period keeps a concurrent acquirer from\n// mistaking that window for an abandoned lock (see `isStaleLock`).\nconst LOCK_STALE_GRACE_MS = 200;\nconst TMP_SUFFIX = \".tmp\";\n\n/**\n * Minimal interface for reading + writing the persisted identity file.\n * Default impl uses `getDeviceJsonPath()` (which honors `SERVICEME_HOME`),\n * but tests can substitute a custom path for isolation.\n */\nexport interface IdentityFileBackend {\n\tread(filePath: string): Promise<PersistedDeviceIdentity | null>;\n\twrite(filePath: string, payload: PersistedDeviceIdentity): Promise<AtomicWriteResult>;\n\texists(filePath: string): Promise<boolean>;\n\tdelete(filePath: string): Promise<void>;\n\tlistDir?(dir: string): Promise<string[]>;\n}\n\nexport interface IdentityStoreOptions {\n\tfilePath?: string;\n\thooks?: IdentityStoreHooks;\n\tlockTimeoutMs?: number;\n\tlockRetryMs?: number;\n\t/** Injectable clock for deterministic tests. */\n\tnow?: () => Date;\n\tbackend?: IdentityFileBackend;\n}\n\n/**\n * Default file backend — uses `node:fs/promises` with the canonical\n * tmp-then-rename atomic-write pattern.\n */\nexport class FsIdentityFileBackend implements IdentityFileBackend {\n\tasync exists(filePath: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait fsp.access(filePath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync read(filePath: string): Promise<PersistedDeviceIdentity | null> {\n\t\ttry {\n\t\t\tconst buf = await fsp.readFile(filePath, \"utf8\");\n\t\t\tconst parsed = JSON.parse(buf) as unknown;\n\t\t\treturn migratePersistedIdentity(parsed);\n\t\t} catch (err) {\n\t\t\tif (isNodeError(err) && err.code === \"ENOENT\") return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync write(filePath: string, payload: PersistedDeviceIdentity): Promise<AtomicWriteResult> {\n\t\tawait fsp.mkdir(path.dirname(filePath), { recursive: true });\n\t\tconst tmpPath = `${filePath}${TMP_SUFFIX}`;\n\t\tconst bytes = Buffer.from(JSON.stringify(payload, null, \"\\t\"), \"utf8\");\n\t\t// Ensure tmp is fresh (in case a previous run died mid-write).\n\t\tawait fsp.rm(tmpPath, { force: true });\n\t\tconst handle = await fsp.open(tmpPath, \"w\", FILE_MODE);\n\t\ttry {\n\t\t\tawait handle.writeFile(bytes);\n\t\t\tawait handle.sync();\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tawait fsp.rename(tmpPath, filePath);\n\t\t// Best-effort chmod for filesystems that ignore mode on create (Windows).\n\t\tawait fsp.chmod(filePath, FILE_MODE).catch(() => undefined);\n\t\treturn { bytesWritten: bytes.byteLength, tmpPath };\n\t}\n\n\tasync delete(filePath: string): Promise<void> {\n\t\tawait fsp.rm(filePath, { force: true });\n\t}\n}\n\n/**\n * Reconcile an unknown on-disk shape into the current `PersistedDeviceIdentity`.\n *\n * - v1 IdentityStore files (current shape) pass through unchanged.\n * - v0 bootstrap files (`{ version: 1, claimed: false, publicKeyFingerprint: null }`)\n * are recognized by their placeholder keys and discarded; the next\n * enroll writes a fresh identity.\n * - Anything else throws — refuse to silently drop user data.\n */\nfunction migratePersistedIdentity(parsed: unknown): PersistedDeviceIdentity | null {\n\tif (!isRecord(parsed)) {\n\t\tthrow new Error(\"device.json: top-level must be an object\");\n\t}\n\tconst version = parsed.version;\n\tif (version === DEVICE_JSON_SCHEMA_VERSION) {\n\t\t// Pre-Phase-5.2 placeholder shape carries `claimed` /\n\t\t// `publicKeyFingerprint` but no real device fields. Recognize\n\t\t// the marker and return null so the next enroll writes fresh data.\n\t\tif (\n\t\t\tparsed.publicId === undefined &&\n\t\t\tparsed.deviceSecret === undefined &&\n\t\t\t(\"claimed\" in parsed || \"publicKeyFingerprint\" in parsed)\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\t// Trust the schema — the writer is also us.\n\t\treturn parsed as unknown as PersistedDeviceIdentity;\n\t}\n\tif (typeof version === \"number\" && version < DEVICE_JSON_SCHEMA_VERSION) {\n\t\t// Pre-Phase-5.2 bootstrap shape — the file is empty placeholder\n\t\t// data; nothing to migrate. Return null to signal \"no identity\".\n\t\treturn null;\n\t}\n\tthrow new Error(`device.json: unsupported schema version ${String(version)}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isNodeError(value: unknown): value is NodeJS.ErrnoException {\n\treturn value instanceof Error && typeof (value as { code?: unknown }).code === \"string\";\n}\n\nconst LOCK_PID_FILE = \"pid\";\n\n/**\n * Check whether a process is still alive (best-effort, cross-platform).\n * Returns `false` for any PID we cannot verify as alive.\n */\nfunction isProcessAlive(pid: number): boolean {\n\ttry {\n\t\t// signal 0 — permission check only, never actually sent\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * mkdir-based advisory file lock with stale-lock recovery.\n *\n * POSIX mkdir is atomic; on Windows modern filesystems (NTFS) it's also\n * atomic at the API level. Sufficient for single-host, single-user\n * scenarios (which is the SERVICEME threat model).\n *\n * Stale lock recovery: a `pid` file inside the lock directory records the\n * owner's PID. On `EEXIST`, if the recorded PID is no longer alive, the\n * lock directory is forcibly removed and acquisition retried immediately.\n * This prevents permanent lockout when a process crashes without calling\n * `release()`.\n */\nclass FileLock {\n\tprivate readonly dirPath: string;\n\tprivate readonly pidFilePath: string;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly retryMs: number;\n\tprivate acquired = false;\n\n\tconstructor(filePath: string, timeoutMs: number, retryMs: number) {\n\t\tthis.dirPath = `${filePath}.lock`;\n\t\tthis.pidFilePath = path.join(this.dirPath, LOCK_PID_FILE);\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.retryMs = retryMs;\n\t}\n\n\tasync acquire(): Promise<void> {\n\t\tconst start = Date.now();\n\t\twhile (true) {\n\t\t\ttry {\n\t\t\t\tawait fsp.mkdir(this.dirPath, { mode: LOCK_DIR_MODE });\n\t\t\t\t// Write PID so a future acquirer can detect if we crash.\n\t\t\t\tawait fsp.writeFile(this.pidFilePath, String(process.pid), \"utf8\").catch(() => undefined);\n\t\t\t\tthis.acquired = true;\n\t\t\t\treturn;\n\t\t\t} catch (err) {\n\t\t\t\tif (!isNodeError(err) || err.code !== \"EEXIST\") {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\t// Lock directory exists — check for stale owner.\n\t\t\t\tconst stale = await this.isStaleLock();\n\t\t\t\tif (stale) {\n\t\t\t\t\tawait fsp.rm(this.dirPath, { recursive: true, force: true });\n\t\t\t\t\t// Retry immediately without counting this iteration against timeout.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (Date.now() - start >= this.timeoutMs) {\n\t\t\t\t\tthrow new Error(`IdentityStore lock acquisition timed out for ${this.dirPath}`);\n\t\t\t\t}\n\t\t\t\tawait delay(this.retryMs);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async isStaleLock(): Promise<boolean> {\n\t\tlet pidStr: string;\n\t\ttry {\n\t\t\tpidStr = await fsp.readFile(this.pidFilePath, \"utf8\");\n\t\t} catch {\n\t\t\t// The pid file may not exist yet because another acquirer just\n\t\t\t// created the lock dir and hasn't finished writing its pid file\n\t\t\t// (mkdir + writeFile is not atomic). Give it a short grace window\n\t\t\t// before concluding the owner crashed between mkdir and writeFile.\n\t\t\ttry {\n\t\t\t\tconst stat = await fsp.stat(this.dirPath);\n\t\t\t\treturn Date.now() - stat.mtimeMs > LOCK_STALE_GRACE_MS;\n\t\t\t} catch {\n\t\t\t\t// Lock dir disappeared concurrently (e.g. released mid-check) —\n\t\t\t\t// not stale, just gone; the caller's next mkdir will succeed.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tconst pid = Number.parseInt(pidStr.trim(), 10);\n\t\tif (!Number.isFinite(pid) || pid <= 0) return true; // malformed pid file → treat as stale\n\t\treturn !isProcessAlive(pid);\n\t}\n\n\tasync release(): Promise<void> {\n\t\tif (!this.acquired) return;\n\t\tthis.acquired = false;\n\t\tawait fsp.rm(this.dirPath, { recursive: true, force: true });\n\t}\n}\n\nexport class IdentityStore {\n\tprivate readonly filePath: string;\n\tprivate readonly backend: IdentityFileBackend;\n\tprivate readonly hooks: IdentityStoreHooks;\n\tprivate readonly lockTimeoutMs: number;\n\tprivate readonly lockRetryMs: number;\n\n\tconstructor(opts: IdentityStoreOptions = {}) {\n\t\tthis.filePath = opts.filePath ?? getDeviceJsonPath();\n\t\tthis.backend = opts.backend ?? new FsIdentityFileBackend();\n\t\tthis.hooks = opts.hooks ?? {};\n\t\tthis.lockTimeoutMs = opts.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;\n\t\tthis.lockRetryMs = opts.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS;\n\t}\n\n\t/** Absolute path to the underlying JSON file (test seam). */\n\tgetFilePath(): string {\n\t\treturn this.filePath;\n\t}\n\n\t/** True when the JSON file already exists on disk. */\n\tasync exists(): Promise<boolean> {\n\t\treturn this.backend.exists(this.filePath);\n\t}\n\n\t/** Read the persisted identity; returns `null` when no identity is stored. */\n\tasync read(): Promise<PersistedDeviceIdentity | null> {\n\t\treturn this.backend.read(this.filePath);\n\t}\n\n\t/**\n\t * Atomically write the given identity. Concurrent writers are\n\t * serialized via the file lock; the read-modify-write happens\n\t * inside the lock so callers can't see a partial state.\n\t */\n\tasync write(next: PersistedDeviceIdentity): Promise<AtomicWriteResult> {\n\t\tawait this.hooks.beforeWrite?.(next);\n\t\tconst lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);\n\t\tawait lock.acquire();\n\t\ttry {\n\t\t\tconst stamped: PersistedDeviceIdentity = {\n\t\t\t\t...next,\n\t\t\t\tversion: DEVICE_JSON_SCHEMA_VERSION,\n\t\t\t};\n\t\t\tconst result = await this.backend.write(this.filePath, stamped);\n\t\t\tawait this.hooks.afterWrite?.(stamped);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tawait lock.release();\n\t\t}\n\t}\n\n\t/**\n\t * Read-modify-write under the same lock. The mutator receives the\n\t * current identity (or `null` on first call) and returns the\n\t * replacement. Throwing inside the mutator aborts the write.\n\t */\n\tasync mutate<T>(\n\t\tmutator: (\n\t\t\tcurrent: PersistedDeviceIdentity | null\n\t\t) => Promise<{ next: PersistedDeviceIdentity; result?: T }>\n\t): Promise<{ result: T | undefined; written: PersistedDeviceIdentity }> {\n\t\tconst lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);\n\t\tawait lock.acquire();\n\t\ttry {\n\t\t\tconst current = await this.backend.read(this.filePath);\n\t\t\tconst { next, result } = await mutator(current);\n\t\t\tconst stamped: PersistedDeviceIdentity = {\n\t\t\t\t...next,\n\t\t\t\tversion: DEVICE_JSON_SCHEMA_VERSION,\n\t\t\t};\n\t\t\tawait this.hooks.beforeWrite?.(stamped);\n\t\t\tawait this.backend.write(this.filePath, stamped);\n\t\t\tawait this.hooks.afterWrite?.(stamped);\n\t\t\treturn { result, written: stamped };\n\t\t} finally {\n\t\t\tawait lock.release();\n\t\t}\n\t}\n\n\t/** Wipe the persisted identity (used by `device.enroll --force`). */\n\tasync clear(): Promise<void> {\n\t\tawait this.backend.delete(this.filePath);\n\t}\n\n\t/**\n\t * Resolve the installation metadata for the current machine.\n\t * Pure helper — no I/O, just `os.*` calls.\n\t */\n\tresolveInstallationMetadata(): Pick<\n\t\tPersistedDeviceIdentity,\n\t\t\"installationId\" | \"machineId\" | \"platform\"\n\t> {\n\t\tconst machineId = os.hostname();\n\t\tconst platform = os.platform();\n\t\t// installationId is derived by `InstallationId.ts` — pass the\n\t\t// caller's already-computed value via `material` so we don't\n\t\t// recompute the SHA twice in a row.\n\t\treturn {\n\t\t\tinstallationId: \"\", // intentionally empty; caller fills via deriveInstallationId()\n\t\t\tmachineId,\n\t\t\tplatform,\n\t\t};\n\t}\n\n\t/**\n\t * Ensure the parent directory exists (`~/.serviceme/`). Idempotent.\n\t * Useful when the bootstrap phase5 placeholder wasn't run yet.\n\t */\n\tasync ensureHome(): Promise<void> {\n\t\tawait fsp.mkdir(getServicemeHome(), { recursive: true });\n\t\tawait fsp.mkdir(path.dirname(this.filePath), { recursive: true });\n\t}\n}\n","import * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n/**\n * SERVICEME user home directory helpers.\n *\n * All paths resolve under {@link getServicemeHome}, which is either the\n * `SERVICEME_HOME` environment variable (when set and non-empty) or\n * `$HOME/.serviceme` on POSIX / `%USERPROFILE%\\.serviceme` on Windows.\n *\n * Tests inject `homeDir` and `servicemeHomeEnv` overrides via\n * {@link setUserHomeOverrides} / {@link resetUserHomeOverrides} so they can\n * exercise the path logic without touching the real user environment.\n */\n\n/** Layout constants — kept in one place so other modules can reuse them. */\nexport const SERVICEME_DIR_NAME = \".serviceme\";\nexport const REPOS_SUBDIR = \"repos\";\nexport const CACHE_SUBDIR = \"cache\";\nexport const DRAFTS_SUBDIR = \"drafts\";\nexport const SKILL_DRAFTS_SUBDIR = \"skills\";\nexport const AGENT_DRAFTS_SUBDIR = \"agents\";\nexport const REPOS_CONFIG_FILENAME = \"repos.json\";\nexport const WORKSPACES_SUBDIR = \"workspaces\";\nexport const WORKSPACE_CONTENT_STATE_FILENAME = \"copilot-content-state.json\";\n\n/** rev.20 — r7 BYOM Server Proxy toggle self-state (read by ext + CLI + server). */\nexport const SERVER_PROXY_GLOBAL_FILENAME = \"server-proxy.json\";\n\n/**\n * Repo id regex — used to validate any `repoId` argument before it is joined\n * into a filesystem path. Keeps path traversal attempts out and gives us a\n * predictable on-disk shape.\n */\nexport const SAFE_REPO_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\n\n/** Environment variable that overrides the user-home root directory. */\nexport const SERVICEME_HOME_ENV = \"SERVICEME_HOME\";\n\n/**\n * Test seam: lets unit tests inject deterministic values for `os.homedir()`\n * and the `SERVICEME_HOME` env override without actually mutating\n * `process.env` (which would leak into other tests).\n */\ninterface UserHomeOverrides {\n\thomeDir?: string | undefined;\n\tservicemeHomeEnv?: string | undefined;\n\tplatform?: NodeJS.Platform | undefined;\n}\n\nlet activeOverrides: UserHomeOverrides = {};\n\nexport function setUserHomeOverrides(overrides: UserHomeOverrides): void {\n\tactiveOverrides = { ...overrides };\n}\n\nexport function resetUserHomeOverrides(): void {\n\tactiveOverrides = {};\n}\n\nfunction resolveHomeDir(): string {\n\tconst injected = activeOverrides.homeDir;\n\tif (injected !== undefined) {\n\t\treturn injected;\n\t}\n\treturn os.homedir();\n}\n\nfunction resolveServicemeHomeEnv(): string | undefined {\n\tconst injected = activeOverrides.servicemeHomeEnv;\n\tif (injected !== undefined) {\n\t\t// Treat empty string as \"not set\" — `process.env` always returns a string\n\t\t// but tests may deliberately pass \"\" to opt out.\n\t\treturn injected.length > 0 ? injected : undefined;\n\t}\n\tconst envValue = process.env[SERVICEME_HOME_ENV];\n\treturn envValue && envValue.length > 0 ? envValue : undefined;\n}\n\nfunction resolvePlatform(): NodeJS.Platform {\n\treturn activeOverrides.platform ?? process.platform;\n}\n\nexport function assertSafeRepoId(repoId: string): string {\n\tif (typeof repoId !== \"string\" || repoId.length === 0 || !SAFE_REPO_ID_PATTERN.test(repoId)) {\n\t\tthrow new Error(\n\t\t\t`Invalid repo id: ${JSON.stringify(repoId)}. ` +\n\t\t\t\t`Must match ${SAFE_REPO_ID_PATTERN} (alphanumeric start, then ` +\n\t\t\t\t`alphanumerics / underscores / hyphens, ≤ 64 chars).`\n\t\t);\n\t}\n\treturn repoId;\n}\n\n/**\n * The raw OS home directory (`os.homedir()`), honoring test overrides\n * ({@link setUserHomeOverrides}). Exported for callers that need a\n * home-relative path *outside* of `~/.serviceme` — e.g. the\n * `~/.agents/{skills,agents}` convention used by `SkillLinker` for\n * user-scope links.\n */\nexport function getHomeDir(): string {\n\treturn resolveHomeDir();\n}\n\n/**\n * Root directory for all SERVICEME user-level state. Resolves to\n * `${SERVICEME_HOME}` when that env var is set, otherwise `${HOME}/.serviceme`\n * (POSIX) or `%USERPROFILE%\\.serviceme` (Windows via `os.homedir`).\n */\nexport function getServicemeHome(): string {\n\tconst override = resolveServicemeHomeEnv();\n\tif (override !== undefined) {\n\t\treturn path.resolve(override);\n\t}\n\treturn path.join(resolveHomeDir(), SERVICEME_DIR_NAME);\n}\n\n/** `$HOME/.serviceme/repos` (or `${SERVICEME_HOME}/repos`). */\nexport function getReposDir(): string {\n\treturn path.join(getServicemeHome(), REPOS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/repos/<repoId>` — validates `repoId` first. */\nexport function getRepoDir(repoId: string): string {\n\treturn path.join(getReposDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/cache` — generic per-user cache. */\nexport function getCacheDir(): string {\n\treturn path.join(getServicemeHome(), CACHE_SUBDIR);\n}\n\n/** `$HOME/.serviceme/cache/<repoId>` — per-repo sync state lives here. */\nexport function getRepoCacheDir(repoId: string): string {\n\treturn path.join(getCacheDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/drafts` — local edits not yet pushed upstream. */\nexport function getDraftsDir(): string {\n\treturn path.join(getServicemeHome(), DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/skills` — local skill drafts. */\nexport function getSkillDraftsDir(): string {\n\treturn path.join(getDraftsDir(), SKILL_DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/agents` — local agent drafts. */\nexport function getAgentDraftsDir(): string {\n\treturn path.join(getDraftsDir(), AGENT_DRAFTS_SUBDIR);\n}\n\n/**\n * `$HOME/.serviceme/repos.json` — the single config entry point for repo\n * metadata. Always under the resolved home root (i.e. follows\n * `SERVICEME_HOME` overrides too).\n */\nexport function getReposConfigPath(): string {\n\treturn path.join(getServicemeHome(), REPOS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/workspaces` — machine-local per-workspace state root. */\nexport function getWorkspacesDir(): string {\n\treturn path.join(getServicemeHome(), WORKSPACES_SUBDIR);\n}\n\n/**\n * Convenience helper for callers that need to switch behaviour on platform\n * (e.g. `SkillLinker` chooses symlink vs junction). Exported mostly so tests\n * can pin the value without touching `process.platform` directly.\n */\nexport function getHomePlatform(): NodeJS.Platform {\n\treturn resolvePlatform();\n}\n\n// ─── Scheduled Tasks paths (added by M1.5.3) ───────────────────────────────\n\n/** Layout constants for scheduled-tasks files. Kept here so other modules\n * can reuse them and the names stay in sync with the design doc. */\nexport const SCHEDULED_TASKS_CONFIG_FILENAME = \"scheduled-tasks.json\";\nexport const SCHEDULED_TASKS_LOG_FILENAME = \"scheduled-tasks-log.json\";\nexport const SCHEDULER_PID_FILENAME = \"scheduler.pid\";\nexport const SCHEDULER_LOCK_FILENAME = \"scheduler.lock\";\nexport const SCHEDULER_LOG_FILENAME = \"scheduler.log\";\nexport const MIGRATION_FAILURES_FILENAME = \"migration-failures.json\";\nexport const KNOWN_WORKSPACES_FILENAME = \"known-workspaces.json\";\n\n/** `~/.serviceme/scheduled-tasks.json` — the global v2 task list. */\nexport function getScheduledTasksConfigPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/scheduled-tasks-log.json` — the global execution log (200 LRU). */\nexport function getScheduledTasksLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_LOG_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.pid` — global daemon PID file. */\nexport function getSchedulerPidPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_PID_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.lock` — global daemon startup flock. */\nexport function getSchedulerLockPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOCK_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.log` — global daemon log (daemon lifecycle, not task execution). */\nexport function getSchedulerLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOG_FILENAME);\n}\n\n/** `~/.serviceme/migration-failures.json` — diagnostics for failed v1→v2 imports. */\nexport function getMigrationFailuresPath(): string {\n\treturn path.join(getServicemeHome(), MIGRATION_FAILURES_FILENAME);\n}\n\n/** `~/.serviceme/known-workspaces.json` — workspace list the extension has seen. */\nexport function getKnownWorkspacesPath(): string {\n\treturn path.join(getServicemeHome(), KNOWN_WORKSPACES_FILENAME);\n}\n\n// ─── r7 BYOM Server Proxy (rev.20) ─────────────────────────────────────────\n\n/**\n * `~/.serviceme/server-proxy.json` — r7 BYOM Server Proxy toggle\n * self-state. Written by the extension's `ProxyConfigService`, readable\n * by the CLI / Server so they can decide whether to route traffic\n * through the corporate proxy without booting VS Code.\n *\n * Lives under user-level `~/.serviceme/` (not under a workspace) because\n * the toggle is a *user preference* — the same human enabling it on\n * machine A should be able to rely on it on machine B after sync, not\n * have it disappear when they switch repos.\n */\nexport function getServerProxyGlobalPath(): string {\n\treturn path.join(getServicemeHome(), SERVER_PROXY_GLOBAL_FILENAME);\n}\n\n// ─── Phase 5 (auth + device + toolbox) placeholders (Spec §11.12) ────────\n\n/** Layout constants for the Phase 5 client-side state files. The server\n * already has the corresponding routes (`/api/v1/auth/...`,\n * `/api/v1/device/...`, etc.) — the client just needs the on-disk\n * file paths + a first-run bootstrap so the auth/device/toolbox\n * services can open + read them without a per-call existence check. */\nexport const CREDENTIALS_CONFIG_FILENAME = \"credentials.json\";\nexport const DEVICE_JSON_FILENAME = \"device.json\";\nexport const TOOLBOX_JSON_FILENAME = \"toolbox.json\";\nexport const MACHINE_ID_FILENAME = \"machine-id\";\nexport const PROFILES_JSON_FILENAME = \"profiles.json\";\n\n/** `~/.serviceme/credentials.json` — better-auth session tokens + refresh state (client-side cache). */\nexport function getCredentialsConfigPath(): string {\n\treturn path.join(getServicemeHome(), CREDENTIALS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/device.json` — device enrollment payload (id, public key fingerprint, claimed-by). */\nexport function getDeviceJsonPath(): string {\n\treturn path.join(getServicemeHome(), DEVICE_JSON_FILENAME);\n}\n\n/** `~/.serviceme/toolbox.json` — local toolbox state (installed tool refs, per-user prefs). */\nexport function getToolboxJsonPath(): string {\n\treturn path.join(getServicemeHome(), TOOLBOX_JSON_FILENAME);\n}\n\n/** `~/.serviceme/machine-id` — opaque stable per-install id (uuid v4 string, no JSON wrapper). */\nexport function getMachineIdPath(): string {\n\treturn path.join(getServicemeHome(), MACHINE_ID_FILENAME);\n}\n\n/** `~/.serviceme/profiles.json` — cached projection of server-side profile rows; refresh on demand. */\nexport function getProfilesJsonPath(): string {\n\treturn path.join(getServicemeHome(), PROFILES_JSON_FILENAME);\n}\n","/**\n * Internal types for the device domain.\n *\n * These types are NOT re-exported from the protocol package — they are\n * implementation details of the IdentityStore + Enroller. Public data\n * models (the bridge wire shape) live in `@serviceme/devtools-protocol`'s\n * `device.ts`.\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `device/types.ts`\n */\n\nimport type { DeviceBindingState } from \"@serviceme/devtools-protocol\";\n\n/**\n * Schema version of the on-disk `device.json` file. Bumped when the\n * shape changes incompatibly. IdentityStore checks this on read and\n * either migrates (versions ≤ 1) or refuses (versions > supported).\n */\nexport const DEVICE_JSON_SCHEMA_VERSION = 1;\n\n/** Internal representation of the persisted identity file. */\nexport interface PersistedDeviceIdentity {\n\tversion: number;\n\t/** Stable per-machine id (UUID v4 shape) — survives secret rotates. */\n\tinstallationId: string;\n\t/** Raw `os.hostname()` for diagnostics. */\n\tmachineId: string;\n\t/** Platform string (e.g. \"darwin\"). */\n\tplatform: string;\n\t/** Optional hostname override for environments where `os.hostname()` is unstable. */\n\thostname?: string;\n\t/** Public, non-secret id returned by the server. 32-char hex. */\n\tpublicId: string;\n\t/** Monotonic secret version counter, starts at 1 after first enroll. */\n\tsecretVersion: number;\n\t/** Current binding state — drives the re-enroll matrix. */\n\tbindingState: DeviceBindingState;\n\t/** HMAC secret (32 bytes hex-encoded = 64 chars). Persisted per `device-header-spec.md` §3.1. */\n\tdeviceSecret: string;\n\t/** Optional: previous secret retained during the grace window (rotation). */\n\tpreviousDeviceSecret?: string;\n\t/** Optional: ISO timestamp at which the previous secret stops being accepted. */\n\tpreviousSecretExpiresAt?: string;\n\t/** ISO timestamp of the most recent successful enroll / rotate. */\n\tlastEnrollAt: string;\n\t/** Optional ISO timestamp of the most recent server sync. */\n\tlastSyncAt?: string;\n\t/** Optional human-readable message for the last sync error. */\n\tlastSyncError?: string;\n}\n\n/** Result of a single atomic write. */\nexport interface AtomicWriteResult {\n\tbytesWritten: number;\n\t/** Path to the temp file (post-rename it no longer exists; useful for diagnostics). */\n\ttmpPath: string;\n}\n\n/** Hook called before/after every identity write — used by tests to assert concurrency safety. */\nexport interface IdentityStoreHooks {\n\tbeforeWrite?: (next: PersistedDeviceIdentity) => void | Promise<void>;\n\tafterWrite?: (next: PersistedDeviceIdentity) => void | Promise<void>;\n}\n","/**\n * DeviceCore — Main entry for the device domain.\n *\n * Aggregates `IdentityStore` + `Enroller` + signer helpers into a single\n * surface that the CLI / Extension / Bridge can call. Pure orchestration\n * — no HTTP of its own (the actual `POST /api/v1/devices/enroll` lives\n * behind `EnrollerOptions.enrollRequest`, wired in Phase 5.4).\n *\n * Refs:\n * - 4.功能规划.md §2.2 — `DeviceCore.ts 主入口`\n * - ADL-003 — data model in `@serviceme/devtools-protocol`\n * - `docs/architecture/phase-5-device-header-spec.md` §3.1\n */\n\nimport type {\n\tDeviceEnrollResult,\n\tDeviceIdentityState,\n\tDeviceMetadata,\n\tDeviceRotateSecretResult,\n\tDeviceStatus,\n} from \"@serviceme/devtools-protocol\";\nimport { buildSignedHeaders, DeviceAuthHeaders, type DeviceSignedHeaders } from \"./deviceAuth\";\nimport { Enroller, type EnrollRequestFn } from \"./Enroller\";\nimport { IdentityStore } from \"./IdentityStore\";\nimport { deriveInstallationId } from \"./InstallationId\";\nimport type { PersistedDeviceIdentity } from \"./types\";\n\nexport interface DeviceCoreOptions {\n\tidentityStore?: IdentityStore;\n\tenrollRequest?: EnrollRequestFn;\n\tnow?: () => Date;\n\t/** Optional override for `deriveInstallationId` (used by tests for determinism). */\n\tresolveInstallationId?: () => string;\n}\n\nexport class DeviceCore {\n\tprivate readonly identity: IdentityStore;\n\tprivate readonly enroller: Enroller;\n\tprivate readonly resolveInstallationId: () => string;\n\n\tconstructor(opts: DeviceCoreOptions = {}) {\n\t\tthis.identity = opts.identityStore ?? new IdentityStore();\n\t\tthis.enroller = new Enroller({\n\t\t\tidentityStore: this.identity,\n\t\t\tenrollRequest: opts.enrollRequest,\n\t\t\tnow: opts.now,\n\t\t});\n\t\tthis.resolveInstallationId = opts.resolveInstallationId ?? deriveInstallationId;\n\t}\n\n\t/** Read-only snapshot of the device status (matches `device.status` wire shape). */\n\tasync status(): Promise<DeviceStatus> {\n\t\tconst stored = await this.identity.read();\n\t\treturn stored\n\t\t\t? {\n\t\t\t\t\tbindingState: stored.bindingState,\n\t\t\t\t\tidentity: projectIdentity(stored),\n\t\t\t\t\tmetadata: projectMetadata(stored),\n\t\t\t\t\tlastSyncAt: stored.lastSyncAt,\n\t\t\t\t\tlastSyncError: stored.lastSyncError,\n\t\t\t\t}\n\t\t\t: { bindingState: \"anonymous\" };\n\t}\n\n\t/** Enroll (or re-enroll) the device. */\n\tasync enroll(opts: { force?: boolean; requireAuth?: boolean } = {}): Promise<DeviceEnrollResult> {\n\t\treturn this.enroller.enroll(opts);\n\t}\n\n\t/** Wait for any in-flight enrollment to finish. Use before `buildSignedHeaders` so that a concurrent `syncDeviceInfo` enrollment has time to write the identity to the store. */\n\tasync waitForEnrollment(): Promise<void> {\n\t\tawait this.enroller.waitForEnrollment();\n\t}\n\n\t/** True when an enrollment is currently in-flight. Used by callers to skip triggering a competing enrollment. */\n\tisEnrolling(): boolean {\n\t\treturn this.enroller.isEnrolling();\n\t}\n\n\t/** Rotate the HMAC secret while keeping the previous one for the grace window. */\n\tasync rotateSecret(opts: { gracePeriodDays?: number } = {}): Promise<DeviceRotateSecretResult> {\n\t\tconst result = await this.enroller.rotateSecret(opts);\n\t\tconst stored = await this.identity.read();\n\t\treturn {\n\t\t\t...result,\n\t\t\tgracePeriodEndsAt: stored?.previousSecretExpiresAt,\n\t\t};\n\t}\n\n\t/** Build the canonical 5-header map for an outbound signed request. */\n\tasync buildSignedHeaders(input: {\n\t\tmethod: string;\n\t\tpath: string;\n\t\tbody: string;\n\t}): Promise<DeviceSignedHeaders | null> {\n\t\tconst stored = await this.identity.read();\n\t\tif (!stored) return null;\n\t\treturn buildSignedHeaders({\n\t\t\tmethod: input.method,\n\t\t\tpath: input.path,\n\t\t\tbody: input.body,\n\t\t\tpublicId: stored.publicId,\n\t\t\tdeviceSecret: stored.deviceSecret,\n\t\t\tsecretVersion: stored.secretVersion,\n\t\t});\n\t}\n\n\t/** Raw stored identity (CLI/extension internal use). Test seam too. */\n\tasync readIdentity(): Promise<PersistedDeviceIdentity | null> {\n\t\treturn this.identity.read();\n\t}\n\n\t/** Wipe the local identity (the `--force` path before re-enroll). */\n\tasync clear(): Promise<void> {\n\t\tawait this.identity.clear();\n\t}\n\n\t/** Mark the device as claimed (called by the bridge after a successful claim). */\n\tasync markClaimed(): Promise<void> {\n\t\tawait this.enroller.markClaimed();\n\t}\n\n\t/** Mark the device as expired (server returned an expiry response). */\n\tasync markExpired(): Promise<void> {\n\t\tawait this.enroller.markExpired();\n\t}\n\n\t/** Expose the identity store (CLI uses it for direct file access in tests). */\n\tgetIdentityStore(): IdentityStore {\n\t\treturn this.identity;\n\t}\n\n\t/** Expose the enroller (CLI uses it for state inspection). */\n\tgetEnroller(): Enroller {\n\t\treturn this.enroller;\n\t}\n\n\t/** Header name constants — re-exported from `deviceAuth.ts`. */\n\tgetHeaderNames(): typeof DeviceAuthHeaders {\n\t\treturn DeviceAuthHeaders;\n\t}\n\n\t/** Compute the installation id for the current machine. */\n\tgetInstallationId(): string {\n\t\treturn this.resolveInstallationId();\n\t}\n}\n\nfunction projectIdentity(stored: PersistedDeviceIdentity): DeviceIdentityState {\n\treturn {\n\t\tpublicId: stored.publicId,\n\t\tsecretVersion: stored.secretVersion,\n\t\tbindingState: stored.bindingState,\n\t};\n}\n\nfunction projectMetadata(stored: PersistedDeviceIdentity): DeviceMetadata {\n\treturn {\n\t\tinstallationId: stored.installationId,\n\t\tmachineId: stored.machineId,\n\t\tplatform: stored.platform,\n\t\thostname: stored.hostname,\n\t};\n}\n"],"mappings":";AAgBA,SAAS,kBAAkB;AAGpB,IAAM,oBAAoB;AAAA,EAChC,UAAU;AAAA,EACV,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,eAAe;AAChB;AAiBO,SAAS,6BAA6B,QAA8C;AAC1F,QAAM,QAAQ;AAAA,IACb,OAAO,OAAO,YAAY;AAAA,IAC1B,OAAO;AAAA,IACP,OAAO,OAAO,SAAS;AAAA,IACvB,OAAO;AAAA,IACP,OAAO;AAAA,EACR,EAAE,KAAK,IAAI;AACX,SAAO,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AACvD;AA2BO,SAAS,mBAAmB,QAAuD;AACzF,QAAM,YAAY,OAAO,aAAa,KAAK,IAAI;AAC/C,QAAM,YAAY,6BAA6B;AAAA,IAC9C,QAAQ,OAAO;AAAA,IACf,MAAM,OAAO;AAAA,IACb;AAAA,IACA,MAAM,OAAO;AAAA,IACb,QAAQ,OAAO;AAAA,EAChB,CAAC;AACD,SAAO;AAAA,IACN,CAAC,kBAAkB,QAAQ,GAAG,OAAO;AAAA,IACrC,CAAC,kBAAkB,YAAY,GAAG,OAAO;AAAA,IACzC,CAAC,kBAAkB,SAAS,GAAG;AAAA,IAC/B,CAAC,kBAAkB,SAAS,GAAG,OAAO,SAAS;AAAA,IAC/C,CAAC,kBAAkB,aAAa,GAAG,OAAO,OAAO,aAAa;AAAA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