dsh-remote-plugin 0.8.8 → 0.9.1

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.
Files changed (66) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +583 -84
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +97 -10
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/announcements.json +36 -0
  11. package/public/app.js +1564 -226
  12. package/public/bc-integration.css +81 -0
  13. package/public/build.json +2 -2
  14. package/public/composer-tools.css +184 -0
  15. package/public/composer-tools.js +888 -0
  16. package/public/desktop/desktop.html +94 -73
  17. package/public/desktop/desktop.js +726 -83
  18. package/public/e2ee-config.js +5 -0
  19. package/public/e2ee-transport.js +23 -4
  20. package/public/file-inbox.js +77 -18
  21. package/public/genui.css +10 -0
  22. package/public/genui.js +22 -4
  23. package/public/history.js +114 -17
  24. package/public/host-queue.js +232 -0
  25. package/public/host-schedule.js +301 -0
  26. package/public/host-state.css +19 -0
  27. package/public/index.html +332 -140
  28. package/public/md.js +21 -1
  29. package/public/network.js +33 -1
  30. package/public/onboarding.js +3 -3
  31. package/public/operations.js +4 -3
  32. package/public/plan-review.css +297 -0
  33. package/public/plan-review.js +642 -0
  34. package/public/plugin.html +29 -28
  35. package/public/relay-autopair.js +30 -10
  36. package/public/relay-devices.js +7 -3
  37. package/public/relay-settings.css +11 -0
  38. package/public/relay-settings.js +372 -30
  39. package/public/session-cache.js +85 -0
  40. package/public/session-management.css +61 -0
  41. package/public/session-management.js +742 -0
  42. package/public/session-search.css +137 -0
  43. package/public/session-search.js +977 -0
  44. package/public/skins/blue-fish/preview.html +3 -3
  45. package/public/skins/bocchi/preview.html +5 -5
  46. package/public/skins/kita/preview.html +6 -6
  47. package/public/skins/miku/SOURCES.json +10 -0
  48. package/public/skins/miku/chibi.png +0 -0
  49. package/public/skins/miku/preview.html +33 -0
  50. package/public/skins/miku/skin.css +82 -0
  51. package/public/skins/nijika/preview.html +6 -6
  52. package/public/skins/penguin/preview.html +3 -3
  53. package/public/skins/ryo/preview.html +6 -6
  54. package/public/slash-suggestions.js +15 -3
  55. package/public/sponsor-entry.js +11 -3
  56. package/public/styles.css +141 -21
  57. package/public/subagents.css +5 -0
  58. package/public/subagents.js +52 -0
  59. package/public/theme-vars.css +65 -1
  60. package/public/theme.js +4 -3
  61. package/public/turn-diff.css +323 -0
  62. package/public/turn-diff.js +778 -0
  63. package/public/update.json +12 -12
  64. package/public/version.json +1 -1
  65. package/public/workflow.css +305 -34
  66. package/public/workflow.js +141 -41
@@ -1,6 +1,7 @@
1
1
  /* Shared settings for the host-owned relay; no credentials enter browser storage. */
2
2
  ;(function(root) {
3
3
  'use strict'
4
+ const e2eeOff = root.DSH_REMOTE_E2EE_DISABLED === true
4
5
  const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
5
6
  const el = (tag, cls, value) => { const node=document.createElement(tag);if(cls)node.className=cls;if(value)node.textContent=value;return node }
6
7
  const messages = {
@@ -13,23 +14,86 @@
13
14
  unauthorized:['请先连接主机,再设置云服务器中转。','Connect to your host before configuring its relay.'],
14
15
  INVALID_RESPONSE:['主机返回了无法识别的中转状态,请检查连接地址和主机 Remote 版本。','Unrecognized relay response. Check the host URL and Remote version.'],
15
16
  UNSUPPORTED_GATEWAY:['此主机尚不支持云中转设置,请更新主机 Remote。','Update the host Remote to use cloud relay settings.'],
17
+ INVALID_ACTIVATION_FILE:['请选择办理页生成的中转激活文件。','Select an activation file from the relay portal.'],
18
+ ACTIVATION_FILE_EXPIRED:['激活文件已过期。可重新下载,或在办理页领取密钥手动配置。','The activation file expired. Download a new one or claim the key for manual setup.'],
19
+ LOCAL_PAIRING_REQUIRED:['请连接主机的局域网地址,或在主机本机管理页导入。','Connect over the LAN or import on the host’s local management page.'],
20
+ RELAY_ACTIVATION_PENDING:['主机已有待确认的导入。请先到电脑管理页处理。','An import is already waiting for confirmation on the host.'],
21
+ RELAY_ACTIVATION_NOT_PENDING:['这项导入已完成或超时,请刷新状态。','This import finished or timed out. Refresh the status.'],
22
+ HOST_ALREADY_CONFIGURED:['此主机已绑定其他中转资格。请核对主机或在管理页手动处理。','This host is bound to a different relay authorization. Check the host or configure it manually.'],
16
23
  }
17
- function mount(target, { connection, path = '/relay', credentials, phonePairingCode, deviceManagement = true } = {}) {
24
+ const registrationLabels={
25
+ idle:['登记状态未查询','Registration not checked'],loading:['正在查询登记进度…','Checking application status…'],
26
+ none:['本设备没有已保存的登记','No application saved on this device'],
27
+ unavailable:['暂时无法确认登记进度','Could not verify application status'],
28
+ draft:['已登记 · 待提交','Registered · Not submitted'],submitted:['已提交 · 等待审核','Submitted · In review'],
29
+ approved:['审核通过','Approved'],renewable:['已有资格 · 可办理续费','Existing service · Renewal available'],
30
+ expired:['登记或资格已到期','Application or eligibility expired'],rejected:['审核未通过','Not approved'],revoked:['资格已撤销','Eligibility revoked']
31
+ }
32
+ function mount(target, { connection, path = '/relay', credentials, phonePairingCode, syncActivation, deviceManagement = true, service = false } = {}) {
18
33
  if (!target || target.dataset.relayMounted) return
34
+ if (e2eeOff) { deviceManagement = false; phonePairingCode = null }
19
35
  target.dataset.relayMounted='true';target.classList.add('relay-settings')
20
36
  const heading=el('div','relay-heading'),title=el('h3'),badge=el('span','relay-badge')
21
37
  heading.append(title,badge)
22
38
  const intro=el('p','relay-muted'),status=el('p','relay-status');status.setAttribute('aria-live','polite')
23
- const sponsor=el('div','relay-sponsor');root.DshSponsor?.mount(sponsor)
39
+ const sponsor=el('div','relay-sponsor')
40
+ const registration=el('section','relay-registration'),registrationTitle=el('h3'),registrationStatus=el('p','relay-status'),registrationHint=el('p','relay-muted')
41
+ registrationStatus.setAttribute('role','status')
42
+ const registrationActions=el('div','relay-actions'),registrationLink=el('a','mini-btn relay-primary'),registrationRecover=el('a','mini-btn'),registrationRefresh=el('button'),registrationInbox=el('button')
43
+ registrationLink.target='_blank';registrationLink.rel='noopener noreferrer';registrationRefresh.type='button'
44
+ registrationInbox.type='button';registrationInbox.hidden=true
45
+ registrationRecover.target='_blank';registrationRecover.rel='noopener noreferrer';registrationRecover.hidden=true
46
+ registrationActions.append(registrationLink,registrationRecover,registrationInbox,registrationRefresh);registration.append(registrationTitle,registrationActions,registrationStatus,registrationHint)
47
+ let hostConnected=false
48
+ const bridge=root.NativeBackground
49
+ const automaticKey='dsh-relay-automatic-checkout-v1'
50
+ const automaticSupported=service&&typeof bridge?.openCloudRelayAutomaticCheckout==='function'&&
51
+ typeof bridge.cloudRelayAutomaticActivation==='function'&&typeof bridge.refreshCloudRelayAutomaticActivation==='function'&&!!root.crypto?.subtle
52
+ let automaticCheckout=null, checkingAutomatic=false, nextAutomaticCheck=0
53
+ if(automaticSupported){try{automaticCheckout=JSON.parse(root.localStorage.getItem(automaticKey))}catch{}}
54
+ const checkRegistration=typeof bridge?.cloudRelayRegistration==='function'&&typeof bridge?.refreshCloudRelayRegistration==='function'
55
+ const checkInbox=typeof bridge?.cloudRelayUnreadMessages==='function'&&typeof bridge?.openCloudRelayInbox==='function'
56
+ registrationRefresh.addEventListener('click',()=>bridge.refreshCloudRelayRegistration())
57
+ registrationInbox.addEventListener('click',()=>bridge.openCloudRelayInbox())
58
+ registrationLink.addEventListener('click',event=>{
59
+ if(registrationLink.dataset.automatic==='true'){
60
+ event.preventDefault()
61
+ void openAutomaticCheckout()
62
+ }else if(root.DshSponsor?.openPortal(registrationLink.dataset.manage==='true'))event.preventDefault()
63
+ })
64
+ registrationRecover.addEventListener('click',event=>{if(root.DshSponsor?.openPortal(true))event.preventDefault()})
24
65
  const address=el('div','relay-address'),link=el('a'),copy=el('button');copy.type='button';link.target='_blank';link.rel='noopener noreferrer';address.append(link,copy)
25
66
  const quota=el('div','relay-quota'),meter=el('progress'),usage=el('p'),reset=el('p','relay-muted');meter.max=100;quota.append(usage,meter,reset)
26
67
  const plan=el('p','relay-muted'),binding=el('p','relay-muted'),form=el('form','relay-form'),keyLabel=el('label'),keyInput=el('input')
27
68
  keyInput.type='password';keyInput.autocomplete='off';keyInput.spellcheck=false;keyInput.maxLength=128;keyInput.name='relay-key'
28
69
  keyLabel.append(el('span'),keyInput)
29
70
  const adminLabel=el('label'),adminInput=el('input');adminInput.type='password';adminInput.autocomplete='off';adminInput.name='relay-admin';adminLabel.append(el('span'),adminInput)
30
- const submit=el('button','relay-primary');submit.type='submit';form.append(keyLabel,adminLabel,submit)
71
+ const submit=el('button','relay-primary');submit.type='submit';form.append(keyLabel)
72
+ if(!service)form.append(adminLabel)
73
+ form.append(submit)
31
74
  const actions=el('div','relay-actions'),toggle=el('button'),refresh=el('button'),takeover=el('button');toggle.type=refresh.type=takeover.type='button';actions.append(takeover,toggle,refresh)
32
75
  const hint=el('p','relay-muted'),notice=el('p','relay-notice');notice.setAttribute('role','status')
76
+ const activation = el('section', 'relay-activation')
77
+ const importButton = el('button', 'relay-primary', text('导入中转激活文件', 'Import relay activation file'))
78
+ const importFile = el('input')
79
+ importButton.type = 'button'; importFile.type = 'file'; importFile.name = 'relay-activation'
80
+ importFile.accept = '.json,application/json'; importFile.hidden = true
81
+ const activationNotice = el('p', 'relay-notice'); activationNotice.setAttribute('role', 'status')
82
+ const approve = el('button', 'relay-primary', text('确认并绑定', 'Approve and bind'))
83
+ const reject = el('button', '', text('拒绝导入', 'Reject import'))
84
+ const retrySync = el('button', '', text('重试配置此手机', 'Retry setup on this phone'))
85
+ const inboxOffer = el('div', 'relay-inbox-offer')
86
+ const inboxTarget = el('p', 'relay-muted')
87
+ const applyInbox = el('button', 'relay-primary', text('应用到此主机', 'Apply to this host'))
88
+ const dismissInbox = el('button', '', text('稍后配置', 'Set up later'))
89
+ applyInbox.type = dismissInbox.type = 'button'
90
+ const inboxActions = el('div', 'relay-actions')
91
+ inboxActions.append(applyInbox, dismissInbox)
92
+ inboxOffer.append(inboxTarget, inboxActions)
93
+ approve.type = reject.type = retrySync.type = 'button'
94
+ const activationActions = el('div', 'relay-actions')
95
+ activationActions.append(importButton, approve, reject, retrySync)
96
+ activation.append(inboxOffer, activationActions, importFile, activationNotice)
33
97
  const phoneGuide=el('section','relay-pair-guide'),phoneTitle=el('h3'),phoneHint=el('p','relay-muted')
34
98
  const showCode=el('button','relay-primary'),hideCode=el('button'),code=el('div','relay-phone-code'),phoneStatus=el('p','relay-pair-progress')
35
99
  showCode.type=hideCode.type='button';phoneStatus.setAttribute('role','status')
@@ -39,12 +103,22 @@
39
103
  hideCode.textContent=text('关闭连接码','Close connection code')
40
104
  const recentPair=el('p','relay-muted')
41
105
  phoneGuide.append(phoneTitle,phoneHint,showCode,hideCode,code,phoneStatus,recentPair)
42
- target.append(heading,intro,status)
43
- if(phonePairingCode)target.append(phoneGuide)
44
- target.append(sponsor,address,plan,quota,binding,form,actions,hint,notice)
45
- const deviceTarget=el('div')
106
+ const hostPanel = service ? el('section', 'relay-host-panel') : target
107
+ hostPanel.append(heading,intro,status)
108
+ hostPanel.append(activation)
109
+ if(phonePairingCode)hostPanel.append(phoneGuide)
110
+ if(!service)hostPanel.append(sponsor)
111
+ const bindOptions=el('details','relay-bind-options')
112
+ const bindSummary=el('summary')
113
+ bindOptions.append(bindSummary,form)
114
+ if(service)hostPanel.append(plan,binding,quota,address,bindOptions)
115
+ else hostPanel.append(address,plan,quota,binding,bindOptions)
116
+ if(service){adminLabel.className='relay-operation-auth';hostPanel.append(adminLabel)}
117
+ hostPanel.append(actions,hint,notice)
118
+ if(service)target.append(registration,hostPanel)
119
+ const deviceTarget=el('div','relay-device-panel')
46
120
  if(deviceManagement)target.append(deviceTarget)
47
- const devices=deviceManagement?root.DshRelayDevices?.mount(deviceTarget,{connection,path:path+'/e2ee',credentials}):null
121
+ let devices=null
48
122
  let activeSetup='',pendingSetup=''
49
123
  function closeCode(){
50
124
  activeSetup='';pendingSetup='';code.textContent='';phoneStatus.textContent=''
@@ -71,17 +145,25 @@
71
145
  }finally{if(current(ctx)&&pendingSetup===setup){pendingSetup='';showCode.disabled=!!activeSetup}}
72
146
  })
73
147
  let identity='',value=null,lastRead=0,busy=false,loading=false,controller=null,destroyed=false,readError=false,failures=0
148
+ let importReading=false, awaitingActivation='', syncedActivation='', syncing=false, activationMessage='', inboxActivation=null, automaticBinding=false
74
149
  function context() { const ctx=connection();return { ...ctx, endpoint:ctx.url(path) } }
75
150
  function current(ctx) { return !destroyed && ctx.valid() && identity===JSON.stringify([ctx.endpoint,ctx.headers?.authorization||'']) }
76
151
  function syncIdentity() {
77
152
  const ctx=context(),next=JSON.stringify([ctx.endpoint,ctx.headers?.authorization||''])
78
- if(next!==identity){identity=next;controller?.abort();controller=null;keyInput.value='';adminInput.value='';value=null;notice.textContent='';lastRead=0;loading=false;busy=false;readError=false;failures=0;closeCode();render()}
153
+ hostConnected=ctx.connected!==false
154
+ if(next!==identity){identity=next;controller?.abort();controller=null;keyInput.value='';adminInput.value='';bindOptions.open=false;value=null;notice.textContent='';lastRead=0;loading=false;busy=false;readError=false;failures=0;closeCode()
155
+ importReading=false;awaitingActivation='';syncedActivation='';syncing=false;automaticBinding=false;activationMessage='';importFile.value='';render()}
79
156
  return ctx
80
157
  }
81
158
  function render() {
159
+ const e2eeAllowed = !!value && value?.e2ee?.allowed !== false
160
+ if (deviceManagement) {
161
+ deviceTarget.hidden = !e2eeAllowed
162
+ if (e2eeAllowed && !devices) devices=root.DshRelayDevices?.mount(deviceTarget,{connection,path:path+'/e2ee',credentials})
163
+ }
82
164
  devices?.update(value)
83
165
  if(phonePairingCode){
84
- phoneGuide.hidden=value?.canManageDevices!==true||!value.enabled||!value.e2ee?.configured
166
+ phoneGuide.hidden=!e2eeAllowed||value?.canManageDevices!==true||!value.enabled||!value.e2ee?.configured
85
167
  if(phoneGuide.hidden&&(activeSetup||pendingSetup))closeCode()
86
168
  const activity=Array.isArray(value?.pairingActivity)?value.pairingActivity:[]
87
169
  if(activeSetup){
@@ -101,19 +183,25 @@
101
183
  if(recentPair.textContent!==message)recentPair.textContent=message
102
184
  }
103
185
  }
104
- root.DshSponsor?.mount(sponsor)
105
- title.textContent=text('云服务器中转','Cloud relay')
106
- intro.textContent=text('让手机通过公网连接这台主机。每位用户使用自己的中转密钥,首次开通会绑定此主机。','Connect to this host over the internet. Your personal relay key binds to this host when activated.')
107
- const phase=value?.phase||(readError?'unavailable':loading?'loading':'unconfigured')
186
+ if(service)renderRegistration()
187
+ else root.DshSponsor?.mount(sponsor)
188
+ title.textContent=service?text('这台主机的中转','Relay for this host'):text('云服务器中转','Cloud relay')
189
+ intro.textContent=service?'':text('让手机通过公网连接这台主机。每位用户使用自己的中转密钥,首次开通会绑定此主机。','Connect to this host over the internet. Your personal relay key binds to this host when activated.')
190
+ const phase=service&&!hostConnected?'disconnected':service&&value?.legacyAvailable?'legacy':service&&value?.phase!=='quota-exceeded'&&value?.configured===false?'unconfigured':value?.phase||(readError?'unavailable':loading||service?'loading':'unconfigured')
108
191
  const names={loading:['正在读取','Loading'],unavailable:['状态读取失败','Status unavailable'],unconfigured:['尚未开通','Not configured'],disabled:['已停用','Disabled'],connecting:['正在连接','Connecting'],online:['主机中转在线','Host relay online'],reconnecting:['正在重连','Reconnecting'],expired:['授权已到期','Expired'],'authorization-inactive':['授权已撤销或到期','Authorization inactive'],'quota-exceeded':['今日流量已用完','Daily quota reached'],'quota-unavailable':['流量服务暂不可用','Quota service unavailable'],error:['连接异常','Connection error']}
192
+ names.disconnected=['尚未连接主机','No host connected'];names.legacy=['已有登记的试用连接','Existing trial connection']
193
+ if(service)names.unconfigured=['此主机未绑定','Host not bound']
109
194
  badge.textContent=phase==='quota-exceeded'&&value?.daily?.period==='month'?text('本月流量已用完','Monthly quota reached'):text(...(names[phase]||names.error));badge.dataset.phase=phase
110
- status.textContent=busy?text('正在保存并绑定,请稍候…','Saving and binding…'):value?.error?text('请检查主机配置或刷新状态。','Check the host configuration or refresh.'):text('开通后会随 Remote 网关启动,无需单独运行工具。','Starts with the Remote gateway after activation.')
195
+ status.textContent=busy?text('正在保存并绑定,请稍候…','Saving and binding…'):value?.error?text('请检查主机配置或刷新状态。','Check the host configuration or refresh.'):service?'':text('开通后会随 Remote 网关启动,无需单独运行工具。','Starts with the Remote gateway after activation.')
111
196
  let safeUrl=''
112
197
  try { const url=new URL(value?.publicUrl);if(url.protocol==='https:'&&!url.username&&!url.password)safeUrl=url.origin } catch {}
113
198
  address.hidden=!safeUrl;link.textContent=safeUrl;link.href=safeUrl||'#';copy.textContent=text('复制地址','Copy URL')
114
199
  const daily=value?.daily
115
- plan.hidden=value?.quotaPeriod!=='month'&&daily?.period!=='month'
116
- plan.textContent=plan.hidden?'':text('基础中转 · 一个服务月 5GB · 单网关绑定 · 支持对话图片,不含文件传输。','Basic relay · 5GB per service month · One gateway · Chat images supported; file transfer excluded.')
200
+ const planType = relayPlan(value)
201
+ plan.hidden = !planType
202
+ const hasPacks=Number(daily?.fallbackLimitBytes)>0 || Number(value?.monthlyLimitBytes)>5e9
203
+ const fileEnabled=value?.fileTransfer===true && hasPacks
204
+ plan.textContent=planType==='early-test'?text('特殊先行测试用户','Special early tester'):plan.hidden?'':fileEnabled?text('流量包已生效 · 支持文件传输','Data pack active · File transfer enabled'):text('基础中转 · 一个服务月 5GB · 单网关绑定 · 支持对话图片,不含文件传输。','Basic relay · 5GB per service month · One gateway · Chat images supported; file transfer excluded.')
117
205
  quota.hidden=!daily
118
206
  if(daily?.unavailable){usage.textContent=text('无法确认流量额度,云端暂停传输。','Quota unavailable; cloud transfer is paused.');meter.hidden=true;reset.textContent=''}
119
207
  else if(daily){
@@ -121,21 +209,191 @@
121
209
  const gb=bytes=>(Math.max(0,Number(bytes)||0)/1e9).toFixed(2)
122
210
  const monthly=daily.period==='month'
123
211
  usage.textContent=text(`${monthly?'本月':'今日'}已用 ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · 剩余 ${gb(daily.remainingBytes)} GB`,`${monthly?'This month':'Today'} ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · ${gb(daily.remainingBytes)} GB left`)
124
- reset.textContent=monthly?text('上传与下载及对话图片合计;额度覆盖本次开通的服务月,不包含文件传输。','Uploads, downloads and chat images share this service month quota; file transfer is excluded.'):text('上传与下载合计;北京时间每天 00:00 重置。','Uploads + downloads; resets daily at 00:00 Beijing time.')
212
+ reset.textContent=monthly?(fileEnabled?text('对话、图片和文件共用本期额度。','Chat, images and files share this service month quota.'):hasPacks&&daily.exhausted?text('文件流量额度已用完。直接 HTTPS 连接可继续使用剩余的文本和图片兜底额度。','File quota reached. Direct HTTPS can use any remaining allowance for chat and images.'):text('上传与下载及对话图片合计;额度覆盖本次开通的服务月。','Uploads, downloads and chat images share this service month quota.')):text('上传与下载合计;北京时间每天 00:00 重置。','Uploads + downloads; resets daily at 00:00 Beijing time.')
125
213
  }
126
214
  const expires=value?.expiresAt?new Date(value.expiresAt).toLocaleString():''
127
- binding.textContent=value?.fingerprint?text(`已绑定此主机 · ${value.fingerprint.slice(0,12)}${expires?' · 有效期至 '+expires:''}`,`Bound to this host · ${value.fingerprint.slice(0,12)}${expires?' · Until '+expires:''}`):''
215
+ binding.textContent=value?.configured?text(`已绑定此主机${expires?' · 有效期至 '+expires:''}`,`Bound to this host${expires?' · Until '+expires:''}`):''
216
+ bindSummary.textContent=text('手动配置中转密钥','Configure relay key manually')
217
+ renderActivation()
218
+ adminLabel.hidden=value?.canManage!==false
128
219
  keyLabel.firstChild.textContent=text(value?.configured?'更换个人中转密钥':'个人中转密钥',value?.configured?'Replace personal relay key':'Personal relay key')
129
220
  keyInput.placeholder='dsrp_…';keyInput.setAttribute('aria-label',keyLabel.firstChild.textContent)
130
- adminLabel.hidden=value?.canManage!==false
131
221
  adminLabel.firstChild.textContent=text('主机管理令牌(仅本次操作)','Host admin token (this operation only)')
132
222
  adminInput.setAttribute('aria-label',adminLabel.firstChild.textContent)
133
223
  submit.textContent=busy?text('正在处理…','Working…'):text(value?.configured?'绑定新密钥':'绑定并开启',value?.configured?'Bind new key':'Bind and enable')
134
224
  submit.disabled=busy||!value;keyInput.disabled=busy;adminInput.disabled=busy
135
- toggle.hidden=!value?.configured;toggle.disabled=busy;toggle.textContent=text(value?.enabled?'停用中转':'开启中转',value?.enabled?'Disable relay':'Enable relay')
225
+ toggle.hidden=!value?.configured;toggle.disabled=busy||service&&readError;toggle.textContent=text(value?.enabled?'停用中转':'开启中转',value?.enabled?'Disable relay':'Enable relay')
136
226
  refresh.textContent=text('刷新状态','Refresh');refresh.disabled=busy||loading
137
227
  takeover.hidden=!value?.legacyAvailable;takeover.disabled=busy;takeover.textContent=text('接管已有试用连接','Take over existing trial')
138
- hint.textContent=value?.quotaPending?text('等待云端确认流量额度…','Waiting for cloud quota…'):value?.e2ee?.configured?text('Android 可从局域网扫码配对。配对文件可在设备管理中手动创建。','Pair Android over the LAN using a connection code. Manual pairing files are available in device management.'):text('手机使用此公网地址和原 Remote 访问令牌。停用会断开通过此入口的连接;授权到期或用满后,请通过本地地址管理。','Use this URL and your existing Remote access token. Disabling disconnects this route; use a local address after expiry or quota exhaustion.')
228
+ hint.textContent=e2eeOff?text('此版本已停用端到端加密;请使用局域网地址或原有公网中转令牌。','End-to-end encryption is disabled in this version. Use a LAN address or the original relay token.'):!e2eeAllowed?text('基础档不含端到端加密。需要加密入口时,请开通或续费时选择流量包。','The basic plan does not include end-to-end encryption. Choose a data pack when opening or renewing to use it.'):value?.quotaPending?text('等待云端确认流量额度…','Waiting for cloud quota…'):service?(value?.enabled?text('停用会断开此公网入口。','Disabling disconnects this public route.'):''):!value?.e2ee?.configured?text('流量包支持端到端加密,默认关闭。可在主机本地管理页启用加密入口后再配对。','The data pack supports end-to-end encryption, off by default. Enable the encrypted host entry locally before pairing.'):text('Android 可从局域网扫码配对。配对文件可在设备管理中手动创建。','Pair Android over the LAN using a connection code. Manual pairing files are available in device management.')
229
+ }
230
+ function renderActivation() {
231
+ const request = value?.activationRequest
232
+ const canApprove = !service && value?.canManageDevices === true && request?.phase === 'pending'
233
+ inboxOffer.hidden = !inboxActivation
234
+ if (inboxActivation) {
235
+ const endpoint = context().endpoint
236
+ let host = ''
237
+ if (hostConnected) { try { host = new URL(endpoint).host } catch {} }
238
+ const description = host
239
+ ? text('收到站内激活。将应用到当前主机:', 'Activation received. Apply it to the current host: ') + host
240
+ : text('收到站内激活。请先通过局域网连接要绑定的主机。', 'Activation received. Connect to the intended host over the LAN first.')
241
+ if (inboxTarget.textContent !== description) inboxTarget.textContent = description
242
+ }
243
+ applyInbox.disabled = busy || loading || syncing
244
+ dismissInbox.disabled = busy
245
+ importButton.disabled = busy || importReading || syncing
246
+ approve.hidden = reject.hidden = !canApprove
247
+ approve.disabled = reject.disabled = busy
248
+ retrySync.hidden = !syncActivation || !value?.enabled || !value.activationId || !value.canPairLocally
249
+ retrySync.disabled = syncing || busy
250
+ const message = canApprove
251
+ ? text('有一台已认证的手机请求绑定中转。确认后将绑定到这台电脑。','An authenticated phone requested relay activation. Approval binds it to this computer.')
252
+ : activationMessage
253
+ if (activationNotice.textContent !== message) activationNotice.textContent = message
254
+ }
255
+ function manualActivation(message) {
256
+ activationMessage = message + ' ' + text('仍可展开「手动配置中转密钥」。','Manual relay-key setup is still available.')
257
+ bindOptions.open = true
258
+ renderActivation()
259
+ }
260
+ function updateActivation(ctx) {
261
+ const request = value?.activationRequest
262
+ if (awaitingActivation) {
263
+ if (request?.id === awaitingActivation && (request.phase === 'pending' || request.phase === 'binding')) return
264
+ const bound = value?.activationId === awaitingActivation || request?.id === awaitingActivation && request.phase === 'bound'
265
+ awaitingActivation = ''
266
+ if (!bound) {
267
+ automaticBinding = false
268
+ manualActivation(request?.error && messages[request.error] ? text(...messages[request.error]) : text('手机发起的导入未完成。请在电脑检查确认结果。','The import from this phone did not complete. Check its confirmation on the host.'))
269
+ return
270
+ }
271
+ activationMessage = text('主机已绑定。','Host bound.')
272
+ }
273
+ if (!document.hidden && (automaticBinding || target.getClientRects().length)) void syncImportedActivation(ctx)
274
+ }
275
+ async function syncImportedActivation(ctx, retry = false) {
276
+ const id = value?.activationId
277
+ if (!syncActivation || !value?.enabled || !value.canPairLocally || !id || syncing || !retry && syncedActivation === id) return
278
+ syncedActivation = id; syncing = true
279
+ activationMessage = text('主机已绑定,正在配置此手机…','Host bound. Setting up this phone…')
280
+ renderActivation()
281
+ let result
282
+ try { result = await syncActivation(value) } catch {}
283
+ if (!current(ctx)) return
284
+ syncing = false
285
+ automaticBinding = false
286
+ if (result?.ok) {
287
+ activationMessage = text('主机已绑定,手机已配置,公网连接已验证。','Host bound. Phone configured and relay connection verified.')
288
+ renderActivation()
289
+ } else {
290
+ manualActivation(text('主机已绑定,手机配置未完成。可重试,也可用下方配对入口或手动添加公网地址。','The host is bound. Retry setup, use pairing below or add the public address manually.'))
291
+ }
292
+ }
293
+ function parseActivation(contents) {
294
+ if (typeof contents !== 'string' || contents.length > 4096) throw Object.assign(Error('INVALID_ACTIVATION_FILE'), { code: 'INVALID_ACTIVATION_FILE' })
295
+ const data = JSON.parse(contents)
296
+ if (!data || data.type !== 'dsh-remote-relay-activation' || data.version !== 1 ||
297
+ typeof data.code !== 'string' || !/^dsra_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(data.code) ||
298
+ !Number.isSafeInteger(data.expiresAt) || Object.keys(data).length !== 4) {
299
+ throw Object.assign(Error('INVALID_ACTIVATION_FILE'), { code: 'INVALID_ACTIVATION_FILE' })
300
+ }
301
+ if (data.expiresAt <= Date.now()) throw Object.assign(Error('ACTIVATION_FILE_EXPIRED'), { code: 'ACTIVATION_FILE_EXPIRED' })
302
+ return data
303
+ }
304
+ function receiveActivation(raw) {
305
+ const ctx = syncIdentity()
306
+ try {
307
+ inboxActivation = parseActivation(raw)
308
+ activationMessage = ''
309
+ renderActivation()
310
+ if (ctx.connected !== false && !busy) void load(true)
311
+ } catch (error) {
312
+ inboxActivation = null
313
+ manualActivation(text(...(messages[error.code] || messages.INVALID_ACTIVATION_FILE)))
314
+ }
315
+ }
316
+ async function hostFingerprint(ctx) {
317
+ const authorization=ctx.headers?.authorization
318
+ if(!authorization)return ''
319
+ const digest=await root.crypto.subtle.digest('SHA-256',new TextEncoder().encode(JSON.stringify([ctx.endpoint,authorization])))
320
+ return Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,'0')).join('')
321
+ }
322
+ async function openAutomaticCheckout() {
323
+ const ctx=syncIdentity()
324
+ try {
325
+ const host=await hostFingerprint(ctx)
326
+ if(!host||!current(ctx)||value?.canPairLocally!==true||value.configured!==false)return
327
+ const ticket=root.crypto.randomUUID().replaceAll('-','')
328
+ const selection={ticket,host}
329
+ root.localStorage.setItem(automaticKey,JSON.stringify(selection))
330
+ automaticCheckout=selection;nextAutomaticCheck=0
331
+ bridge.openCloudRelayAutomaticCheckout(ticket)
332
+ }catch{root.DshSponsor?.openPortal()}
333
+ }
334
+ async function checkAutomaticCheckout() {
335
+ const selection=automaticCheckout
336
+ if(!selection||checkingAutomatic||document.hidden||Date.now()<nextAutomaticCheck||busy||loading)return
337
+ const state=bridge.cloudRelayRegistration()
338
+ if(state!=='submitted'&&state!=='approved'&&state!=='renewable')return
339
+ nextAutomaticCheck=Date.now()+12000;checkingAutomatic=true
340
+ try {
341
+ const ctx=syncIdentity()
342
+ if(ctx.connected===false||await hostFingerprint(ctx)!==selection.host||!current(ctx)||automaticCheckout!==selection)return
343
+ await load(true)
344
+ if(!current(ctx)||readError||value?.activationImport!==true||value.canPairLocally!==true||value.configured!==false||value.legacyAvailable)return
345
+ const raw=bridge.cloudRelayAutomaticActivation(selection.ticket)
346
+ if(!raw){bridge.refreshCloudRelayAutomaticActivation(selection.ticket);return}
347
+ const data=parseActivation(raw)
348
+ root.localStorage.removeItem(automaticKey)
349
+ automaticCheckout=null;automaticBinding=true
350
+ if(!await change('activate-file',{activation:data},ctx)&&current(ctx)){
351
+ automaticBinding=false;inboxActivation=data;renderActivation()
352
+ }
353
+ }catch{}finally{checkingAutomatic=false}
354
+ }
355
+ function renderRegistration() {
356
+ const raw=checkRegistration?bridge.cloudRelayRegistration():'unavailable'
357
+ const state=Object.hasOwn(registrationLabels,raw)?raw:'unavailable'
358
+ const verifiedUnbound=hostConnected&&!readError&&value?.configured===false&&!value.legacyAvailable&&value.phase!=='quota-exceeded'
359
+ const canStart=(state==='none'||!bridge)&&(verifiedUnbound||!hostConnected)
360
+ const automatic=automaticSupported&&canStart&&verifiedUnbound&&value.activationImport===true&&value.canPairLocally===true
361
+ const canRestart=verifiedUnbound&&['expired','rejected','revoked'].includes(state)
362
+ const manageRegistration=!(canStart||canRestart)
363
+ const expiry=['idle','loading','none','unavailable','revoked'].includes(state)?0:bridge?.cloudRelayRegistrationExpiresAt?.()
364
+ const expires=Number.isSafeInteger(expiry)&&expiry>0&&expiry<=8640000000000000
365
+ ?new Date(expiry).toLocaleString(text('zh-CN','en-GB'),{timeZone:'Asia/Shanghai',hour12:false}):''
366
+ const canAddPacks=state==='approved'&&bridge?.cloudRelayRegistrationCanAddPacks?.()===true
367
+ registrationTitle.textContent=text('云中转套餐','Cloud relay plans')
368
+ const label=text(...registrationLabels[state])
369
+ if(registrationStatus.textContent!==label)registrationStatus.textContent=label
370
+ registrationHint.textContent=state==='none'?text('在别处登记过?用原查询凭证恢复后,这台 App 就能收到该编号的运营消息。','Applied elsewhere? Recover your application to receive messages for its number in this app.'):state==='unavailable'?text('可用原查询凭证核对,确认前请勿重复付款。','Verify with your recovery code before paying again.'):''
371
+ if(automatic)registrationHint.textContent=text('申请编号自动保存。审核通过后,App 会尝试配置当前选定的局域网主机。','The application is saved here. After approval, the app will try to configure the selected host over the LAN.')
372
+ else if(expires)registrationHint.textContent=text('服务有效期至 '+expires+'(北京时间)','Service expiry: '+expires+' (Beijing time)')
373
+ registrationLink.dataset.automatic=String(automatic)
374
+ registrationLink.dataset.manage=String(manageRegistration)
375
+ if(root.DshSponsor){
376
+ const portal=root.DshSponsor.applicationUrl
377
+ registrationLink.href=portal+(manageRegistration?'#manage':'')
378
+ registrationRecover.href=portal+'#manage'
379
+ }
380
+ registrationLink.textContent=state==='draft'?text('继续办理','Continue application')
381
+ :state==='submitted'?text('查看审核进度','Check review status')
382
+ :state==='renewable'?text('续费','Renew')
383
+ :canAddPacks?text('购买流量包','Buy data packs')
384
+ :state==='approved'?text('查看云中转资格','View relay service')
385
+ :manageRegistration?text('查询已有申请','Find an existing application')
386
+ :automatic?text('开通并自动配置此主机','Apply and set up this host automatically')
387
+ :text('查看套餐并开通','View plans and activate')
388
+ registrationRecover.textContent=text('查询与续费','Check status and renew')
389
+ registrationRecover.hidden=manageRegistration
390
+ registrationRefresh.hidden=!checkRegistration
391
+ registrationRefresh.disabled=state==='loading'
392
+ registrationRefresh.textContent=text('刷新登记','Refresh application')
393
+ const unread=checkInbox?bridge.cloudRelayUnreadMessages():-1
394
+ registrationInbox.hidden=!checkInbox||unread<0&&['idle','none','loading'].includes(state)
395
+ registrationInbox.textContent=unread>0?text(`站内消息 · ${unread} 条未读`,`Inbox · ${unread} unread`):text('站内消息','Inbox')
396
+ if(state==='idle'&&!document.hidden&&target.getClientRects().length)bridge.refreshCloudRelayRegistration()
139
397
  }
140
398
  async function load(force=false) {
141
399
  const ctx=syncIdentity()
@@ -150,10 +408,11 @@
150
408
  let data
151
409
  try{data=await response.json()}catch{throw Object.assign(Error('INVALID_RESPONSE'),{code:'INVALID_RESPONSE',status:response.status})}
152
410
  if(!current(ctx))return
153
- if(response.status===429&&data.daily){value={phase:'quota-exceeded',daily:data.daily,configured:false};notice.textContent=data.daily.period==='month'?text('本月额度已用完。请用主机本地地址管理;续期需在当前资格到期后重新申请。','Monthly quota reached. Manage through the local host; apply again after expiry.'):text('今日额度已用完。请用主机本地地址进入设置,或等待零点恢复。','Daily quota reached. Use the local host address or wait until reset.');return}
411
+ if(response.status===429&&data.daily){value={phase:'quota-exceeded',daily:data.daily,configured:false};notice.textContent=data.daily.period==='month'?text('本月额度已用完。可从上方查看续费和购买流量包的选项,或用主机本地地址管理。','Monthly quota reached. See the options above for renewal and data packs, or manage through the local host.'):text('今日额度已用完。请用主机本地地址进入设置,或等待零点恢复。','Daily quota reached. Use the local host address or wait until reset.');return}
154
412
  if(!response.ok)throw Object.assign(Error(data.error||'HTTP_'+response.status),{code:data.error,status:response.status})
155
413
  if(data.supported!==true)throw Object.assign(Error('UNSUPPORTED_GATEWAY'),{code:'UNSUPPORTED_GATEWAY'})
156
414
  value=data;notice.textContent='';readError=false;failures=0
415
+ updateActivation(ctx)
157
416
  }catch(error){
158
417
  if(current(ctx)&&!busy&&controller===abort){
159
418
  readError=true;failures++
@@ -161,8 +420,10 @@
161
420
  }
162
421
  }finally{clearTimeout(timer);if(current(ctx)&&controller===abort){loading=false;render()}}
163
422
  }
164
- async function change(action) {
423
+ async function change(action, parameters = {}, captured = null) {
165
424
  const ctx=syncIdentity();if(busy)return
425
+ if (captured && (!current(captured) || captured.endpoint !== ctx.endpoint)) return
426
+ const activationAction = ['activate-file', 'approve-activation', 'reject-activation'].includes(action)
166
427
  const key=keyInput.value.trim(),admin=adminInput.value.trim()
167
428
  if(action==='enroll'&&!/^dsrp_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(key)){notice.textContent=text('请填写完整的个人中转密钥。','Enter the complete personal relay key.');return}
168
429
  busy=true;controller?.abort();loading=false;notice.textContent='';render()
@@ -170,13 +431,71 @@
170
431
  // Clear immediately, including ambiguous network outcomes. Never store the key.
171
432
  keyInput.value='';adminInput.value=''
172
433
  try {
173
- const response=await root.fetch(ctx.endpoint,{method:'POST',headers:{...ctx.headers,...(admin?{authorization:'Bearer '+admin}:{}),'content-type':'application/json'},credentials,body:JSON.stringify({action,...(action==='enroll'?{key}:{})}),signal:abort.signal})
434
+ const response=await root.fetch(ctx.endpoint,{method:'POST',headers:{...ctx.headers,...(admin?{authorization:'Bearer '+admin}:{}),'content-type':'application/json'},credentials,redirect:'error',body:JSON.stringify({action,...parameters,...(action==='enroll'?{key}:{})}),signal:abort.signal})
174
435
  const data=await response.json();if(!current(ctx))return
175
436
  if(!response.ok)throw Object.assign(Error(data.error),{code:data.error})
176
- value={...data,canManageDevices:value?.canManageDevices};notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
177
- }catch(error){if(current(ctx))notice.textContent=messages[error.code]?text(...messages[error.code]):text('暂时无法确认操作结果。请刷新状态后再决定是否重试。','Result unconfirmed. Refresh status before deciding whether to retry.')}
437
+ value={...data,canManageDevices:data.canManageDevices ?? value?.canManageDevices};notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
438
+ if (activationAction) {
439
+ const request = data.activationRequest
440
+ if (action === 'activate-file' && request?.phase === 'pending') {
441
+ awaitingActivation = request.id
442
+ activationMessage = text('请在主机本机的 Remote 管理页确认这项导入。','Approve this import on the host’s local Remote management page.')
443
+ } else if (action === 'reject-activation') {
444
+ activationMessage = text('已拒绝这项导入。','Import rejected.')
445
+ } else if (request?.phase === 'failed') {
446
+ manualActivation(messages[request.error] ? text(...messages[request.error]) : text('绑定失败。','Binding failed.'))
447
+ return false
448
+ } else {
449
+ activationMessage = text('主机已绑定,正在确认云端连接。','Host bound. Confirming the relay connection.')
450
+ updateActivation(ctx)
451
+ }
452
+ }
453
+ return true
454
+ }catch(error){if(current(ctx)){
455
+ const detail = messages[error.code]?text(...messages[error.code]):text('暂时无法确认操作结果。请刷新状态后再决定是否重试。','Result unconfirmed. Refresh status before deciding whether to retry.')
456
+ if(activationAction)manualActivation(detail);else notice.textContent=detail
457
+ }}
178
458
  finally{clearTimeout(timer);if(current(ctx)){busy=false;lastRead=0;render()}}
179
459
  }
460
+ importButton.addEventListener('click', () => importFile.click())
461
+ importFile.addEventListener('change', async () => {
462
+ const ctx = syncIdentity(), file = importFile.files?.[0]
463
+ importFile.value = ''
464
+ if (!file || busy || importReading) return
465
+ if (ctx.connected === false || value?.activationImport !== true) {
466
+ manualActivation(text('请先连接支持导入的主机,或在主机本机导入。','Connect to a compatible host or import on the host itself.'))
467
+ return
468
+ }
469
+ importReading = true; activationMessage = ''; renderActivation()
470
+ try {
471
+ if (file.size > 4096) throw Object.assign(Error('INVALID_ACTIVATION_FILE'), { code: 'INVALID_ACTIVATION_FILE' })
472
+ const data = parseActivation(await file.text())
473
+ if (current(ctx)) await change('activate-file', { activation: data }, ctx)
474
+ } catch (error) {
475
+ if (current(ctx)) manualActivation(text(...(messages[error.code] || messages.INVALID_ACTIVATION_FILE)))
476
+ } finally { if (current(ctx)) { importReading = false; renderActivation() } }
477
+ })
478
+ applyInbox.addEventListener('click', async () => {
479
+ const ctx = syncIdentity(), data = inboxActivation
480
+ if (!data || busy || loading || syncing) return
481
+ if (data.expiresAt <= Date.now()) {
482
+ inboxActivation = null
483
+ manualActivation(text(...messages.ACTIVATION_FILE_EXPIRED))
484
+ return
485
+ }
486
+ if (ctx.connected === false || value?.activationImport !== true || value.canPairLocally !== true) {
487
+ manualActivation(text('请先通过局域网连接支持激活的主机。', 'Connect over the LAN to a host that supports activation.'))
488
+ return
489
+ }
490
+ if (await change('activate-file', { activation: data }, ctx) && inboxActivation === data) {
491
+ inboxActivation = null
492
+ renderActivation()
493
+ }
494
+ })
495
+ dismissInbox.addEventListener('click', () => { inboxActivation = null; renderActivation() })
496
+ approve.addEventListener('click', () => void change('approve-activation', { requestId: value?.activationRequest?.id }))
497
+ reject.addEventListener('click', () => void change('reject-activation', { requestId: value?.activationRequest?.id }))
498
+ retrySync.addEventListener('click', () => void syncImportedActivation(syncIdentity(), true))
180
499
  form.addEventListener('submit',event=>{event.preventDefault();void change('enroll')})
181
500
  toggle.addEventListener('click',()=>void change(value?.enabled?'disable':'enable'))
182
501
  takeover.addEventListener('click',()=>void change('import'))
@@ -186,9 +505,32 @@
186
505
  try{await root.navigator.clipboard.writeText(url);if(current(ctx))notice.textContent=text('地址已复制。','URL copied.')}
187
506
  catch{if(current(ctx))notice.textContent=text('请选中上方地址复制。','Select the URL above to copy it.')}
188
507
  })
189
- function tick(){if(destroyed)return;syncIdentity();render();void load()}
508
+ function tick(){if(destroyed)return;syncIdentity();render();void load(automaticBinding&&!!awaitingActivation&&Date.now()-lastRead>=5000);void checkAutomaticCheckout()}
190
509
  const timer=setInterval(tick,1000);tick()
191
- return { refresh:()=>load(true),destroy:()=>{destroyed=true;clearInterval(timer);controller?.abort();closeCode();devices?.destroy();keyInput.value='';adminInput.value=''} }
510
+ return { receiveActivation, refresh:()=>load(true),destroy:()=>{destroyed=true;inboxActivation=null;clearInterval(timer);controller?.abort();closeCode();devices?.destroy();keyInput.value='';adminInput.value=''} }
511
+ }
512
+ function relayPlan(status) {
513
+ if (status?.quotaPeriod === 'month' || status?.daily?.period === 'month') return 'basic'
514
+ return status?.displayPlan === 'early-test' ? 'early-test' : ''
515
+ }
516
+
517
+ function connectionCategory(status, base) {
518
+ if (status?.supported !== true) return 'unknown'
519
+ if (status.canPairLocally === true) return 'direct'
520
+ try {
521
+ const address = new URL(status.publicUrl)
522
+ if (address.protocol !== 'https:' || address.origin !== new URL(base).origin) return 'unknown'
523
+ } catch {
524
+ return 'unknown'
525
+ }
526
+ const plan = relayPlan(status)
527
+ if (plan) return plan
528
+ try {
529
+ return new URL(status.server).origin !== new URL(root.DshSponsor?.applicationUrl).origin ? 'self-hosted' : 'relay'
530
+ } catch {
531
+ return 'relay'
532
+ }
192
533
  }
193
- root.DshRelaySettings={mount}
534
+
535
+ root.DshRelaySettings={mount,connectionCategory}
194
536
  })(typeof window!=='undefined'?window:globalThis)
@@ -0,0 +1,85 @@
1
+ /* Shared session-list cache keys and migration. No dependencies. */
2
+ 'use strict';
3
+ ;(function(root) {
4
+ const CANONICAL = 'sessionsCacheV2:'
5
+ const HISTORY = 'historyCacheV2:'
6
+ const LEGACY_SUFFIX = ':sessions'
7
+
8
+ function scopeSuffix(scope) {
9
+ const value = String(scope || '')
10
+ return value.startsWith(HISTORY) ? value.slice(HISTORY.length) : value
11
+ }
12
+ function keys(scope) {
13
+ return { canonical: CANONICAL + scopeSuffix(scope), legacy: String(scope || '') + LEGACY_SUFFIX }
14
+ }
15
+ function keysFromCanonical(canonical) {
16
+ const value = String(canonical || '')
17
+ const suffix = value.startsWith(CANONICAL) ? value.slice(CANONICAL.length) : scopeSuffix(value)
18
+ return { canonical: CANONICAL + suffix, legacy: HISTORY + suffix + LEGACY_SUFFIX }
19
+ }
20
+ function parse(raw) {
21
+ if (typeof raw !== 'string' || !raw) return null
22
+ try {
23
+ const value = JSON.parse(raw)
24
+ return Array.isArray(value) ? value : null
25
+ } catch { return null }
26
+ }
27
+ function readRaw(key) {
28
+ try { return root.localStorage.getItem(key) } catch { return null }
29
+ }
30
+ function writeRaw(key, value) {
31
+ try { root.localStorage.setItem(key, JSON.stringify(value)); return true } catch { return false }
32
+ }
33
+ function readPair(pair) {
34
+ const current = parse(readRaw(pair.canonical))
35
+ // A valid [] is authoritative: do not fall back to a stale legacy copy.
36
+ if (current) return current
37
+ const previous = parse(readRaw(pair.legacy))
38
+ if (!previous) return null
39
+ // Keep the legacy copy for the rollback window; only fill the canonical key.
40
+ writeRaw(pair.canonical, previous)
41
+ return previous
42
+ }
43
+ function read(scope) {
44
+ return readPair(keys(scope))
45
+ }
46
+ function readKey(canonical) {
47
+ return readPair(keysFromCanonical(canonical))
48
+ }
49
+ function writePair(pair, list) {
50
+ const value = Array.isArray(list) ? list.slice(0, 80) : []
51
+ if (!writeRaw(pair.canonical, value)) return false
52
+ // Mirror only when a legacy copy already exists, so fresh installs do not create it.
53
+ if (readRaw(pair.legacy) !== null) writeRaw(pair.legacy, value)
54
+ return true
55
+ }
56
+ function write(scope, list) {
57
+ return writePair(keys(scope), list)
58
+ }
59
+ function writeKey(canonical, list) {
60
+ return writePair(keysFromCanonical(canonical), list)
61
+ }
62
+ function clear(scope) {
63
+ const { canonical, legacy } = keys(scope)
64
+ let ok = true
65
+ try { root.localStorage.removeItem(canonical) } catch { ok = false }
66
+ try { root.localStorage.removeItem(legacy) } catch { ok = false }
67
+ return ok
68
+ }
69
+ function clearAll() {
70
+ let ok = true
71
+ try {
72
+ const doomed = []
73
+ for (let index = 0; index < root.localStorage.length; index++) {
74
+ const key = root.localStorage.key(index)
75
+ if (key && (key.startsWith(CANONICAL) || (key.startsWith(HISTORY) && key.endsWith(LEGACY_SUFFIX)))) doomed.push(key)
76
+ }
77
+ for (const key of doomed) root.localStorage.removeItem(key)
78
+ } catch { ok = false }
79
+ return ok
80
+ }
81
+
82
+ const api = { keys, keysFromCanonical, read, readKey, write, writeKey, clear, clearAll }
83
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
84
+ else root.DshSessionCache = api
85
+ })(typeof window === 'undefined' ? globalThis : window)