@paramira/authentik-blueprints 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The paramira authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,82 @@
1
- # Temporary Holding Version
1
+ # @paramira/authentik-blueprints
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Authentik](https://goauthentik.io) blueprints for **email-first accounts with
4
+ no passwords**, made for small organisations and communities, for Authentik
5
+ 2026.2.3:
6
+
7
+ - **sign-up by email:** the person enters an email, opens the link (on any
8
+ device), picks a username and a display name;
9
+ - **sign-in by email link**, answering the same for addresses that have an
10
+ account and addresses that don't;
11
+ - **no duplicate accounts:** signing up again with a registered address sends
12
+ a sign-in link instead of creating a second account (Authentik itself
13
+ doesn't require unique emails);
14
+ - **a brand** and **link emails in plain words**;
15
+ - **a website as an OpenID Connect client** (confidential, PKCE, strict
16
+ redirect URI, a hashed `sub`, never the email).
17
+
18
+ | File | Holds |
19
+ |---|---|
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`) |
22
+ | `templates/paramira/link.html`, `.txt` | the one link email, for sign-up and sign-in |
23
+
24
+ ## Use it
25
+
26
+ Mount the folders into Authentik's server **and** worker, and set the
27
+ environment the blueprints read:
28
+
29
+ ```yaml
30
+ # docker compose, on both server and worker
31
+ volumes:
32
+ - ./node_modules/@paramira/authentik-blueprints/blueprints/paramira:/blueprints/paramira:ro
33
+ - ./node_modules/@paramira/authentik-blueprints/templates:/templates:ro
34
+ environment:
35
+ PARAMIRA_AUTH_DOMAIN: auth.example.org
36
+ PARAMIRA_SITE_CLIENT_ID: paramira-web
37
+ PARAMIRA_SITE_CLIENT_SECRET: ${PARAMIRA_SITE_CLIENT_SECRET} # random, 32+ bytes
38
+ PARAMIRA_SITE_REDIRECT_URI: https://example.org/auth/callback
39
+ PARAMIRA_SITE_URL: https://example.org
40
+ ```
41
+
42
+ The worker applies them on start and whenever a file changes. Email must be
43
+ configured in Authentik (`AUTHENTIK_EMAIL__*`).
44
+
45
+ ## The command
46
+
47
+ ```sh
48
+ npx authentik-blueprints validate # shape, unique ids, !KeyOf only to earlier entries
49
+ npx authentik-blueprints env # the environment variables each blueprint reads
50
+ # with AUTHENTIK_URL and AUTHENTIK_TOKEN (an API token):
51
+ npx authentik-blueprints apply # apply in order, through the API
52
+ npx authentik-blueprints status
53
+ npx authentik-blueprints cleanup [--hours 24] [--dry-run] # remove abandoned sign-ups; run daily
54
+ ```
55
+
56
+ Sign-up creates the account **inactive**, with a temporary `pending-…`
57
+ username, before sending the link (Authentik's email step needs an existing
58
+ user). `cleanup` removes those still inactive after a day.
59
+
60
+ ## With akantu
61
+
62
+ `setup/authentik.blueprints/` is an [akantu](https://codeberg.org/phuman/akantu)
63
+ tool (tier 1): `check` reports whether every blueprint is applied, `apply`
64
+ applies them, `verify` checks again. Inputs: `url`, and `tokenFile`, a file
65
+ holding the API token (the token itself is never an input).
66
+
67
+ ## Known limits (Authentik 2026.2.3)
68
+
69
+ - Email link tokens are stored in plain text, and a failed send logs the email
70
+ with its link; every `email_sent` event also stores it. Keep links short-lived
71
+ (30 and 10 minutes here) and event retention short.
72
+ - Email codes (6 digits) aren't used: they reveal whether an account exists.
73
+
74
+ ## Tests
75
+
76
+ `pnpm test` runs the static checks; with `AUTHENTIK_URL`, `AUTHENTIK_TOKEN`
77
+ and `MAILPIT_URL` set (paramira-web's `pnpm test:dev`), it also runs the
78
+ flows against a real Authentik: sign-up across two sessions, the
79
+ registered-address case, identical answers, the website's OIDC sign-in to the
80
+ token, and the cleanup.
81
+
82
+ MIT. Part of [paramira-web](https://codeberg.org/phuman/paramira-web).
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ // authentik-blueprints validate | apply | status | env | cleanup [--hours N] [--dry-run] | akantu <step>
3
+ // AUTHENTIK_URL and AUTHENTIK_TOKEN (an API token) for apply and status.
4
+ import { readFileSync } from 'node:fs'
5
+ import { createAuthentik } from '@paramira/authentik-client'
6
+ import { applyAll, cleanupPending, envNames, listBlueprints, parseBlueprint, status, validateAll } from '../src/index.js'
7
+
8
+ const [cmd, ...args] = process.argv.slice(2)
9
+
10
+ function client (url = process.env.AUTHENTIK_URL, token = process.env.AUTHENTIK_TOKEN) {
11
+ if (!url || !token) {
12
+ console.error('set AUTHENTIK_URL and AUTHENTIK_TOKEN')
13
+ process.exit(2)
14
+ }
15
+ return createAuthentik({ baseUrl: url, token })
16
+ }
17
+
18
+ async function akantu (step) {
19
+ // akantu tool contract: one JSON object on stdin, one on stdout.
20
+ const input = JSON.parse(readFileSync(0, 'utf8') || '{}').inputs ?? {}
21
+ const token = input.tokenFile ? readFileSync(input.tokenFile, 'utf8').trim() : ''
22
+ const out = (o) => { process.stdout.write(JSON.stringify(o) + '\n') }
23
+ if (!input.url || !token) return out({ status: step === 'check' ? 'todo' : 'failed', message: 'needs inputs url and tokenFile' })
24
+ const ak = client(input.url, token)
25
+ const notDone = (s) => s.filter((b) => b.status !== 'successful')
26
+ if (step === 'check') {
27
+ const left = notDone(await status(ak))
28
+ return out({ status: left.length ? 'todo' : 'done', message: left.length ? `not applied: ${left.map((b) => b.path).join(', ')}` : 'all applied', outputs: {} })
29
+ }
30
+ if (step === 'apply') {
31
+ const failed = notDone(await applyAll(ak))
32
+ return out({ status: failed.length ? 'failed' : 'ok', message: failed.map((b) => `${b.path}: ${b.status}`).join('; ') || 'applied', outputs: {} })
33
+ }
34
+ const left = notDone(await status(ak))
35
+ return out({ status: left.length ? 'failed' : 'ok', message: left.length ? `not applied: ${left.map((b) => b.path).join(', ')}` : 'all applied', outputs: {} })
36
+ }
37
+
38
+ switch (cmd) {
39
+ case 'validate': {
40
+ const results = validateAll()
41
+ for (const r of results) console.log(r.errors.length ? `✗ ${r.path}\n ${r.errors.join('\n ')}` : `✓ ${r.path}`)
42
+ process.exit(results.some((r) => r.errors.length) ? 1 : 0)
43
+ break
44
+ }
45
+ case 'env':
46
+ for (const { path, file } of listBlueprints()) {
47
+ for (const e of envNames(parseBlueprint(readFileSync(file, 'utf8')))) console.log(`${e.name}${e.hasDefault ? '' : ' (required)'}\t${path}`)
48
+ }
49
+ break
50
+ case 'apply':
51
+ for (const r of await applyAll(client())) console.log(`${r.status === 'successful' ? '✓' : '✗'} ${r.path}: ${r.status}${r.message ? ` (${r.message})` : ''}`)
52
+ break
53
+ case 'status':
54
+ for (const r of await status(client())) console.log(`${r.path}\t${r.status}\t${r.lastApplied ?? ''}`)
55
+ break
56
+ case 'cleanup': {
57
+ const hours = args.includes('--hours') ? Number(args[args.indexOf('--hours') + 1]) : 24
58
+ if (!Number.isFinite(hours) || hours < 1) { console.error('--hours must be at least 1'); process.exit(2) }
59
+ const dryRun = args.includes('--dry-run')
60
+ const names = await cleanupPending(client(), { olderThanHours: hours, dryRun })
61
+ console.log(`${dryRun ? 'would remove' : 'removed'} ${names.length} abandoned sign-up(s)${names.length ? ': ' + names.join(', ') : ''}`)
62
+ break
63
+ }
64
+ case 'akantu':
65
+ await akantu(args[0])
66
+ break
67
+ default:
68
+ console.error('usage: authentik-blueprints validate | env | apply | status | cleanup [--hours N] [--dry-run] | akantu <check|apply|verify>')
69
+ process.exit(2)
70
+ }
@@ -0,0 +1,235 @@
1
+ # paramira org accounts: email-first sign-up, email-link sign-in, the brand.
2
+ # Design 0001 (paramira-web), ADR-0003/0004. Authentik 2026.2.3.
3
+ #
4
+ # paramira-enrollment Prompt email -> [new address: User Write, inactive,
5
+ # temporary username | registered address: that
6
+ # account becomes the pending user] -> Email stage
7
+ # (link, 30 min, activates) -> [new only: Prompt
8
+ # profile -> User Write] -> User Login
9
+ # paramira-login-link (designated recovery, so unknown addresses look
10
+ # the same) Identification -> Email stage (link,
11
+ # 10 min) -> User Login
12
+ # paramira-authentication the brand's sign-in: redirects to the link flow,
13
+ # keeping the context (the app it came from)
14
+ #
15
+ # Entries refer only to earlier ones (!KeyOf), so flows come before stages.
16
+ #
17
+ # Environment (on Authentik's server and worker):
18
+ # PARAMIRA_AUTH_DOMAIN the brand's domain, e.g. auth.paramira.org
19
+ version: 1
20
+ metadata:
21
+ name: paramira-accounts
22
+ labels:
23
+ blueprints.goauthentik.io/description: "paramira: org accounts (sign-up and sign-in by email)"
24
+ entries:
25
+ # Groups
26
+ - model: authentik_core.group
27
+ id: g-members
28
+ identifiers: {name: paramira-members}
29
+ - model: authentik_core.group
30
+ id: g-admins
31
+ identifiers: {name: paramira-org-admins}
32
+
33
+ # Prompts
34
+ - model: authentik_stages_prompt.prompt
35
+ id: p-email
36
+ identifiers: {name: paramira-email}
37
+ attrs: {field_key: email, label: Email, type: email, required: true, placeholder: you@example.org, order: 0}
38
+ - model: authentik_stages_prompt.prompt
39
+ id: p-username
40
+ identifiers: {name: paramira-username}
41
+ attrs:
42
+ field_key: username
43
+ label: Username
44
+ type: username
45
+ required: true
46
+ order: 0
47
+ sub_text: Shown to other people. Letters, numbers, dots and dashes.
48
+ - model: authentik_stages_prompt.prompt
49
+ id: p-name
50
+ identifiers: {name: paramira-name}
51
+ attrs: {field_key: name, label: Display name, type: text, required: true, order: 1}
52
+ - model: authentik_stages_prompt.prompt
53
+ id: p-wallet
54
+ identifiers: {name: paramira-wallet-opt-in}
55
+ attrs:
56
+ field_key: attributes.paramira.wallet_opt_in
57
+ label: I want to sign in with an identity wallet too
58
+ type: checkbox
59
+ required: false
60
+ order: 2
61
+ sub_text: Optional. You can always sign in by email.
62
+
63
+ # Policies
64
+ - model: authentik_policies_expression.expressionpolicy
65
+ id: pol-new-or-existing
66
+ identifiers: {name: paramira-enrollment-new-or-existing}
67
+ attrs:
68
+ expression: |
69
+ # Bound to the "create the account" step of sign-up. A registered,
70
+ # active address doesn't get a second account: that account becomes
71
+ # the pending user, the step is skipped, and the email sent next is a
72
+ # sign-in link. A new address gets a temporary username.
73
+ import secrets
74
+ plan = request.context["flow_plan"]
75
+ data = plan.context.setdefault("prompt_data", {})
76
+ email = (data.get("email") or "").strip().lower()
77
+ if not email:
78
+ return False
79
+ data["email"] = email
80
+ existing = ak_user_by(email__iexact=email, is_active=True)
81
+ if existing:
82
+ plan.context["pending_user"] = existing
83
+ plan.context["paramira_existing_account"] = True
84
+ return False
85
+ plan.context["paramira_existing_account"] = False
86
+ data["username"] = "pending-" + secrets.token_hex(8)
87
+ return True
88
+ - model: authentik_policies_expression.expressionpolicy
89
+ id: pol-new-only
90
+ identifiers: {name: paramira-enrollment-new-account-only}
91
+ attrs:
92
+ expression: |
93
+ # The profile steps run only for a new account. (A missing
94
+ # paramira.profile_completed means "not completed"; the site sets it.)
95
+ plan = request.context["flow_plan"]
96
+ return not plan.context.get("paramira_existing_account", False)
97
+
98
+ # Flows
99
+ - model: authentik_flows.flow
100
+ id: f-enroll
101
+ identifiers: {slug: paramira-enrollment}
102
+ attrs:
103
+ name: paramira-enrollment
104
+ title: Create your paramira.org account
105
+ designation: enrollment
106
+ authentication: require_unauthenticated
107
+ - model: authentik_flows.flow
108
+ id: f-link
109
+ identifiers: {slug: paramira-login-link}
110
+ attrs:
111
+ name: paramira-login-link
112
+ title: Sign in to paramira.org
113
+ designation: recovery
114
+ authentication: none
115
+ - model: authentik_flows.flow
116
+ id: f-auth
117
+ identifiers: {slug: paramira-authentication}
118
+ attrs:
119
+ name: paramira-authentication
120
+ title: Sign in to paramira.org
121
+ designation: authentication
122
+ authentication: none
123
+
124
+ # Stages
125
+ - model: authentik_stages_prompt.promptstage
126
+ id: s-email
127
+ identifiers: {name: paramira-enrollment-email}
128
+ attrs:
129
+ fields: [!KeyOf p-email]
130
+ - model: authentik_stages_user_write.userwritestage
131
+ id: s-precreate
132
+ identifiers: {name: paramira-enrollment-create}
133
+ attrs:
134
+ user_creation_mode: always_create
135
+ create_users_as_inactive: true
136
+ create_users_group: !KeyOf g-members
137
+ user_path_template: users/paramira
138
+ - model: authentik_stages_email.emailstage
139
+ id: s-verify
140
+ identifiers: {name: paramira-enrollment-link}
141
+ attrs:
142
+ use_global_settings: true
143
+ token_expiry: minutes=30
144
+ subject: Your paramira.org link
145
+ template: paramira/link.html
146
+ activate_user_on_success: true
147
+ - model: authentik_stages_prompt.promptstage
148
+ id: s-profile
149
+ identifiers: {name: paramira-enrollment-profile}
150
+ attrs:
151
+ fields: [!KeyOf p-username, !KeyOf p-name, !KeyOf p-wallet]
152
+ - model: authentik_stages_user_write.userwritestage
153
+ id: s-write
154
+ identifiers: {name: paramira-enrollment-save}
155
+ attrs:
156
+ user_creation_mode: never_create
157
+ - model: authentik_stages_user_login.userloginstage
158
+ id: s-login
159
+ identifiers: {name: paramira-login}
160
+ attrs:
161
+ session_duration: days=30
162
+ - model: authentik_stages_identification.identificationstage
163
+ id: s-identify
164
+ identifiers: {name: paramira-login-identify}
165
+ attrs:
166
+ user_fields: [email, username]
167
+ case_insensitive_matching: true
168
+ pretend_user_exists: true
169
+ show_matched_user: false
170
+ enrollment_flow: !KeyOf f-enroll
171
+ - model: authentik_stages_email.emailstage
172
+ id: s-link
173
+ identifiers: {name: paramira-login-link}
174
+ attrs:
175
+ use_global_settings: true
176
+ token_expiry: minutes=10
177
+ subject: Your paramira.org link
178
+ template: paramira/link.html
179
+ activate_user_on_success: false
180
+ - model: authentik_stages_redirect.redirectstage
181
+ id: s-to-link
182
+ identifiers: {name: paramira-authentication-to-link}
183
+ attrs:
184
+ mode: flow
185
+ target_flow: !KeyOf f-link
186
+ keep_context: true
187
+
188
+ # Sign-up bindings
189
+ - model: authentik_flows.flowstagebinding
190
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-email, order: 10}
191
+ - model: authentik_flows.flowstagebinding
192
+ id: b-precreate
193
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-precreate, order: 20}
194
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
195
+ - model: authentik_policies.policybinding
196
+ identifiers: {target: !KeyOf b-precreate, policy: !KeyOf pol-new-or-existing, order: 0}
197
+ - model: authentik_flows.flowstagebinding
198
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-verify, order: 30}
199
+ - model: authentik_flows.flowstagebinding
200
+ id: b-profile
201
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-profile, order: 40}
202
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
203
+ - model: authentik_policies.policybinding
204
+ identifiers: {target: !KeyOf b-profile, policy: !KeyOf pol-new-only, order: 0}
205
+ - model: authentik_flows.flowstagebinding
206
+ id: b-write
207
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-write, order: 50}
208
+ attrs: {evaluate_on_plan: false, re_evaluate_policies: true}
209
+ - model: authentik_policies.policybinding
210
+ identifiers: {target: !KeyOf b-write, policy: !KeyOf pol-new-only, order: 0}
211
+ - model: authentik_flows.flowstagebinding
212
+ identifiers: {target: !KeyOf f-enroll, stage: !KeyOf s-login, order: 60}
213
+
214
+ # Sign-in bindings
215
+ - model: authentik_flows.flowstagebinding
216
+ identifiers: {target: !KeyOf f-link, stage: !KeyOf s-identify, order: 10}
217
+ - model: authentik_flows.flowstagebinding
218
+ identifiers: {target: !KeyOf f-link, stage: !KeyOf s-link, order: 20}
219
+ - model: authentik_flows.flowstagebinding
220
+ identifiers: {target: !KeyOf f-link, stage: !KeyOf s-login, order: 30}
221
+ - model: authentik_flows.flowstagebinding
222
+ identifiers: {target: !KeyOf f-auth, stage: !KeyOf s-to-link, order: 10}
223
+
224
+ # Brand
225
+ - model: authentik_brands.brand
226
+ identifiers: {domain: !Env [PARAMIRA_AUTH_DOMAIN, auth.paramira.localhost]}
227
+ attrs:
228
+ default: false
229
+ branding_title: paramira.org
230
+ branding_custom_css: |
231
+ :root { --pf-global--primary-color--100: #2f7d5a; --pf-global--link--Color: #2f7d5a; }
232
+ flow_authentication: !KeyOf f-auth
233
+ flow_recovery: !KeyOf f-link
234
+ flow_invalidation: !Find [authentik_flows.flow, [slug, default-invalidation-flow]]
235
+ flow_user_settings: !Find [authentik_flows.flow, [slug, default-user-settings-flow]]
@@ -0,0 +1,60 @@
1
+ # The paramira.org site as an OpenID Connect client of Authentik.
2
+ # Design 0001 (ADR-0009: a confidential client, code + PKCE, server side).
3
+ # Needs accounts.yaml applied first (its sign-in flow).
4
+ #
5
+ # Environment (on Authentik's server and worker):
6
+ # PARAMIRA_SITE_CLIENT_ID e.g. paramira-web
7
+ # PARAMIRA_SITE_CLIENT_SECRET random, at least 32 bytes; shared with the site
8
+ # PARAMIRA_SITE_REDIRECT_URI e.g. https://paramira.org/auth/callback
9
+ # PARAMIRA_SITE_URL e.g. https://paramira.org
10
+ version: 1
11
+ metadata:
12
+ name: paramira-site
13
+ labels:
14
+ blueprints.goauthentik.io/description: "paramira: the paramira.org site as an OIDC client"
15
+ entries:
16
+ - model: authentik_providers_oauth2.scopemapping
17
+ id: m-paramira
18
+ identifiers: {name: "paramira: account state"}
19
+ attrs:
20
+ scope_name: paramira
21
+ description: Whether your profile is complete and a wallet is linked
22
+ 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
+ }
28
+
29
+ - model: authentik_providers_oauth2.oauth2provider
30
+ id: provider
31
+ identifiers: {name: paramira-web}
32
+ attrs:
33
+ authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
34
+ invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
35
+ authentication_flow: !Find [authentik_flows.flow, [slug, paramira-authentication]]
36
+ client_type: confidential
37
+ client_id: !Env [PARAMIRA_SITE_CLIENT_ID, paramira-web]
38
+ client_secret: !Env PARAMIRA_SITE_CLIENT_SECRET
39
+ redirect_uris:
40
+ - matching_mode: strict
41
+ url: !Env [PARAMIRA_SITE_REDIRECT_URI, "https://paramira.localhost/auth/callback"]
42
+ signing_key: !Find [authentik_crypto.certificatekeypair, [name, authentik Self-signed Certificate]]
43
+ sub_mode: hashed_user_id
44
+ include_claims_in_id_token: true
45
+ access_token_validity: minutes=10
46
+ refresh_token_validity: days=30
47
+ property_mappings:
48
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-openid]]
49
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-email]]
50
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-profile]]
51
+ - !Find [authentik_providers_oauth2.scopemapping, [managed, goauthentik.io/providers/oauth2/scope-offline_access]]
52
+ - !KeyOf m-paramira
53
+
54
+ - model: authentik_core.application
55
+ identifiers: {slug: paramira-web}
56
+ attrs:
57
+ name: paramira.org
58
+ provider: !KeyOf provider
59
+ meta_launch_url: !Env [PARAMIRA_SITE_URL, "https://paramira.localhost"]
60
+ policy_engine_mode: any
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@paramira/authentik-blueprints",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js"
10
+ },
11
+ "bin": {
12
+ "authentik-blueprints": "./bin/authentik-blueprints.js"
13
+ },
14
+ "files": [
15
+ "blueprints",
16
+ "templates",
17
+ "src",
18
+ "bin",
19
+ "setup",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://codeberg.org/phuman/paramira-web.git",
26
+ "directory": "packages/authentik-blueprints"
27
+ },
28
+ "keywords": [
29
+ "authentik",
30
+ "blueprints",
31
+ "passwordless",
32
+ "sso",
33
+ "paramira"
34
+ ],
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "yaml": "2.8.1",
43
+ "@paramira/authentik-client": "0.1.0"
44
+ },
45
+ "devDependencies": {
46
+ "vitest": "4.1.12"
47
+ },
48
+ "scripts": {
49
+ "test": "vitest run"
50
+ }
6
51
  }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # akantu tool step: reads the JSON input on stdin, prints one JSON result.
3
+ set -euo pipefail
4
+ exec node "$AKANTU_TOOL_DIR/../../bin/authentik-blueprints.js" akantu apply
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # akantu tool step: reads the JSON input on stdin, prints one JSON result.
3
+ set -euo pipefail
4
+ exec node "$AKANTU_TOOL_DIR/../../bin/authentik-blueprints.js" akantu check
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # akantu tool step: reads the JSON input on stdin, prints one JSON result.
3
+ set -euo pipefail
4
+ exec node "$AKANTU_TOOL_DIR/../../bin/authentik-blueprints.js" akantu verify
@@ -0,0 +1,12 @@
1
+ id: authentik.blueprints
2
+ description: paramira's Authentik blueprints (email-first accounts, the brand, the site's OIDC client) are applied.
3
+ tier: 1
4
+ platforms: [linux]
5
+ requires: [prereq.node]
6
+ inputs:
7
+ url: { type: string, pattern: "^https://[a-z0-9.-]+(:[0-9]+)?$", description: "Authentik's address, e.g. https://auth.example.org" }
8
+ tokenFile: { type: string, minLength: 1, description: "A file holding an Authentik API token (never the token itself)" }
9
+ outputs: {}
10
+ scripts:
11
+ linux: { check: linux/check.sh, apply: linux/apply.sh, verify: linux/verify.sh }
12
+ timeoutSeconds: 300
package/src/index.js ADDED
@@ -0,0 +1,151 @@
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']
14
+
15
+ /** Every blueprint shipped, as `{ path, file }`; `path` is how Authentik lists it. */
16
+ export function listBlueprints () {
17
+ const out = []
18
+ const walk = (dir) => {
19
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
20
+ const file = join(dir, entry.name)
21
+ if (entry.isDirectory()) walk(file)
22
+ else if (entry.name.endsWith('.yaml')) out.push({ path: relative(BLUEPRINTS_DIR, file), file })
23
+ }
24
+ }
25
+ walk(BLUEPRINTS_DIR)
26
+ const rank = (p) => (ORDER.indexOf(p) === -1 ? ORDER.length : ORDER.indexOf(p))
27
+ return out.sort((a, b) => rank(a.path) - rank(b.path) || a.path.localeCompare(b.path))
28
+ }
29
+
30
+ // Authentik's YAML tags, kept as { tag, value } so a blueprint can be read
31
+ // and checked without Authentik.
32
+ const TAGS = ['KeyOf', 'Find', 'FindObject', 'Env', 'Context', 'Format', 'If', 'Condition', 'Enumerate', 'Index', 'Value', 'AtIndex', 'ParseJSON', 'File']
33
+ const customTags = TAGS.flatMap((name) => ['scalar', 'seq', 'map'].map((kind) => ({
34
+ tag: `!${name}`,
35
+ collection: kind === 'scalar' ? undefined : kind,
36
+ resolve: (value) => ({ tag: name, value: typeof value?.toJSON === 'function' ? value.toJSON() : value }),
37
+ })))
38
+
39
+ export function parseBlueprint (text) {
40
+ const doc = parseDocument(text, { customTags })
41
+ if (doc.errors.length) throw new Error(doc.errors.map((e) => e.message).join('; '))
42
+ return doc.toJS()
43
+ }
44
+
45
+ function walkTags (node, visit) {
46
+ if (Array.isArray(node)) node.forEach((n) => walkTags(n, visit))
47
+ else if (node && typeof node === 'object') {
48
+ if (typeof node.tag === 'string' && 'value' in node && TAGS.includes(node.tag)) visit(node)
49
+ for (const v of Object.values(node)) walkTags(v, visit)
50
+ }
51
+ }
52
+
53
+ /** Environment variables a blueprint reads, and whether each has a default. */
54
+ export function envNames (blueprint) {
55
+ const names = new Map()
56
+ walkTags(blueprint, (t) => {
57
+ if (t.tag !== 'Env') return
58
+ const [name, fallback] = Array.isArray(t.value) ? t.value : [t.value]
59
+ names.set(name, (names.get(name) ?? false) || fallback !== undefined)
60
+ })
61
+ return [...names].map(([name, hasDefault]) => ({ name, hasDefault }))
62
+ }
63
+
64
+ /**
65
+ * Checks Authentik can't do for us before applying: the shape, unique ids,
66
+ * and every !KeyOf pointing to an entry defined earlier in the same file
67
+ * (Authentik fails the whole blueprint otherwise).
68
+ */
69
+ export function validateBlueprint (text) {
70
+ const errors = []
71
+ let bp
72
+ try { bp = parseBlueprint(text) } catch (e) { return [`YAML: ${e.message}`] }
73
+ if (bp?.version !== 1) errors.push('version must be 1')
74
+ if (!bp?.metadata?.name) errors.push('metadata.name is missing')
75
+ if (!Array.isArray(bp?.entries)) return [...errors, 'entries must be a list']
76
+ const seen = new Set()
77
+ bp.entries.forEach((entry, i) => {
78
+ const where = `entry ${i + 1}${entry?.id ? ` (${entry.id})` : ''}`
79
+ if (typeof entry?.model !== 'string' || !/^[a-z0-9_]+\.[a-z0-9_]+$/.test(entry.model)) errors.push(`${where}: model must look like app.model`)
80
+ if (!entry?.identifiers || typeof entry.identifiers !== 'object') errors.push(`${where}: identifiers missing`)
81
+ walkTags({ identifiers: entry?.identifiers, attrs: entry?.attrs }, (t) => {
82
+ if (t.tag === 'KeyOf' && !seen.has(t.value)) errors.push(`${where}: !KeyOf ${t.value} is not defined earlier in the file`)
83
+ })
84
+ if (entry?.id) {
85
+ if (seen.has(entry.id)) errors.push(`${where}: id ${entry.id} is used twice`)
86
+ seen.add(entry.id)
87
+ }
88
+ })
89
+ return errors
90
+ }
91
+
92
+ /** Validate every shipped blueprint: `[{ path, errors }]`. */
93
+ export function validateAll () {
94
+ return listBlueprints().map(({ path, file }) => ({ path, errors: validateBlueprint(readFileSync(file, 'utf8')) }))
95
+ }
96
+
97
+ /**
98
+ * Apply every shipped blueprint, in order, through the API. Authentik must
99
+ * see the same files (mounted under /blueprints/), as `available()` lists.
100
+ *
101
+ * @param {import('@paramira/authentik-client').Authentik} authentik
102
+ */
103
+ export async function applyAll (authentik) {
104
+ const available = new Set((await authentik.blueprints.available()).map((b) => b.path))
105
+ const results = []
106
+ for (const { path } of listBlueprints()) {
107
+ if (!available.has(path)) {
108
+ results.push({ path, status: 'missing', message: 'not mounted in Authentik under /blueprints/' })
109
+ continue
110
+ }
111
+ const instance = await authentik.blueprints.applyPath(path, { name: `paramira: ${path}` })
112
+ results.push({ path, status: instance.status })
113
+ }
114
+ return results
115
+ }
116
+
117
+ /** The state of every shipped blueprint in Authentik: `[{ path, status, lastApplied }]`. */
118
+ export async function status (authentik) {
119
+ const instances = await authentik.blueprints.list()
120
+ return listBlueprints().map(({ path }) => {
121
+ const i = instances.find((x) => x.path === path)
122
+ return { path, status: i?.status ?? 'missing', lastApplied: i?.last_applied ?? null }
123
+ })
124
+ }
125
+
126
+ /**
127
+ * Remove abandoned sign-ups: accounts the sign-up flow created (path
128
+ * users/paramira, username pending-…) that are still inactive after
129
+ * `olderThanHours`. Returns the usernames removed (or that would be, with
130
+ * `dryRun`). Run it daily (cron, a systemd timer, or akantu).
131
+ *
132
+ * @param {import('@paramira/authentik-client').Authentik} authentik
133
+ * @param {{ olderThanHours?: number, dryRun?: boolean, now?: Date }} [options]
134
+ */
135
+ export async function cleanupPending (authentik, { olderThanHours = 24, dryRun = false, now = new Date() } = {}) {
136
+ const cutoff = new Date(now.getTime() - olderThanHours * 3600 * 1000).toISOString()
137
+ const removed = []
138
+ for (;;) {
139
+ const { data, error } = await authentik.raw.GET('/core/users/', {
140
+ params: { query: { path: 'users/paramira', is_active: false, date_joined__lt: cutoff, page_size: 100 } },
141
+ })
142
+ 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)
144
+ if (dryRun) return pending.map((u) => u.username)
145
+ for (const u of pending) {
146
+ await authentik.users.delete(u.pk)
147
+ removed.push(u.username)
148
+ }
149
+ if (pending.length < 100) return removed
150
+ }
151
+ }
@@ -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.org{% 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.org
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 %}