dsh-duet 0.1.3 → 0.1.4

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.
@@ -8,11 +8,12 @@ export class ServiceInfo {
8
8
  async get() {
9
9
  if (this.cached && Date.now() < this.cached.expires) return this.cached.value
10
10
  if (this.inflight) return this.inflight
11
- const epoch = this.epoch, config = this.getConfig()
11
+ const epoch = this.epoch
12
12
  const unavailable = { status: 'unavailable', models: null }
13
13
  const work = async () => {
14
14
  let value = unavailable
15
15
  try {
16
+ const config = await this.getConfig()
16
17
  const url = new URL(config.endpoints.online)
17
18
  url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
18
19
  url.pathname = url.pathname.replace(/\/ws\/?$/, '').replace(/\/$/, '') + '/api/service-info'
@@ -0,0 +1,17 @@
1
+ /** Shared, connection-scoped diagnostics for both voice modes. No account identity. */
2
+ import {randomUUID} from 'node:crypto'
3
+ import {PLUGIN_VERSION} from '../shared/state.mjs'
4
+
5
+ function identifier(value){
6
+ return typeof value==='string'&&/^[A-Za-z0-9_-]{1,64}$/.test(value)?value:''
7
+ }
8
+ export function sessionMetadata(params,mode,anonymousUserId){
9
+ if(!['online','tts_only'].includes(mode))throw Error('invalid_voice_mode')
10
+ return Object.freeze({name:'dsh-duet',version:(params.get('plugin_version')||'').slice(0,64),
11
+ protocol_major:1,metadata_version:'duet_session_v1',mode,
12
+ host_version:PLUGIN_VERSION,page_binding:'connection_owner_v1',
13
+ client_trace_id:identifier(params.get('client_trace_id'))||randomUUID(),
14
+ page_id:identifier(params.get('page_id')),
15
+ ...(typeof anonymousUserId==='string'&&/^anon_[a-f0-9]{32}$/.test(anonymousUserId)
16
+ ?{anonymous_user_id:anonymousUserId,identity_kind:'anonymous_browser'}:{})})
17
+ }
@@ -1,11 +1,22 @@
1
1
  /** Host-only endpoint settings; trial authentication comes from the package. */
2
2
  import { readFileSync } from 'node:fs'
3
3
  import { mkdir, writeFile, rename, unlink } from 'node:fs/promises'
4
- import { dirname, join } from 'node:path'
5
- import { homedir } from 'node:os'
4
+ import { dirname } from 'node:path'
5
+ import { defaultStateFile } from './storage-paths.mjs'
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { duetEnv } from './environment.mjs'
8
- import { publicServiceAuthorization } from './service-defaults.mjs'
8
+ import { publicServiceAuthorization, isPublicTrialEndpoint } from './service-defaults.mjs'
9
+
10
+ export function normalizeBackendURL(value) {
11
+ if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
12
+ const url = new URL(value.trim())
13
+ const baseAddress = url.pathname === '/'
14
+ if (url.protocol === 'http:') url.protocol = 'ws:'
15
+ else if (url.protocol === 'https:') url.protocol = 'wss:'
16
+ if (url.pathname === '/') url.pathname = '/ws'
17
+ if (baseAddress && !url.searchParams.has('protocol')) url.searchParams.set('protocol', 'realtime_v2')
18
+ return url.toString()
19
+ }
9
20
 
10
21
  export function validateBackendURL(value, insecureOrigin = null) {
11
22
  if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
@@ -13,14 +24,14 @@ export function validateBackendURL(value, insecureOrigin = null) {
13
24
  if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_backend_url')
14
25
  // Credentials never belong in URLs or logs.
15
26
  if ([...url.searchParams.keys()].some(k => k !== 'protocol')) throw new Error('backend_url_query_not_allowed')
16
- if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin) throw new Error('backend_requires_wss')
27
+ if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin && !isPublicTrialEndpoint(url.toString())) throw new Error('backend_requires_wss')
17
28
  return url.toString()
18
29
  }
19
30
 
20
31
  export class DuetSettings {
21
32
  constructor(base, { path, debug = false } = {}) {
22
33
  this.base = base
23
- this.path = path || duetEnv('SETTINGS_FILE') || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'voice.json')
34
+ this.path = path || duetEnv('SETTINGS_FILE') || defaultStateFile('voice.json')
24
35
  this.debug = debug
25
36
  this.saved = null
26
37
  this.revision = 0
@@ -66,8 +77,9 @@ export class DuetSettings {
66
77
  if (this.writing) throw new Error('settings_write_in_progress')
67
78
  if (!input || input.revision !== this.revision) throw new Error('settings_revision_conflict')
68
79
  // A deliberate, authenticated per-origin opt-in, never a global TLS bypass.
69
- const insecureOrigin = input.allow_insecure_http === true ? new URL(input.backend_url).origin : this.saved?.insecure_origin
70
- const url = validateBackendURL(input.backend_url, insecureOrigin)
80
+ const normalized = normalizeBackendURL(input.backend_url)
81
+ const insecureOrigin = input.allow_insecure_http === true ? new URL(normalized).origin : this.saved?.insecure_origin
82
+ const url = validateBackendURL(normalized, insecureOrigin)
71
83
  const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin })
72
84
  this.writing = true
73
85
  const temp = `${this.path}.${randomUUID()}.tmp`
@@ -0,0 +1,28 @@
1
+ /** Default private plugin storage; legacy files are copied once, never overwritten. */
2
+ import {existsSync,mkdirSync,copyFileSync,chmodSync,linkSync,unlinkSync} from 'node:fs'
3
+ import {join,dirname} from 'node:path'
4
+ import {homedir} from 'node:os'
5
+ import {randomUUID} from 'node:crypto'
6
+
7
+ export function duetHome(){
8
+ return join(process.env.DSH_HOME||join(homedir(),'.dsh'),'dsh-duet')
9
+ }
10
+
11
+ export function defaultStateFile(name){
12
+ const target=join(duetHome(),name)
13
+ const legacy=join(dirname(duetHome()),'duplex-control',name)
14
+ if(existsSync(target)||!existsSync(legacy))return target
15
+ const temp=`${target}.${randomUUID()}.tmp`
16
+ try {
17
+ mkdirSync(dirname(target),{recursive:true,mode:0o700})
18
+ copyFileSync(legacy,temp)
19
+ chmodSync(temp,0o600)
20
+ // Publish atomically without overwriting another process's completed migration.
21
+ try{linkSync(temp,target)}catch(error){if(error.code!=='EEXIST')throw error}
22
+ return target
23
+ }catch{
24
+ // A read-only/full disk must not discard settings or rotate the feedback identity.
25
+ console.warn('[duet] Storage migration unavailable; keeping legacy file until next startup.')
26
+ return legacy
27
+ }finally{try{unlinkSync(temp)}catch{}}
28
+ }
@@ -1,6 +1,6 @@
1
1
  /** Private, append-only connection capture. Never served as a web asset. */
2
2
  import { createWriteStream, mkdirSync, readdirSync, statSync } from 'node:fs'
3
- import { homedir } from 'node:os'
3
+ import { duetHome } from './storage-paths.mjs'
4
4
  import { join } from 'node:path'
5
5
  import { randomUUID } from 'node:crypto'
6
6
  import { duetEnv } from './environment.mjs'
@@ -19,7 +19,7 @@ export function redact(value, secrets = []) {
19
19
 
20
20
  const budgets = new Map()
21
21
  export class DuetTrace {
22
- constructor(metadata, { root = duetEnv('TRACE_DIR') || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'traces'),
22
+ constructor(metadata, { root = duetEnv('TRACE_DIR') || join(duetHome(), 'traces'),
23
23
  secrets = [], maxBytes = 512 * 1024 ** 2, totalBytes = 20 * 1024 ** 3, queueBytes = 8 * 1024 ** 2 } = {}) {
24
24
  this.id = randomUUID(); this.start = performance.now(); this.seq = 0; this.bytes = 0
25
25
  this.offset = 0; this.closed = false; this.error = null; this.secrets = secrets
@@ -0,0 +1,9 @@
1
+ export const DEFAULT_CONNECTION_HINT='连接成功,可以试试对我说“你好”。'
2
+ export function connectionGuidance(text,revision=null){
3
+ const valid=typeof text==='string'&&text.trim().length>0&&text.length<=200&&!/[\u0000-\u001f\u007f<>]/.test(text)
4
+ return {text:valid?text.trim():DEFAULT_CONNECTION_HINT,source:valid?'router':'default',
5
+ revision:valid&&Number.isSafeInteger(revision)&&revision>=0?revision:null}
6
+ }
7
+ export function normalizeGuidance(value){
8
+ return value?.source==='router'?connectionGuidance(value.text,value.revision):connectionGuidance(null)
9
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.3'
2
+ export const PLUGIN_VERSION = '0.1.4'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
5
  const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''