@fabrika/auth-core 0.3.3 → 0.4.1

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.
@@ -0,0 +1,292 @@
1
+ // The endpoint matcher of every endpoint table. It selects; it decides no access. The proxy and the framework
2
+ // both select with it, so a request reaches the endpoint whose rules the proxy applied.
3
+
4
+ import { isCanonicalPath } from './canonical-path'
5
+ import type { EndpointRow } from './contract'
6
+ import { ANY_METHOD, type InstallationEndpointMethod } from './installation-endpoint'
7
+ import { parameterName } from './path-segment'
8
+
9
+ type Segment = { readonly kind: 'literal'; readonly value: string } | { readonly kind: 'param'; readonly name: string } | {
10
+ readonly kind: 'wildcard'
11
+ }
12
+
13
+ type PatternResult = { readonly ok: true; readonly segments: readonly Segment[] } | { readonly ok: false; readonly problem: string }
14
+
15
+ /**
16
+ * What selection reads of a row. The proxy's manifest rows carry these and the rules, not the schemas. Only an
17
+ * installation row may have the method `*`.
18
+ */
19
+ export interface EndpointPattern {
20
+ readonly id: string
21
+ readonly method: InstallationEndpointMethod
22
+ readonly path: string
23
+ }
24
+
25
+ /** A table of any rows that carry an endpoint pattern; `EndpointTable` is the artifact's. */
26
+ export interface EndpointPatternTable<Row extends EndpointPattern> {
27
+ readonly endpoints: readonly Row[]
28
+ readonly reservedPrefixes: readonly string[]
29
+ }
30
+
31
+ interface CompiledEndpoint<Row extends EndpointPattern> {
32
+ readonly row: Row
33
+ readonly segments: readonly Segment[]
34
+ }
35
+
36
+ /** An endpoint table that `assertNoAmbiguity` accepted, ready for `planEndpoint`. Only `compileEndpointTable` makes one. */
37
+ class CompiledEndpointTable<Row extends EndpointPattern = EndpointRow> {
38
+ readonly #endpoints: readonly CompiledEndpoint<Row>[]
39
+ readonly #reservedPrefixes: readonly string[]
40
+
41
+ constructor(endpoints: readonly CompiledEndpoint<Row>[], reservedPrefixes: readonly string[]) {
42
+ this.#endpoints = endpoints
43
+ this.#reservedPrefixes = reservedPrefixes
44
+ }
45
+
46
+ plan(method: string, rawPath: string): EndpointPlan<Row> {
47
+ return select(this.#endpoints, this.#reservedPrefixes, method, rawPath)
48
+ }
49
+ }
50
+
51
+ export type { CompiledEndpointTable }
52
+
53
+ /** `no-endpoint` is a 403 at the proxy and a 404 in the framework; `non-canonical` is a 400 at both. */
54
+ export type EndpointPlan<Row extends EndpointPattern = EndpointRow> =
55
+ | { readonly outcome: 'non-canonical' }
56
+ | { readonly outcome: 'no-endpoint' }
57
+ | {
58
+ readonly outcome: 'endpoint'
59
+ readonly endpoint: Row
60
+ /** `:name` segments of the selected path, raw and still percent-encoded. */
61
+ readonly params: Readonly<Record<string, string>>
62
+ }
63
+
64
+ export class EndpointTableError extends Error {
65
+ override readonly name = 'EndpointTableError'
66
+ readonly problems: readonly string[]
67
+
68
+ constructor(problems: readonly string[]) {
69
+ super(`the endpoint table is invalid:\n- ${problems.join('\n- ')}`)
70
+ this.problems = problems
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Refuse a table in which a request could select an endpoint by accident: an invalid path or reserved prefix, a
76
+ * duplicate id, or two endpoints of one method whose paths have the same shape, which no specificity orders. The
77
+ * method `*` is every method, so it shares a shape with no other endpoint.
78
+ */
79
+ export function assertNoAmbiguity<Row extends EndpointPattern>(table: EndpointPatternTable<Row>): void {
80
+ analyse(table)
81
+ }
82
+
83
+ /** Validate a table once, where it is loaded, so that `planEndpoint` never meets an invalid one. */
84
+ export function compileEndpointTable<Row extends EndpointPattern = EndpointRow>(table: EndpointPatternTable<Row>): CompiledEndpointTable<Row> {
85
+ return new CompiledEndpointTable(analyse(table), [...table.reservedPrefixes])
86
+ }
87
+
88
+ /**
89
+ * Select the endpoint for a request: refuse a non-canonical raw path, then take the most specific endpoint of the
90
+ * request's method. Under a reserved prefix only the endpoints declared under it compete. There is no fall-through.
91
+ */
92
+ export function planEndpoint<Row extends EndpointPattern>(table: CompiledEndpointTable<Row>, method: string, rawPath: string): EndpointPlan<Row> {
93
+ return table.plan(method, rawPath)
94
+ }
95
+
96
+ function analyse<Row extends EndpointPattern>(table: EndpointPatternTable<Row>): CompiledEndpoint<Row>[] {
97
+ const problems: string[] = []
98
+ const endpoints: CompiledEndpoint<Row>[] = []
99
+ const ids = new Set<string>()
100
+ const shapes = new Map<string, EndpointPattern[]>()
101
+ for (const row of table.endpoints) {
102
+ if (ids.has(row.id)) {
103
+ problems.push(`endpoint id '${row.id}' is declared twice`)
104
+ }
105
+ ids.add(row.id)
106
+ const pattern = parsePattern(row.path)
107
+ if (!pattern.ok) {
108
+ problems.push(`endpoint '${row.id}' has path '${row.path}': ${pattern.problem}`)
109
+ continue
110
+ }
111
+ const shape = JSON.stringify(pattern.segments.map(shapeOf))
112
+ const sameShape = shapes.get(shape) ?? []
113
+ const previous = sameShape.find((other) => methodsOverlap(other.method, row.method))
114
+ if (previous !== undefined) {
115
+ problems.push(`'${row.id}' and '${previous.id}' both serve ${row.method} ${row.path}`)
116
+ }
117
+ shapes.set(shape, [...sameShape, row])
118
+ endpoints.push({ row, segments: pattern.segments })
119
+ }
120
+ const prefixes = new Set<string>()
121
+ for (const prefix of table.reservedPrefixes) {
122
+ if (!isReservedPrefix(prefix)) {
123
+ problems.push(`reserved prefix '${prefix}' must be a literal path below the root, without a trailing '/'`)
124
+ } else if (prefixes.has(prefix)) {
125
+ problems.push(`reserved prefix '${prefix}' is declared twice`)
126
+ }
127
+ prefixes.add(prefix)
128
+ }
129
+ if (problems.length > 0) {
130
+ throw new EndpointTableError(problems)
131
+ }
132
+ return endpoints
133
+ }
134
+
135
+ function select<Row extends EndpointPattern>(
136
+ endpoints: readonly CompiledEndpoint<Row>[],
137
+ reservedPrefixes: readonly string[],
138
+ method: string,
139
+ rawPath: string,
140
+ ): EndpointPlan<Row> {
141
+ if (!isCanonicalPath(rawPath)) {
142
+ return { outcome: 'non-canonical' }
143
+ }
144
+ const path = splitPath(rawPath)
145
+ const reserved = longestPrefixOf(rawPath, reservedPrefixes)
146
+ let best: { readonly endpoint: CompiledEndpoint<Row>; readonly params: Record<string, string> } | null = null
147
+ let tied = false
148
+ for (const endpoint of endpoints) {
149
+ if (!servesMethod(endpoint.row.method, method) || (reserved !== null && !isUnder(endpoint.row.path, reserved))) {
150
+ continue
151
+ }
152
+ const params = matchSegments(endpoint.segments, path)
153
+ if (params === null) {
154
+ continue
155
+ }
156
+ const order = best === null ? -1 : compareSpecificity(endpoint.segments, best.endpoint.segments)
157
+ if (order < 0) {
158
+ best = { endpoint, params }
159
+ tied = false
160
+ } else if (order === 0) {
161
+ tied = true
162
+ }
163
+ }
164
+ // A tie cannot survive `assertNoAmbiguity`; if one ever appears, nothing is selected.
165
+ if (best === null || tied) {
166
+ return { outcome: 'no-endpoint' }
167
+ }
168
+ return { outcome: 'endpoint', endpoint: best.endpoint.row, params: best.params }
169
+ }
170
+
171
+ function methodsOverlap(declared: string, other: string): boolean {
172
+ return declared === other || declared === ANY_METHOD || other === ANY_METHOD
173
+ }
174
+
175
+ /** A request's method is never a pattern: a request sent with the method `*` selects only a `*` endpoint. */
176
+ function servesMethod(declared: string, requested: string): boolean {
177
+ return declared === ANY_METHOD || declared === requested
178
+ }
179
+
180
+ /** Split literally: a trailing `/` stays an empty last segment, so `/a/` and `/a` are different paths. */
181
+ function splitPath(path: string): string[] {
182
+ return path === '/' ? [] : path.slice(1).split('/')
183
+ }
184
+
185
+ /** Names that would reach `Object.prototype` instead of a parameter wherever the parameters land in a plain object. */
186
+ const PROTOTYPE_NAMES: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])
187
+
188
+ function parsePattern(path: string): PatternResult {
189
+ if (!isCanonicalPath(path)) {
190
+ return { ok: false, problem: 'not a canonical path' }
191
+ }
192
+ const raw = splitPath(path)
193
+ const segments: Segment[] = []
194
+ const names = new Set<string>()
195
+ for (const [index, segment] of raw.entries()) {
196
+ if (segment === '*') {
197
+ if (index !== raw.length - 1) {
198
+ return { ok: false, problem: "'*' must be the last segment" }
199
+ }
200
+ segments.push({ kind: 'wildcard' })
201
+ } else if (segment.includes('*')) {
202
+ return { ok: false, problem: "'*' must be a whole segment" }
203
+ } else if (segment.startsWith(':')) {
204
+ const name = parameterName(segment)
205
+ if (name === null) {
206
+ return { ok: false, problem: "':' must start a parameter name of letters, digits and '_'" }
207
+ }
208
+ if (PROTOTYPE_NAMES.has(name)) {
209
+ return { ok: false, problem: `'${name}' is not allowed as a parameter name` }
210
+ }
211
+ if (names.has(name)) {
212
+ return { ok: false, problem: `parameter '${name}' is declared twice` }
213
+ }
214
+ names.add(name)
215
+ segments.push({ kind: 'param', name })
216
+ } else {
217
+ segments.push({ kind: 'literal', value: segment })
218
+ }
219
+ }
220
+ return { ok: true, segments }
221
+ }
222
+
223
+ function isReservedPrefix(prefix: string): boolean {
224
+ const pattern = parsePattern(prefix)
225
+ return pattern.ok && pattern.segments.length > 0 && !prefix.endsWith('/')
226
+ && pattern.segments.every((segment) => segment.kind === 'literal')
227
+ }
228
+
229
+ function isUnder(path: string, prefix: string): boolean {
230
+ return path.startsWith(`${prefix}/`)
231
+ }
232
+
233
+ function longestPrefixOf(path: string, prefixes: readonly string[]): string | null {
234
+ let longest: string | null = null
235
+ for (const prefix of prefixes) {
236
+ if (isUnder(path, prefix) && (longest === null || prefix.length > longest.length)) {
237
+ longest = prefix
238
+ }
239
+ }
240
+ return longest
241
+ }
242
+
243
+ function shapeOf(segment: Segment): string {
244
+ return segment.kind === 'literal' ? `=${segment.value}` : segment.kind
245
+ }
246
+
247
+ function matchSegments(segments: readonly Segment[], path: readonly string[]): Record<string, string> | null {
248
+ const params: [string, string][] = []
249
+ for (const [index, segment] of segments.entries()) {
250
+ if (segment.kind === 'wildcard') {
251
+ // A non-root wildcard needs the `/` before it: `/x/` matches, `/x` does not.
252
+ return index === 0 || path.length > index ? Object.fromEntries(params) : null
253
+ }
254
+ const value = path[index]
255
+ if (value === undefined) {
256
+ return null
257
+ }
258
+ if (segment.kind === 'param') {
259
+ // The empty last segment of a trailing `/` is not a parameter value.
260
+ if (value === '') {
261
+ return null
262
+ }
263
+ params.push([segment.name, value])
264
+ } else if (segment.value !== value) {
265
+ return null
266
+ }
267
+ }
268
+ // `fromEntries` defines own properties, so no name reaches a prototype setter.
269
+ return segments.length === path.length ? Object.fromEntries(params) : null
270
+ }
271
+
272
+ const RANK: Readonly<Record<Segment['kind'], number>> = { literal: 0, param: 1, wildcard: 2 }
273
+
274
+ /**
275
+ * Negative when `a` is more specific: the first segment whose kind differs decides, and a pattern that ends where
276
+ * the other continues is the more specific one. Lexicographic, so it also orders patterns that never overlap.
277
+ */
278
+ function compareSpecificity(a: readonly Segment[], b: readonly Segment[]): number {
279
+ const shared = Math.min(a.length, b.length)
280
+ for (let index = 0; index < shared; index++) {
281
+ const left = a[index]
282
+ const right = b[index]
283
+ if (left === undefined || right === undefined) {
284
+ break
285
+ }
286
+ const order = RANK[left.kind] - RANK[right.kind]
287
+ if (order !== 0) {
288
+ return order
289
+ }
290
+ }
291
+ return a.length - b.length
292
+ }
@@ -0,0 +1,114 @@
1
+ import { FABRIKA_IAM_APP_ID } from './app-environment'
2
+ import { FABRIKA_CONTRACT_DIGEST } from './endpoint-digest'
3
+ import { FABRIKA_IAM_ISSUER } from './environment'
4
+ import { FABRIKA_PROXY_SECRET } from './wire'
5
+
6
+ /**
7
+ * The environment names only the platform writes into an application
8
+ * ([ADR-0043](../../../docs/decisions/0043-validate-and-render-one-zerops-descriptor-meaning.md)). Control refuses an
9
+ * application variable or secret under one of them, and so does every provider, for every surface that writes one.
10
+ * A work unit that gives an application a new credential adds its name here.
11
+ */
12
+ export const FRAMEWORK_VARIABLE_NAMES = [
13
+ 'FABRIKA_RELEASE',
14
+ FABRIKA_CONTRACT_DIGEST,
15
+ FABRIKA_IAM_ISSUER,
16
+ FABRIKA_IAM_APP_ID,
17
+ 'FABRIKA_OPERATIONS_DSN',
18
+ 'FABRIKA_APP_ID',
19
+ 'FABRIKA_ENVIRONMENT',
20
+ 'FABRIKA_SERVICE_KEY',
21
+ 'FABRIKA_APP_DATABASE_URL',
22
+ 'FABRIKA_APP_RUNTIME_DATABASE_URL',
23
+ 'FABRIKA_APP_STORAGE_ENDPOINT',
24
+ 'FABRIKA_APP_STORAGE_BUCKET',
25
+ 'FABRIKA_APP_STORAGE_ACCESS_KEY_ID',
26
+ 'FABRIKA_APP_STORAGE_SECRET_ACCESS_KEY',
27
+ 'FABRIKA_STORAGE_PROVENANCE',
28
+ FABRIKA_PROXY_SECRET,
29
+ 'FABRIKA_IAM_RPC_URL',
30
+ 'FABRIKA_IAM_RPC_KEY',
31
+ ] as const
32
+
33
+ export type FrameworkVariableName = (typeof FRAMEWORK_VARIABLE_NAMES)[number]
34
+
35
+ /**
36
+ * The name families only the platform writes: one variable per job or webhook, named after it (`workloadKeyVariable`),
37
+ * and a connector import's address, key and Worker binding (`connectVariables`). Every name under one is framework-only.
38
+ */
39
+ export const FRAMEWORK_VARIABLE_PREFIXES = ['FABRIKA_JOB_', 'FABRIKA_WEBHOOK_', 'FABRIKA_CONNECT_'] as const
40
+
41
+ const FRAMEWORK_VARIABLES: ReadonlySet<string> = new Set(FRAMEWORK_VARIABLE_NAMES)
42
+
43
+ /** Whether only the platform may write `name`. */
44
+ export function isFrameworkVariableName(name: string): boolean {
45
+ return FRAMEWORK_VARIABLES.has(name) || FRAMEWORK_VARIABLE_PREFIXES.some((prefix) => name.length > prefix.length && name.startsWith(prefix))
46
+ }
47
+
48
+ /** A contract name as one segment of a variable name: `nightlyDigest` → `NIGHTLY_DIGEST`. */
49
+ export function variableSegment(name: string): string {
50
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()
51
+ }
52
+
53
+ const WORKLOAD_KEY_VARIABLE = /^FABRIKA_(?:JOB|WEBHOOK)_[A-Z0-9][A-Z0-9_]*_KEY$/
54
+
55
+ /** Whether `name` is the variable of a job's or a webhook's credential, as `workloadKeyVariable` names one. */
56
+ export function isWorkloadKeyVariable(name: string): boolean {
57
+ return WORKLOAD_KEY_VARIABLE.test(name)
58
+ }
59
+
60
+ /** The variable a job's or a webhook's credential travels under: `FABRIKA_JOB_NIGHTLY_DIGEST_KEY`. */
61
+ export function workloadKeyVariable(kind: 'job' | 'webhook', name: string): string {
62
+ return `FABRIKA_${kind.toUpperCase()}_${variableSegment(name)}_KEY`
63
+ }
64
+
65
+ /** The variables that carry one connector import, and the Cloudflare service binding that carries its calls. */
66
+ export interface ConnectVariables {
67
+ /** The owner's origin, `https://<owner host>`; on Cloudflare also the URL a binding request carries. */
68
+ readonly url: string
69
+ /** The consumer's `app` key at the owner. */
70
+ readonly key: string
71
+ /** The service binding to the owner's proxy Worker. */
72
+ readonly binding: string
73
+ }
74
+
75
+ /** `catalog` → `FABRIKA_CONNECT_CATALOG_URL`, `_KEY` and the binding `FABRIKA_CONNECT_CATALOG`. */
76
+ export function connectVariables(importName: string): ConnectVariables {
77
+ const binding = `FABRIKA_CONNECT_${variableSegment(importName)}`
78
+ return { url: `${binding}_URL`, key: `${binding}_KEY`, binding }
79
+ }
80
+
81
+ const CONNECT_KEY_VARIABLE = /^FABRIKA_CONNECT_[A-Z0-9][A-Z0-9_]*_KEY$/
82
+ const CONNECT_URL_VARIABLE = /^FABRIKA_CONNECT_[A-Z0-9][A-Z0-9_]*_URL$/
83
+
84
+ /** Whether `name` carries a connector import's key, as `connectVariables` names it. */
85
+ export function isConnectKeyVariable(name: string): boolean {
86
+ return CONNECT_KEY_VARIABLE.test(name)
87
+ }
88
+
89
+ /** Whether `name` carries a connector import's owner origin, as `connectVariables` names it. */
90
+ export function isConnectUrlVariable(name: string): boolean {
91
+ return CONNECT_URL_VARIABLE.test(name)
92
+ }
93
+
94
+ /** A Zerops reference: `${NAME}`, `${RUNTIME_NAME}`, `${<host>_NAME}` or `${RUNTIME_<host>_NAME}`. */
95
+ const REFERENCE = /\$\{([^}]*)\}?/g
96
+ const RUNTIME_PREFIX = /^RUNTIME_/
97
+ const HOST_PREFIX = /^[a-z0-9]{1,25}_/
98
+
99
+ /**
100
+ * The first reference in `text` to a framework-only variable, or `null`. A value that references one copies a
101
+ * platform credential into a variable the application controls, so every surface that writes authored values refuses
102
+ * it. A reference nested in another is refused too, because its name is only known once Zerops resolves it.
103
+ */
104
+ export function frameworkVariableReference(text: string): string | null {
105
+ for (const match of text.matchAll(REFERENCE)) {
106
+ const inner = match[1] ?? ''
107
+ if (inner.includes('${')) return match[0]
108
+ const local = inner.replace(RUNTIME_PREFIX, '')
109
+ for (const name of [inner, local, local.replace(HOST_PREFIX, '')]) {
110
+ if (isFrameworkVariableName(name)) return match[0]
111
+ }
112
+ }
113
+ return null
114
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,23 @@
1
1
  // @fabrika/auth-core — pure logic, types, and wire names shared across auth components and apps.
2
+ export * from './app-environment'
3
+ export * from './canonical-path'
4
+ export * from './contract'
5
+ export * from './contract-canonical'
2
6
  export * from './device'
7
+ export * from './endpoint-digest'
8
+ export * from './endpoints'
3
9
  export * from './environment'
4
- export * from './gates'
10
+ export * from './framework-variables'
11
+ export * from './installation-endpoint'
5
12
  export { parseJsonStringArray } from './json'
13
+ export * from './locale'
14
+ export * from './mail'
15
+ export * from './membership'
16
+ export * from './oauth'
6
17
  export * from './permissions'
18
+ export * from './requirement'
7
19
  export * from './rpc'
20
+ export { sha256Hex } from './sha256'
8
21
  export * from './token'
9
22
  export * from './types'
10
23
  export * from './wire'
@@ -0,0 +1,61 @@
1
+ // The endpoint forms only an installation service's table may use (ADR-0022 "Installation entries"). Types only,
2
+ // like the contract artifact: each reader parses them, and no application contract can declare them.
3
+
4
+ import type { BodyAdmission, Caller, EndpointMethod } from './contract'
5
+
6
+ /** Any method. The ambiguity check treats it as overlapping every method of the same path shape. */
7
+ export const ANY_METHOD = '*'
8
+
9
+ export type InstallationEndpointMethod = EndpointMethod | typeof ANY_METHOD
10
+
11
+ /** The caller an OAuth resource token presents. Only an installation row may admit it. */
12
+ export const OAUTH_CALLER = 'oauth'
13
+
14
+ /** Every caller a verified token can present: an application caller, or `oauth`. */
15
+ export type TokenCaller = Caller | typeof OAUTH_CALLER
16
+
17
+ export type InstallationCaller = 'human' | 'machine' | typeof OAUTH_CALLER
18
+
19
+ /** `service` verifies a credential; `protocol` and `health` are anonymous, and `protocol` keeps `Authorization`. */
20
+ export type InstallationEndpointKind = 'service' | 'protocol' | 'health'
21
+
22
+ /** The caller kind must be one of the row's callers; no permission is needed. */
23
+ export interface AuthenticatedRequirement {
24
+ readonly kind: 'authenticated'
25
+ }
26
+
27
+ /** What a row that admits `oauth` requires of an OAuth resource token: every one of these scopes. */
28
+ export interface OAuthEndpointScopes {
29
+ readonly scopes: readonly string[]
30
+ }
31
+
32
+ interface InstallationEndpointBase {
33
+ readonly id: string
34
+ readonly method: InstallationEndpointMethod
35
+ /** The same pattern syntax as an application endpoint's path. */
36
+ readonly path: string
37
+ readonly admission: BodyAdmission | null
38
+ }
39
+
40
+ export interface InstallationCredentialedEndpoint extends InstallationEndpointBase {
41
+ readonly kind: 'service'
42
+ readonly callers: readonly [InstallationCaller, ...InstallationCaller[]]
43
+ readonly requirement: AuthenticatedRequirement
44
+ /** Present exactly when `callers` holds `oauth`. */
45
+ readonly oauth: OAuthEndpointScopes | null
46
+ }
47
+
48
+ export interface InstallationAnonymousEndpoint extends InstallationEndpointBase {
49
+ readonly kind: 'protocol' | 'health'
50
+ readonly callers: readonly []
51
+ readonly requirement: null
52
+ readonly oauth: null
53
+ }
54
+
55
+ export type InstallationEndpointRow = InstallationCredentialedEndpoint | InstallationAnonymousEndpoint
56
+
57
+ /** An installation service's endpoint table: what `planEndpoint` selects from, with the installation forms. */
58
+ export interface InstallationEndpointTable {
59
+ readonly endpoints: readonly InstallationEndpointRow[]
60
+ readonly reservedPrefixes: readonly string[]
61
+ }
package/src/locale.ts ADDED
@@ -0,0 +1,35 @@
1
+ // How an application names itself to a person on IAM's pages and e-mails: the language IAM speaks for it and the name
2
+ // it shows. The contract declares both; IAM's catalog covers every locale here, so adding one fails its typecheck.
3
+
4
+ /** The languages IAM renders its pages and its own e-mails in. */
5
+ export const LOCALES = ['en', 'cs'] as const
6
+
7
+ export type Locale = (typeof LOCALES)[number]
8
+
9
+ /** IAM's language for a request that names no application, or one that declares none. */
10
+ export const DEFAULT_LOCALE: Locale = 'en'
11
+
12
+ export function isLocale(value: unknown): value is Locale {
13
+ return LOCALES.some((locale) => locale === value)
14
+ }
15
+
16
+ /** The longest display name, in code points: it is a page heading and part of an e-mail subject. */
17
+ export const MAX_DISPLAY_NAME_LENGTH = 80
18
+
19
+ /**
20
+ * Why `value` cannot be an application's display name, or `null` when it can. It is plain text that IAM escapes, so
21
+ * the rule only keeps it one short line: trimmed, non-empty, bounded, without a control character (an e-mail subject
22
+ * carries it).
23
+ */
24
+ export function displayNameProblem(value: string): string | null {
25
+ if (value.trim() !== value || value === '') {
26
+ return 'is empty or starts or ends with whitespace'
27
+ }
28
+ if (Array.from(value).length > MAX_DISPLAY_NAME_LENGTH) {
29
+ return `is longer than ${MAX_DISPLAY_NAME_LENGTH} characters`
30
+ }
31
+ if (/\p{Cc}/u.test(value)) {
32
+ return 'contains a control character'
33
+ }
34
+ return null
35
+ }