credentials.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /**
  2. * Host owner of the `credentials` Remote namespace: the reference half of
  3. * `ctx.credentials` as a browser configuration page reads and writes it.
  4. *
  5. * @module @deepseek-ai/dsh-api-settings-controller/src/credentials.ts
  6. */
  7. import { Context } from '@deepseek-ai/cordis'
  8. import { credentialRef } from '@deepseek-ai/dsh-credentials'
  9. import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
  10. import type { CredentialInfo } from '@deepseek-ai/dsh-credentials/types'
  11. import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  12. import { z } from 'zod'
  13. /**
  14. * Fan-out bound on one remote `describe` batch. A settings page asks about the
  15. * references its own rows name, so this is far above any real page and still
  16. * keeps one authenticated request from starting unbounded provider work.
  17. */
  18. const MAX_DESCRIBE_REFS = 64
  19. const credentialRefSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)
  20. const describeRequestSchema = z.object({
  21. refs: z.array(credentialRefSchema).max(MAX_DESCRIBE_REFS),
  22. })
  23. const setRequestSchema = z.object({ ref: credentialRefSchema, value: z.string().min(1) })
  24. const unsetRequestSchema = z.object({ ref: credentialRefSchema })
  25. /** Parse the domain constraints that are more specific than generated TypeScript codecs. */
  26. function parseRequest<T>(method: string, schema: z.ZodType<T>, value: unknown): T {
  27. const parsed = schema.safeParse(value)
  28. if (!parsed.success) {
  29. throw new RemoteError('gateway/bad-request', `invalid payload for ${method}`, { issues: parsed.error.issues })
  30. }
  31. return parsed.data
  32. }
  33. /**
  34. * Copy exactly the fields {@link CredentialInfo} declares. The Gateway returns
  35. * a business result without decoding it, so a provider whose `describe` carried
  36. * extra enumerable properties would otherwise serialize them to the caller.
  37. * @param info - the provider's answer for one reference.
  38. * @returns the same facts with nothing else attached.
  39. */
  40. function projectCredentialInfo(info: CredentialInfo): CredentialInfo {
  41. return {
  42. configured: info.configured,
  43. ...info.source === undefined ? {} : { source: info.source },
  44. writable: info.writable,
  45. }
  46. }
  47. declare module '@deepseek-ai/cordis' {
  48. interface Context {
  49. /** Host owner of the `credentials` Remote namespace. */
  50. credentialsController: CredentialsController
  51. }
  52. }
  53. /**
  54. * Host service backing the generated `ctx.remote.credentials` namespace. It
  55. * carries every wire obligation the credential seam itself does not: the batch
  56. * fan-out bound, the field-by-field view projection, the reference-grammar
  57. * guard, and the refusal mapping. Secret values cross in one direction only —
  58. * no method here returns one.
  59. */
  60. export class CredentialsController extends TypertRemoteService {
  61. /** @param ctx - Host context where a credential provider may be mounted. */
  62. constructor(ctx: Context) {
  63. super(ctx, 'credentialsController', { namespace: 'credentials' })
  64. }
  65. /**
  66. * Describe several references for one configuration surface. Batched because
  67. * a settings page describes every reference its rows name at once, and one
  68. * round trip keeps those rows from settling separately.
  69. * @param refs - reference names, at most {@link MAX_DESCRIBE_REFS}; a name outside the grammar
  70. * rejects the whole call as `gateway/bad-request`.
  71. * @returns one view per requested name, keyed by that name.
  72. * @throws RemoteError when the request is invalid or no credential provider is mounted.
  73. */
  74. @Remote
  75. async describe(refs: string[]): Promise<Record<string, CredentialInfo>> {
  76. const request = parseRequest('credentials.describe', describeRequestSchema, { refs })
  77. const branded = request.refs.map(ref => [ref, credentialRef(ref)] as const)
  78. const credentials = this.provider()
  79. const entries = await Promise.all(branded.map(async ([ref, key]) =>
  80. [ref, projectCredentialInfo(await credentials.describe(key))] as const))
  81. return Object.fromEntries(entries)
  82. }
  83. /**
  84. * Store one value from a configuration surface. The value crosses the wire in
  85. * this direction only: no read path returns it.
  86. * @param ref - reference name to store under.
  87. * @param value - the non-empty secret value.
  88. * @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
  89. */
  90. @Remote
  91. async set(ref: string, value: string): Promise<void> {
  92. const request = parseRequest('credentials.set', setRequestSchema, { ref, value })
  93. const branded = credentialRef(request.ref)
  94. const credentials = this.provider()
  95. await this.write(request.ref, () => credentials.set(branded, request.value))
  96. }
  97. /**
  98. * Remove one reference from a configuration surface.
  99. * @param ref - reference name to remove.
  100. * @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
  101. */
  102. @Remote
  103. async unset(ref: string): Promise<void> {
  104. const request = parseRequest('credentials.unset', unsetRequestSchema, { ref })
  105. const branded = credentialRef(request.ref)
  106. const credentials = this.provider()
  107. await this.write(request.ref, () => credentials.unset(branded))
  108. }
  109. /** Resolve the optional provider or report how to supply it. */
  110. private provider(): CredentialProvider {
  111. const credentials = this.ctx.get('credentials')
  112. if (credentials === undefined) {
  113. throw new RemoteError(
  114. 'gateway/internal',
  115. 'credentials service is absent: this deployment does not mount a credential provider (e.g. @deepseek-ai/dsh-credentials-local) in its composition',
  116. {},
  117. )
  118. }
  119. return credentials
  120. }
  121. /**
  122. * Run one remote write and report every refusal as `credential/rejected`
  123. * carrying the seam's own message: a read-only source shadowing the reference
  124. * is what a configuration surface must show verbatim. Callers brand the
  125. * reference before entering, so a name outside the grammar never reaches this
  126. * path and fails the same way it does on the read side. The details name only
  127. * the reference, so no failure path can carry the value back out.
  128. */
  129. private async write(ref: string, write: () => Promise<void>): Promise<void> {
  130. try {
  131. await write()
  132. } catch (error: unknown) {
  133. throw new RemoteError(
  134. 'credential/rejected',
  135. error instanceof Error ? error.message : String(error),
  136. { ref },
  137. { cause: error },
  138. )
  139. }
  140. }
  141. }
  142. export default CredentialsController