@paramira/authentik-blueprints 0.0.0-stage → 0.2.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.
package/src/index.js ADDED
@@ -0,0 +1,355 @@
1
+ // @paramira/authentik-blueprints: the blueprints, their templates, and the
2
+ // helpers to check and apply them.
3
+ import { readdirSync, readFileSync } from 'node:fs'
4
+ import { dirname, join, relative } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { parseDocument } from 'yaml'
7
+
8
+ const here = dirname(fileURLToPath(import.meta.url))
9
+ export const BLUEPRINTS_DIR = join(here, '..', 'blueprints')
10
+ export const TEMPLATES_DIR = join(here, '..', 'templates')
11
+
12
+ /** Apply order: later files may !Find objects made by earlier ones. */
13
+ export const ORDER = ['paramira/accounts.yaml', 'paramira/site.yaml', 'paramira/readfine.yaml', 'paramira-wallet/wallet.yaml', 'paramira-ecosystem/matrix.yaml']
14
+ /**
15
+ * Applied only where they are mounted: the wallet needs its bridge running;
16
+ * an ecosystem tool's client, the tool (design 0007).
17
+ */
18
+ export const OPTIONAL = ['paramira-wallet/wallet.yaml', 'paramira-ecosystem/matrix.yaml']
19
+
20
+ /** The site's roles (design 0003, ADR-0018), as Authentik groups. */
21
+ export const SITE_GROUPS = ['paramira-web-community', 'paramira-web-contributor', 'paramira-web-editor', 'paramira-web-customer', 'paramira-web-admin']
22
+ /** The groups the people service may move people in and out of: never admin. */
23
+ export const PEOPLE_GROUPS = SITE_GROUPS.filter((g) => g !== 'paramira-web-admin')
24
+ /** Suspended accounts (ADR-0036): not a role; the flows and applications refuse its members, never an admin. */
25
+ export const SUSPENDED_GROUP = 'paramira-web-suspended'
26
+
27
+ const GROUP_MEMBERSHIP = ['authentik_core.view_group', 'authentik_core.add_user_to_group', 'authentik_core.remove_user_from_group']
28
+
29
+ /**
30
+ * Permissions blueprints can't grant, given to roles after their blueprint is
31
+ * applied: a string is a model-level permission; `{ group, permissions }` is
32
+ * on that one group only.
33
+ *
34
+ * - The onboarding service links accounts to wallets and nothing else: no
35
+ * permission on users.
36
+ * - The people service sees the site's groups (who has which role) and moves
37
+ * people in and out of four of them; on the admin group it can only look.
38
+ * It makes, sees and deletes invitations (design 0008: /admin/invites),
39
+ * and sees flows (to name the sign-up flow an invitation is for). It
40
+ * suspends accounts by moving them in and out of the suspended group,
41
+ * and never changes an account (ADR-0036); it may delete an account only
42
+ * while it is pending sign-up (granted per account, by the sign-up flow).
43
+ */
44
+ export const ROLE_PERMISSIONS = {
45
+ 'paramira/site.yaml': {
46
+ 'paramira-people': [
47
+ ...PEOPLE_GROUPS.map((group) => ({ group, permissions: GROUP_MEMBERSHIP })),
48
+ { group: 'paramira-web-admin', permissions: ['authentik_core.view_group'] },
49
+ { group: SUSPENDED_GROUP, permissions: GROUP_MEMBERSHIP },
50
+ 'authentik_stages_invitation.add_invitation',
51
+ 'authentik_stages_invitation.view_invitation',
52
+ 'authentik_stages_invitation.delete_invitation',
53
+ 'authentik_flows.view_flow',
54
+ ],
55
+ },
56
+ 'paramira-wallet/wallet.yaml': {
57
+ 'paramira-onboarding': [
58
+ 'authentik_sources_oauth.view_oauthsource',
59
+ 'authentik_sources_oauth.view_useroauthsourceconnection',
60
+ 'authentik_sources_oauth.delete_useroauthsourceconnection',
61
+ ],
62
+ },
63
+ }
64
+
65
+ /**
66
+ * Permissions a role had and no longer needs: taken back on apply, wherever
67
+ * an earlier apply granted them. The onboarding service no longer creates
68
+ * connections: the person links their wallet themselves (ADR-0028).
69
+ */
70
+ export const ROLE_PERMISSIONS_WITHDRAWN = {
71
+ 'paramira-wallet/wallet.yaml': {
72
+ 'paramira-onboarding': ['authentik_sources_oauth.add_useroauthsourceconnection'],
73
+ },
74
+ }
75
+
76
+ async function findGroup (authentik, name) {
77
+ const { data } = await authentik.raw.GET('/core/groups/', { params: { query: { name, include_users: false } } })
78
+ const group = (data?.results ?? []).find((g) => g.name === name)
79
+ if (!group) throw new Error(`group ${name} not found (is paramira/accounts.yaml applied?)`)
80
+ return group
81
+ }
82
+
83
+ /**
84
+ * Lets the people service see one account (so an admin can give it a role).
85
+ * Sign-up does this for new accounts (accounts.yaml, pol-people-can-see).
86
+ */
87
+ export async function allowPeopleToSee (authentik, userPk) {
88
+ const roles = (await authentik.raw.GET('/rbac/roles/', { params: { query: { search: 'paramira-people' } } })).data?.results ?? []
89
+ const role = roles.find((r) => r.name === 'paramira-people')
90
+ if (!role) throw new Error('role paramira-people not found (is paramira/site.yaml applied?)')
91
+ const { error, response } = await authentik.raw.POST('/rbac/permissions/assigned_by_roles/{uuid}/assign/', {
92
+ params: { path: { uuid: role.pk } },
93
+ body: { permissions: ['authentik_core.view_user'], model: 'authentik_core.user', object_pk: String(userPk) },
94
+ })
95
+ if (error || !response.ok) throw new Error(`letting the people service see user ${userPk} failed: ${JSON.stringify(error)}`)
96
+ }
97
+
98
+ /** Lets the people service delete one account still pending sign-up (ADR-0036). */
99
+ async function allowPeopleToDelete (authentik, userPk) {
100
+ const roles = (await authentik.raw.GET('/rbac/roles/', { params: { query: { search: 'paramira-people' } } })).data?.results ?? []
101
+ const role = roles.find((r) => r.name === 'paramira-people')
102
+ const { error, response } = await authentik.raw.POST('/rbac/permissions/assigned_by_roles/{uuid}/assign/', {
103
+ params: { path: { uuid: role.pk } },
104
+ body: { permissions: ['authentik_core.delete_user'], model: 'authentik_core.user', object_pk: String(userPk) },
105
+ })
106
+ if (error || !response.ok) throw new Error(`letting the people service delete user ${userPk} failed: ${JSON.stringify(error)}`)
107
+ }
108
+
109
+ /** An account sign-up made and nobody finished (`cleanupPending` removes them). */
110
+ export const isPending = (u) => !u.is_active && /^pending-[0-9a-f]{16}$/.test(u.username)
111
+
112
+ /**
113
+ * Every paramira account (path users/paramira) in the community group and
114
+ * visible to the people service: for accounts made before the roles existed.
115
+ * Accounts still pending sign-up may be deleted by it (as sign-up now
116
+ * allows: ADR-0036). Idempotent; run by `apply` after site.yaml.
117
+ */
118
+ export async function backfillPeople (authentik) {
119
+ const community = (await authentik.raw.GET('/core/groups/', { params: { query: { name: 'paramira-web-community', include_users: true } } })).data?.results?.[0]
120
+ if (!community) throw new Error('group paramira-web-community not found (is paramira/accounts.yaml applied?)')
121
+ const members = new Set(community.users)
122
+ let added = 0
123
+ let total = 0
124
+ for (let page = 1; page; ) {
125
+ const { data } = await authentik.raw.GET('/core/users/', { params: { query: { path: 'users/paramira', page, page_size: 100 } } })
126
+ for (const user of data?.results ?? []) {
127
+ total++
128
+ try {
129
+ await allowPeopleToSee(authentik, user.pk)
130
+ if (isPending(user)) await allowPeopleToDelete(authentik, user.pk)
131
+ } catch (e) {
132
+ // Deleted since it was listed: nothing to do for it any more.
133
+ if (!/Object does not exist/.test(e.message)) throw e
134
+ continue
135
+ }
136
+ if (!members.has(user.pk)) {
137
+ const { response } = await authentik.raw.POST('/core/groups/{group_uuid}/add_user/', { params: { path: { group_uuid: community.pk } }, body: { pk: user.pk } })
138
+ if (!response.ok) throw new Error(`adding user ${user.pk} to community failed: ${response.status}`)
139
+ added++
140
+ }
141
+ }
142
+ page = data?.pagination?.next || 0
143
+ }
144
+ return { accounts: total, joinedCommunity: added }
145
+ }
146
+
147
+ /** Give each role exactly the permissions above that it lacks (idempotent). */
148
+ export async function grantRolePermissions (authentik, path) {
149
+ const granted = []
150
+ for (const [roleName, wanted] of Object.entries(ROLE_PERMISSIONS[path] ?? {})) {
151
+ const roles = (await authentik.raw.GET('/rbac/roles/', { params: { query: { search: roleName } } })).data?.results ?? []
152
+ const role = roles.find((r) => r.name === roleName)
153
+ if (!role) throw new Error(`role ${roleName} not found (is ${path} applied?)`)
154
+ const assign = async (body) => {
155
+ const { error, response } = await authentik.raw.POST('/rbac/permissions/assigned_by_roles/{uuid}/assign/', { params: { path: { uuid: role.pk } }, body })
156
+ if (error || !response.ok) throw new Error(`granting ${body.permissions.join(', ')} to ${roleName} failed: ${JSON.stringify(error)}`)
157
+ }
158
+
159
+ const modelLevel = wanted.filter((p) => typeof p === 'string')
160
+ // The role's model permissions (since 2026.8, `/rbac/permissions/roles/?uuid=` lists none).
161
+ const have = new Set(((await authentik.raw.GET('/rbac/permissions/', { params: { query: { role: role.pk, page_size: 500 } } })).data?.results ?? [])
162
+ .map((p) => `${p.app_label}.${p.codename}`))
163
+ const missing = modelLevel.filter((p) => !have.has(p))
164
+ if (missing.length) await assign({ permissions: missing })
165
+ const withdrawn = (ROLE_PERMISSIONS_WITHDRAWN[path]?.[roleName] ?? []).filter((p) => have.has(p))
166
+ if (withdrawn.length) {
167
+ const { error, response } = await authentik.raw.PATCH('/rbac/permissions/assigned_by_roles/{uuid}/unassign/', { params: { path: { uuid: role.pk } }, body: { permissions: withdrawn } })
168
+ if (error || !response.ok) throw new Error(`taking back ${withdrawn.join(', ')} from ${roleName} failed: ${JSON.stringify(error)}`)
169
+ }
170
+
171
+ const objects = []
172
+ for (const { group, permissions } of wanted.filter((p) => typeof p === 'object')) {
173
+ const { pk } = await findGroup(authentik, group)
174
+ await assign({ permissions, model: 'authentik_core.group', object_pk: String(pk) })
175
+ objects.push(group)
176
+ }
177
+ granted.push({ role: roleName, added: missing, ...(withdrawn.length && { withdrawn }), ...(objects.length && { groups: objects }) })
178
+ }
179
+ return granted
180
+ }
181
+
182
+ /** Every blueprint shipped, as `{ path, file }`; `path` is how Authentik lists it. */
183
+ export function listBlueprints () {
184
+ const out = []
185
+ const walk = (dir) => {
186
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
187
+ const file = join(dir, entry.name)
188
+ if (entry.isDirectory()) walk(file)
189
+ else if (entry.name.endsWith('.yaml')) out.push({ path: relative(BLUEPRINTS_DIR, file), file })
190
+ }
191
+ }
192
+ walk(BLUEPRINTS_DIR)
193
+ const rank = (p) => (ORDER.indexOf(p) === -1 ? ORDER.length : ORDER.indexOf(p))
194
+ return out.sort((a, b) => rank(a.path) - rank(b.path) || a.path.localeCompare(b.path))
195
+ }
196
+
197
+ // Authentik's YAML tags, kept as { tag, value } so a blueprint can be read
198
+ // and checked without Authentik.
199
+ const TAGS = ['KeyOf', 'Find', 'FindObject', 'Env', 'Context', 'Format', 'If', 'Condition', 'Enumerate', 'Index', 'Value', 'AtIndex', 'ParseJSON', 'File']
200
+ const customTags = TAGS.flatMap((name) => ['scalar', 'seq', 'map'].map((kind) => ({
201
+ tag: `!${name}`,
202
+ collection: kind === 'scalar' ? undefined : kind,
203
+ resolve: (value) => ({ tag: name, value: typeof value?.toJSON === 'function' ? value.toJSON() : value }),
204
+ })))
205
+
206
+ export function parseBlueprint (text) {
207
+ const doc = parseDocument(text, { customTags })
208
+ if (doc.errors.length) throw new Error(doc.errors.map((e) => e.message).join('; '))
209
+ return doc.toJS()
210
+ }
211
+
212
+ function walkTags (node, visit) {
213
+ if (Array.isArray(node)) node.forEach((n) => walkTags(n, visit))
214
+ else if (node && typeof node === 'object') {
215
+ if (typeof node.tag === 'string' && 'value' in node && TAGS.includes(node.tag)) visit(node)
216
+ for (const v of Object.values(node)) walkTags(v, visit)
217
+ }
218
+ }
219
+
220
+ /** Environment variables a blueprint reads, and whether each has a default. */
221
+ export function envNames (blueprint) {
222
+ const names = new Map()
223
+ walkTags(blueprint, (t) => {
224
+ if (t.tag !== 'Env') return
225
+ const [name, fallback] = Array.isArray(t.value) ? t.value : [t.value]
226
+ names.set(name, (names.get(name) ?? false) || fallback !== undefined)
227
+ })
228
+ return [...names].map(([name, hasDefault]) => ({ name, hasDefault }))
229
+ }
230
+
231
+ /**
232
+ * Checks Authentik can't do for us before applying: the shape, unique ids,
233
+ * and every !KeyOf pointing to an entry defined earlier in the same file
234
+ * (Authentik fails the whole blueprint otherwise).
235
+ */
236
+ export function validateBlueprint (text) {
237
+ const errors = []
238
+ let bp
239
+ try { bp = parseBlueprint(text) } catch (e) { return [`YAML: ${e.message}`] }
240
+ if (bp?.version !== 1) errors.push('version must be 1')
241
+ if (!bp?.metadata?.name) errors.push('metadata.name is missing')
242
+ if (!Array.isArray(bp?.entries)) return [...errors, 'entries must be a list']
243
+ const seen = new Set()
244
+ bp.entries.forEach((entry, i) => {
245
+ const where = `entry ${i + 1}${entry?.id ? ` (${entry.id})` : ''}`
246
+ if (typeof entry?.model !== 'string' || !/^[a-z0-9_]+\.[a-z0-9_]+$/.test(entry.model)) errors.push(`${where}: model must look like app.model`)
247
+ if (!entry?.identifiers || typeof entry.identifiers !== 'object') errors.push(`${where}: identifiers missing`)
248
+ walkTags({ identifiers: entry?.identifiers, attrs: entry?.attrs }, (t) => {
249
+ if (t.tag === 'KeyOf' && !seen.has(t.value)) errors.push(`${where}: !KeyOf ${t.value} is not defined earlier in the file`)
250
+ })
251
+ if (entry?.id) {
252
+ if (seen.has(entry.id)) errors.push(`${where}: id ${entry.id} is used twice`)
253
+ seen.add(entry.id)
254
+ }
255
+ })
256
+ return errors
257
+ }
258
+
259
+ /** Validate every shipped blueprint: `[{ path, errors }]`. */
260
+ export function validateAll () {
261
+ return listBlueprints().map(({ path, file }) => ({ path, errors: validateBlueprint(readFileSync(file, 'utf8')) }))
262
+ }
263
+
264
+ /**
265
+ * Apply every shipped blueprint, in order, through the API. Authentik must
266
+ * see the same files (mounted under /blueprints/), as `available()` lists.
267
+ *
268
+ * @param {import('@paramira/authentik-client').Authentik} authentik
269
+ */
270
+ // Right after Authentik starts, its blueprint endpoints answer 5xx for a
271
+ // moment (the worker isn't ready): retry those, briefly.
272
+ async function retrying (fn, { tries = 15, delayMs = 2000 } = {}) {
273
+ for (let i = 1; ; i++) {
274
+ try { return await fn() } catch (e) {
275
+ if (i >= tries || !(e?.status >= 500)) throw e
276
+ await new Promise((r) => setTimeout(r, delayMs))
277
+ }
278
+ }
279
+ }
280
+
281
+ export async function applyAll (authentik) {
282
+ const available = new Set((await retrying(() => authentik.blueprints.available())).map((b) => b.path))
283
+ const results = []
284
+ for (const { path } of listBlueprints()) {
285
+ if (!available.has(path)) {
286
+ results.push(OPTIONAL.includes(path)
287
+ ? { path, status: 'skipped', message: 'optional, not mounted' }
288
+ : { path, status: 'missing', message: 'not mounted in Authentik under /blueprints/' })
289
+ continue
290
+ }
291
+ const status = await applyAndWait(authentik, path)
292
+ const result = { path, status }
293
+ if (status === 'successful' && ROLE_PERMISSIONS[path]) result.granted = await grantRolePermissions(authentik, path)
294
+ if (status === 'successful' && path === 'paramira/site.yaml') result.people = await backfillPeople(authentik)
295
+ results.push(result)
296
+ }
297
+ return results
298
+ }
299
+
300
+ // Authentik's apply endpoint queues a task and answers at once, with the
301
+ // instance's previous status. Wait until it has been applied again; retry once
302
+ // (the worker applies mounted blueprints by itself, and two applies at the
303
+ // same moment can collide).
304
+ async function applyAndWait (authentik, path, { timeoutMs = 60000, retries = 1 } = {}) {
305
+ const before = (await authentik.blueprints.findByPath(path))?.last_applied ?? null
306
+ await authentik.blueprints.applyPath(path, { name: `paramira: ${path}` })
307
+ const end = Date.now() + timeoutMs
308
+ for (;;) {
309
+ const now = await authentik.blueprints.findByPath(path)
310
+ if (now && now.last_applied !== before) {
311
+ if (now.status === 'error' && retries > 0) return applyAndWait(authentik, path, { timeoutMs, retries: retries - 1 })
312
+ return now.status
313
+ }
314
+ if (Date.now() > end) return 'timeout'
315
+ await new Promise((r) => setTimeout(r, 500))
316
+ }
317
+ }
318
+
319
+ /** The state of every shipped blueprint in Authentik: `[{ path, status, lastApplied }]`. */
320
+ export async function status (authentik) {
321
+ const instances = await retrying(() => authentik.blueprints.list())
322
+ const available = new Set((await retrying(() => authentik.blueprints.available())).map((b) => b.path))
323
+ return listBlueprints().map(({ path }) => {
324
+ const i = instances.find((x) => x.path === path)
325
+ const absent = OPTIONAL.includes(path) && !available.has(path) ? 'skipped' : 'missing'
326
+ return { path, status: i?.status ?? absent, lastApplied: i?.last_applied ?? null }
327
+ })
328
+ }
329
+
330
+ /**
331
+ * Remove abandoned sign-ups: accounts the sign-up flow created (path
332
+ * users/paramira, username pending-…) that are still inactive after
333
+ * `olderThanHours`. Returns the usernames removed (or that would be, with
334
+ * `dryRun`). Run it daily (cron, a systemd timer, or akantu).
335
+ *
336
+ * @param {import('@paramira/authentik-client').Authentik} authentik
337
+ * @param {{ olderThanHours?: number, dryRun?: boolean, now?: Date }} [options]
338
+ */
339
+ export async function cleanupPending (authentik, { olderThanHours = 24, dryRun = false, now = new Date() } = {}) {
340
+ const cutoff = new Date(now.getTime() - olderThanHours * 3600 * 1000).toISOString()
341
+ const removed = []
342
+ for (;;) {
343
+ const { data, error } = await authentik.raw.GET('/core/users/', {
344
+ params: { query: { path: 'users/paramira', is_active: false, date_joined__lt: cutoff, page_size: 100 } },
345
+ })
346
+ if (error) throw new Error(`listing users failed: ${JSON.stringify(error)}`)
347
+ const pending = data.results.filter(isPending)
348
+ if (dryRun) return pending.map((u) => u.username)
349
+ for (const u of pending) {
350
+ await authentik.users.delete(u.pk)
351
+ removed.push(u.username)
352
+ }
353
+ if (pending.length < 100) return removed
354
+ }
355
+ }
@@ -0,0 +1,39 @@
1
+ {% extends "email/base.html" %}
2
+ {% load i18n %}
3
+ {# paramira: the one link email, for sign-up (the account isn't active yet) and sign-in. #}
4
+ {% block content %}
5
+ <tr>
6
+ <td align="center">
7
+ <h1>{% if user.is_active %}Sign in to Paramira{% else %}Confirm your email{% endif %}</h1>
8
+ </td>
9
+ </tr>
10
+ <tr>
11
+ <td align="center">
12
+ <table border="0">
13
+ <tr>
14
+ <td align="center" style="max-width: 300px; padding: 20px 0; color: #212124;">
15
+ {% if user.is_active %}
16
+ Someone, probably you, asked to sign in to paramira.org with this email address. Open the link to sign in.
17
+ {% else %}
18
+ Someone, probably you, started creating a paramira.org account with this email address. Open the link to finish.
19
+ {% endif %}
20
+ The link works once, until {{ expires|date:"H:i" }} (UTC).
21
+ </td>
22
+ </tr>
23
+ <tr>
24
+ <td align="center" class="btn btn-primary">
25
+ <a id="link" href="{{ url }}" rel="noopener noreferrer" target="_blank">{% if user.is_active %}Sign in{% else %}Confirm and continue{% endif %}</a>
26
+ </td>
27
+ </tr>
28
+ </table>
29
+ </td>
30
+ </tr>
31
+ {% endblock %}
32
+ {% block sub_content %}
33
+ <tr>
34
+ <td style="padding: 20px; font-size: 12px; color: #212124; word-break: break-all; overflow-wrap: break-word;" align="center">
35
+ If you didn't ask for this, ignore this email: nothing happens without the link.<br>
36
+ If the button doesn't work, copy this address into your browser: {{ url }}
37
+ </td>
38
+ </tr>
39
+ {% endblock %}
@@ -0,0 +1,10 @@
1
+ {% load i18n %}{% autoescape off %}{% if user.is_active %}Sign in to Paramira
2
+
3
+ Someone, probably you, asked to sign in to paramira.org with this email address. Open the link to sign in:{% else %}Confirm your email
4
+
5
+ Someone, probably you, started creating a paramira.org account with this email address. Open the link to finish:{% endif %}
6
+
7
+ {{ url }}
8
+
9
+ The link works once, until {{ expires|date:"H:i" }} (UTC). If you didn't ask for this, ignore this email: nothing happens without the link.
10
+ {% endautoescape %}