local.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join, resolve } from 'node:path'
  6. import { credentialRef } from '@deepseek-ai/dsh-credentials'
  7. import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
  8. import { CredentialsLocal, resolveSpec } from '../src/index.ts'
  9. const KEY = credentialRef('DSH_CRED_TEST')
  10. const OTHER = credentialRef('DSH_CRED_OTHER')
  11. const cleanups: Array<() => Promise<void>> = []
  12. afterEach(async () => {
  13. vi.unstubAllEnvs()
  14. while (cleanups.length > 0) await cleanups.pop()!()
  15. })
  16. async function tempDir(): Promise<string> {
  17. const dir = await mkdtemp(join(tmpdir(), 'dsh-credentials-local-'))
  18. cleanups.push(() => rm(dir, { recursive: true, force: true }))
  19. return dir
  20. }
  21. async function boot(config: ConstructorParameters<typeof CredentialsLocal>[1]): Promise<Context> {
  22. const ctx = new Context()
  23. const fiber = ctx.plugin(CredentialsLocal, config)
  24. cleanups.push(async () => {
  25. await fiber.dispose()
  26. })
  27. await fiber
  28. return ctx
  29. }
  30. function updates(ctx: Context): CredentialRef[] {
  31. const seen: CredentialRef[] = []
  32. ctx.on('credentials/updated', (ref) => {
  33. seen.push(ref)
  34. })
  35. return seen
  36. }
  37. describe('resolveSpec', () => {
  38. it('defaults to .env under the harness home with watching on', () => {
  39. const spec = resolveSpec({ dshHome: '/custom/home' })
  40. expect(spec).toEqual({ filename: resolve('/custom/home/.env'), watch: true, debounceMs: 100 })
  41. })
  42. it('lets an explicit path win over the home', () => {
  43. const spec = resolveSpec({ path: '/etc/dsh/creds.env', dshHome: '/ignored', watch: false, debounceMs: 5 })
  44. expect(spec).toEqual({ filename: resolve('/etc/dsh/creds.env'), watch: false, debounceMs: 5 })
  45. })
  46. })
  47. describe('layering and reads', () => {
  48. it('treats an absent file as an empty writable store', async () => {
  49. const dir = await tempDir()
  50. const ctx = await boot({ path: join(dir, '.env'), watch: false })
  51. expect(await ctx.credentials.resolve(KEY)).toBeUndefined()
  52. expect(await ctx.credentials.describe(KEY)).toEqual({ configured: false, writable: true })
  53. })
  54. it('serves file entries, including export-prefixed and quoted values', async () => {
  55. const dir = await tempDir()
  56. const path = join(dir, '.env')
  57. await writeFile(path, '# notes\nexport DSH_CRED_TEST=plain\nDSH_CRED_OTHER="with space"\n')
  58. const ctx = await boot({ path, watch: false })
  59. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' })
  60. expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' })
  61. expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
  62. })
  63. it('lets a non-empty process environment win read-only over the file', async () => {
  64. const dir = await tempDir()
  65. const path = join(dir, '.env')
  66. await writeFile(path, 'DSH_CRED_TEST=from-file\n')
  67. const ctx = await boot({ path, watch: false })
  68. vi.stubEnv('DSH_CRED_TEST', 'from-env')
  69. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-env', source: 'env' })
  70. expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: false })
  71. })
  72. it('treats empty values as absent in both layers', async () => {
  73. const dir = await tempDir()
  74. const path = join(dir, '.env')
  75. await writeFile(path, 'DSH_CRED_TEST=\n')
  76. const ctx = await boot({ path, watch: false })
  77. vi.stubEnv('DSH_CRED_TEST', '')
  78. expect(await ctx.credentials.resolve(KEY)).toBeUndefined()
  79. expect(await ctx.credentials.describe(KEY)).toEqual({ configured: false, writable: true })
  80. })
  81. it('fails boot loud when the document exists but cannot be read', async () => {
  82. const dir = await tempDir()
  83. const path = join(dir, 'occupied')
  84. await mkdir(path)
  85. const ctx = new Context()
  86. await expect(ctx.plugin(CredentialsLocal, { path, watch: false })).rejects.toThrow()
  87. })
  88. })
  89. describe('line-editing writes', () => {
  90. it('appends a missing key to a fresh 0600 document and emits the commit', async () => {
  91. const dir = await tempDir()
  92. const path = join(dir, '.env')
  93. const ctx = await boot({ path, watch: false })
  94. const seen = updates(ctx)
  95. await ctx.credentials.set(KEY, 'sk-fresh')
  96. expect(await readFile(path, 'utf8')).toBe('DSH_CRED_TEST=sk-fresh\n')
  97. expect((await stat(path)).mode & 0o777).toBe(0o600)
  98. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'sk-fresh', source: 'file' })
  99. expect(seen).toEqual([KEY])
  100. })
  101. it('rewrites one line in place, preserving every other byte and dropping duplicates', async () => {
  102. const dir = await tempDir()
  103. const path = join(dir, '.env')
  104. await writeFile(path, '# deployment notes\nFIRST=one\n\nDSH_CRED_TEST=old\nTRAILING=x\nDSH_CRED_TEST=older')
  105. const ctx = await boot({ path, watch: false })
  106. await ctx.credentials.set(KEY, 'new value!')
  107. expect(await readFile(path, 'utf8')).toBe('# deployment notes\nFIRST=one\n\nDSH_CRED_TEST=\'new value!\'\nTRAILING=x\n')
  108. })
  109. it('quotes hostile values so they round-trip through a fresh provider', async () => {
  110. const dir = await tempDir()
  111. const path = join(dir, '.env')
  112. const ctx = await boot({ path, watch: false })
  113. const singleQuoted = 'with "quote", back\\slash and space'
  114. const doubleQuoted = "it's got an apostrophe"
  115. await ctx.credentials.set(KEY, singleQuoted)
  116. await ctx.credentials.set(OTHER, doubleQuoted)
  117. const reread = await boot({ path, watch: false })
  118. expect(await reread.credentials.resolve(KEY)).toEqual({ value: singleQuoted, source: 'file' })
  119. expect(await reread.credentials.resolve(OTHER)).toEqual({ value: doubleQuoted, source: 'file' })
  120. })
  121. it('fails loud on values no .env quoting style reads back verbatim', async () => {
  122. const dir = await tempDir()
  123. const ctx = await boot({ path: join(dir, '.env'), watch: false })
  124. await expect(ctx.credentials.set(KEY, 'line one\nline two')).rejects.toThrow(/control characters/)
  125. await expect(ctx.credentials.set(KEY, 'both \' and "')).rejects.toThrow(/mixes quoting/)
  126. })
  127. it('unsets only the owning line and keeps an absent unset silent', async () => {
  128. const dir = await tempDir()
  129. const path = join(dir, '.env')
  130. await writeFile(path, '# keep\nDSH_CRED_TEST=gone\nDSH_CRED_OTHER=stays\n')
  131. const ctx = await boot({ path, watch: false })
  132. const seen = updates(ctx)
  133. await ctx.credentials.unset(KEY)
  134. expect(await readFile(path, 'utf8')).toBe('# keep\nDSH_CRED_OTHER=stays\n')
  135. await ctx.credentials.unset(KEY)
  136. expect(seen).toEqual([KEY])
  137. })
  138. it('rejects empty values, shadowed writes, and multi-line entries', async () => {
  139. const dir = await tempDir()
  140. const path = join(dir, '.env')
  141. await writeFile(path, 'DSH_CRED_TEST="line one\nline two"\n')
  142. const ctx = await boot({ path, watch: false })
  143. await expect(ctx.credentials.set(KEY, '')).rejects.toThrow(/empty value/)
  144. await expect(ctx.credentials.set(KEY, 'next')).rejects.toThrow(/multi-line/)
  145. await expect(ctx.credentials.unset(KEY)).rejects.toThrow(/multi-line/)
  146. vi.stubEnv('DSH_CRED_TEST', 'shadowing')
  147. await expect(ctx.credentials.set(KEY, 'next')).rejects.toThrow(/shadowed/)
  148. await expect(ctx.credentials.unset(KEY)).rejects.toThrow(/shadowed/)
  149. })
  150. it('leaves an empty document after unsetting the only entry', async () => {
  151. const dir = await tempDir()
  152. const path = join(dir, '.env')
  153. await writeFile(path, 'DSH_CRED_TEST=only\n')
  154. const ctx = await boot({ path, watch: false })
  155. await ctx.credentials.unset(KEY)
  156. expect(await readFile(path, 'utf8')).toBe('')
  157. })
  158. it('chains past a rejected write so one bad value cannot poison the queue', async () => {
  159. const dir = await tempDir()
  160. const path = join(dir, '.env')
  161. const ctx = await boot({ path, watch: false })
  162. const bad = expect(ctx.credentials.set(KEY, 'both \' and "')).rejects.toThrow(/mixes quoting/)
  163. const good = ctx.credentials.set(OTHER, 'lands')
  164. await bad
  165. await good
  166. expect(await readFile(path, 'utf8')).toBe('DSH_CRED_OTHER=lands\n')
  167. })
  168. it('serializes concurrent writes so both land in the one document', async () => {
  169. const dir = await tempDir()
  170. const path = join(dir, '.env')
  171. const ctx = await boot({ path, watch: false })
  172. await Promise.all([
  173. ctx.credentials.set(KEY, 'one'),
  174. ctx.credentials.set(OTHER, 'two'),
  175. ])
  176. expect(await readFile(path, 'utf8')).toBe('DSH_CRED_TEST=one\nDSH_CRED_OTHER=two\n')
  177. })
  178. it('refuses writes after disposal', async () => {
  179. const dir = await tempDir()
  180. const ctx = new Context()
  181. const fiber = ctx.plugin(CredentialsLocal, { path: join(dir, '.env'), watch: false })
  182. await fiber
  183. // Capture the handle first: disposal also removes the ctx.credentials service.
  184. const service = ctx.credentials
  185. await fiber.dispose()
  186. await expect(service.set(KEY, 'late')).rejects.toThrow(/disposed/)
  187. })
  188. })
  189. describe('real hot reload', () => {
  190. it('publishes external edits, replaces the snapshot wholesale, and suppresses self-writes', async () => {
  191. const dir = await tempDir()
  192. const path = join(dir, '.env')
  193. // Watching starts on an existing document: creation racing watcher setup
  194. // is a chokidar readiness gap, not the reload contract under test.
  195. await writeFile(path, 'DSH_CRED_TEST=boot\n')
  196. const ctx = await boot({ path, debounceMs: 10 })
  197. const seen = updates(ctx)
  198. await writeFile(path, 'DSH_CRED_TEST=live\nDSH_CRED_OTHER=extra\n')
  199. await vi.waitFor(async () => {
  200. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'live', source: 'file' })
  201. })
  202. // Wholesale replacement: an entry deleted on disk never lingers in memory.
  203. await writeFile(path, 'DSH_CRED_TEST=live\n')
  204. await vi.waitFor(async () => {
  205. expect(await ctx.credentials.resolve(OTHER)).toBeUndefined()
  206. })
  207. const before = seen.length
  208. await ctx.credentials.set(KEY, 'self-written')
  209. await new Promise(resolvePause => setTimeout(resolvePause, 200))
  210. // Exactly the committed write's own event: the watcher echo of our own
  211. // content is recognized by the text cache and publishes nothing extra.
  212. expect(seen.length).toBe(before + 1)
  213. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'self-written', source: 'file' })
  214. })
  215. })