A full-featured download manager.
fix(bridge): authenticate safari installation continuity (#2473)
Dr_rOot4051aca79623
diff --git a/docs/bridge-pairing-protocol.md b/docs/bridge-pairing-protocol.mdindex ee8df2f5..41d383e1 100644--- a/docs/bridge-pairing-protocol.md+++ b/docs/bridge-pairing-protocol.md@@ -956,6 +956,70 @@ the first application message, now inside the envelope.---+### 8.1 Safari installation continuity++Safari changes its extension URL host on every browser launch. A transport+Origin therefore cannot identify a long-lived Safari installation. Supporting+servers advertise `X-Motrix-Safari-Continuity: 1` on `/discovery`, exposing that+header to browser clients without changing the strict JSON discovery document.+This is an unauthenticated compatibility hint, never authorization. Updated+Safari clients require support for first pairing; Chromium and Firefox retain+their existing wire behavior.++A Safari installation generates and durably stores one random Ed25519 private+key. The private key never leaves extension storage. A new `pairHello` includes+`safariInstallationKey`, the canonical base64url 32-byte public key, allowed only+for Safari. Append `enc("MBP1/safari-installation/v1") ‖ enc(safariInstallationKey)`+to §6.4's `A_id` (the latter is the ASCII wire string). Successful code confirmation+binds this public key to the credential principal. It proves installation+continuity; it does not raise the `official` / `unverified` identity classification.++A returning client adds this object to `reconnectResponse`:++```json+{ "safariResume": { "installationKey": "<public key>", "proof": "<signature>", "nmTicket": "<optional native ticket object>" } }+```++Let `RT0` be §8's transcript using the **live** transport Origin, `Kpub` the raw+32-byte installation public key, and `D` the §6.4 digest of `nmTicket`, or empty+bytes when absent:++```+RT = RT0 ‖ enc("MBP1/safari-resume/v1") ‖ enc(Kpub) ‖ enc(D)+proof = Ed25519.Sign(Kpriv, enc("MBP1/safari-resume-proof/v1") ‖ S ‖ C ‖ RT)+```++Both reconnect MACs use this extended `RT`. Verify a canonical non-small-order,+prime-subgroup public key and a strict RFC 8032 signature (`zip215: false`). A+bound public key must match exactly; even a same-Origin connection must supply+its proof once enrolled. Replacing the Origin, challenge, instance, credential,+public key, or ticket invalidates authentication. Possession of `mutualKey` alone+cannot enroll a replacement key from a new Origin.++A legacy credential may enroll while its original Origin still matches. Across+Origins, automatic enrollment additionally requires an `official` Safari+credential and a fresh §9 ticket attesting `app.motrix.safari.extension`, bound+to `Kpub`; the signature above proves possession. Expired, replayed, wrong-generation,+wrong-caller, invalid or downgraded tickets cannot authorize migration. The native+request preserves `allowLaunch: false`. A remote legacy credential whose Origin+has already changed requires one explicit code pairing; the new credential then+survives subsequent Safari restarts without native attestation.++Enrollment is durable before `reconnectAccept`, with the credential, principal,+key and authorization epoch rechecked inside the store transaction. Preserve the+credential's original Origin as its routing and revocation identity; authenticate+the current transport Origin separately. Session adoption rechecks the stored+identity's admission/revocation gate. This preserves task routing, keeps browser+profiles separate, and prevents revocation races from resurrecting authorization.++Extension lookup uses backend authority plus Safari installation ID. Legacy+origin-bound entries are read into that namespace without trusting the lookup as+authentication. Only a verified server MAC permits activation, key enrollment and+pruning of stale local rows. Other authorities and installations are untouched.+Historical server approvals remain independently revocable; possession of one+credential does not authorize deleting other server credentials by a claimed+installation ID.+## 9. NM attestation ticketBrowsers pass the calling extension's identity to NM hosts (Chromium: callerdiff --git a/docs/bridge-pairing-protocol.zh-CN.md b/docs/bridge-pairing-protocol.zh-CN.mdindex 927f4329..f805dd25 100644--- a/docs/bridge-pairing-protocol.zh-CN.md+++ b/docs/bridge-pairing-protocol.zh-CN.md@@ -680,6 +680,58 @@ kS2C = HKDF-SHA-256(ikm=mutualKey, salt=S ‖ C, info="MBP1-traffic-s2c", L=32)---+### 8.1 Safari 安装身份连续性++Safari 每次启动都会更换扩展 URL 的 host,因此连接 Origin 不能标识长期+安装身份。支持此能力的服务端在 `/discovery` 返回并向浏览器公开+`X-Motrix-Safari-Continuity: 1`,保持严格 JSON discovery 文档不变。+此标记仅用于兼容性检查,不授予权限。新版 Safari 客户端首次配对要求此+能力;Chromium 与 Firefox 保持原有消息行为。++每个 Safari 安装生成并持久保存一份随机 Ed25519 私钥,私钥只保存在扩展+存储中。新的 `pairHello` 包含仅限 Safari 使用的 `safariInstallationKey`,+即规范 base64url 编码的 32 字节公钥。在 §6.4 的 `A_id` 后追加+`enc("MBP1/safari-installation/v1") ‖ enc(safariInstallationKey)`,后一项编码+ASCII 消息字符串。配对码确认成功后,凭据 principal 绑定该公钥。它证明安装+身份连续性,不提升 `official` / `unverified` 身份等级。++重连客户端在 `reconnectResponse` 中增加:++```json+{ "safariResume": { "installationKey": "<public key>", "proof": "<signature>", "nmTicket": "<optional native ticket object>" } }+```++`RT0` 为按**当前连接 Origin** 计算的 §8 transcript;`Kpub` 为公钥原始+32 字节;`D` 为 `nmTicket` 的 §6.4 digest,无票据时为空字节:++```+RT = RT0 ‖ enc("MBP1/safari-resume/v1") ‖ enc(Kpub) ‖ enc(D)+proof = Ed25519.Sign(Kpriv, enc("MBP1/safari-resume-proof/v1") ‖ S ‖ C ‖ RT)+```++两方向重连 MAC 均使用扩展后的 `RT`。公钥必须为规范编码、非小阶、位于素数+阶子群;签名按严格 RFC 8032 验证(`zip215: false`)。已绑定公钥必须完全+匹配,完成绑定后即使 Origin 相同也不得省略证明。改变 Origin、challenge、+实例、凭据、公钥或票据会导致认证失败。仅持有 `mutualKey` 不足以从新 Origin+注册替代公钥。++旧凭据可在原 Origin 尚未改变时注册公钥。跨 Origin 自动迁移还要求旧凭据+是 `official` Safari 身份,并提供新的 §9 原生票据,证明调用方是+`app.motrix.safari.extension` 且绑定到 `Kpub`;上述签名证明持有对应私钥。+过期、重放、generation 不符、调用方不符、无效或降级的票据均不能授权迁移。+原生请求保持 `allowLaunch: false`。远程旧凭据若 Origin 已变化,需要一次+显式配对码配对,此后新凭据可跨 Safari 重启恢复,无需原生认证。++注册必须在 `reconnectAccept` 前持久完成,并在存储事务中重新检查凭据、+principal、密钥与 authorization epoch。保留凭据最初的 Origin 作为任务路由+和撤销身份,单独认证当前连接 Origin。会话接入再次检查存储身份的准入与撤销+状态,以保留任务路由、隔离浏览器配置文件,并防止撤销竞态恢复授权。++扩展按后端 authority 与 Safari 安装 ID 查找凭据,将旧 Origin 索引读入此+命名空间;查询命中本身不构成认证。只有验证服务端 MAC 后才能激活、保存公钥+绑定及清理本地旧条目,其他后端与安装不受影响。服务端历史授权仍可分别撤销;+持有一个凭据不代表可以凭自报安装 ID 删除其他服务端凭据。+## 9. NM attestation ticket浏览器会把调用方扩展的身份传给 NM host(Chromium:argv 中的 callerdiff --git a/src/core/bridge/__tests__/mbp1-client.ts b/src/core/bridge/__tests__/mbp1-client.tsindex 5c28b957..bc4b5669 100644--- a/src/core/bridge/__tests__/mbp1-client.ts+++ b/src/core/bridge/__tests__/mbp1-client.ts@@ -15,11 +15,12 @@ import { randomBytes } from 'node:crypto'import { request as httpRequest } from 'node:http'import { request as httpsRequest } from 'node:https'import { createMdxpConnection, type MdxpConnection } from '@motrix/mdxp'+import { ed25519 } from '@noble/curves/ed25519.js'import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser } from '@shared/protocol/bridge'import WebSocket, { type RawData } from 'ws'import { principalKey } from '../credential-store'-import { fromBase64Url, toBase64Url } from '../mbp1/canonical'+import { concatBytes, enc, fromBase64Url, toBase64Url } from '../mbp1/canonical'import {DIR_C2S,DIR_S2C,@@ -37,6 +38,7 @@ import {reconnectMacServer,reconnectTrafficKeys,} from '../mbp1/reconnect-mac'+import { bindSafariResume } from '../mbp1/safari-installation'import { deriveW } from '../mbp1/scrypt-w'import {buildTT,@@ -197,6 +199,7 @@ export interface PairAttemptOptions {browser: BrowserclaimedExtensionId: stringclientInstallationId?: string+ safariInstallationKey?: stringticket?: ClientTicket/** Test-only public surface prefix, such as `/bridge`. */routePrefix?: string@@ -323,6 +326,9 @@ export async function startPair(browser: opts.browser,claimedExtensionId: opts.claimedExtensionId,clientInstallationId,+ ...(opts.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: opts.safariInstallationKey }),...(opts.ticket? {nmTicket: opts.ticket.wire,@@ -347,6 +353,9 @@ export async function startPair(verifiedOrigin: opts.transcriptOrigin ?? opts.origin,claimedExtensionId: opts.claimedExtensionId,clientInstallationId,+ ...(opts.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: opts.safariInstallationKey }),}),aad: buildAad(MBP1_PROTOCOL_VERSION,@@ -535,6 +544,8 @@ export async function reconnect(opts: {instanceId: stringcredential: IssuedCredential/** Overrides the credentialId actually sent, for the unknown-id case. */+ safariKey?: Uint8Array+ safariTicket?: unknowncredentialIdOverride?: string/** Corrupts the MAC, for the bad-MAC case. */corruptMac?: boolean@@ -560,16 +571,23 @@ export async function reconnect(opts: {const s = fromBase64Url(challenge.S)const c = random(32)const credentialId = opts.credentialIdOverride ?? opts.credential.credentialId- const rt = buildRT({+ let rt = buildRT({protocolVersion: MBP1_PROTOCOL_VERSION,credentialId,// The caller-supplied principal, not automatically `opts.origin` — see the// doc comment above. This distinction lets tests model both honest drift// and an active stolen-key attacker.browser: opts.credential.browser,- verifiedOrigin: opts.credential.origin,+ verifiedOrigin:+ opts.safariKey === undefined ? opts.credential.origin : opts.origin,instanceId: opts.instanceId,})+ const safariPublicKey =+ opts.safariKey === undefined+ ? undefined+ : toBase64Url(ed25519.getPublicKey(opts.safariKey))+ if (safariPublicKey !== undefined)+ rt = bindSafariResume(rt, safariPublicKey, opts.safariTicket)const mac = reconnectMacClient(opts.credential.mutualKey, s, c, rt)if (opts.corruptMac) {mac[0] ^= 0xff@@ -580,6 +598,22 @@ export async function reconnect(opts: {credentialId,C: toBase64Url(c),mac: toBase64Url(mac),+ ...(opts.safariKey === undefined+ ? {}+ : {+ safariResume: {+ installationKey: safariPublicKey,+ proof: toBase64Url(+ ed25519.sign(+ concatBytes(enc('MBP1/safari-resume-proof/v1'), s, c, rt),+ opts.safariKey+ )+ ),+ ...(opts.safariTicket === undefined+ ? {}+ : { nmTicket: opts.safariTicket }),+ },+ }),})const accept = await wire.takeJson<{ type: string; mac: string }>()diff --git a/src/core/bridge/__tests__/mbp1-transport.test.ts b/src/core/bridge/__tests__/mbp1-transport.test.tsindex 67a3b453..ebf4af0d 100644--- a/src/core/bridge/__tests__/mbp1-transport.test.ts+++ b/src/core/bridge/__tests__/mbp1-transport.test.ts@@ -10,9 +10,11 @@ import {WebSocketBridgeServer,} from '@core/bridge/web-socket-bridge-server'import { ErrorCodes, Notifications } from '@motrix/mdxp'+import { ed25519 } from '@noble/curves/ed25519.js'import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser, ClientIdentity } from '@shared/protocol/bridge'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { toBase64Url } from '../mbp1/canonical'import {type FakeDialogs,makeAllowlist,@@ -173,6 +175,7 @@ async function pairFully(browser?: BrowserclaimedExtensionId?: stringclientInstallationId?: string+ safariInstallationKey?: string} = {}): Promise<{wire: WireClient@@ -183,6 +186,9 @@ async function pairFully(port: h.port,origin: opts.origin ?? OFFICIAL_ORIGIN,browser: opts.browser ?? 'chromium',+ ...(opts.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: opts.safariInstallationKey }),claimedExtensionId: opts.claimedExtensionId ?? OFFICIAL_ID,...(opts.clientInstallationId? { clientInstallationId: opts.clientInstallationId }@@ -2641,3 +2647,74 @@ function closeServer(server.close((err) => (err ? reject(err) : resolve())))}++describe('Safari continuity over a real WebSocket', () => {+ let h: Harness+ beforeEach(async () => {+ h = await makeHarness()+ })+ afterEach(async () => {+ await h.server.stop()+ })++ it('pairs with a signing key, adopts a changed origin under the original identity, and revokes that live connection', async () => {+ const origin = 'safari-web-extension://41cf2a73-eb74-4f1d-a74b-da20e9f24d8b'+ const changed =+ 'safari-web-extension://dc0ebd48-d655-4c58-baca-87b4960e6534'+ const key = new Uint8Array(32).fill(17)+ const paired = await pairFully(h, {+ origin,+ browser: 'safari',+ claimedExtensionId: 'app.motrix.safari.extension',+ safariInstallationKey: toBase64Url(ed25519.getPublicKey(key)),+ })+ expect(+ h.credentials.findForAuth(paired.credential.credentialId)?.principal+ .safariInstallationKey+ ).toBe(toBase64Url(ed25519.getPublicKey(key)))+ paired.wire.ws.close()+ await paired.wire.closed+ const resumed = await reconnect({+ port: h.port,+ origin: changed,+ instanceId: INSTANCE_ID,+ credential: paired.credential,+ safariKey: key,+ })+ const conn = mdxpOverChannel(resumed.wire, resumed.channel)+ const params = initializeParams('app.motrix.safari.extension')+ await conn.sendRequest('motrix/initialize', {+ ...params,+ client: { ...params.client, browser: 'safari' },+ })+ await conn.sendNotification('motrix/initialized', undefined)+ await conn.sendRequest('task/list', {})+ const sessionKey = installationSessionKey(origin, 'safari', 'install-1')+ expect(h.server.getSession(sessionKey)?.conn.isAuthorized()).toBe(true)+ expect(h.authenticated.at(-1)?.identity).toEqual({+ kind: 'extension',+ browser: 'safari',+ extensionId: origin.slice('safari-web-extension://'.length),+ })+ await h.server.revokeExtensionAccess(+ {+ kind: 'extension',+ browser: 'safari',+ extensionId: origin.slice('safari-web-extension://'.length),+ },+ 'user-revoked'+ )+ await resumed.wire.closed+ expect(h.server.getSession(sessionKey)).toBeUndefined()+ await expect(+ reconnect({+ port: h.port,+ origin: changed,+ instanceId: INSTANCE_ID,+ credential: paired.credential,+ safariKey: key,+ })+ ).rejects.toBeInstanceOf(PairAborted)+ conn.dispose()+ })+})diff --git a/src/core/bridge/credential-store.ts b/src/core/bridge/credential-store.tsindex aa362f07..1815b5ac 100644--- a/src/core/bridge/credential-store.ts+++ b/src/core/bridge/credential-store.ts@@ -34,8 +34,17 @@ const CredentialPrincipalSchema = zbrowser: BrowserSchema,verifiedOrigin: z.string().min(1).max(MAX_VERIFIED_ORIGIN_LENGTH),clientInstallationId: z.string().min(1).max(MAX_INSTALLATION_ID_LENGTH),+ safariInstallationKey: z+ .string()+ .regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/)+ .optional(),}).strict()+ .refine(+ (principal) =>+ principal.safariInstallationKey === undefined ||+ principal.browser === 'safari'+ )/** Spec §6.7: a second browser profile is a new principal, so issuing or* rotating one credential never affects another. */@@ -348,6 +357,11 @@ export class Mbp1CredentialStore {!isExpiredAt(c, operationNow))if (slot) {+ if (+ slot.principal.safariInstallationKey !==+ parsedPrincipal.safariInstallationKey+ )+ throw new Error(CommittedExtensionCredentialError.InvalidInput)return {credentialId: slot.credentialId,mutualKeyB64: slot.mutualKeyB64,@@ -384,6 +398,38 @@ export class Mbp1CredentialStore {})}+ /** Register continuity only after MAC, installation proof and migration policy pass.+ * The exact credential and authorization epoch are compared again inside the queue.+ * Its original principal remains the stable routing/revocation identity. */+ async bindSafariInstallation(+ expected: StoredCredential,+ publicKey: string+ ): Promise<void> {+ await this.enqueue(async () => {+ const current = this.credentials.find(+ (c) => c.credentialId === expected.credentialId+ )+ if (+ current?.principal.browser !== 'safari' ||+ current.mutualKeyB64 !== expected.mutualKeyB64 ||+ current.authorizationEpoch !== expected.authorizationEpoch ||+ principalKey(current.principal) !== principalKey(expected.principal) ||+ (current.principal.safariInstallationKey !== undefined &&+ current.principal.safariInstallationKey !== publicKey) ||+ isExpiredAt(current, this.readNow())+ )+ throw new Error('Safari continuity credential changed')+ const principal = parseCredentialPrincipal({+ ...current.principal,+ safariInstallationKey: publicKey,+ })+ if (current.principal.safariInstallationKey === publicKey) return+ await this.persist(+ this.credentials.map((c) => (c === current ? { ...c, principal } : c))+ )+ })+ }+/*** `credentialAck` path (§6.7 step 3): commit durably, then the caller sends* `credentialCommitted`. When the pair flow ran inside an authenticateddiff --git a/src/core/bridge/mbp1/frames.ts b/src/core/bridge/mbp1/frames.tsindex badbe965..612fabf6 100644--- a/src/core/bridge/mbp1/frames.ts+++ b/src/core/bridge/mbp1/frames.ts@@ -135,12 +135,15 @@ export const pairHelloFrameSchema = zbrowser: browserField,claimedExtensionId: asciiString(),clientInstallationId: asciiString(),+ safariInstallationKey: base64UrlBytes(KEY_BYTES).optional(),nmTicket: z.unknown().optional(),ticketBindingKey: base64UrlBytes(KEY_BYTES).optional(),}).strict().refine(- (f) => (f.nmTicket === undefined) === (f.ticketBindingKey === undefined),+ (f) =>+ (f.nmTicket === undefined) === (f.ticketBindingKey === undefined) &&+ (f.safariInstallationKey === undefined || f.browser === 'safari'),{message:'ticketBindingKey is required if and only if nmTicket is present',@@ -265,6 +268,14 @@ export type ReconnectChallengeFrame = z.infer<export const reconnectResponseFrameSchema = z.object({type: z.literal('reconnectResponse'),+ safariResume: z+ .object({+ installationKey: base64UrlBytes(KEY_BYTES),+ proof: base64UrlBytes(SIGNATURE_BYTES),+ nmTicket: z.unknown().optional(),+ })+ .strict()+ .optional(),credentialId: asciiString(),C: base64UrlBytes(NONCE_BYTES),mac: base64UrlBytes(MAC_BYTES),diff --git a/src/core/bridge/mbp1/pair-session.ts b/src/core/bridge/mbp1/pair-session.tsindex 6ccc863d..7aec13bf 100644--- a/src/core/bridge/mbp1/pair-session.ts+++ b/src/core/bridge/mbp1/pair-session.ts@@ -94,6 +94,7 @@ import {} from './spake2-core'import {type TicketReplayCache,+ validateBindingPub,verifyNmTicket,verifyTicketProofStrict,} from './ticket-verify'@@ -238,6 +239,7 @@ interface HelloContext {browser: BrowserclaimedExtensionId: stringclientInstallationId: string+ safariInstallationKey?: stringaId: Uint8Arrayaad: Uint8Arrayidentity: IdentityTriState@@ -455,6 +457,14 @@ export class PairSession {return}+ if (+ frame.safariInstallationKey !== undefined &&+ !validateBindingPub(fromBase64Url(frame.safariInstallationKey))+ ) {+ this.violation()+ return+ }+// §7.3, before any session state, ticket work, or prompt.const admission = this.deps.admit(this.deps.verifiedOrigin)if (!admission.ok) {@@ -493,6 +503,9 @@ export class PairSession {verifiedOrigin: this.deps.verifiedOrigin,claimedExtensionId: frame.claimedExtensionId,clientInstallationId: frame.clientInstallationId,+ ...(frame.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: frame.safariInstallationKey }),})} catch {this.fail('pairingFailed')@@ -503,6 +516,9 @@ export class PairSession {browser: frame.browser,claimedExtensionId: frame.claimedExtensionId,clientInstallationId: frame.clientInstallationId,+ ...(frame.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: frame.safariInstallationKey }),aId,aad,identity: resolved.identity,@@ -913,6 +929,9 @@ export class PairSession {browser: this.deps.browser,verifiedOrigin: this.deps.verifiedOrigin,clientInstallationId: this.hello.clientInstallationId,+ ...(this.hello.safariInstallationKey === undefined+ ? {}+ : { safariInstallationKey: this.hello.safariInstallationKey }),}let offer: { credentialId: string; mutualKeyB64: string }diff --git a/src/core/bridge/mbp1/reconnect-session.ts b/src/core/bridge/mbp1/reconnect-session.tsindex 25a7e268..c71ef5df 100644--- a/src/core/bridge/mbp1/reconnect-session.ts+++ b/src/core/bridge/mbp1/reconnect-session.ts@@ -56,6 +56,8 @@ import {reconnectMacServer,reconnectTrafficKeys,} from './reconnect-mac'+import { bindSafariResume, verifySafariResume } from './safari-installation'+import { type TicketContext, verifyNmTicket } from './ticket-verify'/** The whole challenge–response must complete within this many ms of `start()` (§8). */const RECONNECT_DEADLINE_MS = 10_000@@ -87,6 +89,10 @@ export interface ReconnectCredentialAuthenticator {* whose `state` is `provisional` — the store rejects anything else.*/promoteOnReconnect(credentialId: string): Promise<void>+ bindSafariInstallation?(+ expected: StoredCredential,+ publicKey: string+ ): Promise<void>}export interface ReconnectSessionDeps {@@ -94,6 +100,10 @@ export interface ReconnectSessionDeps {verifiedOrigin: stringbrowser: BrowserinstanceId: string+ safariTicketContext?: Pick<+ TicketContext,+ 'localToken' | 'serverGeneration' | 'replay'+ >credentials: ReconnectCredentialAuthenticatorsendText(json: object): voidclose(reason: string): void@@ -244,6 +254,12 @@ export class ReconnectSession {verifiedOrigin: this.deps.verifiedOrigin,instanceId: this.deps.instanceId,})+ if (parsed.data.safariResume)+ rt = bindSafariResume(+ rt,+ parsed.data.safariResume.installationKey,+ parsed.data.safariResume.nmTicket+ )key =credential === null? DUMMY_MUTUAL_KEY@@ -263,8 +279,52 @@ export class ReconnectSession {rt,presentedMac)- const principalMatches =+ const resume = parsed.data.safariResume+ let principalMatches =credential !== null && this.matchesLivePrincipal(credential)+ if (resume !== undefined) {+ principalMatches = false+ if (+ macOk &&+ credential !== null &&+ this.deps.browser === 'safari' &&+ credential.principal.browser === 'safari' &&+ verifySafariResume(+ resume.installationKey,+ resume.proof,+ this.challengeS,+ c,+ rt+ )+ ) {+ const bound = credential.principal.safariInstallationKey+ if (bound !== undefined) {+ principalMatches = bound === resume.installationKey+ } else if (+ credential.principal.verifiedOrigin === this.deps.verifiedOrigin+ ) {+ principalMatches = true+ } else if (+ resume.nmTicket !== undefined &&+ credential.identity === 'official' &&+ this.deps.safariTicketContext+ ) {+ const verdict = verifyNmTicket(resume.nmTicket, {+ ...this.deps.safariTicketContext,+ nowMs: this.deps.now(),+ helloBrowser: 'safari',+ helloClaimedExtensionId: 'app.motrix.safari.extension',+ helloTicketBindingKey: fromBase64Url(resume.installationKey),+ })+ principalMatches =+ verdict.kind === 'attested' &&+ verdict.callerId === 'app.motrix.safari.extension'+ }+ }+ } else if (credential?.principal.safariInstallationKey !== undefined) {+ // Once continuity is enrolled, an origin match cannot strip its proof.+ principalMatches = false+ }if (credential === null || !macOk || !principalMatches) {this.fail('authFailed')@@ -311,7 +371,11 @@ export class ReconnectSession {this.terminate('reconnectPromotedCredentialMissing')return}- if (!this.matchesLivePrincipal(promoted)) {+ if (+ JSON.stringify(promoted.principal) !==+ JSON.stringify(credential.principal) ||+ promoted.mutualKeyB64 !== credential.mutualKeyB64+ ) {// A store replacement/race must not change the principal between MAC// verification and adoption. Keep the peer-facing result uniform with// every other credential authentication failure.@@ -321,6 +385,36 @@ export class ReconnectSession {authenticated = promoted}+ if (resume !== undefined) {+ if (!this.deps.credentials.bindSafariInstallation) {+ this.fail('authFailed')+ return+ }+ try {+ await this.deps.credentials.bindSafariInstallation(+ authenticated,+ resume.installationKey+ )+ } catch {+ this.fail('authFailed')+ return+ }+ if (this.state !== 'processing') return+ const current = this.deps.credentials.findForAuth(+ authenticated.credentialId+ )+ if (+ !current ||+ current.principal.safariInstallationKey !== resume.installationKey ||+ current.mutualKeyB64 !== authenticated.mutualKeyB64 ||+ current.authorizationEpoch !== authenticated.authorizationEpoch+ ) {+ this.fail('authFailed')+ return+ }+ authenticated = current+ }+// §8's 10 s deadline covers the whole exchange, including the durable// promotion await above — never send an accept the client's own deadline// has already abandoned. The promotion itself stands either way (§6.7diff --git a/src/core/bridge/mbp1/safari-continuity.test.ts b/src/core/bridge/mbp1/safari-continuity.test.tsnew file mode 100644index 00000000..e854dfaf--- /dev/null+++ b/src/core/bridge/mbp1/safari-continuity.test.ts@@ -0,0 +1,318 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { ed25519 } from '@noble/curves/ed25519.js'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { Mbp1CredentialStore, type StoredCredential } from '../credential-store'+import {+ concatBytes,+ enc,+ fromBase64Url,+ hmacSha256,+ toBase64Url,+} from './canonical'+import { buildRT, reconnectMacClient } from './reconnect-mac'+import { ReconnectSession } from './reconnect-session'+import { bindSafariResume } from './safari-installation'+import {+ deriveTicketKey,+ TicketReplayCache,+ ticketMacInput,+} from './ticket-verify'++const oldOrigin = 'safari-web-extension://41cf2a73-eb74-4f1d-a74b-da20e9f24d8b'+const newOrigin = 'safari-web-extension://dc0ebd48-d655-4c58-baca-87b4960e6534'+const instanceId = 'fixture-instance'+const secret = new Uint8Array(32).fill(17)+const publicKey = toBase64Url(ed25519.getPublicKey(secret))+const folders: string[] = []+afterEach(async () => {+ await Promise.all(+ folders.splice(0).map((path) => rm(path, { recursive: true, force: true }))+ )+})++async function fixture(+ enrolled = true,+ identity: 'official' | 'unverified' = 'official'+) {+ const dir = await mkdtemp(join(tmpdir(), 'motrix-safari-continuity-'))+ folders.push(dir)+ const file = join(dir, 'credentials.json')+ const store = await Mbp1CredentialStore.load(file)+ const principal = {+ browser: 'safari' as const,+ verifiedOrigin: oldOrigin,+ clientInstallationId: 'installation-a',+ ...(enrolled ? { safariInstallationKey: publicKey } : {}),+ }+ const offer = await store.offerProvisional(principal, identity)+ await store.commitFromPair(offer.credentialId)+ const credential = store.findForAuth(offer.credentialId)+ if (!credential) throw new Error('Missing fixture credential')+ return { file, store, credential }+}++function ticket(overrides: Record<string, unknown> = {}) {+ const fields = {+ v: 1,+ purpose: 'mbp1-attestation',+ protocolVersion: 1,+ serverGeneration: 'generation',+ browser: 'safari',+ callerId: 'app.motrix.safari.extension',+ exp: Math.floor(Date.now() / 1000) + 30,+ bindingPub: ed25519.getPublicKey(secret),+ ...overrides,+ }+ return {+ ...fields,+ bindingPub: toBase64Url(fields.bindingPub),+ mac: toBase64Url(+ hmacSha256(deriveTicketKey('local-token'), ticketMacInput(fields))+ ),+ }+}++async function resume(+ store: Mbp1CredentialStore,+ credential: StoredCredential,+ options: {+ origin?: string+ signingKey?: Uint8Array+ proof?: boolean+ nmTicket?: unknown+ replay?: TicketReplayCache+ mutate?: (frame: Record<string, unknown>) => void+ } = {}+) {+ const origin = options.origin ?? newOrigin+ const frames: Record<string, unknown>[] = []+ let authenticated: StoredCredential | null = null+ const s = new Uint8Array(32).fill(23)+ const c = new Uint8Array(32).fill(37)+ const session = new ReconnectSession({+ browser: 'safari',+ verifiedOrigin: origin,+ instanceId,+ credentials: store,+ safariTicketContext: {+ localToken: 'local-token',+ serverGeneration: 'generation',+ replay: options.replay ?? new TicketReplayCache(),+ },+ now: Date.now,+ random: () => s,+ close: () => {},+ sendText: (frame) => frames.push(frame as Record<string, unknown>),+ onAuthenticated: (_channel, value) => {+ authenticated = value+ },+ })+ session.start()+ let rt = buildRT({+ protocolVersion: 1,+ credentialId: credential.credentialId,+ browser: 'safari',+ verifiedOrigin: origin,+ instanceId,+ })+ const key = options.signingKey ?? secret+ const pub = toBase64Url(ed25519.getPublicKey(key))+ if (options.proof !== false) rt = bindSafariResume(rt, pub, options.nmTicket)+ const frame: Record<string, unknown> = {+ type: 'reconnectResponse',+ credentialId: credential.credentialId,+ C: toBase64Url(c),+ mac: toBase64Url(+ reconnectMacClient(fromBase64Url(credential.mutualKeyB64), s, c, rt)+ ),+ ...(options.proof === false+ ? {}+ : {+ safariResume: {+ installationKey: pub,+ proof: toBase64Url(+ ed25519.sign(+ concatBytes(enc('MBP1/safari-resume-proof/v1'), s, c, rt),+ key+ )+ ),+ ...(options.nmTicket === undefined+ ? {}+ : { nmTicket: options.nmTicket }),+ },+ }),+ }+ options.mutate?.(frame)+ const json = JSON.stringify(frame)+ await session.handleText(json, Buffer.byteLength(json))+ session.dispose('socket-closed')+ return { frames, authenticated }+}++describe('Safari origin continuity', () => {+ it('survives repeated browser and backend restarts while preserving routing and revocation identity', async () => {+ const f = await fixture()+ const first = await resume(f.store, f.credential)+ expect(first.authenticated).toMatchObject({+ principal: f.credential.principal,+ authorizationEpoch: f.credential.authorizationEpoch,+ })+ const reloaded = await Mbp1CredentialStore.load(f.file)+ const second = await resume(reloaded, f.credential, {+ origin: 'safari-web-extension://080fc68d-07a6-46aa-8525-3debc6d0ee01',+ })+ expect(second.frames.at(-1)?.type).toBe('reconnectAccept')+ })++ it.each([oldOrigin, newOrigin])(+ 'rejects proof stripping even with a valid mutual-key MAC (%s)',+ async (origin) => {+ const f = await fixture()+ const result = await resume(f.store, f.credential, {+ origin,+ proof: false,+ })+ expect(result.frames.at(-1)).toEqual({+ type: 'pairError',+ code: 'authFailed',+ })+ expect(result.authenticated).toBeNull()+ }+ )++ it('rejects a stolen mutual key used with another installation key', async () => {+ const f = await fixture()+ expect(+ (+ await resume(f.store, f.credential, {+ signingKey: new Uint8Array(32).fill(18),+ })+ ).authenticated+ ).toBeNull()+ })++ it('rejects a forged signature even when the credential MAC is valid', async () => {+ const f = await fixture()+ const result = await resume(f.store, f.credential, {+ mutate: (frame) => {+ ;(frame.safariResume as { proof: string }).proof = toBase64Url(+ new Uint8Array(64)+ )+ },+ })+ expect(result.authenticated).toBeNull()+ })++ it('requires fresh native attestation to migrate a legacy official credential across origins', async () => {+ const f = await fixture(false)+ expect((await resume(f.store, f.credential)).authenticated).toBeNull()+ expect(+ f.store.findForAuth(f.credential.credentialId)?.principal+ .safariInstallationKey+ ).toBeUndefined()+ const result = await resume(f.store, f.credential, { nmTicket: ticket() })+ expect(result.authenticated).toMatchObject({+ principal: {+ verifiedOrigin: oldOrigin,+ safariInstallationKey: publicKey,+ },+ })+ const loaded = await Mbp1CredentialStore.load(f.file)+ expect(+ (+ await resume(+ loaded,+ loaded.findForAuth(f.credential.credentialId) as StoredCredential+ )+ ).authenticated+ ).not.toBeNull()+ })++ it.each([+ { serverGeneration: 'old-generation' },+ { callerId: 'another.extension' },+ { browser: 'firefox' },+ { exp: 1 },+ ])('rejects unusable native migration evidence: %j', async (overrides) => {+ const f = await fixture(false)+ expect(+ (await resume(f.store, f.credential, { nmTicket: ticket(overrides) }))+ .authenticated+ ).toBeNull()+ })++ it('does not use official native evidence to raise an unverified legacy identity', async () => {+ const f = await fixture(false, 'unverified')+ expect(+ (await resume(f.store, f.credential, { nmTicket: ticket() }))+ .authenticated+ ).toBeNull()+ })++ it('can enroll a remote legacy credential only while its original origin still matches', async () => {+ const f = await fixture(false, 'unverified')+ expect(+ (await resume(f.store, f.credential, { origin: oldOrigin })).authenticated+ ).not.toBeNull()+ const current = f.store.findForAuth(+ f.credential.credentialId+ ) as StoredCredential+ expect((await resume(f.store, current)).authenticated).not.toBeNull()+ })++ it('does not resurrect a revoked credential during continuity enrollment', async () => {+ const f = await fixture(false)+ await f.store.revokeExtensionIdentity(+ 'safari',+ oldOrigin.slice('safari-web-extension://'.length)+ )+ await expect(+ f.store.bindSafariInstallation(f.credential, publicKey)+ ).rejects.toThrow()+ expect(+ (await resume(f.store, f.credential, { nmTicket: ticket() }))+ .authenticated+ ).toBeNull()+ })+ it('consumes a migration ticket once even when another valid credential and signature are supplied', async () => {+ const f = await fixture(false)+ const replay = new TicketReplayCache()+ const nmTicket = ticket()+ expect(+ (await resume(f.store, f.credential, { nmTicket, replay })).authenticated+ ).not.toBeNull()+ const next = await f.store.offerProvisional(+ {+ browser: 'safari',+ verifiedOrigin: oldOrigin,+ clientInstallationId: 'installation-b',+ },+ 'official'+ )+ await f.store.commitFromPair(next.credentialId)+ const other = f.store.findForAuth(next.credentialId) as StoredCredential+ expect(+ (await resume(f.store, other, { nmTicket, replay })).authenticated+ ).toBeNull()+ })++ it('rechecks revocation after signature verification and before sending an accept', async () => {+ const f = await fixture(false)+ const bind = f.store.bindSafariInstallation.bind(f.store)+ vi.spyOn(f.store, 'bindSafariInstallation').mockImplementation(+ async (expected, key) => {+ await f.store.revoke(expected.credentialId)+ await bind(expected, key)+ }+ )+ const result = await resume(f.store, f.credential, { nmTicket: ticket() })+ expect(result.authenticated).toBeNull()+ expect(result.frames.at(-1)).toEqual({+ type: 'pairError',+ code: 'authFailed',+ })+ expect(f.store.findForAuth(f.credential.credentialId)).toBeNull()+ })+})diff --git a/src/core/bridge/mbp1/safari-installation.ts b/src/core/bridge/mbp1/safari-installation.tsnew file mode 100644index 00000000..b23ebe08--- /dev/null+++ b/src/core/bridge/mbp1/safari-installation.ts@@ -0,0 +1,47 @@+import { ed25519 } from '@noble/curves/ed25519.js'+import { concatBytes, enc, fromBase64Url } from './canonical'+import { nmTicketWireSchema } from './frames'+import { validateBindingPub } from './ticket-verify'+import { ticketDigest } from './transcript'++export function bindSafariResume(+ rt: Uint8Array,+ publicKey: string,+ nmTicket?: unknown+): Uint8Array {+ let digest: Uint8Array = new Uint8Array()+ if (nmTicket !== undefined) {+ const ticket = nmTicketWireSchema.parse(nmTicket)+ digest = ticketDigest({+ ...ticket,+ bindingPub: fromBase64Url(ticket.bindingPub),+ mac: fromBase64Url(ticket.mac),+ })+ }+ return concatBytes(+ rt,+ enc('MBP1/safari-resume/v1'),+ enc(fromBase64Url(publicKey)),+ enc(digest)+ )+}++export function verifySafariResume(+ publicKey: string,+ proof: string,+ s: Uint8Array,+ c: Uint8Array,+ rt: Uint8Array+): boolean {+ try {+ if (!validateBindingPub(fromBase64Url(publicKey))) return false+ return ed25519.verify(+ fromBase64Url(proof),+ concatBytes(enc('MBP1/safari-resume-proof/v1'), s, c, rt),+ fromBase64Url(publicKey),+ { zip215: false }+ )+ } catch {+ return false+ }+}diff --git a/src/core/bridge/mbp1/transcript.ts b/src/core/bridge/mbp1/transcript.tsindex 380c8c74..3b4ca54d 100644--- a/src/core/bridge/mbp1/transcript.ts+++ b/src/core/bridge/mbp1/transcript.ts@@ -22,13 +22,17 @@ export function buildAId(f: {verifiedOrigin: stringclaimedExtensionId: stringclientInstallationId: string+ safariInstallationKey?: string}): Uint8Array {return concatBytes(enc(A_ID_LABEL),enc(f.browser),enc(f.verifiedOrigin),enc(f.claimedExtensionId),- enc(f.clientInstallationId)+ enc(f.clientInstallationId),+ ...(f.safariInstallationKey === undefined+ ? []+ : [enc('MBP1/safari-installation/v1'), enc(f.safariInstallationKey)]))}diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex 7eddb954..e80b65a3 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -706,7 +706,6 @@ export class WebSocketBridgeServer {socket,head,peer,- identity,mbp1,route.releaseAdmission ?? (() => undefined))@@ -736,6 +735,11 @@ export class WebSocketBridgeServer {res.end()return}+ res.setHeader('X-Motrix-Safari-Continuity', '1')+ res.setHeader(+ 'Access-Control-Expose-Headers',+ 'X-Motrix-Safari-Continuity'+ )writeJson(res, 200, {app: 'motrix-bridge',apiVersion: 1,@@ -2027,7 +2031,6 @@ export class WebSocketBridgeServer {socket: Duplex,head: Buffer,peer: ExtensionPeer,- identity: ClientIdentity & { kind: 'extension' },mbp1: Mbp1Wiring,releaseAdmission: () => void): void {@@ -2075,6 +2078,11 @@ export class WebSocketBridgeServer {ws.on('error', () => {})const session = new ReconnectSession({+ safariTicketContext: {+ localToken: this.opts.localToken,+ serverGeneration: mbp1.serverGeneration,+ replay: this.replay,+ },verifiedOrigin: peer.origin,// Derived from the Origin scheme, never from a stored or claimed// field: §8 binds the live connection's values into the MAC.@@ -2087,9 +2095,24 @@ export class WebSocketBridgeServer {detachPreAuth()this.preAuthReconnect.settle(entry)entry.releaseAdmission()+ const authenticatedTransport = transportIdentityForPrincipal(+ credential.principal+ )+ if (!authenticatedTransport) {+ ws.close()+ return+ }+ const authenticatedIdentity = {+ kind: 'extension' as const,+ ...authenticatedTransport,+ }+ if (!this.canAdmitExtensionIdentity(authenticatedIdentity)) {+ ws.close()+ return+ }this.adoptAuthenticatedSession(ws,- identity,+ authenticatedIdentity,channel,credential.credentialId)