@raidiant/notifai 10.1.1 → 10.1.2

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 (156) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands-core.d.ts +1 -1
  3. package/dist/commands-init.js +9 -6
  4. package/dist/commands-init.js.map +1 -1
  5. package/dist/commands-send-support.js +3 -0
  6. package/dist/commands-send-support.js.map +1 -1
  7. package/dist/commands-skill.js +72 -54
  8. package/dist/commands-skill.js.map +1 -1
  9. package/dist/invocation-context.d.ts +1 -0
  10. package/dist/invocation-context.js +9 -1
  11. package/dist/invocation-context.js.map +1 -1
  12. package/dist/native-skills.d.ts +13 -3
  13. package/dist/native-skills.js +51 -12
  14. package/dist/native-skills.js.map +1 -1
  15. package/dist/node-floor.d.ts +2 -1
  16. package/dist/node-floor.js +9 -5
  17. package/dist/node-floor.js.map +1 -1
  18. package/dist/orca-session-title.d.ts +5 -4
  19. package/dist/orca-session-title.js +32 -19
  20. package/dist/orca-session-title.js.map +1 -1
  21. package/dist/platform.d.ts +11 -17
  22. package/dist/platform.js +20 -23
  23. package/dist/platform.js.map +1 -1
  24. package/dist/release.d.ts +5 -5
  25. package/dist/release.js +5 -5
  26. package/dist/setup-destinations.js +1 -1
  27. package/dist/setup-destinations.js.map +1 -1
  28. package/dist/skill-integrity.d.ts +49 -0
  29. package/dist/skill-integrity.js +154 -0
  30. package/dist/skill-integrity.js.map +1 -0
  31. package/dist/skill-source/manifest.json +16 -0
  32. package/dist/skill-source/notifai/SKILL.md +390 -0
  33. package/dist/skill-source/notifai/references/harness-setup.md +220 -0
  34. package/package.json +11 -14
  35. package/src/atomic-file.ts +0 -198
  36. package/src/claude-wake.test.ts +0 -321
  37. package/src/claude-wake.ts +0 -499
  38. package/src/cli-bin.test.ts +0 -176
  39. package/src/cli-bin.ts +0 -233
  40. package/src/cli-release.test.ts +0 -46
  41. package/src/cli-release.ts +0 -78
  42. package/src/cli-update-contract.ts +0 -9
  43. package/src/cli-update.test.ts +0 -125
  44. package/src/client.test.ts +0 -390
  45. package/src/client.ts +0 -352
  46. package/src/codex-wake.test.ts +0 -254
  47. package/src/codex-wake.ts +0 -301
  48. package/src/command-session.ts +0 -38
  49. package/src/commands-agent-sessions.ts +0 -72
  50. package/src/commands-auth.ts +0 -238
  51. package/src/commands-config.ts +0 -336
  52. package/src/commands-core.ts +0 -312
  53. package/src/commands-devices.ts +0 -180
  54. package/src/commands-doctor.ts +0 -1501
  55. package/src/commands-guidance.ts +0 -181
  56. package/src/commands-harness-context.ts +0 -207
  57. package/src/commands-hook-shape.ts +0 -69
  58. package/src/commands-hooks.ts +0 -2318
  59. package/src/commands-init.ts +0 -1055
  60. package/src/commands-io.ts +0 -108
  61. package/src/commands-logs.ts +0 -243
  62. package/src/commands-project.ts +0 -47
  63. package/src/commands-send-support.test.ts +0 -156
  64. package/src/commands-send-support.ts +0 -311
  65. package/src/commands-send.ts +0 -875
  66. package/src/commands-setup-proof.test.ts +0 -72
  67. package/src/commands-setup-proof.ts +0 -124
  68. package/src/commands-skill.test.ts +0 -44
  69. package/src/commands-skill.ts +0 -204
  70. package/src/commands-sounds.test.ts +0 -106
  71. package/src/commands-sounds.ts +0 -49
  72. package/src/commands-update.ts +0 -180
  73. package/src/commands.test.ts +0 -8297
  74. package/src/commands.ts +0 -77
  75. package/src/config-schema.test.ts +0 -153
  76. package/src/config-schema.ts +0 -349
  77. package/src/config.test.ts +0 -581
  78. package/src/config.ts +0 -475
  79. package/src/credentials.test.ts +0 -403
  80. package/src/credentials.ts +0 -403
  81. package/src/file-lock-process-worker.test.ts +0 -64
  82. package/src/file-lock.test.ts +0 -320
  83. package/src/file-lock.ts +0 -393
  84. package/src/fixtures/hermes-0.20.6-classic-cli-local.json +0 -50
  85. package/src/fixtures/openclaw-2026.7.1-2-agent-local.json +0 -57
  86. package/src/generated-session-label.ts +0 -155
  87. package/src/guidance-content.ts +0 -278
  88. package/src/guidance-render.ts +0 -56
  89. package/src/guidance.test.ts +0 -327
  90. package/src/guidance.ts +0 -233
  91. package/src/harness-integration.test.ts +0 -294
  92. package/src/harnesses.test.ts +0 -149
  93. package/src/harnesses.ts +0 -164
  94. package/src/hook-adapter.test.ts +0 -496
  95. package/src/hook-adapter.ts +0 -424
  96. package/src/hook-input.test.ts +0 -39
  97. package/src/hook-input.ts +0 -72
  98. package/src/hooks.test.ts +0 -5824
  99. package/src/hooks.ts +0 -4011
  100. package/src/install-hooks.test.ts +0 -1614
  101. package/src/install-hooks.ts +0 -1501
  102. package/src/interactive.test.ts +0 -387
  103. package/src/interactive.ts +0 -858
  104. package/src/invocation-context.test.ts +0 -352
  105. package/src/invocation-context.ts +0 -197
  106. package/src/logging-process-worker.test.ts +0 -45
  107. package/src/logging.test.ts +0 -544
  108. package/src/logging.ts +0 -698
  109. package/src/main-run.ts +0 -45
  110. package/src/main.ts +0 -12
  111. package/src/native-skills.test.ts +0 -115
  112. package/src/native-skills.ts +0 -162
  113. package/src/node-floor.test.ts +0 -27
  114. package/src/node-floor.ts +0 -37
  115. package/src/onboarding-docs.test.ts +0 -25
  116. package/src/openclaw-plugin.ts +0 -409
  117. package/src/opencode-plugin.ts +0 -298
  118. package/src/orca-session-title.test.ts +0 -54
  119. package/src/orca-session-title.ts +0 -103
  120. package/src/pack-feedback-slice.test.ts +0 -212
  121. package/src/pack-feedback-slice.ts +0 -187
  122. package/src/platform.test.ts +0 -152
  123. package/src/platform.ts +0 -173
  124. package/src/program.test.ts +0 -317
  125. package/src/program.ts +0 -842
  126. package/src/project-enablement.test.ts +0 -55
  127. package/src/project-enablement.ts +0 -99
  128. package/src/question-caps.test.ts +0 -49
  129. package/src/question-settlement-process.ts +0 -47
  130. package/src/question-timing.ts +0 -56
  131. package/src/readiness.test.ts +0 -25
  132. package/src/readiness.ts +0 -212
  133. package/src/release.ts +0 -51
  134. package/src/send-attempts.test.ts +0 -143
  135. package/src/send-attempts.ts +0 -188
  136. package/src/send.test.ts +0 -28
  137. package/src/send.ts +0 -436
  138. package/src/session-activation.ts +0 -61
  139. package/src/session-end-log-lock-worker.test.ts +0 -35
  140. package/src/session-labels.test.ts +0 -490
  141. package/src/session-labels.ts +0 -474
  142. package/src/setup-destinations.test.ts +0 -41
  143. package/src/setup-destinations.ts +0 -50
  144. package/src/skill.test.ts +0 -426
  145. package/src/sound-ref.test.ts +0 -31
  146. package/src/sound-ref.ts +0 -34
  147. package/src/trust-policy.test.ts +0 -701
  148. package/src/ui/banner.ts +0 -95
  149. package/src/ui/config-view.test.ts +0 -90
  150. package/src/ui/config-view.ts +0 -138
  151. package/src/ui/help.test.ts +0 -16
  152. package/src/ui/help.ts +0 -128
  153. package/src/ui/theme.test.ts +0 -92
  154. package/src/ui/theme.ts +0 -265
  155. package/src/url-policy.ts +0 -399
  156. package/tsconfig.json +0 -10
@@ -1,108 +0,0 @@
1
- import { openUrl } from './platform.js'
2
- import type { CommandIo } from './commands-core.js'
3
-
4
- // ---------------------------------------------------------------------------
5
- // production IO
6
- // ---------------------------------------------------------------------------
7
-
8
- /**
9
- * Whether a human is driving this terminal.
10
- *
11
- * A TTY alone is NOT that evidence: agent harnesses frequently allocate a PTY
12
- * for the commands they run, and a prompt shown to an agent does not fail — it
13
- * hangs, because every prompt library waits on stdin rather than erroring. So
14
- * this also honours `CI` and an explicit `NOTIFAI_NO_INPUT=1` escape hatch,
15
- * and every interactive affordance stays strictly optional: anything `init`
16
- * can ask, a flag can answer.
17
- */
18
- function isHumanTerminal(env: NodeJS.ProcessEnv): boolean {
19
- return (
20
- process.stdin.isTTY === true &&
21
- process.stdout.isTTY === true &&
22
- (env['CI'] ?? '') === '' &&
23
- (env['NOTIFAI_NO_INPUT'] ?? '') === ''
24
- )
25
- }
26
-
27
- /**
28
- * Lazy on purpose: the hook path runs in front of every prompt the user types,
29
- * and must not pay for a prompt library it will never show.
30
- */
31
- async function clack() {
32
- return await import('@clack/prompts')
33
- }
34
-
35
- export function realIo(env: NodeJS.ProcessEnv = process.env): CommandIo {
36
- const interactive = () => isHumanTerminal(env)
37
- return {
38
- out: (line) => console.log(line),
39
- err: (line) => console.error(line),
40
- get interactive() {
41
- return interactive()
42
- },
43
- confirm: async (question, fallback = false) => {
44
- if (!interactive()) return fallback
45
- const p = await clack()
46
- const answer = await p.confirm({ message: question, initialValue: fallback })
47
- // Ctrl-C mid-prompt arrives as a cancel symbol, not a SIGINT; treat it
48
- // as the safe answer rather than letting a Symbol escape into logic.
49
- return p.isCancel(answer) ? false : answer
50
- },
51
- select: async (message, options) => {
52
- if (!interactive()) return null
53
- const p = await clack()
54
- const answer = await p.select({ message, options })
55
- return p.isCancel(answer) ? null : (answer as string)
56
- },
57
- multiselect: async (message, options, initial) => {
58
- if (!interactive()) return null
59
- const p = await clack()
60
- const answer = await p.multiselect({
61
- message,
62
- options,
63
- required: true,
64
- ...(initial !== undefined && initial.length > 0 ? { initialValues: initial } : {}),
65
- })
66
- return p.isCancel(answer) ? null : (answer as string[])
67
- },
68
- intro: async (title) => {
69
- if (!interactive()) return
70
- ;(await clack()).intro(title)
71
- },
72
- outro: async (message) => {
73
- if (!interactive()) return
74
- ;(await clack()).outro(message)
75
- },
76
- note: async (message, title) => {
77
- if (!interactive()) return
78
- ;(await clack()).note(message, title)
79
- },
80
- spinner: async (message) => {
81
- if (!interactive()) return null
82
- const progress = (await clack()).spinner()
83
- progress.start(message)
84
- return {
85
- message: (next) => progress.message(next),
86
- stop: (next) => progress.stop(next),
87
- error: (next) => progress.error(next),
88
- }
89
- },
90
- check: async (ok, message, tone) => {
91
- if (!interactive()) return
92
- const { log } = await clack()
93
- switch (tone ?? (ok ? 'ok' : 'bad')) {
94
- case 'ok':
95
- return log.success(message)
96
- case 'warn':
97
- return log.warn(message)
98
- case 'pending':
99
- // Never checked. `log.info` reads as neutral, which is the honest
100
- // rendering for a state no evidence was gathered about.
101
- return log.info(message)
102
- case 'bad':
103
- return log.error(message)
104
- }
105
- },
106
- openUrl,
107
- }
108
- }
@@ -1,243 +0,0 @@
1
- import { unlinkSync } from 'node:fs'
2
- import { type LogLevel } from './config.js'
3
- import {
4
- LOG_EVENTS,
5
- RECORD_LEVELS,
6
- activeLogPath,
7
- archiveLogPaths,
8
- logsDiskUsage,
9
- readLogRecords,
10
- renderRecord,
11
- type LogQuery,
12
- } from './logging.js'
13
- import { EXIT, loadLoggedConfig, type CommandDeps } from './commands-core.js'
14
-
15
- // ---------------------------------------------------------------------------
16
- // logs
17
- // ---------------------------------------------------------------------------
18
-
19
- export interface LogsFlags {
20
- json?: boolean
21
- limit?: number
22
- all?: boolean
23
- since?: string
24
- level?: string
25
- event?: string[]
26
- run?: string
27
- request?: string
28
- session?: string
29
- project?: string
30
- allProjects?: boolean
31
- grep?: string
32
- path?: boolean
33
- clear?: boolean
34
- }
35
-
36
- const LOG_RECORD_OPTIONS: readonly (readonly [keyof LogsFlags, string])[] = [
37
- ['limit', '--limit'],
38
- ['all', '--all'],
39
- ['since', '--since'],
40
- ['level', '--level'],
41
- ['event', '--event'],
42
- ['run', '--run'],
43
- ['request', '--request'],
44
- ['session', '--session'],
45
- ['project', '--project'],
46
- ['allProjects', '--all-projects'],
47
- ['grep', '--grep'],
48
- ]
49
-
50
- /**
51
- * Deliberately small. The reader is usually a model with a finite context, and
52
- * a log command whose default answer is ten thousand lines gets used once.
53
- * Everything beyond this is reachable by asking for it.
54
- */
55
- const DEFAULT_LOG_LIMIT = 30
56
- /** Even `--all` stops somewhere; an unbounded dump is never the useful answer. */
57
- const MAX_LOG_LIMIT = 2_000
58
-
59
- /** `10m`, `2h`, `1d`, or an ISO 8601 instant. */
60
- export function parseSince(raw: string, now: number): number | null {
61
- const relative = /^(\d+)([smhd])$/.exec(raw.trim())
62
- if (relative !== null) {
63
- const amount = Number(relative[1])
64
- const unit = relative[2] as 's' | 'm' | 'h' | 'd'
65
- const seconds = { s: 1, m: 60, h: 3600, d: 86400 }[unit]
66
- return now - amount * seconds * 1000
67
- }
68
- const absolute = Date.parse(raw)
69
- return Number.isNaN(absolute) ? null : absolute
70
- }
71
-
72
- /**
73
- * What this machine recorded about itself.
74
- *
75
- * The retrieval half of the local log, and the half that decides whether the
76
- * log is worth having. Three things make it usable by an agent rather than
77
- * merely available to one: the default is bounded and scoped to this project,
78
- * the filters match the questions actually asked ("that run", "that
79
- * notification", "just the failures"), and `--json` gives the machine the
80
- * records untouched on stdout while every word of explanation goes to stderr.
81
- */
82
- export function logsCommand(deps: CommandDeps, flags: LogsFlags): number {
83
- const selectedRetrievalOptions = LOG_RECORD_OPTIONS
84
- .filter(([key]) => {
85
- const value = flags[key]
86
- return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== false
87
- })
88
- .map(([, name]) => name)
89
-
90
- if (flags.path === true && flags.clear === true) {
91
- deps.io.err('Pass --path or --clear, not both.')
92
- return EXIT.usage
93
- }
94
- if (flags.path === true && selectedRetrievalOptions.length > 0) {
95
- deps.io.err(`--path cannot be combined with record options: ${selectedRetrievalOptions.join(', ')}.`)
96
- return EXIT.usage
97
- }
98
- if (flags.clear === true && selectedRetrievalOptions.length > 0) {
99
- deps.io.err(`--clear cannot be combined with record options: ${selectedRetrievalOptions.join(', ')}.`)
100
- return EXIT.usage
101
- }
102
- if (flags.project !== undefined && flags.allProjects === true) {
103
- deps.io.err('Pass --project or --all-projects, not both.')
104
- return EXIT.usage
105
- }
106
- if (flags.limit !== undefined && flags.all === true) {
107
- deps.io.err('Pass --limit or --all, not both.')
108
- return EXIT.usage
109
- }
110
- if (flags.limit !== undefined && (!Number.isInteger(flags.limit) || flags.limit <= 0)) {
111
- deps.io.err('--limit must be a positive integer.')
112
- return EXIT.usage
113
- }
114
- if (flags.limit !== undefined && flags.limit > MAX_LOG_LIMIT) {
115
- deps.io.err(`--limit cannot exceed ${MAX_LOG_LIMIT}; narrow the result with --since or filters.`)
116
- return EXIT.usage
117
- }
118
-
119
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
120
- const now = (deps.now ?? Date.now)()
121
-
122
- if (flags.path === true) {
123
- const usage = logsDiskUsage(deps.env)
124
- const archives = archiveLogPaths(deps.env)
125
- if (flags.json === true) {
126
- deps.io.out(
127
- JSON.stringify(
128
- {
129
- active: activeLogPath(deps.env),
130
- archives,
131
- files: usage.files,
132
- bytes: usage.bytes,
133
- level: config.log_level.value,
134
- max_bytes: config.log_max_bytes.value,
135
- max_files: config.log_max_files.value,
136
- local_only: true,
137
- },
138
- null,
139
- 2,
140
- ),
141
- )
142
- return EXIT.ok
143
- }
144
- deps.io.out(activeLogPath(deps.env))
145
- for (const archive of archives) deps.io.out(archive)
146
- deps.io.err(
147
- `${usage.files} file(s), ${Math.round(usage.bytes / 1024)} KB, level ${config.log_level.value}. These stay on this machine.`,
148
- )
149
- return EXIT.ok
150
- }
151
-
152
- if (flags.clear === true) {
153
- let removed = 0
154
- for (const file of [activeLogPath(deps.env), ...archiveLogPaths(deps.env)]) {
155
- try {
156
- unlinkSync(file)
157
- removed += 1
158
- } catch {
159
- // Absent, or not ours to remove; either way there is nothing to report.
160
- }
161
- }
162
- deps.io.out(
163
- flags.json === true
164
- ? JSON.stringify({ cleared_files: removed })
165
- : `Cleared ${removed} log file${removed === 1 ? '' : 's'}.`,
166
- )
167
- return EXIT.ok
168
- }
169
-
170
- const query: LogQuery = {
171
- limit: flags.limit ?? (flags.all === true ? MAX_LOG_LIMIT : DEFAULT_LOG_LIMIT),
172
- }
173
-
174
- if (flags.since !== undefined) {
175
- const since = parseSince(flags.since, now)
176
- if (since === null) {
177
- deps.io.err(`Could not read "${flags.since}" as a time. Use 10m, 2h, 1d, or an ISO 8601 instant.`)
178
- return EXIT.usage
179
- }
180
- query.since = since
181
- }
182
- if (flags.level !== undefined) {
183
- if (!(RECORD_LEVELS as readonly string[]).includes(flags.level)) {
184
- deps.io.err(`--level takes one of: ${RECORD_LEVELS.join(', ')} — not "${flags.level}".`)
185
- return EXIT.usage
186
- }
187
- query.level = flags.level as LogLevel
188
- }
189
- if (flags.event !== undefined && flags.event.length > 0) {
190
- const unknown = flags.event.filter((name) => !(LOG_EVENTS as readonly string[]).includes(name))
191
- if (unknown.length > 0) {
192
- deps.io.err(`Unknown event ${unknown.join(', ')}. Valid: ${LOG_EVENTS.join(', ')}`)
193
- return EXIT.usage
194
- }
195
- query.event = flags.event
196
- }
197
- if (flags.run !== undefined) query.run = flags.run
198
- if (flags.session !== undefined) query.session = flags.session
199
- if (flags.request !== undefined) query.request = flags.request
200
- if (flags.grep !== undefined) query.contains = flags.grep
201
-
202
- // Scoped to this project by default. A machine commonly runs several agents
203
- // in several worktrees at once, and the answer to "what just happened" is
204
- // useless if three other projects are interleaved through it.
205
- const scope =
206
- flags.project ?? (flags.allProjects === true ? undefined : (config.project.value ?? undefined))
207
- if (scope !== undefined) query.project = scope
208
-
209
- const result = readLogRecords(deps.env, query)
210
-
211
- if (flags.json === true) {
212
- for (const record of result.records) deps.io.out(JSON.stringify(record))
213
- } else {
214
- for (const record of result.records) deps.io.out(renderRecord(record))
215
- }
216
-
217
- if (result.records.length === 0) {
218
- if (config.log_level.value === 'off') {
219
- deps.io.err('Nothing is being recorded: log_level is off.')
220
- deps.io.err('Turn it on with `notifai config set log_level info --yes`.')
221
- } else if (logsDiskUsage(deps.env).files === 0) {
222
- deps.io.err('No log yet. It is written the next time a notifai command or harness hook runs.')
223
- } else {
224
- deps.io.err('No records matched. Widen it with --all-projects, --since 1d, or --all.')
225
- }
226
- return EXIT.ok
227
- }
228
-
229
- // Everything explanatory goes to stderr so `--json` leaves stdout as clean
230
- // JSONL for whatever is parsing it.
231
- const notes: string[] = []
232
- if (scope !== undefined) notes.push(`project ${scope} (--all-projects for every project)`)
233
- if (result.more) {
234
- notes.push(
235
- query.limit! < MAX_LOG_LIMIT
236
- ? `more history behind this (-n ${Math.min(query.limit! * 4, MAX_LOG_LIMIT)} or --all)`
237
- : `more history exists beyond the ${MAX_LOG_LIMIT}-record safety cap; narrow with --since or filters`,
238
- )
239
- }
240
- if (config.log_level.value !== 'debug') notes.push('`log_level = debug` records request detail')
241
- if (notes.length > 0) deps.io.err(`— ${result.records.length} records; ${notes.join('; ')}`)
242
- return EXIT.ok
243
- }
@@ -1,47 +0,0 @@
1
- import { loadLoggedConfig, EXIT, type CommandDeps } from './commands-core.js'
2
- import {
3
- disableProject,
4
- enableProject,
5
- projectBinding,
6
- projectEnabled,
7
- } from './project-enablement.js'
8
-
9
- function bindingFor(deps: CommandDeps) {
10
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
11
- return projectBinding(deps.cwd, deps.env, config.project.value)
12
- }
13
-
14
- export function projectEnableCommand(deps: CommandDeps): number {
15
- const binding = bindingFor(deps)
16
- if (binding === null) {
17
- deps.io.err('No Project can be inferred here. Run inside a Project or configure an explicit Project id.')
18
- return EXIT.usage
19
- }
20
- enableProject(binding)
21
- deps.io.out(`Notifai lifecycle behavior is enabled for Project "${binding.project}".`)
22
- return EXIT.ok
23
- }
24
-
25
- export function projectDisableCommand(deps: CommandDeps): number {
26
- const binding = bindingFor(deps)
27
- if (binding === null) {
28
- deps.io.err('No Project can be inferred here. Run inside a Project or configure an explicit Project id.')
29
- return EXIT.usage
30
- }
31
- disableProject(binding)
32
- deps.io.out(`Notifai lifecycle behavior is disabled for Project "${binding.project}".`)
33
- return EXIT.ok
34
- }
35
-
36
- export function projectStatusCommand(deps: CommandDeps, json = false): number {
37
- const binding = bindingFor(deps)
38
- const enabled = projectEnabled(binding)
39
- if (json) {
40
- deps.io.out(JSON.stringify({ project: binding?.project ?? null, enabled }))
41
- } else if (binding === null) {
42
- deps.io.out('No Project can be inferred here; lifecycle behavior is disabled.')
43
- } else {
44
- deps.io.out(`Project "${binding.project}": lifecycle behavior ${enabled ? 'enabled' : 'disabled'}.`)
45
- }
46
- return EXIT.ok
47
- }
@@ -1,156 +0,0 @@
1
- import { NOTIFICATION_IMAGE_MAX_BYTES } from '@raidiant/notifai-protocol'
2
- import { createServer, type Server } from 'node:http'
3
- import type { AddressInfo } from 'node:net'
4
- import { afterEach, describe, expect, it } from 'vitest'
5
- import { EXIT, type CommandDeps, type CommandIo } from './commands-core.js'
6
- import { readCappedBytes, uploadImage } from './commands-send-support.js'
7
- import type { ApiClient } from './client.js'
8
-
9
- let server: Server | undefined
10
-
11
- afterEach(async () => {
12
- if (server) {
13
- const closing = server
14
- server = undefined
15
- await new Promise<void>((resolve) => closing.close(() => resolve()))
16
- }
17
- })
18
-
19
- async function serving(handler: Parameters<typeof createServer>[1]): Promise<string> {
20
- server = createServer(handler)
21
- await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', resolve))
22
- const { port } = server.address() as AddressInfo
23
- return `http://127.0.0.1:${port}`
24
- }
25
-
26
- function io(): CommandIo {
27
- return {
28
- out: () => undefined,
29
- err: () => undefined,
30
- confirm: async () => false,
31
- openUrl: () => undefined,
32
- }
33
- }
34
-
35
- describe('readCappedBytes', () => {
36
- it('refuses Content-Length over the cap before reading the body', async () => {
37
- const response = new Response(null, { headers: { 'content-length': '64' } })
38
- expect(await readCappedBytes(response, 16)).toBe('too-large')
39
- })
40
-
41
- it('stops reading once the downloaded bytes exceed the cap', async () => {
42
- const response = new Response(
43
- new ReadableStream({
44
- start(controller) {
45
- controller.enqueue(new Uint8Array(12))
46
- controller.enqueue(new Uint8Array(12))
47
- controller.close()
48
- },
49
- }),
50
- )
51
- expect(await readCappedBytes(response, 16)).toBe('too-large')
52
- })
53
-
54
- it('returns a payload that fits the cap', async () => {
55
- const payload = new Uint8Array([1, 2, 3, 4])
56
- expect(await readCappedBytes(new Response(payload), 16)).toEqual(payload)
57
- })
58
- })
59
-
60
- function uploadingClient(uploaded: number[]): ApiClient {
61
- return {
62
- createMediaUpload: async () => ({
63
- media_id: 'med_1',
64
- upload_url: 'https://upload.invalid/1',
65
- upload_headers: {},
66
- expires_at: new Date(Date.now() + 60_000).toISOString(),
67
- }),
68
- uploadMedia: async (_grant: unknown, bytes: Uint8Array) => {
69
- uploaded.push(bytes.byteLength)
70
- },
71
- } as unknown as ApiClient
72
- }
73
-
74
- function refusingClient(): ApiClient {
75
- return {
76
- createMediaUpload: async () => {
77
- throw new Error('must not request an upload')
78
- },
79
- } as unknown as ApiClient
80
- }
81
-
82
- describe('uploadImage remote fetch', () => {
83
- it('uploads bytes under the media limit from an allowed self-hosted origin', async () => {
84
- const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47])
85
- const baseUrl = await serving((_request, response) => {
86
- response.setHeader('content-type', 'image/png')
87
- response.end(Buffer.from(png))
88
- })
89
- const uploaded: number[] = []
90
- const deps = { io: io(), env: {}, cwd: '/tmp' } as CommandDeps
91
-
92
- const result = await uploadImage(deps, uploadingClient(uploaded), `${baseUrl}/shot.png`, [
93
- baseUrl,
94
- ])
95
- expect(result).toEqual({ ok: true, mediaId: 'med_1' })
96
- expect(uploaded).toEqual([png.byteLength])
97
- })
98
-
99
- it('refuses that same loopback origin when the User has not allowed it', async () => {
100
- const baseUrl = await serving((_request, response) => {
101
- response.setHeader('content-type', 'image/png')
102
- response.end(Buffer.from(new Uint8Array([0x89, 0x50, 0x4e, 0x47])))
103
- })
104
- const deps = { io: io(), env: {}, cwd: '/tmp' } as CommandDeps
105
-
106
- const result = await uploadImage(deps, refusingClient(), `${baseUrl}/shot.png`)
107
- expect(result.ok).toBe(false)
108
- if (result.ok) throw new Error('expected refusal')
109
- expect(result.exit).toBe(EXIT.usage)
110
- expect(result.error).toContain('media_origins')
111
- })
112
-
113
- it('refuses a remote image whose Content-Length exceeds the server media limit', async () => {
114
- const baseUrl = await serving((_request, response) => {
115
- response.setHeader('content-type', 'image/png')
116
- response.setHeader('content-length', String(NOTIFICATION_IMAGE_MAX_BYTES + 1))
117
- response.end()
118
- })
119
- const deps = { io: io(), env: {}, cwd: '/tmp' } as CommandDeps
120
-
121
- const result = await uploadImage(deps, refusingClient(), `${baseUrl}/huge.png`, [baseUrl])
122
- expect(result.ok).toBe(false)
123
- if (result.ok) throw new Error('expected refusal')
124
- expect(result.exit).toBe(EXIT.usage)
125
- expect(result.error).toContain(String(NOTIFICATION_IMAGE_MAX_BYTES))
126
- })
127
-
128
- it('refuses a redirect out of an allowed origin into an unallowed one', async () => {
129
- const target = await serving((_request, response) => {
130
- response.setHeader('content-type', 'image/png')
131
- response.end(Buffer.from(new Uint8Array([0x89, 0x50, 0x4e, 0x47])))
132
- })
133
- // A second loopback origin the User never allowed. The first hop is
134
- // trusted; the destination is not, and each hop is checked on its own.
135
- const redirector = createServer((_request, response) => {
136
- response.writeHead(302, { location: `${target}/shot.png` })
137
- response.end()
138
- })
139
- await new Promise<void>((resolve) => redirector.listen(0, '127.0.0.1', resolve))
140
- const { port } = redirector.address() as AddressInfo
141
- const redirectOrigin = `http://127.0.0.1:${port}`
142
- const deps = { io: io(), env: {}, cwd: '/tmp' } as CommandDeps
143
-
144
- try {
145
- const result = await uploadImage(deps, refusingClient(), `${redirectOrigin}/shot.png`, [
146
- redirectOrigin,
147
- ])
148
- expect(result.ok).toBe(false)
149
- if (result.ok) throw new Error('expected refusal')
150
- expect(result.exit).toBe(EXIT.usage)
151
- expect(result.error).toContain('media_origins')
152
- } finally {
153
- await new Promise<void>((resolve) => redirector.close(() => resolve()))
154
- }
155
- })
156
- })