@paramira/authentik-blueprints 0.1.0 → 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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [Authentik](https://goauthentik.io) blueprints for **email-first accounts with
4
4
  no passwords**, made for small organisations and communities, for Authentik
5
- 2026.2.3:
5
+ 2026.8.3 (written on 2026.2.3):
6
6
 
7
7
  - **sign-up by email:** the person enters an email, opens the link (on any
8
8
  device), picks a username and a display name;
@@ -11,14 +11,19 @@ no passwords**, made for small organisations and communities, for Authentik
11
11
  - **no duplicate accounts:** signing up again with a registered address sends
12
12
  a sign-in link instead of creating a second account (Authentik itself
13
13
  doesn't require unique emails);
14
+ - **invitations with a role:** an invitation's `fixed_data` `{email,
15
+ paramira_role}` fills in the address, refuses another one, and gives the
16
+ role (community, contributor, editor or customer; never admin) once the
17
+ email link is opened; the person then lands on the site's `/welcome`;
14
18
  - **a brand** and **link emails in plain words**;
15
19
  - **a website as an OpenID Connect client** (confidential, PKCE, strict
16
20
  redirect URI, a hashed `sub`, never the email).
17
21
 
18
22
  | File | Holds |
19
23
  |---|---|
20
- | `blueprints/paramira/accounts.yaml` | groups `paramira-members` and `paramira-org-admins`; the flows `paramira-enrollment`, `paramira-login-link` (designated *recovery*: only there does Authentik pretend to send for an unknown address) and `paramira-authentication` (the brand's sign-in, which hands over to the link flow and comes back to the app); the brand |
21
- | `blueprints/paramira/site.yaml` | the OIDC provider and application `paramira-web`, and a `paramira` scope (`profile_completed`, `wallet_enrolled`) |
24
+ | `blueprints/paramira/accounts.yaml` | the site's role groups `paramira-web-community` (everyone, from sign-up), `-contributor`, `-editor`, `-customer`, `-admin` (ADR-0018); sign-up lets the people service see the new account; the flows `paramira-enrollment`, `paramira-login-link` (designated *recovery*: only there does Authentik pretend to send for an unknown address) and `paramira-authentication` (the brand's sign-in, which hands over to the link flow and comes back to the app); the brand |
25
+ | `blueprints/paramira/site.yaml` | the OIDC provider and application `paramira-web`; a `paramira` scope (`user_pk`, `wallet_enrolled`, `wallet_opt_in`, `groups`); the people service (role, account, token `PARAMIRA_PEOPLE_TOKEN`) that moves people between four of the role groups, never admin, and makes, sees and deletes invitations. `apply` gives it its permissions and backfills existing accounts (community, visible to it) |
26
+ | `blueprints/paramira/readfine.yaml` | readfine, the dictionary (paramira-web design 0013, ADR-0053): its own OIDC provider and application `readfine`, with the `paramira` scope from `site.yaml` (the same roles), a strict redirect URI and the grants listed; suspended accounts refused. Environment: `PARAMIRA_READFINE_CLIENT_SECRET` (and `_CLIENT_ID`, `_REDIRECT_URI`, `_URL`) |
22
27
  | `templates/paramira/link.html`, `.txt` | the one link email, for sign-up and sign-in |
23
28
 
24
29
  ## Use it
@@ -51,8 +56,12 @@ npx authentik-blueprints env # the environment variables each blueprint r
51
56
  npx authentik-blueprints apply # apply in order, through the API
52
57
  npx authentik-blueprints status
53
58
  npx authentik-blueprints cleanup [--hours 24] [--dry-run] # remove abandoned sign-ups; run daily
59
+ npx authentik-blueprints invite [--days 7] [--email a@b.org [--role contributor]] # a sign-up link
54
60
  ```
55
61
 
62
+ `invite` without `--email` prints a single-use link for anyone; with it, a
63
+ link bound to that address (another is refused), giving `--role` at sign-up.
64
+
56
65
  Sign-up creates the account **inactive**, with a temporary `pending-…`
57
66
  username, before sending the link (Authentik's email step needs an existing
58
67
  user). `cleanup` removes those still inactive after a day.
@@ -64,7 +73,7 @@ tool (tier 1): `check` reports whether every blueprint is applied, `apply`
64
73
  applies them, `verify` checks again. Inputs: `url`, and `tokenFile`, a file
65
74
  holding the API token (the token itself is never an input).
66
75
 
67
- ## Known limits (Authentik 2026.2.3)
76
+ ## Known limits (Authentik 2026.2.3, still so in 2026.8)
68
77
 
69
78
  - Email link tokens are stored in plain text, and a failed send logs the email
70
79
  with its link; every `email_sent` event also stores it. Keep links short-lived
@@ -1,12 +1,19 @@
1
1
  #!/usr/bin/env node
2
- // authentik-blueprints validate | apply | status | env | cleanup [--hours N] [--dry-run] | akantu <step>
2
+ // authentik-blueprints validate | apply | status | env | cleanup [--hours N] [--dry-run]
3
+ // | invite [--name text] [--days N] [--email address [--role R]] | akantu <step>
3
4
  // AUTHENTIK_URL and AUTHENTIK_TOKEN (an API token) for apply and status.
4
5
  import { readFileSync } from 'node:fs'
5
6
  import { createAuthentik } from '@paramira/authentik-client'
6
- import { applyAll, cleanupPending, envNames, listBlueprints, parseBlueprint, status, validateAll } from '../src/index.js'
7
+ import { applyAll, cleanupPending, envNames, listBlueprints, parseBlueprint, PEOPLE_GROUPS, status, validateAll } from '../src/index.js'
7
8
 
8
9
  const [cmd, ...args] = process.argv.slice(2)
9
10
 
11
+ process.on('unhandledRejection', (e) => {
12
+ // One line, not an HTML error page.
13
+ console.error(`authentik-blueprints ${cmd}: ${e?.message ?? e}`)
14
+ process.exit(1)
15
+ })
16
+
10
17
  function client (url = process.env.AUTHENTIK_URL, token = process.env.AUTHENTIK_TOKEN) {
11
18
  if (!url || !token) {
12
19
  console.error('set AUTHENTIK_URL and AUTHENTIK_TOKEN')
@@ -22,7 +29,7 @@ async function akantu (step) {
22
29
  const out = (o) => { process.stdout.write(JSON.stringify(o) + '\n') }
23
30
  if (!input.url || !token) return out({ status: step === 'check' ? 'todo' : 'failed', message: 'needs inputs url and tokenFile' })
24
31
  const ak = client(input.url, token)
25
- const notDone = (s) => s.filter((b) => b.status !== 'successful')
32
+ const notDone = (s) => s.filter((b) => b.status !== 'successful' && b.status !== 'skipped')
26
33
  if (step === 'check') {
27
34
  const left = notDone(await status(ak))
28
35
  return out({ status: left.length ? 'todo' : 'done', message: left.length ? `not applied: ${left.map((b) => b.path).join(', ')}` : 'all applied', outputs: {} })
@@ -48,7 +55,7 @@ switch (cmd) {
48
55
  }
49
56
  break
50
57
  case 'apply':
51
- for (const r of await applyAll(client())) console.log(`${r.status === 'successful' ? '✓' : '✗'} ${r.path}: ${r.status}${r.message ? ` (${r.message})` : ''}`)
58
+ for (const r of await applyAll(client())) console.log(`${r.status === 'successful' ? '✓' : r.status === 'skipped' ? '-' : '✗'} ${r.path}: ${r.status}${r.message ? ` (${r.message})` : ''}`)
52
59
  break
53
60
  case 'status':
54
61
  for (const r of await status(client())) console.log(`${r.path}\t${r.status}\t${r.lastApplied ?? ''}`)
@@ -61,10 +68,39 @@ switch (cmd) {
61
68
  console.log(`${dryRun ? 'would remove' : 'removed'} ${names.length} abandoned sign-up(s)${names.length ? ': ' + names.join(', ') : ''}`)
62
69
  break
63
70
  }
71
+ case 'invite': {
72
+ // A sign-up link (sign-up is invite-only unless PARAMIRA_SIGNUP_OPEN=true).
73
+ // With --email, bound to that address (another is refused) and, with
74
+ // --role, giving that role at sign-up (never admin; ADR-0030), the same
75
+ // rules as /admin/invites. Without, a single-use link for anyone.
76
+ const opt = (flag) => (args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined)
77
+ const days = opt('--days') ? Number(opt('--days')) : 7
78
+ if (!Number.isFinite(days) || days <= 0 || days > 90) { console.error('--days must be between 1 and 90'); process.exit(2) }
79
+ const email = opt('--email')?.trim().toLowerCase()
80
+ const role = opt('--role')
81
+ const ROLES = PEOPLE_GROUPS.map((g) => g.replace('paramira-web-', ''))
82
+ if (role && !email) { console.error('--role needs --email: a role is only given to the address invited'); process.exit(2) }
83
+ if (role && !ROLES.includes(role)) { console.error(`--role is one of ${ROLES.join(', ')} (admin is given in Authentik only)`); process.exit(2) }
84
+ if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { console.error('--email: not an email address'); process.exit(2) }
85
+ const name = opt('--name') ?? `invite-${new Date().toISOString().slice(0, 10)}`
86
+ const ak = client()
87
+ const invitation = await ak.invitations.create({
88
+ name: name.toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 50),
89
+ flowSlug: 'paramira-enrollment',
90
+ // Bound to an address, more uses give nothing more; a single-use link
91
+ // is spent when first opened.
92
+ singleUse: !email,
93
+ expires: new Date(Date.now() + days * 86400_000),
94
+ ...(email && { fixedData: { email, ...(role && { paramira_role: role }) } })
95
+ })
96
+ console.log(ak.invitations.link(invitation, 'paramira-enrollment'))
97
+ console.error(email ? `for ${email}${role ? ` as ${role}` : ''}, valid for ${days} day(s)` : `single use, valid for ${days} day(s)`)
98
+ break
99
+ }
64
100
  case 'akantu':
65
101
  await akantu(args[0])
66
102
  break
67
103
  default:
68
- console.error('usage: authentik-blueprints validate | env | apply | status | cleanup [--hours N] [--dry-run] | akantu <check|apply|verify>')
104
+ console.error('usage: authentik-blueprints validate | env | apply | status | cleanup [--hours N] [--dry-run] | invite [--name text] [--days N] [--email address [--role R]] | akantu <check|apply|verify>')
69
105
  process.exit(2)
70
106
  }
@@ -15,20 +15,52 @@
15
15
  # Entries refer only to earlier ones (!KeyOf), so flows come before stages.
16
16
  #
17
17
  # Environment (on Authentik's server and worker):
18
- # PARAMIRA_AUTH_DOMAIN the brand's domain, e.g. auth.paramira.org
18
+ # PARAMIRA_AUTH_DOMAIN the brand's domain: a domain of its own when the
19
+ # Authentik is shared (e.g. login.paramira.org), so
20
+ # other apps keep their brand and flows
21
+ # PARAMIRA_SITE_URL where someone who signed up from an invitation
22
+ # lands (its /welcome)
23
+ # PARAMIRA_SIGNUP_OPEN "true" lets anyone sign up; otherwise (default)
24
+ # sign-up needs an invitation link
25
+ # (authentik-blueprints invite, or /admin/invites)
26
+ #
27
+ # An invitation may carry `fixed_data` {email, paramira_role} (ADR-0030):
28
+ # the email prompt is filled with the email, another address is refused,
29
+ # and once the link in the email was opened the account gets the role if it
30
+ # is community, contributor, editor or customer (never admin).
31
+ #
32
+ # A suspended account (in paramira-web-suspended, never an admin: ADR-0036)
33
+ # is refused once its email link is opened, in both flows.
19
34
  version: 1
20
35
  metadata:
21
36
  name: paramira-accounts
22
37
  labels:
23
38
  blueprints.goauthentik.io/description: "paramira: org accounts (sign-up and sign-in by email)"
24
39
  entries:
25
- # Groups
40
+ # Groups: the site's roles (design 0003, ADR-0018). Everyone joins
41
+ # community at sign-up; an admin moves people between community,
42
+ # contributor, editor and customer (the people service, site.yaml); admin
43
+ # is given only here, in Authentik. A person can be in several.
26
44
  - model: authentik_core.group
27
45
  id: g-members
28
- identifiers: {name: paramira-members}
46
+ identifiers: {name: paramira-web-community}
47
+ - model: authentik_core.group
48
+ id: g-contributors
49
+ identifiers: {name: paramira-web-contributor}
50
+ - model: authentik_core.group
51
+ id: g-editors
52
+ identifiers: {name: paramira-web-editor}
53
+ - model: authentik_core.group
54
+ id: g-customers
55
+ identifiers: {name: paramira-web-customer}
29
56
  - model: authentik_core.group
30
57
  id: g-admins
31
- identifiers: {name: paramira-org-admins}
58
+ identifiers: {name: paramira-web-admin}
59
+ # Suspended accounts (ADR-0036): refused by the flows below and by the
60
+ # site's and chat's applications; an admin never is.
61
+ - model: authentik_core.group
62
+ id: g-suspended
63
+ identifiers: {name: paramira-web-suspended}
32
64
 
33
65
  # Prompts
34
66
  - model: authentik_stages_prompt.prompt
@@ -85,15 +117,126 @@ entries:
85
117
  plan.context["paramira_existing_account"] = False
86
118
  data["username"] = "pending-" + secrets.token_hex(8)
87
119
  return True
120
+ - model: authentik_policies_expression.expressionpolicy
121
+ id: pol-forget-temp-username
122
+ identifiers: {name: paramira-enrollment-forget-temporary-username}
123
+ attrs:
124
+ expression: |
125
+ # Bound to the email-link step, after the account was created: the
126
+ # temporary username must not come back pre-filled in the profile step.
127
+ data = request.context["flow_plan"].context.get("prompt_data", {})
128
+ if str(data.get("username", "")).startswith("pending-"):
129
+ del data["username"]
130
+ return True
131
+ - model: authentik_policies_expression.expressionpolicy
132
+ id: pol-people-can-see
133
+ identifiers: {name: paramira-enrollment-people-can-see}
134
+ attrs:
135
+ expression: |
136
+ # Bound to the email-link step, after the account was created: the
137
+ # people service (site.yaml) may see this account, so an admin can
138
+ # give it a role. It sees paramira accounts only, never the other
139
+ # apps' users on a shared Authentik (design 0003, ADR-0018).
140
+ from authentik.rbac.models import Role
141
+ # An account just made for a new address (still pending) may also be
142
+ # deleted by it, so an abandoned sign-up can be cleared from the
143
+ # site; taken back when sign-up finishes (pol-people-cannot-delete).
144
+ plan = request.context["flow_plan"]
145
+ user = plan.context.get("pending_user")
146
+ role = Role.objects.filter(name="paramira-people").first()
147
+ if user is not None and user.pk and role is not None:
148
+ role.assign_perms("authentik_core.view_user", obj=user)
149
+ if not plan.context.get("paramira_existing_account") and not user.is_active and user.username.startswith("pending-"):
150
+ role.assign_perms("authentik_core.delete_user", obj=user)
151
+ return True
152
+ - model: authentik_policies_expression.expressionpolicy
153
+ id: pol-people-cannot-delete
154
+ identifiers: {name: paramira-enrollment-people-cannot-delete}
155
+ attrs:
156
+ expression: |
157
+ # Bound to the last step (signing in): the account is no longer an
158
+ # abandoned sign-up, so the people service may no longer delete it.
159
+ from authentik.rbac.models import Role
160
+ user = request.context["flow_plan"].context.get("pending_user")
161
+ role = Role.objects.filter(name="paramira-people").first()
162
+ if user is not None and user.pk and role is not None:
163
+ role.remove_perms("authentik_core.delete_user", obj=user)
164
+ return True
165
+ - model: authentik_policies_expression.expressionpolicy
166
+ id: pol-suspended
167
+ identifiers: {name: paramira-suspended}
168
+ attrs:
169
+ expression: |
170
+ # Passes for a suspended account (ADR-0036), never an admin: in a
171
+ # flow, the account signing in; on an application (bound negated),
172
+ # the person asking for it.
173
+ plan = request.context.get("flow_plan")
174
+ user = plan.context.get("pending_user") if plan else request.user
175
+ if user is None or not user.pk:
176
+ return False
177
+ return ak_is_group_member(user, name="paramira-web-suspended") and not ak_is_group_member(user, name="paramira-web-admin")
178
+ - model: authentik_policies_expression.expressionpolicy
179
+ id: pol-own-username
180
+ identifiers: {name: paramira-enrollment-own-username}
181
+ attrs:
182
+ expression: |
183
+ # Validation of the profile step: a username of the person's own.
184
+ username = str(request.context.get("prompt_data", {}).get("username", "")).strip()
185
+ if not username or username.lower().startswith("pending-"):
186
+ ak_message("Choose a username of your own.")
187
+ return False
188
+ return True
88
189
  - model: authentik_policies_expression.expressionpolicy
89
190
  id: pol-new-only
90
191
  identifiers: {name: paramira-enrollment-new-account-only}
91
192
  attrs:
92
193
  expression: |
93
- # The profile steps run only for a new account. (A missing
94
- # paramira.profile_completed means "not completed"; the site sets it.)
194
+ # The profile steps run only for a new account. (Whether this is the
195
+ # first sign-in is tracked by the site itself.)
95
196
  plan = request.context["flow_plan"]
96
197
  return not plan.context.get("paramira_existing_account", False)
198
+ - model: authentik_policies_expression.expressionpolicy
199
+ id: pol-not-invited-email
200
+ identifiers: {name: paramira-enrollment-not-the-invited-email}
201
+ attrs:
202
+ expression: |
203
+ # Bound to the step that refuses sign-up: passes (so the sign-up is
204
+ # refused) when an invitation names an email and this isn't it. A
205
+ # forwarded invitation gives nothing (ADR-0030).
206
+ plan = request.context["flow_plan"]
207
+ invite = plan.context.get("invitation")
208
+ invited = str((invite.fixed_data or {}).get("email", "") if invite else "").strip().lower()
209
+ given = str(plan.context.get("prompt_data", {}).get("email", "")).strip().lower()
210
+ return bool(invited) and given != invited
211
+ - model: authentik_policies_expression.expressionpolicy
212
+ id: pol-invited-role
213
+ identifiers: {name: paramira-enrollment-invited-role}
214
+ attrs:
215
+ expression: |
216
+ # Bound to the last step (signing in), after the email link was
217
+ # opened: the invitation's role (ADR-0030) is given to the account,
218
+ # new or existing, if it is one an admin may give; admin never.
219
+ from authentik.core.models import Group
220
+ plan = request.context["flow_plan"]
221
+ invite = plan.context.get("invitation")
222
+ user = plan.context.get("pending_user")
223
+ role = (invite.fixed_data or {}).get("paramira_role") if invite else None
224
+ if user is not None and user.pk and role in ("community", "contributor", "editor", "customer"):
225
+ group = Group.objects.filter(name="paramira-web-" + role).first()
226
+ if group is not None:
227
+ user.groups.add(group)
228
+ return True
229
+
230
+ - model: authentik_policies_expression.expressionpolicy
231
+ id: pol-from-invitation
232
+ identifiers: {name: paramira-enrollment-from-invitation}
233
+ attrs:
234
+ expression: |
235
+ # Bound to the step after signing in: someone who came from an
236
+ # invitation link (not from a site's sign-in, which goes back there)
237
+ # goes on to the site's welcome page.
238
+ plan = request.context["flow_plan"]
239
+ return bool(plan.context.get("invitation")) and not plan.context.get("application")
97
240
 
98
241
  # Flows
99
242
  - model: authentik_flows.flow
@@ -101,7 +244,7 @@ entries:
101
244
  identifiers: {slug: paramira-enrollment}
102
245
  attrs:
103
246
  name: paramira-enrollment
104
- title: Create your paramira.org account
247
+ title: Create your Paramira account
105
248
  designation: enrollment
106
249
  authentication: require_unauthenticated
107
250
  - model: authentik_flows.flow
@@ -109,7 +252,7 @@ entries:
109
252
  identifiers: {slug: paramira-login-link}
110
253
  attrs:
111
254
  name: paramira-login-link
112
- title: Sign in to paramira.org
255
+ title: Sign in to Paramira
113
256
  designation: recovery
114
257
  authentication: none
115
258
  - model: authentik_flows.flow
@@ -117,16 +260,31 @@ entries:
117
260
  identifiers: {slug: paramira-authentication}
118
261
  attrs:
119
262
  name: paramira-authentication
120
- title: Sign in to paramira.org
263
+ title: Sign in to Paramira
121
264
  designation: authentication
122
265
  authentication: none
123
266
 
124
267
  # Stages
268
+ - model: authentik_stages_invitation.invitationstage
269
+ id: s-invitation
270
+ identifiers: {name: paramira-enrollment-invitation}
271
+ attrs:
272
+ continue_flow_without_invitation: !Env [PARAMIRA_SIGNUP_OPEN, false]
125
273
  - model: authentik_stages_prompt.promptstage
126
274
  id: s-email
127
275
  identifiers: {name: paramira-enrollment-email}
128
276
  attrs:
129
277
  fields: [!KeyOf p-email]
278
+ - model: authentik_stages_deny.denystage
279
+ id: s-suspended
280
+ identifiers: {name: paramira-suspended}
281
+ attrs:
282
+ deny_message: This account is suspended. Write to support@paramira.org if you think it's a mistake.
283
+ - model: authentik_stages_deny.denystage
284
+ id: s-not-invited
285
+ identifiers: {name: paramira-enrollment-not-invited}
286
+ attrs:
287
+ deny_message: This invitation is for another email address. Use the address it was sent to.
130
288
  - model: authentik_stages_user_write.userwritestage
131
289
  id: s-precreate
132
290
  identifiers: {name: paramira-enrollment-create}
@@ -141,7 +299,7 @@ entries:
141
299
  attrs:
142
300
  use_global_settings: true
143
301
  token_expiry: minutes=30
144
- subject: Your paramira.org link
302
+ subject: Your Paramira sign-in link
145
303
  template: paramira/link.html
146
304
  activate_user_on_success: true
147
305
  - model: authentik_stages_prompt.promptstage
@@ -149,6 +307,7 @@ entries:
149
307
  identifiers: {name: paramira-enrollment-profile}
150
308
  attrs:
151
309
  fields: [!KeyOf p-username, !KeyOf p-name, !KeyOf p-wallet]
310
+ validation_policies: [!KeyOf pol-own-username]
152
311
  - model: authentik_stages_user_write.userwritestage
153
312
  id: s-write
154
313
  identifiers: {name: paramira-enrollment-save}
@@ -159,6 +318,12 @@ entries:
159
318
  identifiers: {name: paramira-login}
160
319
  attrs:
161
320
  session_duration: days=30
321
+ - model: authentik_stages_redirect.redirectstage
322
+ id: s-to-site
323
+ identifiers: {name: paramira-enrollment-to-site}
324
+ attrs:
325
+ mode: static
326
+ target_static: !Format ["%s/welcome", !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]]
162
327
  - model: authentik_stages_identification.identificationstage
163
328
  id: s-identify
164
329
  identifiers: {name: paramira-login-identify}
@@ -174,7 +339,7 @@ entries:
174
339
  attrs:
175
340
  use_global_settings: true
176
341
  token_expiry: minutes=10
177
- subject: Your paramira.org link
342
+ subject: Your Paramira sign-in link
178
343
  template: paramira/link.html
179
344
  activate_user_on_success: false
180
345
  - model: authentik_stages_redirect.redirectstage
@@ -186,8 +351,16 @@ entries:
186
351
  keep_context: true
187
352
 
188
353
  # Sign-up bindings
354
+ - model: authentik_flows.flowstagebinding
355
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-invitation, order: 5}
189
356
  - model: authentik_flows.flowstagebinding
190
357
  identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-email, order: 10}
358
+ - model: authentik_flows.flowstagebinding
359
+ id: b-not-invited
360
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-not-invited, order: 15}
361
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
362
+ - model: authentik_policies.policybinding
363
+ identifiers: {target: !KeyOf b-not-invited, policy: !KeyOf pol-not-invited-email, order: 0}
191
364
  - model: authentik_flows.flowstagebinding
192
365
  id: b-precreate
193
366
  identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-precreate, order: 20}
@@ -195,7 +368,19 @@ entries:
195
368
  - model: authentik_policies.policybinding
196
369
  identifiers: {target: !KeyOf b-precreate, policy: !KeyOf pol-new-or-existing, order: 0}
197
370
  - model: authentik_flows.flowstagebinding
371
+ id: b-verify
198
372
  identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-verify, order: 30}
373
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
374
+ - model: authentik_policies.policybinding
375
+ identifiers: {target: !KeyOf b-verify, policy: !KeyOf pol-forget-temp-username, order: 0}
376
+ - model: authentik_policies.policybinding
377
+ identifiers: {target: !KeyOf b-verify, policy: !KeyOf pol-people-can-see, order: 1}
378
+ - model: authentik_flows.flowstagebinding
379
+ id: b-enroll-suspended
380
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-suspended, order: 35}
381
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
382
+ - model: authentik_policies.policybinding
383
+ identifiers: {target: !KeyOf b-enroll-suspended, policy: !KeyOf pol-suspended, order: 0}
199
384
  - model: authentik_flows.flowstagebinding
200
385
  id: b-profile
201
386
  identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-profile, order: 40}
@@ -209,13 +394,31 @@ entries:
209
394
  - model: authentik_policies.policybinding
210
395
  identifiers: {target: !KeyOf b-write, policy: !KeyOf pol-new-only, order: 0}
211
396
  - model: authentik_flows.flowstagebinding
397
+ id: b-login
212
398
  identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-login, order: 60}
399
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
400
+ - model: authentik_policies.policybinding
401
+ identifiers: {target: !KeyOf b-login, policy: !KeyOf pol-invited-role, order: 0}
402
+ - model: authentik_policies.policybinding
403
+ identifiers: {target: !KeyOf b-login, policy: !KeyOf pol-people-cannot-delete, order: 1}
404
+ - model: authentik_flows.flowstagebinding
405
+ id: b-to-site
406
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-to-site, order: 70}
407
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
408
+ - model: authentik_policies.policybinding
409
+ identifiers: {target: !KeyOf b-to-site, policy: !KeyOf pol-from-invitation, order: 0}
213
410
 
214
411
  # Sign-in bindings
215
412
  - model: authentik_flows.flowstagebinding
216
413
  identifiers: {target: !KeyOf f-link, stage: !KeyOf s-identify, order: 10}
217
414
  - model: authentik_flows.flowstagebinding
218
415
  identifiers: {target: !KeyOf f-link, stage: !KeyOf s-link, order: 20}
416
+ - model: authentik_flows.flowstagebinding
417
+ id: b-link-suspended
418
+ identifiers: {target: !KeyOf f-link, stage: !KeyOf s-suspended, order: 25}
419
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
420
+ - model: authentik_policies.policybinding
421
+ identifiers: {target: !KeyOf b-link-suspended, policy: !KeyOf pol-suspended, order: 0}
219
422
  - model: authentik_flows.flowstagebinding
220
423
  identifiers: {target: !KeyOf f-link, stage: !KeyOf s-login, order: 30}
221
424
  - model: authentik_flows.flowstagebinding
@@ -226,7 +429,7 @@ entries:
226
429
  identifiers: {domain: !Env [PARAMIRA_AUTH_DOMAIN, auth.paramira.localhost]}
227
430
  attrs:
228
431
  default: false
229
- branding_title: paramira.org
432
+ branding_title: Paramira
230
433
  branding_custom_css: |
231
434
  :root { --pf-global--primary-color--100: #2f7d5a; --pf-global--link--Color: #2f7d5a; }
232
435
  flow_authentication: !KeyOf f-auth
@@ -0,0 +1,63 @@
1
+ # readfine (design 0013, ADR-0053): the dictionary's site as an OpenID
2
+ # Connect client of Authentik, with the same accounts and roles as
3
+ # paramira.org (ADR-0018). Its own client, so neither site can read the
4
+ # other's session: a person signed in on paramira.org signs in here with one
5
+ # click through Authentik's session.
6
+ # Needs accounts.yaml (the sign-in flow, the suspended policy) and site.yaml
7
+ # (the `paramira` scope) applied first.
8
+ #
9
+ # Environment (on Authentik's server and worker):
10
+ # PARAMIRA_READFINE_CLIENT_ID e.g. readfine
11
+ # PARAMIRA_READFINE_CLIENT_SECRET random, at least 32 bytes; shared with readfine
12
+ # PARAMIRA_READFINE_REDIRECT_URI e.g. https://readfine.paramira.org/auth/callback
13
+ # PARAMIRA_READFINE_URL e.g. https://readfine.paramira.org
14
+ version: 1
15
+ metadata:
16
+ name: paramira-readfine
17
+ labels:
18
+ blueprints.goauthentik.io/description: "paramira: readfine, the dictionary, as an OIDC client"
19
+ entries:
20
+ - model: authentik_providers_oauth2.oauth2provider
21
+ id: provider
22
+ identifiers: {name: readfine}
23
+ attrs:
24
+ authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
25
+ invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
26
+ authentication_flow: !Find [authentik_flows.flow, [slug, paramira-authentication]]
27
+ # A confidential client: the code flow with PKCE runs on readfine's
28
+ # server (ADR-0009); no token reaches the browser.
29
+ client_type: confidential
30
+ # Authentik 2026.8 allows only the grants listed.
31
+ grant_types: [authorization_code, refresh_token]
32
+ client_id: !Env [PARAMIRA_READFINE_CLIENT_ID, readfine]
33
+ client_secret: !Env PARAMIRA_READFINE_CLIENT_SECRET
34
+ redirect_uris:
35
+ - matching_mode: strict
36
+ url: !Env [PARAMIRA_READFINE_REDIRECT_URI, "https://readfine.paramira.localhost/auth/callback"]
37
+ signing_key: !Find [authentik_crypto.certificatekeypair, [name, authentik Self-signed Certificate]]
38
+ sub_mode: hashed_user_id
39
+ include_claims_in_id_token: true
40
+ access_token_validity: minutes=10
41
+ refresh_token_validity: days=30
42
+ property_mappings:
43
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-openid]]
44
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-email]]
45
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-profile]]
46
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-offline_access]]
47
+ # site.yaml's: the account number, the roles, when the account was made
48
+ - !Find [authentik_providers_oauth2.scopemapping, [name, "paramira: account state"]]
49
+
50
+ - model: authentik_core.application
51
+ id: app
52
+ identifiers: {slug: readfine}
53
+ attrs:
54
+ name: readfine
55
+ provider: !KeyOf provider
56
+ meta_launch_url: !Env [PARAMIRA_READFINE_URL, "https://readfine.paramira.localhost"]
57
+ policy_engine_mode: any
58
+ # A suspended account (ADR-0036) can't sign in here either.
59
+ - model: authentik_policies.policybinding
60
+ identifiers: {target: !KeyOf app, order: 0}
61
+ attrs:
62
+ policy: !Find [authentik_policies_expression.expressionpolicy, [name, paramira-suspended]]
63
+ negate: true
@@ -7,6 +7,18 @@
7
7
  # PARAMIRA_SITE_CLIENT_SECRET random, at least 32 bytes; shared with the site
8
8
  # PARAMIRA_SITE_REDIRECT_URI e.g. https://paramira.org/auth/callback
9
9
  # PARAMIRA_SITE_URL e.g. https://paramira.org
10
+ #
11
+ # The `paramira` scope adds user_pk, wallet_enrolled (linked at the
12
+ # paramira-wallet source, if it exists), wallet_opt_in (asked at sign-up) and
13
+ # groups (the site's roles: the account's paramira-web-* groups) and joined
14
+ # (when the account was made: a vote refuses accounts made during it,
15
+ # ADR-0022).
16
+ #
17
+ # The people service (design 0003, ADR-0018): an account whose token can see
18
+ # the paramira-web-* groups and move people in and out of four of them
19
+ # (community, contributor, editor, customer), never admin. Its permissions
20
+ # are given per group by `authentik-blueprints apply` (src/index.js).
21
+ # PARAMIRA_PEOPLE_TOKEN the people service's API token (48+ random characters)
10
22
  version: 1
11
23
  metadata:
12
24
  name: paramira-site
@@ -18,13 +30,16 @@ entries:
18
30
  identifiers: {name: "paramira: account state"}
19
31
  attrs:
20
32
  scope_name: paramira
21
- description: Whether your profile is complete and a wallet is linked
33
+ description: Your account number, whether a wallet is linked, and your roles on the site
22
34
  expression: |
23
- p = (request.user.attributes or {}).get("paramira", {})
24
- return {
25
- "profile_completed": bool(p.get("profile_completed", False)),
26
- "wallet_enrolled": bool(p.get("wallet_enrolled", False)),
27
- }
35
+ # user_pk is for the site's server (it links wallets by it); the
36
+ # browser never sees the ID token (ADR-0009).
37
+ from authentik.sources.oauth.models import UserOAuthSourceConnection
38
+ linked = UserOAuthSourceConnection.objects.filter(user=request.user, source__slug="paramira-wallet").exists()
39
+ opted_in = bool(((request.user.attributes or {}).get("paramira") or {}).get("wallet_opt_in", False))
40
+ groups = sorted({g.name for g in request.user.groups.all() if g.name.startswith("paramira-web-")})
41
+ joined = request.user.date_joined.isoformat() if request.user.date_joined else None
42
+ return {"user_pk": request.user.pk, "wallet_enrolled": linked, "wallet_opt_in": opted_in, "groups": groups, "joined": joined}
28
43
 
29
44
  - model: authentik_providers_oauth2.oauth2provider
30
45
  id: provider
@@ -34,6 +49,9 @@ entries:
34
49
  invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
35
50
  authentication_flow: !Find [authentik_flows.flow, [slug, paramira-authentication]]
36
51
  client_type: confidential
52
+ # Authentik 2026.8 allows only the grants listed: none by default for a
53
+ # new provider, every one for a provider made before the upgrade.
54
+ grant_types: [authorization_code, refresh_token]
37
55
  client_id: !Env [PARAMIRA_SITE_CLIENT_ID, paramira-web]
38
56
  client_secret: !Env PARAMIRA_SITE_CLIENT_SECRET
39
57
  redirect_uris:
@@ -52,9 +70,54 @@ entries:
52
70
  - !KeyOf m-paramira
53
71
 
54
72
  - model: authentik_core.application
73
+ id: app
55
74
  identifiers: {slug: paramira-web}
56
75
  attrs:
57
- name: paramira.org
76
+ name: Paramira
58
77
  provider: !KeyOf provider
59
- meta_launch_url: !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]
78
+ # Where Authentik sends an external user (every sign-up) who lands on its
79
+ # own pages, as after linking a wallet (ADR-0028): their profile.
80
+ meta_launch_url: !Format ["%s/profile", !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]]
60
81
  policy_engine_mode: any
82
+ # A suspended account (ADR-0036) can't sign in to the site, even with an
83
+ # Authentik session still open.
84
+ - model: authentik_policies.policybinding
85
+ identifiers: {target: !KeyOf app, order: 0}
86
+ attrs:
87
+ policy: !Find [authentik_policies_expression.expressionpolicy, [name, paramira-suspended]]
88
+ negate: true
89
+
90
+ # Site accounts are external users: after any sign-in without a way back
91
+ # (an email link opened on its own), send them to the site, not to
92
+ # Authentik's user interface (which is for internal users).
93
+ - model: authentik_brands.brand
94
+ identifiers: {domain: !Env [PARAMIRA_AUTH_DOMAIN, auth.paramira.localhost]}
95
+ attrs:
96
+ default_application: !KeyOf app
97
+ # The logo, the tab's icon and the sign-in page's background, served by
98
+ # the site itself (apps/web/public/brand): nothing from another site.
99
+ branding_logo: !Format ["%s/brand/paramira-wordmark.png", !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]]
100
+ branding_favicon: !Format ["%s/brand/paramira-mark-32.png", !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]]
101
+ branding_default_flow_background: !Format ["%s/brand/paramira-login-background.webp", !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]]
102
+
103
+ # The people service: moves people between four of the site's groups.
104
+ - model: authentik_rbac.role
105
+ id: people-role
106
+ identifiers: {name: paramira-people}
107
+ - model: authentik_core.user
108
+ id: people-svc
109
+ identifiers: {username: paramira-people}
110
+ attrs:
111
+ name: paramira people service
112
+ type: service_account
113
+ path: service-accounts/paramira
114
+ is_active: true
115
+ roles: [!KeyOf people-role]
116
+ - model: authentik_core.token
117
+ identifiers: {identifier: paramira-people}
118
+ attrs:
119
+ intent: api
120
+ user: !KeyOf people-svc
121
+ key: !Env PARAMIRA_PEOPLE_TOKEN
122
+ expiring: false
123
+ description: paramira people service (site roles, never admin)
@@ -0,0 +1,85 @@
1
+ # Chat (design 0007, recipes/matrix): Matrix's sign-in service (MAS) as an
2
+ # OIDC client. Applied only where it is mounted (where Matrix runs). Everyone
3
+ # with an account may sign in (ADR-0032).
4
+ version: 1
5
+ metadata:
6
+ name: paramira-ecosystem-matrix
7
+ labels:
8
+ blueprints.goauthentik.io/description: "paramira: chat (Matrix) as an OIDC client"
9
+ entries:
10
+ # Authentik's own email mapping always says email_verified: false. Every
11
+ # paramira account's address was verified by an email link before the
12
+ # account existed (design 0001), so clients may trust it.
13
+ - model: authentik_providers_oauth2.scopemapping
14
+ id: m-email
15
+ identifiers: {name: "paramira: email (verified at sign-up)"}
16
+ attrs:
17
+ scope_name: email
18
+ description: Your email address
19
+ expression: |
20
+ return {"email": request.user.email, "email_verified": bool(request.user.email)}
21
+
22
+ - model: authentik_providers_oauth2.oauth2provider
23
+ id: provider
24
+ identifiers: {name: paramira-chat}
25
+ attrs:
26
+ authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
27
+ invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
28
+ authentication_flow: !Find [authentik_flows.flow, [slug, paramira-authentication]]
29
+ client_type: confidential
30
+ # Authentik 2026.8 allows only the grants listed.
31
+ grant_types: [authorization_code]
32
+ client_id: !Env [PARAMIRA_MATRIX_CLIENT_ID, paramira-chat]
33
+ client_secret: !Env PARAMIRA_MATRIX_CLIENT_SECRET
34
+ redirect_uris:
35
+ # MAS's callback for its upstream provider (its id: recipes/matrix/mas/config.yaml).
36
+ - matching_mode: strict
37
+ url: !Env [PARAMIRA_MATRIX_REDIRECT_URI, "https://account.paramira.localhost/upstream/callback/01JBXK5N2Q8Z4M7R3W9T6YVHCD"]
38
+ signing_key: !Find [authentik_crypto.certificatekeypair, [name, authentik Self-signed Certificate]]
39
+ sub_mode: hashed_user_id
40
+ include_claims_in_id_token: true
41
+ property_mappings:
42
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-openid]]
43
+ - !KeyOf m-email
44
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-profile]]
45
+
46
+ - model: authentik_core.application
47
+ id: app
48
+ identifiers: {slug: paramira-chat}
49
+ attrs:
50
+ name: Chat
51
+ provider: !KeyOf provider
52
+ meta_launch_url: !Env [PARAMIRA_MATRIX_URL, "https://chat.paramira.localhost"]
53
+ policy_engine_mode: all
54
+
55
+ # Who may sign in: everyone with an account (community, from sign-up;
56
+ # ADR-0032, amending ADR-0029), and the roles above it, in case an account
57
+ # was taken out of community; never a suspended account (ADR-0036).
58
+ - model: authentik_policies_expression.expressionpolicy
59
+ id: pol-who
60
+ identifiers: {name: paramira-chat-who}
61
+ attrs:
62
+ expression: |
63
+ roles = ("community", "contributor", "editor", "customer", "admin")
64
+ return any(ak_is_group_member(request.user, name="paramira-web-" + r) for r in roles)
65
+ - model: authentik_policies.policybinding
66
+ identifiers: {target: !KeyOf app, order: 0}
67
+ attrs: {policy: !KeyOf pol-who}
68
+ - model: authentik_policies.policybinding
69
+ identifiers: {target: !KeyOf app, order: 1}
70
+ attrs:
71
+ policy: !Find [authentik_policies_expression.expressionpolicy, [name, paramira-suspended]]
72
+ negate: true
73
+ # The group bindings this replaced (each would have let its group in alone).
74
+ - model: authentik_policies.policybinding
75
+ state: absent
76
+ identifiers: {target: !KeyOf app, order: 5}
77
+ - model: authentik_policies.policybinding
78
+ state: absent
79
+ identifiers: {target: !KeyOf app, order: 10}
80
+ - model: authentik_policies.policybinding
81
+ state: absent
82
+ identifiers: {target: !KeyOf app, order: 20}
83
+ - model: authentik_policies.policybinding
84
+ state: absent
85
+ identifiers: {target: !KeyOf app, order: 30}
@@ -0,0 +1,109 @@
1
+ # Sign in with an identity wallet: @paramira/wallet-oidc-bridge as an OAuth
2
+ # source. Design 0001, ADR-0006: users are matched by the identifier (the
3
+ # credential's opaque subject), never by email; no enrollment flow, so a wallet
4
+ # nobody linked is refused. The link is made by the onboarding service through
5
+ # the API (a source user connection).
6
+ #
7
+ # Optional: mount it only where the bridge runs. Authentik checks the source's
8
+ # URLs when it is created, so the bridge must answer first.
9
+ # Needs accounts.yaml applied first.
10
+ #
11
+ # Environment (on Authentik's server and worker):
12
+ # PARAMIRA_WALLET_URL the bridge, e.g. https://wallet.paramira.org
13
+ # PARAMIRA_WALLET_CLIENT_ID the bridge's client id for Authentik
14
+ # PARAMIRA_WALLET_CLIENT_SECRET its secret (the bridge's CLIENT_SECRET)
15
+ # PARAMIRA_ONBOARDING_TOKEN the onboarding service's API token (48+ random characters)
16
+ #
17
+ # The onboarding service's role gets its model-level permissions from
18
+ # `authentik-blueprints apply` (blueprints can only grant object-level ones):
19
+ # view the wallet source; view, add and delete source connections. Nothing on
20
+ # users. Guard its token like an admin secret: it can link any account to a
21
+ # wallet.
22
+ version: 1
23
+ metadata:
24
+ name: paramira-wallet
25
+ labels:
26
+ blueprints.goauthentik.io/description: "paramira: sign in with an identity wallet (OAuth source on the bridge)"
27
+ entries:
28
+ - model: authentik_flows.flow
29
+ id: f-source-auth
30
+ identifiers: {slug: paramira-source-authentication}
31
+ attrs:
32
+ name: paramira-source-authentication
33
+ title: Signing you in
34
+ designation: authentication
35
+ authentication: none
36
+ - model: authentik_flows.flowstagebinding
37
+ identifiers: {target: !KeyOf f-source-auth, stage: !Find [authentik_stages_user_login.userloginstage, [name, paramira-login]], order: 10}
38
+
39
+ - model: authentik_sources_oauth.oauthsource
40
+ id: src
41
+ identifiers: {slug: paramira-wallet}
42
+ attrs:
43
+ name: Identity wallet
44
+ provider_type: openidconnect
45
+ consumer_key: !Env [PARAMIRA_WALLET_CLIENT_ID, authentik]
46
+ consumer_secret: !Env PARAMIRA_WALLET_CLIENT_SECRET
47
+ authorization_url: !Format ["%s/auth", !Env PARAMIRA_WALLET_URL]
48
+ access_token_url: !Format ["%s/token", !Env PARAMIRA_WALLET_URL]
49
+ profile_url: !Format ["%s/me", !Env PARAMIRA_WALLET_URL]
50
+ additional_scopes: ""
51
+ pkce: S256
52
+ user_matching_mode: identifier
53
+ authentication_flow: !KeyOf f-source-auth
54
+ enrollment_flow: null
55
+ enabled: true
56
+ promoted: false
57
+
58
+ # "Sign in with a wallet" straight from a site. An identification stage
59
+ # with no user fields and one source sends the browser straight to that
60
+ # source, and as a flow it keeps `next` (the site's authorize request) for
61
+ # when the wallet sign-in comes back. (Authentik's Source stage would do the
62
+ # same, but needs an Enterprise licence.) Open it as
63
+ # /if/flow/paramira-wallet-login/?next=<authorize path and query>
64
+ - model: authentik_stages_identification.identificationstage
65
+ id: s-wallet-identify
66
+ identifiers: {name: paramira-wallet-identify}
67
+ attrs:
68
+ user_fields: []
69
+ sources: [!KeyOf src]
70
+ show_source_labels: true
71
+ pretend_user_exists: true
72
+ - model: authentik_flows.flow
73
+ id: f-wallet-login
74
+ identifiers: {slug: paramira-wallet-login}
75
+ attrs:
76
+ name: paramira-wallet-login
77
+ title: Sign in with your wallet
78
+ designation: authentication
79
+ authentication: none
80
+ - model: authentik_flows.flowstagebinding
81
+ identifiers: {target: !KeyOf f-wallet-login, stage: !KeyOf s-wallet-identify, order: 10}
82
+
83
+ # Offer it on the sign-in page, next to the email field.
84
+ - model: authentik_stages_identification.identificationstage
85
+ identifiers: {name: paramira-login-identify}
86
+ attrs:
87
+ sources: [!KeyOf src]
88
+
89
+ # The onboarding service: links an account to its wallet, nothing else.
90
+ - model: authentik_rbac.role
91
+ id: role
92
+ identifiers: {name: paramira-onboarding}
93
+ - model: authentik_core.user
94
+ id: svc
95
+ identifiers: {username: paramira-onboarding}
96
+ attrs:
97
+ name: paramira onboarding service
98
+ type: service_account
99
+ path: service-accounts/paramira
100
+ is_active: true
101
+ roles: [!KeyOf role]
102
+ - model: authentik_core.token
103
+ identifiers: {identifier: paramira-onboarding}
104
+ attrs:
105
+ intent: api
106
+ user: !KeyOf svc
107
+ key: !Env PARAMIRA_ONBOARDING_TOKEN
108
+ expiring: false
109
+ description: paramira onboarding service (wallet links only)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paramira/authentik-blueprints",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Authentik blueprints for email-first accounts (sign-up and sign-in by email link, no passwords), a brand, link emails in plain words, and a site as an OIDC client; a CLI to validate and apply them; an akantu setup tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -40,7 +40,7 @@
40
40
  },
41
41
  "dependencies": {
42
42
  "yaml": "2.8.1",
43
- "@paramira/authentik-client": "0.1.0"
43
+ "@paramira/authentik-client": "0.2.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "vitest": "4.1.12"
package/src/index.js CHANGED
@@ -10,7 +10,174 @@ export const BLUEPRINTS_DIR = join(here, '..', 'blueprints')
10
10
  export const TEMPLATES_DIR = join(here, '..', 'templates')
11
11
 
12
12
  /** Apply order: later files may !Find objects made by earlier ones. */
13
- export const ORDER = ['paramira/accounts.yaml', 'paramira/site.yaml']
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
+ }
14
181
 
15
182
  /** Every blueprint shipped, as `{ path, file }`; `path` is how Authentik lists it. */
16
183
  export function listBlueprints () {
@@ -100,26 +267,63 @@ export function validateAll () {
100
267
  *
101
268
  * @param {import('@paramira/authentik-client').Authentik} authentik
102
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
+
103
281
  export async function applyAll (authentik) {
104
- const available = new Set((await authentik.blueprints.available()).map((b) => b.path))
282
+ const available = new Set((await retrying(() => authentik.blueprints.available())).map((b) => b.path))
105
283
  const results = []
106
284
  for (const { path } of listBlueprints()) {
107
285
  if (!available.has(path)) {
108
- results.push({ path, status: 'missing', message: 'not mounted in Authentik under /blueprints/' })
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/' })
109
289
  continue
110
290
  }
111
- const instance = await authentik.blueprints.applyPath(path, { name: `paramira: ${path}` })
112
- results.push({ path, status: instance.status })
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)
113
296
  }
114
297
  return results
115
298
  }
116
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
+
117
319
  /** The state of every shipped blueprint in Authentik: `[{ path, status, lastApplied }]`. */
118
320
  export async function status (authentik) {
119
- const instances = await authentik.blueprints.list()
321
+ const instances = await retrying(() => authentik.blueprints.list())
322
+ const available = new Set((await retrying(() => authentik.blueprints.available())).map((b) => b.path))
120
323
  return listBlueprints().map(({ path }) => {
121
324
  const i = instances.find((x) => x.path === path)
122
- return { path, status: i?.status ?? 'missing', lastApplied: i?.last_applied ?? null }
325
+ const absent = OPTIONAL.includes(path) && !available.has(path) ? 'skipped' : 'missing'
326
+ return { path, status: i?.status ?? absent, lastApplied: i?.last_applied ?? null }
123
327
  })
124
328
  }
125
329
 
@@ -140,7 +344,7 @@ export async function cleanupPending (authentik, { olderThanHours = 24, dryRun =
140
344
  params: { query: { path: 'users/paramira', is_active: false, date_joined__lt: cutoff, page_size: 100 } },
141
345
  })
142
346
  if (error) throw new Error(`listing users failed: ${JSON.stringify(error)}`)
143
- const pending = data.results.filter((u) => /^pending-[0-9a-f]{16}$/.test(u.username) && !u.is_active)
347
+ const pending = data.results.filter(isPending)
144
348
  if (dryRun) return pending.map((u) => u.username)
145
349
  for (const u of pending) {
146
350
  await authentik.users.delete(u.pk)
@@ -4,7 +4,7 @@
4
4
  {% block content %}
5
5
  <tr>
6
6
  <td align="center">
7
- <h1>{% if user.is_active %}Sign in to paramira.org{% else %}Confirm your email{% endif %}</h1>
7
+ <h1>{% if user.is_active %}Sign in to Paramira{% else %}Confirm your email{% endif %}</h1>
8
8
  </td>
9
9
  </tr>
10
10
  <tr>
@@ -1,4 +1,4 @@
1
- {% load i18n %}{% autoescape off %}{% if user.is_active %}Sign in to paramira.org
1
+ {% load i18n %}{% autoescape off %}{% if user.is_active %}Sign in to Paramira
2
2
 
3
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
4