@fabrika/auth-core 0.9.0-dev.5 → 0.9.0-dev.50

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 (55) hide show
  1. package/package.json +3 -2
  2. package/src/agent.ts +89 -0
  3. package/src/canonical-path.ts +18 -0
  4. package/src/client-address.ts +74 -0
  5. package/src/contract-canonical.ts +168 -2
  6. package/src/contract-encoding.ts +181 -0
  7. package/src/contract.ts +220 -17
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +70 -0
  11. package/src/framework-variables.ts +14 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +7 -0
  14. package/src/installation-endpoint.ts +3 -2
  15. package/src/locale.ts +13 -1
  16. package/src/managed-environment.ts +11 -0
  17. package/src/membership.ts +12 -4
  18. package/src/oauth.ts +19 -0
  19. package/src/ops.ts +487 -16
  20. package/src/permissions.ts +42 -0
  21. package/src/public-egress.ts +168 -0
  22. package/src/requirement.ts +12 -4
  23. package/src/rpc.ts +137 -9
  24. package/src/scope-values.ts +123 -0
  25. package/src/sha256.ts +52 -14
  26. package/src/token.ts +195 -14
  27. package/src/types.ts +72 -1
  28. package/src/wire.ts +2 -1
  29. package/types/src/agent.d.ts +37 -0
  30. package/types/src/canonical-path.d.ts +6 -0
  31. package/types/src/client-address.d.ts +7 -0
  32. package/types/src/contract-canonical.d.ts +11 -1
  33. package/types/src/contract-encoding.d.ts +18 -0
  34. package/types/src/contract.d.ts +205 -16
  35. package/types/src/egress.d.ts +27 -0
  36. package/types/src/endpoint-digest.d.ts +5 -0
  37. package/types/src/framework-release.d.ts +23 -0
  38. package/types/src/framework-variables.d.ts +6 -1
  39. package/types/src/iam-mail.d.ts +92 -0
  40. package/types/src/index.d.ts +7 -0
  41. package/types/src/installation-endpoint.d.ts +3 -2
  42. package/types/src/locale.d.ts +11 -1
  43. package/types/src/managed-environment.d.ts +1 -1
  44. package/types/src/membership.d.ts +8 -3
  45. package/types/src/oauth.d.ts +11 -0
  46. package/types/src/ops.d.ts +133 -8
  47. package/types/src/permissions.d.ts +12 -0
  48. package/types/src/public-egress.d.ts +31 -0
  49. package/types/src/requirement.d.ts +5 -4
  50. package/types/src/rpc.d.ts +113 -6
  51. package/types/src/scope-values.d.ts +61 -0
  52. package/types/src/sha256.d.ts +10 -0
  53. package/types/src/token.d.ts +70 -8
  54. package/types/src/types.d.ts +48 -1
  55. package/types/src/wire.d.ts +2 -1
@@ -0,0 +1,354 @@
1
+ // IAM's own e-mails, in every language it speaks, and how an application's wording of them (`mail`, `MailTemplate`)
2
+ // is rendered. IAM sends them; `fabrika app dev`'s stand-in IAM shows the same messages, so both read them from here
3
+ // and a preview matches what IAM of the same release sends. A value is plain text: every one is escaped where HTML inserts it.
4
+ // The wording is IAM's and changes with IAM, in any release: an application words its e-mails through its contract's
5
+ // `mail` templates, not by reading these strings.
6
+
7
+ import { DEFAULT_LOCALE, type Locale } from './locale'
8
+ import {
9
+ fillMailTemplate,
10
+ type MailHtmlToken,
11
+ mailHtmlTokens,
12
+ type MailPlaceholder,
13
+ type MailTemplate,
14
+ mailTemplateProblems,
15
+ type MessageKind,
16
+ } from './mail'
17
+
18
+ /** A rendered e-mail: the subject and both bodies, from the same values. */
19
+ export interface RenderedMessage {
20
+ readonly subject: string
21
+ readonly text: string
22
+ readonly html: string
23
+ }
24
+
25
+ /**
26
+ * How the owner of an invitation's mailbox accepts it. `create`: no principal holds the mailbox and accepting creates
27
+ * one with the password its owner chooses (ADR-0051). `sign_in`: a principal holds it, or single sign-on would admit
28
+ * it, so its owner signs in and accepts. `no_account`: neither, so the owner cannot accept until someone gives the
29
+ * mailbox an account.
30
+ */
31
+ export type InvitationAcceptance = 'create' | 'sign_in' | 'no_account'
32
+
33
+ export interface PasswordActionValues {
34
+ /** The application the action returns to; `null` for an action on the installation itself. */
35
+ readonly appName: string | null
36
+ readonly recipient: string
37
+ readonly actionUrl: string
38
+ readonly expiresAt: number
39
+ }
40
+
41
+ /**
42
+ * The closed set of values each IAM message is rendered from. Every value is plain text; a template escapes it. IAM
43
+ * builds the action URL itself, and a template places it. `expiresAt` is the link's expiry in seconds since the epoch.
44
+ */
45
+ export interface MessageValues {
46
+ readonly invitation: {
47
+ readonly appName: string
48
+ readonly role: string
49
+ readonly scope: string
50
+ readonly recipient: string
51
+ readonly inviterLabel: string
52
+ /** The invited person's company, as the inviting application names it; empty when the invitation names none. */
53
+ readonly companyLabel: string
54
+ /** The inviter's personal message; empty when the invitation carries none. */
55
+ readonly message: string
56
+ readonly actionUrl: string
57
+ readonly expiresAt: number
58
+ /** How the mailbox's owner accepts, as IAM can tell when it sends; it picks IAM's words, and is no placeholder. */
59
+ readonly acceptance: InvitationAcceptance
60
+ }
61
+ readonly enrollment: PasswordActionValues
62
+ readonly reset: PasswordActionValues
63
+ }
64
+
65
+ /** One template per message. IAM's catalog supplies a default set per language. */
66
+ export type MessageTemplates = { readonly [K in MessageKind]: (values: MessageValues[K]) => RenderedMessage }
67
+
68
+ /** IAM's words around an application's own wording of a message: the HTML part's button and the expiry. */
69
+ export interface ApplicationMailText {
70
+ readonly button: { readonly [K in MessageKind]: string }
71
+ /** `expiresAt` in seconds since the epoch, as the `{{expiry}}` placeholder shows it. */
72
+ readonly expiry: (expiresAt: number) => string
73
+ }
74
+
75
+ /** IAM's wording of its e-mails in one language. */
76
+ export interface IamMailCatalog {
77
+ readonly messages: MessageTemplates
78
+ readonly applicationMail: ApplicationMailText
79
+ }
80
+
81
+ /** Escape a value for HTML text and a quoted attribute, as IAM's pages do. */
82
+ function escapeHtml(value: string): string {
83
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;')
84
+ }
85
+
86
+ /** The HTML of an inviter's personal message: its introduction, then the message escaped and quoted, line breaks kept. */
87
+ function quotedNote(note: { readonly intro: string; readonly message: string } | null): string {
88
+ if (note === null) return ''
89
+ const paragraphs = note.message.replaceAll('\r\n', '\n').split(/\n{2,}/).filter((paragraph) => paragraph.trim() !== '')
90
+ const quoted = paragraphs.map((paragraph) => `<p>${escapeHtml(paragraph).replaceAll('\n', '<br>')}</p>`).join('')
91
+ return `<p>${escapeHtml(note.intro)}</p><blockquote>${quoted}</blockquote>`
92
+ }
93
+
94
+ /** An invitation in one language's words: the sentence of what it gives, the note's introduction, how to accept. */
95
+ interface InvitationWords {
96
+ readonly subject: (appName: string) => string
97
+ readonly invited: (what: string) => string
98
+ readonly what: (values: { readonly appName: string; readonly role: string; readonly scope: string; readonly companyLabel: string }) => string
99
+ readonly writes: (inviterLabel: string) => string
100
+ readonly accept: { readonly [A in InvitationAcceptance]: string }
101
+ readonly button: string
102
+ readonly ignore: string
103
+ }
104
+
105
+ function invitationMessage(words: InvitationWords): MessageTemplates['invitation'] {
106
+ return ({ appName, role, scope, inviterLabel, companyLabel, message, actionUrl, acceptance }) => {
107
+ const what = words.what({ appName, role, scope, companyLabel })
108
+ const note = message === '' ? null : { intro: words.writes(inviterLabel), message }
109
+ const accept = words.accept[acceptance]
110
+ return {
111
+ subject: words.subject(appName),
112
+ text: [words.invited(what), ...(note === null ? [] : [note.intro, note.message]), accept, actionUrl, words.ignore].join('\n\n'),
113
+ html: `<p>${escapeHtml(words.invited(what))}</p>${quotedNote(note)}<p>${escapeHtml(accept)}</p><p><a href="${escapeHtml(actionUrl)}">${
114
+ escapeHtml(words.button)
115
+ }</a></p><p>${escapeHtml(words.ignore)}</p>`,
116
+ }
117
+ }
118
+ }
119
+
120
+ /** A password message in one language's words: the link sentence before the link, and the closing line. */
121
+ function passwordMessage(intro: (action: string) => string, ignore: string) {
122
+ return (subject: string, action: string, actionUrl: string): RenderedMessage => ({
123
+ subject,
124
+ text: `${intro(action)}\n\n${actionUrl}\n\n${ignore}`,
125
+ html: `<p>${escapeHtml(intro(action))}</p><p><a href="${escapeHtml(actionUrl)}">${escapeHtml(subject)}</a></p><p>${escapeHtml(ignore)}</p>`,
126
+ })
127
+ }
128
+
129
+ const expiryIn = (tag: string): ApplicationMailText['expiry'] => {
130
+ const format = new Intl.DateTimeFormat(tag, { dateStyle: 'long', timeStyle: 'short', timeZone: 'UTC' })
131
+ return (expiresAt) => `${format.format(new Date(expiresAt * 1000))} UTC`
132
+ }
133
+
134
+ function enCatalog(): IamMailCatalog {
135
+ const password = passwordMessage((action) => `Use this one-time link to ${action}:`, 'If you did not request this, you can ignore this email.')
136
+ return {
137
+ messages: {
138
+ invitation: invitationMessage({
139
+ subject: (appName) => `You are invited to ${appName}`,
140
+ invited: (what) => `You are invited to join a ${what}.`,
141
+ what: ({ appName, role, scope, companyLabel }) => `${scope} of ${appName} as ${role}${companyLabel === '' ? '' : `, for ${companyLabel}`}`,
142
+ writes: (inviterLabel) => `${inviterLabel} writes:`,
143
+ accept: {
144
+ create: 'Open this one-time link to accept. With an account here, sign in with this address first; without one, you choose a password.',
145
+ sign_in: 'Open this one-time link and sign in with this address to accept.',
146
+ no_account:
147
+ 'There is no account for this address here yet, and this invitation does not create one. Ask the person who invited you to have one set up, then open this one-time link and sign in to accept.',
148
+ },
149
+ button: 'Accept the invitation',
150
+ ignore: 'If you did not expect this, you can ignore this email.',
151
+ }),
152
+ enrollment: ({ appName, actionUrl }) =>
153
+ password(
154
+ appName === null ? 'Set your Fabrika password' : `Set your password for ${appName}`,
155
+ appName === null ? 'set your Fabrika password' : `set your password for ${appName}`,
156
+ actionUrl,
157
+ ),
158
+ reset: ({ appName, actionUrl }) =>
159
+ password(
160
+ appName === null ? 'Reset your Fabrika password' : `Reset your password for ${appName}`,
161
+ appName === null ? 'reset your Fabrika password' : `reset your password for ${appName}`,
162
+ actionUrl,
163
+ ),
164
+ },
165
+ applicationMail: {
166
+ button: { invitation: 'Accept the invitation', enrollment: 'Set your password', reset: 'Reset your password' },
167
+ expiry: expiryIn('en-GB'),
168
+ },
169
+ }
170
+ }
171
+
172
+ function csCatalog(): IamMailCatalog {
173
+ const password = passwordMessage((action) => `Tímto jednorázovým odkazem ${action}:`, 'Pokud jste o to nežádali, můžete tento e-mail ignorovat.')
174
+ return {
175
+ messages: {
176
+ invitation: invitationMessage({
177
+ subject: (appName) => `Pozvánka do aplikace ${appName}`,
178
+ invited: (what) => `Dostali jste pozvánku ${what}.`,
179
+ what: ({ appName, role, scope, companyLabel }) =>
180
+ `do aplikace ${appName} s rolí ${role} (${scope})${companyLabel === '' ? '' : ` za ${companyLabel}`}`,
181
+ writes: (inviterLabel) => `${inviterLabel} píše:`,
182
+ accept: {
183
+ create: 'Pozvánku přijmete tímto jednorázovým odkazem. Máte-li zde účet, nejprve se přihlaste touto adresou; pokud ho nemáte, zvolíte si heslo.',
184
+ sign_in: 'Pozvánku přijmete tímto jednorázovým odkazem po přihlášení touto adresou.',
185
+ no_account:
186
+ 'Pro tuto adresu tu zatím není účet a tato pozvánka ho nezakládá. Požádejte toho, kdo vás pozval, aby vám ho zřídil; potom pozvánku přijmete tímto jednorázovým odkazem po přihlášení.',
187
+ },
188
+ button: 'Přijmout pozvánku',
189
+ ignore: 'Pokud jste pozvánku nečekali, můžete tento e-mail ignorovat.',
190
+ }),
191
+ enrollment: ({ appName, actionUrl }) =>
192
+ password(appName === null ? 'Nastavení hesla' : `Nastavení hesla pro aplikaci ${appName}`, 'si nastavíte heslo', actionUrl),
193
+ reset: ({ appName, actionUrl }) =>
194
+ password(appName === null ? 'Obnovení hesla' : `Obnovení hesla pro aplikaci ${appName}`, 'si obnovíte heslo', actionUrl),
195
+ },
196
+ applicationMail: {
197
+ button: { invitation: 'Přijmout pozvánku', enrollment: 'Nastavit heslo', reset: 'Obnovit heslo' },
198
+ expiry: expiryIn('cs'),
199
+ },
200
+ }
201
+ }
202
+
203
+ function ukCatalog(): IamMailCatalog {
204
+ const password = passwordMessage(
205
+ (action) => `Скористайтеся цим одноразовим посиланням, щоб ${action}:`,
206
+ 'Якщо ви цього не запитували, просто проігноруйте цей лист.',
207
+ )
208
+ return {
209
+ messages: {
210
+ invitation: invitationMessage({
211
+ subject: (appName) => `Запрошення до застосунку ${appName}`,
212
+ invited: (what) => `Вас запрошено ${what}.`,
213
+ what: ({ appName, role, scope, companyLabel }) =>
214
+ `до застосунку ${appName} з роллю ${role} (${scope})${companyLabel === '' ? '' : `, організація: ${companyLabel}`}`,
215
+ writes: (inviterLabel) => `${inviterLabel} пише:`,
216
+ accept: {
217
+ create:
218
+ 'Щоб прийняти запрошення, відкрийте це одноразове посилання. Якщо у вас тут уже є обліковий запис, спочатку увійдіть із цією адресою; якщо немає, ви створите пароль.',
219
+ sign_in: 'Щоб прийняти запрошення, відкрийте це одноразове посилання й увійдіть із цією адресою.',
220
+ no_account:
221
+ 'Для цієї адреси тут ще немає облікового запису, і це запрошення його не створює. Попросіть того, хто вас запросив, створити його, а потім відкрийте це одноразове посилання й увійдіть, щоб прийняти запрошення.',
222
+ },
223
+ button: 'Прийняти запрошення',
224
+ ignore: 'Якщо ви не очікували цього запрошення, просто проігноруйте цей лист.',
225
+ }),
226
+ enrollment: ({ appName, actionUrl }) =>
227
+ password(appName === null ? 'Створення пароля' : `Створення пароля для застосунку ${appName}`, 'створити пароль', actionUrl),
228
+ reset: ({ appName, actionUrl }) =>
229
+ password(appName === null ? 'Відновлення пароля' : `Відновлення пароля для застосунку ${appName}`, 'відновити пароль', actionUrl),
230
+ },
231
+ applicationMail: {
232
+ button: { invitation: 'Прийняти запрошення', enrollment: 'Створити пароль', reset: 'Відновити пароль' },
233
+ expiry: expiryIn('uk'),
234
+ },
235
+ }
236
+ }
237
+
238
+ /** Each language's words, built on first use: a consumer of this package that sends no IAM e-mail bundles none of them. */
239
+ const catalogs: { readonly [L in Locale]: () => IamMailCatalog } = { en: enCatalog, cs: csCatalog, uk: ukCatalog }
240
+ const built: { [L in Locale]?: IamMailCatalog } = {}
241
+
242
+ /** IAM's wording of its e-mails in `locale`. */
243
+ export function iamMailCatalog(locale: Locale): IamMailCatalog {
244
+ built[locale] ??= catalogs[locale]()
245
+ return built[locale]
246
+ }
247
+
248
+ /**
249
+ * The language IAM writes an e-mail in: the person's own (the language an invitation names, else the one the mailbox's
250
+ * principal keeps, ADR-0077), else the application's, else the default. An e-mail has no request to ask, so IAM's
251
+ * `chooseLocale` without one comes to the same language; IAM's tests hold the two equal.
252
+ */
253
+ export function mailLocale(sources: { readonly person?: Locale | null; readonly app?: Locale | null }): Locale {
254
+ return sources.person ?? sources.app ?? DEFAULT_LOCALE
255
+ }
256
+
257
+ type Placeholders<K extends MessageKind> = { readonly [P in MailPlaceholder<K>]: string }
258
+
259
+ /** The values an application's template of each message names, beside those every message names. */
260
+ const PLACEHOLDER_VALUES: {
261
+ readonly [K in MessageKind]: (values: MessageValues[K]) => Omit<Placeholders<K>, 'displayName' | 'expiry' | 'appUrl'>
262
+ } = {
263
+ invitation: ({ recipient, inviterLabel, companyLabel, message, actionUrl }) => ({ recipient, inviterLabel, companyLabel, message, actionUrl }),
264
+ enrollment: ({ recipient, actionUrl }) => ({ recipient, actionUrl }),
265
+ reset: ({ recipient, actionUrl }) => ({ recipient, actionUrl }),
266
+ }
267
+
268
+ /** What an IAM e-mail of one application is rendered with, beside its message's values. */
269
+ export interface MailRendering {
270
+ /** The e-mail's language (`mailLocale`). */
271
+ readonly locale: Locale
272
+ /** The application's own template of the message in that language; `null` when it declares none. */
273
+ readonly template: MailTemplate | null
274
+ /** `{{displayName}}`: the application's display name, else its id. */
275
+ readonly displayName: string
276
+ /** `{{appUrl}}`: the application's address with a trailing slash; `null` while no return origin is registered. */
277
+ readonly appUrl: string | null
278
+ /** The longest subject the sender accepts: a filled template's subject gives way at its end. */
279
+ readonly maxSubjectLength: number
280
+ }
281
+
282
+ /**
283
+ * The template IAM renders a `kind` e-mail with: the application's own wording when it declares one in the e-mail's
284
+ * language, else the catalog's. A template the rule no longer admits is the catalog's, and so is one that names
285
+ * `{{appUrl}}` while the application has no registered return origin to build it from.
286
+ */
287
+ export function iamMessageTemplate<K extends MessageKind>(kind: K, rendering: MailRendering): (values: MessageValues[K]) => RenderedMessage {
288
+ const catalog = iamMailCatalog(rendering.locale)
289
+ const { template, appUrl } = rendering
290
+ if (template === null) return catalog.messages[kind]
291
+ const html = template.html === undefined ? null : mailHtmlTokens(template.html)
292
+ const namesAppUrl = [template.subject, template.text, template.html ?? ''].some((part) => part.includes('{{appUrl}}'))
293
+ if (mailTemplateProblems(kind, template).length > 0 || (namesAppUrl && appUrl === null)) {
294
+ return catalog.messages[kind]
295
+ }
296
+ const tokens = html !== null && html.ok ? html.tokens : null
297
+ return (values) => {
298
+ const placeholders: Readonly<Record<string, string>> = {
299
+ ...PLACEHOLDER_VALUES[kind](values),
300
+ displayName: rendering.displayName,
301
+ expiry: catalog.applicationMail.expiry(values.expiresAt),
302
+ appUrl: appUrl ?? '',
303
+ }
304
+ const message = applicationMessage(template, placeholders, values.actionUrl, catalog.applicationMail.button[kind], rendering.maxSubjectLength)
305
+ return tokens === null ? message : { ...message, html: renderHtml(tokens, placeholders) }
306
+ }
307
+ }
308
+
309
+ /**
310
+ * An application's HTML body, rendered from its tokens and never from its source: each element as the subset writes
311
+ * it, the literal text as the application wrote it (`mailHtmlTokens` admitted no `<` and no bare `&` in it), every value
312
+ * escaped, and each link's `href` the escaped URL it names.
313
+ */
314
+ function renderHtml(tokens: readonly MailHtmlToken[], placeholders: Readonly<Record<string, string>>): string {
315
+ return tokens.map((token) => {
316
+ if (token.kind === 'close') return `</${token.name}>`
317
+ if (token.kind === 'open') {
318
+ return token.href === null ? `<${token.name}>` : `<${token.name} href="${escapeHtml(fillMailTemplate(token.href, placeholders))}">`
319
+ }
320
+ return token.text.replaceAll(/\{\{([^{}]*)\}\}/g, (_, name: string) => escapeHtml(placeholders[name] ?? ''))
321
+ }).join('')
322
+ }
323
+
324
+ /**
325
+ * An application's wording filled in: the text as written, the subject on one line, and IAM's own HTML part — the
326
+ * escaped text as paragraphs and IAM's button to the action URL. An application's own HTML body replaces that part.
327
+ */
328
+ function applicationMessage(
329
+ template: MailTemplate,
330
+ placeholders: Readonly<Record<string, string>>,
331
+ actionUrl: string,
332
+ button: string,
333
+ maxSubjectLength: number,
334
+ ): RenderedMessage {
335
+ const text = fillMailTemplate(template.text, placeholders).replaceAll('\r\n', '\n')
336
+ const oneLine = Object.fromEntries(Object.entries(placeholders).map(([name, value]) => [name, value.replaceAll(/\p{Cc}+/gu, ' ')]))
337
+ const paragraphs = text.split(/\n{2,}/).filter((paragraph) => paragraph.trim() !== '')
338
+ const html = [
339
+ ...paragraphs.map((paragraph) => `<p>${escapeHtml(paragraph).replaceAll('\n', '<br>')}</p>`),
340
+ `<p><a href="${escapeHtml(actionUrl)}">${escapeHtml(button)}</a></p>`,
341
+ ].join('')
342
+ return { subject: boundedSubject(fillMailTemplate(template.subject, oneLine), maxSubjectLength), text, html }
343
+ }
344
+
345
+ /** A filled subject the sender accepts: values can expand a short template past its limit, so the end gives way. */
346
+ function boundedSubject(subject: string, max: number): string {
347
+ if (subject.length <= max) return subject
348
+ let bounded = ''
349
+ for (const character of subject) {
350
+ if (bounded.length + character.length > max - 1) break
351
+ bounded += character
352
+ }
353
+ return `${bounded}…`
354
+ }
package/src/index.ts CHANGED
@@ -1,15 +1,20 @@
1
1
  // @fabrika/auth-core — pure logic, types, and wire names shared across auth components and apps.
2
+ export * from './agent'
2
3
  export * from './app-environment'
3
4
  export * from './canonical-path'
5
+ export * from './client-address'
4
6
  export * from './contract'
5
7
  export * from './contract-canonical'
8
+ export * from './contract-encoding'
6
9
  export * from './dev-environment'
7
10
  export * from './device'
11
+ export * from './egress'
8
12
  export * from './endpoint-digest'
9
13
  export * from './endpoints'
10
14
  export * from './environment'
11
15
  export * from './framework-release'
12
16
  export * from './framework-variables'
17
+ export * from './iam-mail'
13
18
  export * from './installation-endpoint'
14
19
  export { parseJsonStringArray } from './json'
15
20
  export * from './locale'
@@ -19,8 +24,10 @@ export * from './membership'
19
24
  export * from './oauth'
20
25
  export * from './ops'
21
26
  export * from './permissions'
27
+ export * from './public-egress'
22
28
  export * from './requirement'
23
29
  export * from './rpc'
30
+ export * from './scope-values'
24
31
  export { sha256Hex } from './sha256'
25
32
  export * from './terminal'
26
33
  export * from './token'
@@ -1,6 +1,7 @@
1
1
  // The endpoint forms only an installation service's table may use (ADR-0022 "Installation entries"). Types only,
2
2
  // like the contract artifact: each reader parses them, and no application contract can declare them.
3
3
 
4
+ import type { AGENT_CALLER } from './agent'
4
5
  import type { BodyAdmission, Caller, EndpointMethod } from './contract'
5
6
 
6
7
  /** Any method. The ambiguity check treats it as overlapping every method of the same path shape. */
@@ -11,8 +12,8 @@ export type InstallationEndpointMethod = EndpointMethod | typeof ANY_METHOD
11
12
  /** The caller an OAuth resource token presents. Only an installation row may admit it. */
12
13
  export const OAUTH_CALLER = 'oauth'
13
14
 
14
- /** Every caller a verified token can present: an application caller, or `oauth`. */
15
- export type TokenCaller = Caller | typeof OAUTH_CALLER
15
+ /** Every caller a verified token can present: an application caller, `oauth`, or an agent's exchanged grant. */
16
+ export type TokenCaller = Caller | typeof OAUTH_CALLER | typeof AGENT_CALLER
16
17
 
17
18
  export type InstallationCaller = 'human' | 'machine' | typeof OAUTH_CALLER
18
19
 
package/src/locale.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // it shows. The contract declares both; IAM's catalog covers every locale here, so adding one fails its typecheck.
3
3
 
4
4
  /** The languages IAM renders its pages and its own e-mails in. */
5
- export const LOCALES = ['en', 'cs'] as const
5
+ export const LOCALES = ['en', 'cs', 'uk'] as const
6
6
 
7
7
  export type Locale = (typeof LOCALES)[number]
8
8
 
@@ -13,6 +13,18 @@ export function isLocale(value: unknown): value is Locale {
13
13
  return LOCALES.some((locale) => locale === value)
14
14
  }
15
15
 
16
+ /**
17
+ * The cookie that names the language a browser reads fabrika's pages in, host-only on whichever host wrote it: IAM's
18
+ * on IAM's host, an application's on its own. An application's proxy passes the value on its host to IAM's sign-in as
19
+ * `LOCALE_PARAM`. It picks words and nothing else: no credential, landing or authority depends on it, and a value
20
+ * that is not a `Locale` counts as none. Its name does not start with `FABRIKA_COOKIE_PREFIX`, so the proxy leaves it
21
+ * on the request it sends an application.
22
+ */
23
+ export const LOCALE_COOKIE = '__Host-fabrika_locale'
24
+
25
+ /** The query parameter IAM's pages read the reader's language from: IAM's own links and the proxy's sign-in bounce. */
26
+ export const LOCALE_PARAM = 'locale'
27
+
16
28
  /** The longest display name, in code points: it is a page heading and part of an e-mail subject. */
17
29
  export const MAX_DISPLAY_NAME_LENGTH = 80
18
30
 
@@ -3,6 +3,7 @@ import { FABRIKA_CONTRACT_DIGEST } from './endpoint-digest'
3
3
  import { FABRIKA_IAM_ISSUER } from './environment'
4
4
  import {
5
5
  FABRIKA_APP_ORIGIN,
6
+ FABRIKA_EGRESS_REFUSED_HOSTS,
6
7
  FABRIKA_OPS_KEY_DIGESTS,
7
8
  FABRIKA_TOKEN_KEYS,
8
9
  FRAMEWORK_VARIABLE_PREFIXES,
@@ -35,6 +36,7 @@ export const MANAGED_VARIABLE_NAMES = [
35
36
  FABRIKA_APP_ORIGIN,
36
37
  FABRIKA_TOKEN_KEYS,
37
38
  FABRIKA_OPS_KEY_DIGESTS,
39
+ FABRIKA_EGRESS_REFUSED_HOSTS,
38
40
  ] as const satisfies readonly FrameworkVariableName[]
39
41
 
40
42
  export type ManagedVariableName = (typeof MANAGED_VARIABLE_NAMES)[number]
@@ -53,6 +55,15 @@ const PUBLIC_VARIABLES: ReadonlySet<string> = new Set<FrameworkVariableName>([
53
55
  FABRIKA_APP_ORIGIN,
54
56
  // SHA-256 of 256-bit random keys: a digest neither is a key nor lets anyone forge one.
55
57
  FABRIKA_OPS_KEY_DIGESTS,
58
+ // Host names anyone can look up in DNS.
59
+ FABRIKA_EGRESS_REFUSED_HOSTS,
60
+ // The storage's region, a public name like `eu-central-1`, and two mode words.
61
+ 'FABRIKA_APP_STORAGE_REGION',
62
+ 'FABRIKA_APP_STORAGE_ADDRESSING',
63
+ 'FABRIKA_APP_STORAGE_CREDENTIALS',
64
+ // A mode word and a deploy's generation: neither opens anything.
65
+ 'FABRIKA_JOBS_SCHEDULE',
66
+ 'FABRIKA_JOBS_SCHEDULE_GENERATION',
56
67
  ])
57
68
 
58
69
  const PLATFORM_URL_VARIABLES: ReadonlySet<string> = new Set(PLATFORM_RECEIVERS.map((receiver) => platformTransportVariables(receiver).url))
package/src/membership.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  // and a platform component that implements `IamRpc` does not have to.
7
7
 
8
8
  import type { ContractArtifact, DimensionArtifact, EndpointRow } from './contract'
9
+ import { isLocale, type Locale, LOCALES } from './locale'
9
10
  import type { PrincipalAffiliation, Scope } from './types'
10
11
 
11
12
  /**
@@ -174,17 +175,24 @@ export const MAX_INVITATION_MESSAGE_LENGTH = 1000
174
175
  * What an invitation by address carries besides its role. `label` is the invited person's company as the application
175
176
  * names it, `message` the inviter's personal note; both are plain text IAM escapes wherever it inserts them. `resend`
176
177
  * rotates the open invitation's link, restarts its lifetime and sends it again; without it, repeating an invitation
177
- * answers the open one and sends nothing.
178
+ * answers the open one and sends nothing. `locale` is the invited person's language, when the application knows it: IAM
179
+ * writes the invitation and the pages its link opens in it, and its acceptance keeps it as the person's, so IAM's later
180
+ * e-mails (a password reset) and pages speak it too. Without one, IAM speaks the language the person already has, else the
181
+ * application's. A resend that names one replaces the stored one.
178
182
  */
179
183
  export interface InvitationOptions {
180
184
  readonly label?: string
181
185
  readonly message?: string
182
186
  readonly resend?: boolean
187
+ readonly locale?: Locale
183
188
  }
184
189
 
185
- /** Why IAM refuses an invitation's label or message, or `null`. A message may break lines; nothing else is a control character. */
190
+ /** Why IAM refuses an invitation's label, message or locale, or `null`. A message may break lines; nothing else is a control character. */
186
191
  export function invitationOptionsProblem(options: InvitationOptions): string | null {
187
- const { label, message } = options
192
+ const { label, message, locale } = options
193
+ if (locale !== undefined && !isLocale(locale)) {
194
+ return `an invitation locale is one of ${LOCALES.map((value) => `'${value}'`).join(', ')}`
195
+ }
188
196
  if (label !== undefined && (label.length > MAX_INVITATION_LABEL_LENGTH || /\p{Cc}/u.test(label))) {
189
197
  return `an invitation label is at most ${MAX_INVITATION_LABEL_LENGTH} characters on one line`
190
198
  }
@@ -233,7 +241,7 @@ export interface AssignMemberInput extends MembershipCaller {
233
241
  scope: Scope
234
242
  role: string
235
243
  member: MemberTarget
236
- /** Only with an address: the invitation's label, message and resend (`InvitationOptions`). */
244
+ /** Only with an address: the invitation's label, message, resend and locale (`InvitationOptions`). */
237
245
  invitation?: InvitationOptions
238
246
  }
239
247
 
package/src/oauth.ts CHANGED
@@ -27,6 +27,20 @@ export function isCimdClientId(value: unknown): value is string {
27
27
  }
28
28
  }
29
29
 
30
+ /**
31
+ * The client id of every installation's own command-line client: a public client IAM knows without a metadata document.
32
+ * It is the one client id that is not a CIMD URL.
33
+ */
34
+ export const OAUTH_CLI_CLIENT_ID = 'fabrika-cli'
35
+
36
+ /** The public device client an agent obtains an application grant with (ADR-0090). It is never served Control's resources. */
37
+ export const AGENT_CLIENT_ID = 'agent-cli'
38
+
39
+ /** A client id a token or revocation request may name: a CIMD document's URL, or one of the two built-in clients. */
40
+ export function isOAuthClientId(value: unknown): value is string {
41
+ return value === OAUTH_CLI_CLIENT_ID || value === AGENT_CLIENT_ID || isCimdClientId(value)
42
+ }
43
+
30
44
  /** RFC 6749 scope-token syntax; duplicates and empty sets are refused. */
31
45
  export function parseOAuthScopes(value: unknown): string[] | null {
32
46
  if (!Array.isArray(value) || value.length === 0 || value.length > 64) return null
@@ -40,6 +54,11 @@ export function parseOAuthScopes(value: unknown): string[] | null {
40
54
  return scopes
41
55
  }
42
56
 
57
+ /** A scope dimension type, or a value of one, as a parameterized scope token carries it (`deploy:alpha`, `read:project=a`). */
58
+ export function isScopeParameterText(value: unknown): value is string {
59
+ return typeof value === 'string' && value.length <= 100 && /^[A-Za-z0-9][A-Za-z0-9._@-]*$/.test(value)
60
+ }
61
+
43
62
  function isUriText(value: unknown): value is string {
44
63
  return typeof value === 'string' && value.length > 0 && value.length <= 2048 && !/[\s\\<>"{}|^`]/.test(value)
45
64
  && !/%(?![A-Fa-f0-9]{2})/.test(value) && /^https?:\/\/[^/?#]+(?:[/?#]|$)/i.test(value)