rvlib-shipkit 2.21.0 → 2.22.0

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 (100) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +8 -7
  4. package/src/assets/kits/identity-kit.ts +158 -2
  5. package/src/cli/cmd_Bump.ts +3 -3
  6. package/src/cli/cmd_Rec.ts +349 -0
  7. package/src/cli/cmd_Releases.ts +4 -1
  8. package/src/cli/cmd_Secret.ts +10 -3
  9. package/src/cli/cmd_Sign.ts +24 -0
  10. package/src/cli/cmd_Social.ts +44 -1
  11. package/src/cli/family-pages.ts +1 -0
  12. package/src/cli/registry.ts +4 -0
  13. package/src/core/agent-spawn.ts +4 -17
  14. package/src/core/code-lines.ts +49 -0
  15. package/src/core/discover-checks.ts +27 -3
  16. package/src/core/hard-reset.ts +34 -0
  17. package/src/core/raw-access.ts +3 -13
  18. package/src/core/throwaway-worktree.ts +72 -0
  19. package/src/home/app-sign.ts +98 -0
  20. package/src/home/gui-app.ts +31 -12
  21. package/src/home/home-routes.ts +6 -0
  22. package/src/home/serve-web.ts +1 -1
  23. package/src/identities/identities.ts +6 -0
  24. package/src/media-kinds.ts +5 -3
  25. package/src/media-store/forget.ts +54 -0
  26. package/src/media-store/put.ts +4 -3
  27. package/src/media-store/space.ts +63 -24
  28. package/src/recordings/delete.ts +19 -0
  29. package/src/recordings/edit.ts +231 -0
  30. package/src/recordings/load.ts +37 -0
  31. package/src/recordings/marks-draw.ts +111 -0
  32. package/src/recordings/marks-png.ts +25 -0
  33. package/src/recordings/marks.ts +138 -0
  34. package/src/recordings/media-kind.ts +67 -0
  35. package/src/recordings/model.ts +170 -0
  36. package/src/recordings/open.ts +33 -0
  37. package/src/recordings/place.ts +89 -0
  38. package/src/recordings/presets.ts +99 -0
  39. package/src/recordings/recorder-app/Capture.swift +510 -0
  40. package/src/recordings/recorder-app/Clip.swift +107 -0
  41. package/src/recordings/recorder-app/Editor.swift +39 -0
  42. package/src/recordings/recorder-app/Tray.swift +298 -0
  43. package/src/recordings/recorder-app/main.swift +859 -0
  44. package/src/recordings/recorder-app.ts +46 -0
  45. package/src/recordings/recorder.shipkit.ts +11 -0
  46. package/src/recordings/routes.ts +140 -0
  47. package/src/recordings/run-recorder.ts +40 -0
  48. package/src/recordings/share.ts +107 -0
  49. package/src/recordings/take.ts +146 -0
  50. package/src/recordings/view.ts +40 -0
  51. package/src/release/gate-checkout.ts +74 -0
  52. package/src/release/release-scope.ts +35 -26
  53. package/src/release/run-bump.ts +79 -37
  54. package/src/release/run-release.ts +67 -53
  55. package/src/releases/add.ts +7 -2
  56. package/src/releases/from-card.ts +3 -3
  57. package/src/releases/model.ts +29 -7
  58. package/src/repo-config.ts +7 -3
  59. package/src/review/trailer-desk.ts +1 -0
  60. package/src/review/trailer-model.ts +2 -0
  61. package/src/secrets/manager.ts +18 -1
  62. package/src/serve/hub-app/home-st.ts +15 -5
  63. package/src/serve/hub-app/home.html +1 -0
  64. package/src/serve/hub-app/hub-app.tsx +6 -1
  65. package/src/serve/hub-app/icons.tsx +2 -0
  66. package/src/serve/hub-app/palette-st.ts +1 -0
  67. package/src/serve/hub-app/project-list.tsx +1 -0
  68. package/src/serve/hub-app/projects-svc.ts +1 -1
  69. package/src/serve/hub-app/recordings-st.ts +641 -0
  70. package/src/serve/hub-app/recordings-view.tsx +504 -0
  71. package/src/serve/hub-app/recordings.css +82 -0
  72. package/src/serve/hub-app/repo-st.ts +1 -1
  73. package/src/serve/hub-app/review/trailer-page.tsx +1 -0
  74. package/src/serve/hub-app/review/trailer-st.ts +16 -0
  75. package/src/serve/hub-app/review/trailer-timeline.tsx +3 -0
  76. package/src/serve/hub-app/review.css +2 -0
  77. package/src/serve/hub-app/social/post-card.tsx +31 -3
  78. package/src/serve/hub-app/social/social-model.ts +4 -0
  79. package/src/serve/hub-app/social/social-st.ts +12 -0
  80. package/src/serve/hub-app/social.css +4 -0
  81. package/src/shipkit.ts +2 -2
  82. package/src/shot/box.ts +23 -17
  83. package/src/shot/browser-slot.ts +13 -3
  84. package/src/shot/film-box.ts +193 -117
  85. package/src/shot/shooter.ts +5 -3
  86. package/src/smoke/run-smoke.ts +8 -6
  87. package/src/social/compose.ts +14 -0
  88. package/src/social/drafts.ts +1 -1
  89. package/src/social/load.ts +16 -2
  90. package/src/social/publish/index.ts +3 -1
  91. package/src/social/publish/secret.ts +12 -4
  92. package/src/social/release-card.ts +69 -0
  93. package/src/social/release-stage.ts +49 -10
  94. package/src/social/routes.ts +5 -0
  95. package/src/social/stage.ts +9 -5
  96. package/src/trailer/build.ts +24 -0
  97. package/src/trailer/ffmpeg.ts +8 -0
  98. package/src/trailer/grammar.ts +9 -2
  99. package/src/trailer/look.ts +7 -0
  100. package/src/veille/chrome.ts +6 -3
@@ -9,11 +9,13 @@
9
9
  // The icon is core/app-icon.ts: the repo's mark, its margin cut, on a plate in
10
10
  // the repo's colour. Rebuilt only when the source, the icon, the colours or the
11
11
  // start url changed (a stamp in the bundle). No compiler, or not macOS: the caller falls back.
12
+ // The same build makes the menu bar recorder from its own source (recordings/recorder-app.ts).
12
13
  import { createHash } from 'crypto'
13
14
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
14
15
  import { dirname, join } from 'path'
15
16
  import { appIconOf, appIconPngs, identityOfRoot } from '../core/app-icon.ts'
16
17
  import { identityOfName, type Identity } from '../core/identity-color.ts'
18
+ import { SIGN_NAME, signArgs } from './app-sign.ts'
17
19
  import { homeDir } from './home-paths.ts'
18
20
  import { appNameOf, appsDir, GUI_SOURCE as SOURCE, shipkitBundleOf, wrapperBundleId, wrapperPath, type AppOf } from './process-apps.ts'
19
21
 
@@ -33,6 +35,14 @@ export type AppSpec = {
33
35
  /** where the bundle lands */
34
36
  app: string
35
37
  version: string
38
+ /** the binary's name in the bundle (default `shipkit-gui`): a bundle of another source names its own */
39
+ exe?: string
40
+ /** a menu bar app: no dock icon, no app menu (LSUIElement) */
41
+ agent?: boolean
42
+ /** why it asks for the microphone, the words of the system's prompt */
43
+ micWhy?: string
44
+ /** more plist keys, as `<key>…</key><value>` xml lines */
45
+ plist?: string
36
46
  }
37
47
 
38
48
  const xml = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
@@ -49,6 +59,7 @@ function atsOf(url: string | null): string {
49
59
  }
50
60
 
51
61
  export function infoPlist(o: Omit<AppSpec, 'app' | 'icon' | 'identity'>): string {
62
+ const exe = o.exe ?? 'shipkit-gui'
52
63
  return `<?xml version="1.0" encoding="UTF-8"?>
53
64
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
54
65
  <plist version="1.0">
@@ -56,16 +67,16 @@ export function infoPlist(o: Omit<AppSpec, 'app' | 'icon' | 'identity'>): string
56
67
  \t<key>CFBundleName</key><string>${xml(o.name)}</string>
57
68
  \t<key>CFBundleDisplayName</key><string>${xml(o.name)}</string>
58
69
  \t<key>CFBundleIdentifier</key><string>${xml(o.bundleId)}</string>
59
- \t<key>CFBundleExecutable</key><string>shipkit-gui</string>
70
+ \t<key>CFBundleExecutable</key><string>${xml(exe)}</string>
60
71
  \t<key>CFBundleIconFile</key><string>AppIcon</string>
61
72
  \t<key>CFBundlePackageType</key><string>APPL</string>
62
73
  \t<key>CFBundleShortVersionString</key><string>${xml(o.version)}</string>
63
74
  \t<key>CFBundleVersion</key><string>${xml(o.version)}</string>
64
75
  ${o.url == null ? '' : `\t<key>ShipkitStartURL</key><string>${xml(o.url)}</string>\n`}\t<key>LSMinimumSystemVersion</key><string>12.0</string>
65
76
  \t<key>NSHighResolutionCapable</key><true/>
66
- \t<key>NSMicrophoneUsageDescription</key><string>A page you open here records your voice, a trailer's lines for one.</string>
77
+ \t<key>NSMicrophoneUsageDescription</key><string>${xml(o.micWhy ?? "A page you open here records your voice, a trailer's lines for one.")}</string>
67
78
  \t<key>NSAppTransportSecurity</key>${atsOf(o.url)}
68
- </dict>
79
+ ${o.agent ? '\t<key>LSUIElement</key><true/>\n' : ''}${o.plist ?? ''}</dict>
69
80
  </plist>
70
81
  `
71
82
  }
@@ -89,12 +100,12 @@ export function stampOf(source: string, icon: string | null, identity = ''): str
89
100
 
90
101
  /** the window's binary, compiled once per source text into `bins`: swiftc
91
102
  * takes about a minute, and every bundle runs the same binary */
92
- function compiledGui(source: string, text: string, run: Run, bins: string): string {
93
- const bin = join(bins, `shipkit-gui-${createHash('sha256').update(text).digest('hex').slice(0, 16)}`)
103
+ function compiledGui(source: string | readonly string[], text: string, run: Run, bins: string, exe = 'shipkit-gui'): string {
104
+ const bin = join(bins, `${exe}-${createHash('sha256').update(text).digest('hex').slice(0, 16)}`)
94
105
  if (existsSync(bin)) return bin
95
106
  mkdirSync(bins, { recursive: true })
96
107
  const tmp = `${bin}.building-${process.pid}`
97
- const built = run(['swiftc', '-O', '-o', tmp, source])
108
+ const built = run(['swiftc', '-O', '-o', tmp, ...(typeof source === 'string' ? [source] : source)])
98
109
  if (built.code !== 0 || !existsSync(tmp)) {
99
110
  rmSync(tmp, { force: true })
100
111
  throw new Error(`swiftc could not build the window: ${built.err.slice(0, 400)}`)
@@ -105,15 +116,18 @@ function compiledGui(source: string, text: string, run: Run, bins: string): stri
105
116
 
106
117
  /** one app, built or rebuilt when stale. Throws with the step that failed.
107
118
  * `rebuilt` tells the caller a running copy is now the old one */
108
- export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string; bins?: string } = {}): Promise<{ app: string; rebuilt: boolean }> {
119
+ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string | readonly string[]; bins?: string; sign?: string[] } = {}): Promise<{ app: string; rebuilt: boolean }> {
109
120
  const { app, icon } = spec
110
121
  const run = o.run ?? runSync
111
122
  const source = o.source ?? SOURCE
112
- const text = readFileSync(source, 'utf8')
113
- const stamp = stampOf(text, icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING]))
123
+ // several sources: one module, main.swift its entry; the stamp reads them all
124
+ const text = (typeof source === 'string' ? [source] : source).map((f) => readFileSync(f, 'utf8')).join('\n')
125
+ // the machine's signing identity, when it has one, names the app across rebuilds (app-sign.ts): signed anew once it appears
126
+ const sign = o.sign ?? signArgs()
127
+ const stamp = stampOf(text, icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING, ...(spec.exe || spec.agent || spec.plist || spec.micWhy ? [spec.exe, spec.agent, spec.plist, spec.micWhy] : []), ...(sign[1] !== '-' ? [sign[1]] : [])]))
114
128
  const stampFile = join(app, 'Contents', 'Resources', 'stamp')
115
129
  if (existsSync(stampFile) && readFileSync(stampFile, 'utf8') === stamp) return { app, rebuilt: false }
116
- const bin = compiledGui(source, text, run, o.bins ?? join(homeDir(), 'gui-bin'))
130
+ const bin = compiledGui(source, text, run, o.bins ?? join(homeDir(), 'gui-bin'), spec.exe)
117
131
  const tmp = `${app}.building-${process.pid}`
118
132
  const fail = (msg: string): never => { rmSync(tmp, { recursive: true, force: true }); throw new Error(msg) }
119
133
  rmSync(tmp, { recursive: true, force: true })
@@ -121,7 +135,7 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string;
121
135
  mkdirSync(join(tmp, 'Contents', 'MacOS'), { recursive: true })
122
136
  mkdirSync(res, { recursive: true })
123
137
  writeFileSync(join(tmp, 'Contents', 'Info.plist'), infoPlist(spec))
124
- const exe = join(tmp, 'Contents', 'MacOS', 'shipkit-gui')
138
+ const exe = join(tmp, 'Contents', 'MacOS', spec.exe ?? 'shipkit-gui')
125
139
  copyFileSync(bin, exe)
126
140
  chmodSync(exe, 0o755)
127
141
  if (icon != null) {
@@ -137,7 +151,12 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string;
137
151
  }
138
152
  writeFileSync(join(res, 'stamp'), stamp)
139
153
  // signed as the bundle it is, never as the bare binary: macOS refuses notifications to a bundle its signature does not name
140
- const signed = run(['codesign', '--force', '--sign', '-', tmp])
154
+ let signed = run(['codesign', '--force', ...sign, tmp])
155
+ if (signed.code !== 0 && sign[1] !== '-') {
156
+ // the identity refused (a locked or moved keychain): the app still opens, ad hoc, and says so
157
+ console.error(`WARN app: ${spec.name} signed ad hoc, ${SIGN_NAME} refused: ${signed.err.slice(0, 200)}; its macOS permissions will not survive the next rebuild (sk sign-setup)`)
158
+ signed = run(['codesign', '--force', '--sign', '-', tmp])
159
+ }
141
160
  if (signed.code !== 0) fail(`codesign could not sign the bundle: ${signed.err.slice(0, 200)}`)
142
161
  mkdirSync(dirname(app), { recursive: true })
143
162
  // a rename, never `mv`: a build that lands in between would get this one nested inside it
@@ -200,6 +200,12 @@ export function homeRoutes(d: HomeDeps) {
200
200
  const tracked = await postTrackerRoute(req, path)
201
201
  if (tracked != null) return tracked
202
202
  if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
203
+ // the screen recorder's takes of every repo (recordings/routes.ts)
204
+ if (path.startsWith('/api/home/recordings')) {
205
+ const { recordingsRoute } = await import('../recordings/routes.ts')
206
+ const r = await recordingsRoute(req, path)
207
+ if (r != null) return r
208
+ }
203
209
  if (path.startsWith('/api/projects')) return d.gutter.handle(req, path)
204
210
  // who speaks for each repo, and where its data lives (identities/machine-route.ts)
205
211
  if (path.startsWith('/api/home/identities')) return identitiesRoute(req, path, d.root)
@@ -19,7 +19,7 @@ import { HMR_BEAT_MS, HMR_KEEP_SCRIPT, HMR_WORDS } from './hmr-keep.ts'
19
19
  /** the page routes: ONE app for the overview, the plan, and the hub page of
20
20
  * each known repo, which moves between them in place (home-st.ts) */
21
21
  export function pageRoutes<T>(names: string[], page: T): Record<string, T> {
22
- const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page, '/identities': page }
22
+ const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page, '/recordings': page, '/identities': page }
23
23
  for (const n of names) out[`${hubBase(n)}/`] = page
24
24
  return out
25
25
  }
@@ -75,6 +75,10 @@ export type Account = {
75
75
  /** the page where its profile is edited (the name, the bio, the avatar) */
76
76
  settings: string
77
77
  max: number | null
78
+ /** the most tags its tag field takes (`max tags`); null, no cap */
79
+ maxTags: number | null
80
+ /** who a post may be shown to (`tiers`, its labels as the platform shows them, the open one first); empty, no tiers */
81
+ tiers: string[]
78
82
  /** the field a message's text goes in: description, comment; empty, the post's own text */
79
83
  text: string
80
84
  /** the word the accounts that take the same messages share, or empty */
@@ -349,6 +353,8 @@ function account(identity: string, id: string, dir: string, shared: ProfileRow[]
349
353
  stats: meta.stats ?? '',
350
354
  settings: meta.settings ?? '',
351
355
  max: meta.max ? Number(meta.max) : null,
356
+ maxTags: meta['max tags'] ? Number(meta['max tags']) : null,
357
+ tiers: (meta.tiers ?? '').split(',').map((t) => t.trim()).filter(Boolean),
352
358
  text: meta.text ?? '',
353
359
  group: meta.group ?? '',
354
360
  place: meta.place ?? '',
@@ -2,14 +2,16 @@
2
2
  // this list. A new caller writes its kind beside its own code and adds its line here
3
3
  import type { MediaKind } from './media-store/kind.ts'
4
4
  import { handKind, labelsInIndex } from './media-store/hand.ts'
5
+ import { recordingKinds, recordingMedia } from './recordings/media-kind.ts'
5
6
  import { reviewMedia } from './review/media-kind.ts'
6
7
  import { trailerMedia } from './review/trailer-media.ts'
7
8
  import { socialMedia } from './social/media-kind.ts'
8
9
 
9
- export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia, socialMedia]
10
+ export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia, socialMedia, recordingMedia]
10
11
 
11
- /** the kinds of the code, then the generic kind of every other label the index holds (`sk media put`) */
12
+ /** the kinds of the code (a recording kind per root a take went to), then the generic kind of every other label the
13
+ * index holds (`sk media put`) */
12
14
  export function mediaKinds(): MediaKind[] {
13
15
  const code = new Set(MEDIA_KINDS.map((k) => k.kind))
14
- return [...MEDIA_KINDS, ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
16
+ return [...MEDIA_KINDS.filter((k) => k !== recordingMedia), ...recordingKinds(), ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
15
17
  }
@@ -0,0 +1,54 @@
1
+ // the ONE place an object leaves the Space for good (wiki tools/shipkit/media-store.md, What it guarantees): every version of it
2
+ // deleted, so no link and no undo reaches it, and its index rows dropped. Only an owner's explicit delete of his own
3
+ // file calls it (a recording, tools/shipkit/recordings.md, Delete); a purge, a sync or any command of its own never does.
4
+ // The guard test (tests/media-store/no-remote-delete.test.ts) refuses an S3 delete in any other file
5
+ import { existsSync, realpathSync } from 'node:fs'
6
+ import { join, sep } from 'node:path'
7
+ import { mediaDb } from './db.ts'
8
+ import { houseSpaceConfig, signedCall, signedDelete } from './space.ts'
9
+
10
+ /** every version of the key and every delete marker over it, as S3 lists them (ListObjectVersions) */
11
+ async function versionsOf(key: string): Promise<string[]> {
12
+ const { config, why } = await houseSpaceConfig()
13
+ if (!config) throw new Error(why)
14
+ const xml = await signedCall(config, 'GET', null, { versions: '', prefix: key })
15
+ const ids: string[] = []
16
+ for (const m of xml.matchAll(/<(?:Version|DeleteMarker)>([\s\S]*?)<\/(?:Version|DeleteMarker)>/g)) {
17
+ const k = /<Key>([^<]*)<\/Key>/.exec(m[1]!)?.[1]
18
+ const v = /<VersionId>([^<]*)<\/VersionId>/.exec(m[1]!)?.[1]
19
+ if (k === key && v) ids.push(v)
20
+ }
21
+ return ids
22
+ }
23
+
24
+ /** the keys gone from the Space for good, each version of each, and from the index; a key an index row outside the
25
+ * owner's folder still names (the same content kept elsewhere) is kept and said */
26
+ export async function forgetForGood(keys: readonly string[], o: { owner: string }): Promise<{ gone: string[]; kept: { key: string; why: string }[] }> {
27
+ const { config, why } = await houseSpaceConfig()
28
+ if (!config) throw new Error(`nothing is deleted: ${why}`)
29
+ const db = mediaDb()
30
+ if (!db) throw new Error('the media index does not open: nothing is deleted')
31
+ const gone: string[] = []
32
+ const kept: { key: string; why: string }[] = []
33
+ // a hand put keeps the real path (links resolved), a kind's scan the path it was given: the owner's folder both ways
34
+ const owners = [join(o.owner), ...(existsSync(o.owner) ? [realpathSync(o.owner)] : [])]
35
+ for (const key of keys) {
36
+ // a row is the owner's when its file sits in the owner's folder (a hand put of it lands under any store)
37
+ const inside = (store: string, item: string): boolean => owners.some((ow) => (join(store, item) + sep).startsWith(ow + sep))
38
+ const others = (db.query('select store, item from files where key = ?').all(key) as { store: string; item: string }[]).filter((r) => !inside(r.store, r.item))
39
+ if (others.length > 0) {
40
+ kept.push({ key, why: `${others[0]!.store}/${others[0]!.item} holds the same content` })
41
+ continue
42
+ }
43
+ // a bucket lists every object with its versions (an unversioned one under the version `null`): an empty list
44
+ // is a key already gone, and a plain delete would only leave a marker behind
45
+ for (const v of await versionsOf(key)) await signedDelete(config, key, { versionId: v })
46
+ if ((await versionsOf(key)).length > 0) throw new Error(`${key}: versions remain after the delete`)
47
+ db.transaction(() => {
48
+ db.query('delete from files where key = ?').run(key)
49
+ db.query('delete from objects where key = ?').run(key)
50
+ })()
51
+ gone.push(key)
52
+ }
53
+ return { gone, kept }
54
+ }
@@ -113,14 +113,15 @@ async function keyOf(ref: string): Promise<{ key: string; size: number; name: st
113
113
  return { key: same[0]!.key, size: same[0]!.size, name: at.name }
114
114
  }
115
115
 
116
- /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`) */
117
- export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number }): Promise<Link> {
116
+ /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`); `inline` plays it in
117
+ * the browser that opens it */
118
+ export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number; inline?: boolean }): Promise<Link> {
118
119
  if (o.seconds > SIGNED_MAX_S) throw new Error(`a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
119
120
  const k = await keyOf(ref)
120
121
  const { space, why } = await machineSpace()
121
122
  if (!space) throw new Error(why)
122
123
  if (!(await confirmedUp(k.key, k.size))) throw new Error(`${k.key}: not in the Space yet (sk media upload sends what waits)`)
123
124
  const name = o.name ?? k.name ?? basename(k.key)
124
- const url = space.signed(k.key, o.seconds, { name, type: typeOf(name) })
125
+ const url = space.signed(k.key, o.seconds, { name, type: typeOf(name), ...(o.inline ? { inline: true } : {}) })
125
126
  return { key: k.key, sha: shaOfKey(k.key) ?? '', size: k.size, name, url, expires: new Date((o.now ?? Date.now()) + o.seconds * 1000).toISOString() }
126
127
  }
@@ -48,8 +48,9 @@ export interface Space {
48
48
  head(key: string): Promise<{ size: number } | null>
49
49
  /** a GET URL good for `seconds`, on the CDN edge when the Space has one: signed for the origin host, which the edge
50
50
  * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch). `as` signs a download
51
- * under that file name: `response-content-disposition` and `response-content-type` ride in the signed query */
52
- signed(key: string, seconds?: number, as?: { name: string; type: string }): string
51
+ * under that file name: `response-content-disposition` and `response-content-type` ride in the signed query;
52
+ * `inline` plays it in the browser that opens the link, the name kept for a save */
53
+ signed(key: string, seconds?: number, as?: { name: string; type: string; inline?: boolean }): string
53
54
  /** the permanent URL of a `public/` object, on the CDN edge when the Space has one; throws for any other key */
54
55
  publicUrl(key: string): string
55
56
  /** the object written at `to`, through a file beside it renamed: no reader sees half of it */
@@ -70,26 +71,46 @@ const missing = (e: unknown): boolean => {
70
71
  /** the longest a signed URL can last: the SigV4 limit */
71
72
  export const SIGNED_MAX_S = 7 * 86_400
72
73
 
73
- /** `attachment` under the name: a plain ascii fallback, the exact name in `filename*` when it is not ascii */
74
- export function attachment(name: string): string {
74
+ /** `attachment` (or `inline`) under the name: a plain ascii fallback, the exact name in `filename*` when it is not ascii */
75
+ export function attachment(name: string, inline = false): string {
76
+ const how = inline ? 'inline' : 'attachment'
75
77
  const plain = name.replace(/[^\x20-\x7e]|["\\]/g, '_')
76
- return plain === name ? `attachment; filename="${name}"` : `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`
78
+ return plain === name ? `${how}; filename="${name}"` : `${how}; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`
77
79
  }
78
80
 
79
81
  const hex = (b: ArrayBuffer | Uint8Array): string => Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString('hex')
80
82
  const sha256 = (s: string): string => new Bun.CryptoHasher('sha256').update(s).digest('hex')
81
83
  const hmac = (key: string | Uint8Array, s: string): Uint8Array => new Uint8Array(new Bun.CryptoHasher('sha256', key).update(s).digest())
82
84
 
83
- /** one bucket call Bun's S3 client has no verb for, signed by hand (SigV4, header auth): `?<sub>` on the bucket */
84
- async function bucketCall(c: SpaceConfig, method: 'GET' | 'PUT', sub: string, body = ''): Promise<string> {
85
- const url = new URL(c.path === true ? `${c.endpoint}/${c.bucket}` : `${c.endpoint}/`)
86
- url.search = sub
85
+ /** S3's own encoding of a path or query part: every byte but the unreserved ones, `/` kept in a path */
86
+ const s3enc = (v: string, path = false): string => {
87
+ const e = encodeURIComponent(v).replace(/[!'()*]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`)
88
+ return path ? e.replace(/%2F/g, '/') : e
89
+ }
90
+
91
+ /** one call Bun's S3 client has no verb for, signed by hand (SigV4, header auth): on the bucket (`key` null) or on an
92
+ * object, with its query (a sub resource is a name with an empty value, `{ versioning: '' }`). Answers its text.
93
+ * No DELETE here: the one delete of the Space is signedDelete, which forget.ts alone calls */
94
+ export function signedCall(c: SpaceConfig, method: 'GET' | 'PUT', key: string | null, query: Record<string, string>, body = ''): Promise<string> {
95
+ return signed(c, method, key, query, body)
96
+ }
97
+
98
+ /** an object's version deleted for good: forget.ts alone calls it (tests/media-store/no-remote-delete.test.ts) */
99
+ export function signedDelete(c: SpaceConfig, key: string, query: Record<string, string>): Promise<string> {
100
+ return signed(c, 'DELETE', key, query)
101
+ }
102
+
103
+ async function signed(c: SpaceConfig, method: 'GET' | 'PUT' | 'DELETE', key: string | null, query: Record<string, string>, body = ''): Promise<string> {
104
+ const base = c.path === true ? `${c.endpoint}/${c.bucket}` : c.endpoint
105
+ const url = new URL(key === null ? (c.path === true ? base : `${base}/`) : `${base}/${s3enc(key, true)}`)
106
+ const qs = Object.keys(query).sort().map((k) => `${s3enc(k)}=${s3enc(query[k]!)}`).join('&')
107
+ url.search = qs
87
108
  const now = new Date().toISOString().replace(/[-:]|\.\d{3}/g, '')
88
109
  const day = now.slice(0, 8)
89
110
  const payload = sha256(body)
90
111
  const headers: Record<string, string> = { host: url.host, 'x-amz-content-sha256': payload, 'x-amz-date': now }
91
112
  const names = Object.keys(headers).sort()
92
- const canonical = [method, url.pathname, `${sub}=`, ...names.map((n) => `${n}:${headers[n]}`), '', names.join(';'), payload].join('\n')
113
+ const canonical = [method, url.pathname, qs, ...names.map((n) => `${n}:${headers[n]}`), '', names.join(';'), payload].join('\n')
93
114
  const scope = `${day}/${c.region}/s3/aws4_request`
94
115
  const toSign = ['AWS4-HMAC-SHA256', now, scope, sha256(canonical)].join('\n')
95
116
  const k = hmac(hmac(hmac(hmac(`AWS4${c.creds.secretAccessKey}`, day), c.region), 's3'), 'aws4_request')
@@ -98,10 +119,12 @@ async function bucketCall(c: SpaceConfig, method: 'GET' | 'PUT', sub: string, bo
98
119
  const md5: Record<string, string> = body !== '' ? { 'Content-MD5': new Bun.CryptoHasher('md5').update(body).digest('base64') } : {}
99
120
  const r = await fetch(url, { method, headers: { ...sent, ...md5, Authorization: auth }, ...(body !== '' ? { body } : {}) })
100
121
  const text = await r.text()
101
- if (!r.ok) throw new Error(`${method} ?${sub} on ${c.bucket}: ${r.status} ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? text.slice(0, 200)}`)
122
+ if (!r.ok) throw new Error(`${method} ${key ?? ''}?${qs} on ${c.bucket}: ${r.status} ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? text.slice(0, 200)}`)
102
123
  return text
103
124
  }
104
125
 
126
+ const bucketCall = (c: SpaceConfig, method: 'GET' | 'PUT', sub: string, body = ''): Promise<string> => signedCall(c, method, null, { [sub]: '' }, body)
127
+
105
128
  export function spaceOf(c: SpaceConfig): Space {
106
129
  const client = new S3Client({ ...c.creds, bucket: c.bucket, region: c.region, endpoint: c.endpoint, virtualHostedStyle: c.path !== true })
107
130
  const origin = new URL(c.endpoint).host
@@ -121,7 +144,7 @@ export function spaceOf(c: SpaceConfig): Space {
121
144
  }
122
145
  },
123
146
  signed(key, seconds = SIGNED_S, as) {
124
- const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET', ...(as ? { contentDisposition: attachment(as.name), type: as.type } : {}) }))
147
+ const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET', ...(as ? { contentDisposition: attachment(as.name, as.inline === true), type: as.type } : {}) }))
125
148
  if (edge && url.host === origin) url.host = edge
126
149
  return url.toString()
127
150
  },
@@ -168,30 +191,46 @@ export function machineSpace(): Promise<{ space: Space | null; why: string }> {
168
191
  return held
169
192
  }
170
193
 
171
- /** the house's Space signed with the key pair of `secret` (the config's own key when none is given), read anew: a one
172
- * time key with more rights (turning versioning on) never replaces the machine's held one */
173
- export function spaceFromHouse(secret?: string): Promise<{ space: Space | null; why: string }> {
174
- return (async () => {
175
- if (process.env.SHIPKIT_SPACES === 'off') return { space: null, why: 'SHIPKIT_SPACES=off' }
194
+ /** the house's Space signed with the key pair of `secret` (the config's own key when none is given). A one time key
195
+ * with more rights (turning versioning on) is read anew and never held; the house's own is held for the process */
196
+ export async function spaceFromHouse(secret?: string): Promise<{ space: Space | null; why: string }> {
197
+ const c = await houseSpaceConfig(secret)
198
+ return { space: c.config ? spaceOf(c.config) : null, why: c.why }
199
+ }
200
+
201
+ let config: { config: SpaceConfig | null; why: string } | null = null
202
+
203
+ /** the house's Space as a config, the key pair read: what a hand signed call needs (forget.ts) */
204
+ export async function houseSpaceConfig(secret?: string): Promise<{ config: SpaceConfig | null; why: string }> {
205
+ if (secret === undefined && config) return config
206
+ const out = await (async (): Promise<{ config: SpaceConfig | null; why: string }> => {
207
+ if (process.env.SHIPKIT_SPACES === 'off') return { config: null, why: 'SHIPKIT_SPACES=off' }
176
208
  const { houseRootOf } = await import('../home/home-start.ts')
177
209
  const { loadRepoConfig } = await import('../repo-config.ts')
178
210
  const house = houseRootOf(process.cwd())
179
- if (!house) return { space: null, why: `no house repo seen from ${process.cwd()}` }
211
+ if (!house) return { config: null, why: `no house repo seen from ${process.cwd()}` }
180
212
  const c = await loadRepoConfig(house)
181
213
  const r = c.serve?.mediaSpace
182
- if (!r) return { space: null, why: `the house config (${house}) names no serve.mediaSpace` }
183
- if (!c.credsReadCommand) return { space: null, why: `the house config (${house}) declares no credsReadCommand to read ${r.secret}` }
214
+ if (!r) return { config: null, why: `the house config (${house}) names no serve.mediaSpace` }
215
+ if (!c.credsReadCommand) return { config: null, why: `the house config (${house}) declares no credsReadCommand to read ${r.secret}` }
184
216
  const name = secret ?? r.secret
185
217
  let v = ''
186
218
  try {
187
219
  v = readSecret(c.credsReadCommand, name)
188
220
  } catch (e) {
189
- return { space: null, why: (e as Error).message }
221
+ return { config: null, why: (e as Error).message }
190
222
  }
191
223
  const at = v.indexOf(':')
192
- if (at <= 0) return { space: null, why: `the secret ${name} is no KEY:SECRET pair` }
193
- return { space: spaceOf({ ...r, cdn: r.cdn ?? null, creds: { accessKeyId: v.slice(0, at), secretAccessKey: v.slice(at + 1) } }), why: '' }
194
- })().catch((e: unknown) => ({ space: null, why: `the house config does not load: ${(e as Error).message}` }))
224
+ if (at <= 0) return { config: null, why: `the secret ${name} is no KEY:SECRET pair` }
225
+ return { config: { ...r, cdn: r.cdn ?? null, creds: { accessKeyId: v.slice(0, at), secretAccessKey: v.slice(at + 1) } }, why: '' }
226
+ })().catch((e: unknown) => ({ config: null, why: `the house config does not load: ${(e as Error).message}` }))
227
+ if (secret === undefined && out.config) config = out
228
+ return out
229
+ }
230
+
231
+ /** a test's own Space config in place of the house's (forget.ts); undefined reads the house's again */
232
+ export function useSpaceConfig(c: SpaceConfig | null | undefined): void {
233
+ config = c === undefined ? null : { config: c, why: c ? '' : 'no Space in this test' }
195
234
  }
196
235
 
197
236
  /** a test's own Space in place of the machine's; undefined gives the machine's back */
@@ -0,0 +1,19 @@
1
+ // a recording deleted for good (wiki tools/shipkit/recordings.md, Delete): every Space key it ever had (its files, an
2
+ // older export, every public copy) off the Space, every version, so a private link dies at once (a public one when the
3
+ // CDN's copy expires, an hour at most); then its folder to the Trash. The Space goes first: a failure
4
+ // there keeps the take on the disk, so the delete can run again
5
+ import { mediaKey } from '../media-store/content.ts'
6
+ import { forgetForGood } from '../media-store/forget.ts'
7
+ import { RECORDING_KIND } from './media-kind.ts'
8
+ import type { Recording } from './model.ts'
9
+ import { trash } from './open.ts'
10
+ import { publicKeyOf } from './share.ts'
11
+
12
+ export async function deleteRecording(r: Recording, o: { trash?: (dir: string) => Promise<void> } = {}): Promise<{ gone: number; kept: string[] }> {
13
+ // what it holds now, every key it held before (an older export, an older public copy), and its public copy
14
+ const keys = new Set([...Object.entries(r.files).map(([name, f]) => mediaKey(RECORDING_KIND, f, name)), ...(r.former ?? [])])
15
+ if (r.publicUrl) keys.add(publicKeyOf(r.publicUrl))
16
+ const res = await forgetForGood([...keys], { owner: r.dir })
17
+ await (o.trash ?? trash)(r.dir)
18
+ return { gone: res.gone.length, kept: res.kept.map((k) => `${k.key}: ${k.why}`) }
19
+ }