@crombolo/core 0.33.1 → 0.35.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.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @crombolo/core
2
+
3
+ **Internal to crombolo.** This package is published because
4
+ [`@crombolo/crombolo`](https://www.npmjs.com/package/@crombolo/crombolo)
5
+ depends on it, and its exports can change in any release, a patch included.
6
+
7
+ Import from `@crombolo/crombolo` instead:
8
+
9
+ - `@crombolo/crombolo` for a site: its config, its boot and its views.
10
+ - `@crombolo/crombolo/bundle` for a server bundle's author.
11
+ - `@crombolo/crombolo/host` for whoever runs sites.
12
+
13
+ Those three entry points carry the compatibility promise in
14
+ [`docs/api.md`](https://github.com/kineco-au/crombolo-cms/blob/main/docs/api.md).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crombolo/core",
3
- "version": "0.33.1",
4
- "description": "Domain model, entity keys and shared contracts for crombolo. No I/O.",
3
+ "version": "0.35.2",
4
+ "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. Domain model, entity keys and shared contracts for crombolo. No I/O.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
7
7
  "homepage": "https://github.com/kineco-au/crombolo-cms#readme",
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ export * from './form-submissions.ts'
5
5
  export * from './forms.ts'
6
6
  export * from './json-patch.ts'
7
7
  export * from './keys.ts'
8
+ export * from './media-access.ts'
8
9
  export * from './notifications.ts'
9
10
  export * from './object-types.ts'
10
11
  export * from './paging.ts'
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Who may read and change a media item (story 196). A folder or item may carry
3
+ * a rule naming member groups that may read and write; the nearest rule on an
4
+ * item's path governs, as for protected pages. Each item also has its own read
5
+ * and write policy, stamped from the folder's defaults when it was created.
6
+ */
7
+
8
+ /** An item's own setting: `inherit` follows the nearest rule. */
9
+ export type MediaPolicy = 'inherit' | 'public' | 'groups' | 'creator' | 'none'
10
+
11
+ /** Who may see a file created in a folder later. */
12
+ export type NewMediaRead = 'public' | 'groups' | 'creator'
13
+ /** Who may change a file created in a folder later. */
14
+ export type NewMediaWrite = 'groups' | 'creator' | 'none'
15
+
16
+ export const MEDIA_POLICIES: readonly MediaPolicy[] = [
17
+ 'inherit',
18
+ 'public',
19
+ 'groups',
20
+ 'creator',
21
+ 'none',
22
+ ]
23
+ export const NEW_MEDIA_READ: readonly NewMediaRead[] = ['public', 'groups', 'creator']
24
+ export const NEW_MEDIA_WRITE: readonly NewMediaWrite[] = ['groups', 'creator', 'none']
25
+
26
+ /** A rule set on a media folder or item, governing it and everything below that sets none. */
27
+ export interface MediaRule {
28
+ /** The node the rule is set on. */
29
+ nodeId: number
30
+ /** Anyone may read, whatever the groups say. */
31
+ publicRead: boolean
32
+ readGroups: readonly string[]
33
+ writeGroups: readonly string[]
34
+ /** What files created below get; null leaves them following the rule. */
35
+ newRead: NewMediaRead | null
36
+ newWrite: NewMediaWrite | null
37
+ /** File types a member may upload below (story 198), by name; empty is none. */
38
+ memberTypes: readonly string[]
39
+ /** The largest file a member may upload below, in bytes; null sets no limit of its own. */
40
+ memberMaxBytes: number | null
41
+ }
42
+
43
+ /** What an item says about itself. */
44
+ export interface MediaItemAccess {
45
+ readPolicy: MediaPolicy
46
+ writePolicy: MediaPolicy
47
+ /** The member who created it, by key. */
48
+ creatorMemberKey: string | null
49
+ }
50
+
51
+ /** The member asking, by key and the names of their groups. */
52
+ export interface MediaMember {
53
+ key: string
54
+ groups: readonly string[]
55
+ }
56
+
57
+ export const OPEN_MEDIA: MediaItemAccess = {
58
+ readPolicy: 'inherit',
59
+ writePolicy: 'inherit',
60
+ creatorMemberKey: null,
61
+ }
62
+
63
+ export const parseMediaPolicy = (value: unknown): MediaPolicy =>
64
+ MEDIA_POLICIES.includes(value as MediaPolicy) ? (value as MediaPolicy) : 'inherit'
65
+
66
+ /** The nearest rule on a path of node ids (`-1,1050,1063`), the node's own first. Pure. */
67
+ export function nearestMediaRule(
68
+ path: string,
69
+ rules: ReadonlyMap<number, MediaRule>,
70
+ ): MediaRule | undefined {
71
+ const ids = path.split(',').map(Number)
72
+ for (let i = ids.length - 1; i >= 0; i--) {
73
+ const rule = rules.get(ids[i] as number)
74
+ if (rule) return rule
75
+ }
76
+ return undefined
77
+ }
78
+
79
+ const inGroups = (names: readonly string[], member: MediaMember | undefined) => {
80
+ if (!member) return false
81
+ const held = new Set(member.groups.map((g) => g.toLowerCase()))
82
+ return names.some((name) => held.has(name.toLowerCase()))
83
+ }
84
+
85
+ /**
86
+ * Whether a member, or a visitor when `member` is undefined, may read or change
87
+ * an item. The item's own policy wins; `inherit` follows the nearest rule, and
88
+ * with no rule anyone may read and no member may change. Groups match in any
89
+ * case. Pure.
90
+ */
91
+ export function memberMay(
92
+ action: 'read' | 'write',
93
+ item: MediaItemAccess,
94
+ rule: MediaRule | undefined,
95
+ member: MediaMember | undefined,
96
+ ): boolean {
97
+ const policy = action === 'read' ? item.readPolicy : item.writePolicy
98
+ const groups = action === 'read' ? (rule?.readGroups ?? []) : (rule?.writeGroups ?? [])
99
+ switch (policy) {
100
+ case 'public':
101
+ return action === 'read'
102
+ case 'groups':
103
+ return inGroups(groups, member)
104
+ case 'creator':
105
+ return (
106
+ member !== undefined &&
107
+ item.creatorMemberKey !== null &&
108
+ member.key.toLowerCase() === item.creatorMemberKey.toLowerCase()
109
+ )
110
+ case 'none':
111
+ return false
112
+ case 'inherit':
113
+ if (action === 'read') return !rule || rule.publicRead || inGroups(groups, member)
114
+ return inGroups(groups, member)
115
+ }
116
+ }
117
+
118
+ /** Whether an item is closed to a visitor who is not signed in. Pure. */
119
+ export const isProtectedMedia = (item: MediaItemAccess, rule: MediaRule | undefined): boolean =>
120
+ !memberMay('read', item, rule, undefined)
121
+
122
+ /** The policies a new file gets from the rule above it. Pure. */
123
+ export function stampedPolicies(rule: MediaRule | undefined): {
124
+ readPolicy: MediaPolicy
125
+ writePolicy: MediaPolicy
126
+ } {
127
+ return { readPolicy: rule?.newRead ?? 'inherit', writePolicy: rule?.newWrite ?? 'inherit' }
128
+ }
package/src/uploads.ts CHANGED
@@ -39,3 +39,127 @@ export function isUploadAllowed(fileName: string, settings: UploadSettings): boo
39
39
  if (settings.disallowedExtensions.includes(extension)) return false
40
40
  return settings.allowedExtensions.length === 0 || settings.allowedExtensions.includes(extension)
41
41
  }
42
+
43
+ /** The extension of a file name, lowercase and without the dot; `''` when it has none. Pure. */
44
+ export const extensionOf = (fileName: string): string => {
45
+ const dot = fileName.lastIndexOf('.')
46
+ return dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : ''
47
+ }
48
+
49
+ /**
50
+ * A file type a member may be allowed to upload into a media folder (story
51
+ * 198), recognised by its first bytes. `image` types are re-encoded on the way
52
+ * in, so their metadata is stripped.
53
+ */
54
+ export interface MemberFileType {
55
+ /** Stored on the folder's rule. */
56
+ id: string
57
+ label: string
58
+ extensions: readonly string[]
59
+ image: boolean
60
+ }
61
+
62
+ export const MEMBER_FILE_TYPES: readonly MemberFileType[] = [
63
+ { id: 'jpeg', label: 'JPEG image', extensions: ['jpg', 'jpeg'], image: true },
64
+ { id: 'png', label: 'PNG image', extensions: ['png'], image: true },
65
+ { id: 'gif', label: 'GIF image', extensions: ['gif'], image: true },
66
+ { id: 'webp', label: 'WebP image', extensions: ['webp'], image: true },
67
+ { id: 'avif', label: 'AVIF image', extensions: ['avif'], image: true },
68
+ { id: 'heic', label: 'HEIC image (iPhone)', extensions: ['heic', 'heif'], image: true },
69
+ { id: 'pdf', label: 'PDF document', extensions: ['pdf'], image: false },
70
+ { id: 'mp3', label: 'MP3 audio', extensions: ['mp3'], image: false },
71
+ { id: 'wav', label: 'WAV audio', extensions: ['wav'], image: false },
72
+ { id: 'mp4', label: 'MP4 video', extensions: ['mp4', 'm4v'], image: false },
73
+ { id: 'mov', label: 'QuickTime video', extensions: ['mov'], image: false },
74
+ ]
75
+
76
+ const memberFileType = (id: string) => MEMBER_FILE_TYPES.find((type) => type.id === id)
77
+
78
+ const ascii = (bytes: Uint8Array, at: number, length: number) =>
79
+ String.fromCharCode(...bytes.subarray(at, at + length))
80
+
81
+ /** The brands an ISO media file's `ftyp` box names: its major brand and the compatible ones. */
82
+ function ftypBrands(bytes: Uint8Array): string[] {
83
+ if (bytes.length < 12 || ascii(bytes, 4, 4) !== 'ftyp') return []
84
+ const size = Math.min(
85
+ bytes.length,
86
+ ((bytes[0] as number) << 24) |
87
+ ((bytes[1] as number) << 16) |
88
+ ((bytes[2] as number) << 8) |
89
+ (bytes[3] as number),
90
+ )
91
+ const brands = [ascii(bytes, 8, 4)]
92
+ for (let at = 16; at + 4 <= size; at += 4) brands.push(ascii(bytes, at, 4))
93
+ return brands
94
+ }
95
+
96
+ /**
97
+ * What a file is, read from its first bytes (its magic number) for the types
98
+ * members may be allowed to upload; undefined for anything else. Pure.
99
+ */
100
+ export function detectFileType(bytes: Uint8Array): string | undefined {
101
+ const starts = (...values: number[]) => values.every((value, i) => bytes[i] === value)
102
+ if (starts(0xff, 0xd8, 0xff)) return 'jpeg'
103
+ if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return 'png'
104
+ if (ascii(bytes, 0, 6) === 'GIF87a' || ascii(bytes, 0, 6) === 'GIF89a') return 'gif'
105
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'webp'
106
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WAVE') return 'wav'
107
+ if (ascii(bytes, 0, 5) === '%PDF-') return 'pdf'
108
+ if (ascii(bytes, 0, 3) === 'ID3' || (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0))
109
+ return 'mp3'
110
+ const brands = ftypBrands(bytes)
111
+ if (brands.length > 0) {
112
+ if (brands.some((b) => b === 'avif' || b === 'avis')) return 'avif'
113
+ if (
114
+ brands.some((b) =>
115
+ ['heic', 'heix', 'heim', 'heis', 'hevc', 'hevx', 'mif1', 'msf1'].includes(b),
116
+ )
117
+ )
118
+ return 'heic'
119
+ if (brands[0] === 'qt ') return 'mov'
120
+ if (
121
+ brands.some((b) =>
122
+ ['isom', 'iso2', 'iso4', 'iso5', 'iso6', 'mp41', 'mp42', 'avc1', 'M4V ', 'dash'].includes(
123
+ b,
124
+ ),
125
+ )
126
+ )
127
+ return 'mp4'
128
+ }
129
+ return undefined
130
+ }
131
+
132
+ /** Why a member's upload is refused, or the type it is. */
133
+ export type MemberUploadCheck =
134
+ | { ok: true; type: MemberFileType }
135
+ | { ok: false; reason: string; status: 400 | 415 }
136
+
137
+ /**
138
+ * Whether a member may upload this file where `allowed` lists the types
139
+ * accepted: what its first bytes say it is, its extension and the list must
140
+ * all agree, and the site's own upload settings must not refuse it. Pure.
141
+ */
142
+ export function checkMemberUpload(
143
+ fileName: string,
144
+ head: Uint8Array,
145
+ allowed: readonly string[],
146
+ settings: UploadSettings = DEFAULT_UPLOAD_SETTINGS,
147
+ ): MemberUploadCheck {
148
+ const extension = extensionOf(fileName)
149
+ if (!extension)
150
+ return { ok: false, status: 400, reason: 'The file needs an extension, such as .jpg.' }
151
+ if (!isUploadAllowed(fileName, settings))
152
+ return { ok: false, status: 415, reason: `This site does not accept .${extension} files.` }
153
+ const detected = detectFileType(head)
154
+ const type = detected ? memberFileType(detected) : undefined
155
+ if (!type) return { ok: false, status: 415, reason: 'This kind of file cannot be uploaded here.' }
156
+ if (!type.extensions.includes(extension))
157
+ return {
158
+ ok: false,
159
+ status: 415,
160
+ reason: `The file is named .${extension} but is a ${type.label}; rename it and try again.`,
161
+ }
162
+ if (!allowed.includes(type.id))
163
+ return { ok: false, status: 415, reason: `A ${type.label} cannot be uploaded here.` }
164
+ return { ok: true, type }
165
+ }