@selfauth/spec 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.
@@ -0,0 +1,135 @@
1
+ # Authorization specification
2
+
3
+ - **specVersion:** 0.1 (draft — open for review)
4
+ - **Related:** [AUTHENTICATION_SPEC](AUTHENTICATION_SPEC.md) ·
5
+ [DATA_MODEL](DATA_MODEL.md) · [ERRORS](ERRORS.md)
6
+
7
+ The MVP model is **role-based access control (RBAC)** with explicit,
8
+ project-defined permissions, plus a **resource-policy** hook for ownership and
9
+ resource-level decisions. Complex policy engines (ABAC, ReBAC, policy
10
+ languages) are deferred.
11
+
12
+ ## 1. Core rules
13
+
14
+ - **[AUTHZ-CORE-001]** (MUST) Authorization MUST be **deny by default**: an
15
+ operation is permitted only if an explicit rule grants it. A protected
16
+ operation with no rule configured MUST be denied.
17
+ - **[AUTHZ-CORE-002]** (MUST) Every protected backend operation MUST perform an
18
+ authorization check on the server, on every request.
19
+ - **[AUTHZ-CORE-003]** (MUST) Authorization decisions MUST be computed from
20
+ server-side state (the session's user, their roles, role permissions, and the
21
+ resource), never from client-supplied role, permission, or ownership claims.
22
+ - **[AUTHZ-CORE-004]** (MUST) Frontend permission state is a UX hint only.
23
+ Bypassing every frontend check MUST NOT grant access to any protected backend
24
+ operation.
25
+ - **[AUTHZ-CORE-005]** (MUST) A request without a valid session to a protected
26
+ operation MUST fail with `UNAUTHENTICATED`; an authenticated request lacking
27
+ permission MUST fail with `FORBIDDEN`, except where [AUTHZ-RES-004] applies.
28
+ - **[AUTHZ-CORE-006]** (MUST) Changes to a user's roles or to a role's
29
+ permissions MUST take effect no later than the user's next request.
30
+ Implementations MAY cache within a single request only.
31
+
32
+ ## 2. Permissions
33
+
34
+ - **[AUTHZ-PERM-001]** (MUST) A permission is a string of two or more
35
+ dot-separated segments, each matching `[a-z][a-z0-9_]*`
36
+ (e.g. `orders.view`, `billing.invoices.refund`). Other strings MUST be
37
+ rejected when configured.
38
+ - **[AUTHZ-PERM-002]** (MUST) Projects define their own permissions in
39
+ configuration. The `auth.` prefix is reserved for system permissions (§5) and
40
+ MUST NOT be used for project permissions.
41
+ - **[AUTHZ-PERM-003]** (MUST NOT) Wildcards, prefix matching, or negative
42
+ ("deny") permissions MUST NOT be supported in this spec version. A check for
43
+ `orders.view` is satisfied only by `orders.view`.
44
+ - **[AUTHZ-PERM-004]** (MUST) Checking a permission that is not defined in
45
+ configuration MUST be treated as an error at startup or registration time
46
+ (fail fast), not silently denied or allowed at request time.
47
+
48
+ ## 3. Roles (RBAC)
49
+
50
+ - **[AUTHZ-RBAC-001]** (MUST) A role MUST have a unique name
51
+ (`[a-z][a-z0-9_-]*`) and a set of permissions. A user has zero or more roles.
52
+ - **[AUTHZ-RBAC-002]** (MUST) A user's **effective permissions** MUST be exactly
53
+ the union of the permissions of all roles assigned to them.
54
+ - **[AUTHZ-RBAC-003]** (MUST) Newly registered users MUST receive only the
55
+ configured default role(s) (default: `user`, which has no permissions unless the project
56
+ grants them).
57
+ - **[AUTHZ-RBAC-004]** (MUST) A system role `admin` MUST exist holding all `auth.*`
58
+ system permissions. Projects MAY grant it project permissions too.
59
+ - **[AUTHZ-RBAC-005]** (MUST) Role definitions from configuration MUST be
60
+ synchronized to storage by an explicit, reviewable step (seed or migration),
61
+ never implicitly on application startup in production.
62
+
63
+ ## 4. Resource-level authorization
64
+
65
+ The resource-policy contract:
66
+
67
+ ```text
68
+ authorize(subject, action, resource) → allow | deny
69
+ subject : { userId, roles, permissions } (from the session, server-side)
70
+ action : permission string, e.g. "orders.view"
71
+ resource : { type, id, ownerId?, ...attributes loaded server-side }
72
+ ```
73
+
74
+ - **[AUTHZ-RES-001]** (MUST) Implementations MUST provide an `authorize`
75
+ function (or equivalent) implementing the contract above, where
76
+ application code registers a policy per resource type.
77
+ - **[AUTHZ-RES-002]** (MUST) If no policy is registered for a resource type,
78
+ `authorize` MUST deny.
79
+ - **[AUTHZ-RES-003]** (MUST) Resource attributes used for decisions (owner,
80
+ tenant, status) MUST be loaded server-side from storage, not taken from the
81
+ request body, query, or headers.
82
+ - **[AUTHZ-RES-004]** (SHOULD) When a subject may not even know a resource
83
+ exists, the operation SHOULD fail with `NOT_FOUND` rather than `FORBIDDEN`,
84
+ consistently for existing and non-existing IDs.
85
+ - **[AUTHZ-RES-005]** (MUST) The built-in ownership helper MUST allow an action
86
+ only if the subject holds the permission **and** `resource.ownerId` equals
87
+ `subject.userId`; holding the corresponding `*_any` permission
88
+ (e.g. `orders.view_any`), when the project defines one, allows the action
89
+ regardless of owner.
90
+ - **[AUTHZ-RES-006]** (MUST) List/query operations MUST apply authorization as a
91
+ filter (e.g. "only rows owned by subject"), not by fetching all rows and
92
+ hiding some in the presentation layer.
93
+
94
+ ## 5. Administrative operations
95
+
96
+ System permissions:
97
+
98
+ | Permission | Allows |
99
+ | --- | --- |
100
+ | `auth.users.read` | View any user's account data (not credentials) |
101
+ | `auth.users.manage` | Suspend, disable, re-activate, or delete users |
102
+ | `auth.sessions.manage` | List and revoke other users' sessions |
103
+ | `auth.roles.assign` | Assign/remove roles to/from users |
104
+ | `auth.roles.manage` | Create/modify roles and their permissions |
105
+ | `auth.audit.read` | Read security events |
106
+
107
+ - **[AUTHZ-ADMIN-001]** (MUST) Every administrative operation MUST require its
108
+ system permission and MUST record a security event identifying actor, target,
109
+ and change.
110
+ - **[AUTHZ-ADMIN-002]** (MUST) Assigning or removing a role MUST require
111
+ `auth.roles.assign`. An actor without `auth.roles.manage` MUST NOT be able to
112
+ assign or remove a role that grants a permission the actor does not hold (no
113
+ privilege escalation by delegation, and no demoting of more privileged
114
+ users). Holders of `auth.roles.manage` are exempt because they can already
115
+ redefine roles.
116
+ - **[AUTHZ-ADMIN-003]** (MUST) The system MUST prevent removing the `admin` role
117
+ from, or suspending/disabling/deleting, the last active user holding it.
118
+ - **[AUTHZ-ADMIN-004]** (SHOULD) Administrative operations SHOULD require recent
119
+ authentication (password re-entry within
120
+ `authorization.reauthenticationWindowMinutes`, default 15), failing with
121
+ `REAUTHENTICATION_REQUIRED` otherwise.
122
+ - **[AUTHZ-ADMIN-005]** (MUST NOT) Operations reachable by an unauthenticated
123
+ client, including registration, MUST NOT grant roles or system
124
+ permissions; the first administrator is created through an explicit,
125
+ developer-run command or seed.
126
+ - **[AUTHZ-ADMIN-006]** (MUST) Suspending, disabling, or deleting a user through
127
+ an admin operation MUST revoke the user's sessions ([IDENT-STATE-003]).
128
+
129
+ ## 6. Security events for authorization
130
+
131
+ - **[AUTHZ-AUDIT-001]** (MUST) Role assignment, role removal, and role
132
+ permission changes MUST be recorded as security events.
133
+ - **[AUTHZ-AUDIT-002]** (SHOULD) Denied authorization decisions SHOULD be
134
+ recorded (`authz.denied`), with sampling or rate limiting to avoid log
135
+ flooding.
@@ -0,0 +1,117 @@
1
+ # Configuration specification
2
+
3
+ - **specVersion:** 0.1 (draft — open for review)
4
+ - **Machine-readable form:** `selfAuthConfigSchema` exported by `@selfauth/spec`
5
+ (Zod; a JSON Schema is exported for non-TypeScript adapters).
6
+
7
+ The project configuration file (e.g. `selfauth.config.ts`) is committed to the
8
+ application repository. It holds **behavior**, never **secrets**.
9
+
10
+ Every default below is a secure starting point and can be changed by the
11
+ project. Security-relevant values have hard bounds (a floor on password length
12
+ and hashing cost, a ceiling on token lifetimes) that configuration cannot cross.
13
+
14
+ ## Rules
15
+
16
+ - **[CONF-FILE-001]** (MUST) Configuration MUST be validated before use; unknown
17
+ keys MUST be rejected (typos in security settings must not be silently
18
+ ignored).
19
+ - **[CONF-FILE-002]** (MUST NOT) The configuration file MUST NOT contain secrets
20
+ ([SEC-SECRET-001]); secrets come from environment variables.
21
+ - **[CONF-FILE-003]** (MUST) Values outside the bounds below MUST be rejected,
22
+ not clamped.
23
+ - **[CONF-FILE-004]** (MUST) The configuration MUST be validated against the
24
+ selected adapter's capabilities (e.g. an adapter that does not support
25
+ `optional` verification mode rejects it).
26
+ - **[CONF-FILE-005]** (MUST) Configuration records the `specVersion` it targets;
27
+ an adapter MUST refuse a major `specVersion` it does not implement.
28
+
29
+ ## Schema
30
+
31
+ | Key | Type | Default | Bounds / notes |
32
+ | --- | --- | --- | --- |
33
+ | `specVersion` | string `"MAJOR.MINOR"` | `"0.1"` | |
34
+ | `adapter.backend` | `"express"` | — (required) | MVP |
35
+ | `adapter.frontend` | `"vue" \| "react" \| "none"` | `"none"` | |
36
+ | `adapter.database` | `"postgresql" \| "mongodb" \| "memory"` | — (required) | `memory` is for development and demos only (single process, not persistent) |
37
+ | `adapter.orm` | `"prisma" \| "mongoose" \| "none"` | — (required) | postgresql↔prisma, mongodb↔mongoose, memory↔none |
38
+ | `authentication.methods` | `["password"]` | `["password"]` | MVP supports only `password` |
39
+ | `authentication.emailVerification.mode` | `"required" \| "optional" \| "off"` | `"required"` | `optional`/`off` activate accounts immediately; registration logs the user in only with `signInAfterRegistration` |
40
+ | `authentication.emailVerification.tokenTtlMinutes` | int | `1440` (24 h) | 5 – 10080 (7 days) |
41
+ | `authentication.registration.revealExistingEmail` | boolean | `false` | `true` returns `EMAIL_TAKEN` for registered emails (privacy trade-off, SEC-ENUM-004) |
42
+ | `authentication.registration.signInAfterRegistration` | boolean | `false` | requires `revealExistingEmail: true` and verification mode `optional`/`off` |
43
+ | `authentication.passwordReset.tokenTtlMinutes` | int | `30` | 5 – 60 |
44
+ | `authentication.password.minLength` | int | `12` | ≥ 8, ≤ `maxLength` |
45
+ | `authentication.password.maxLength` | int | `128` | 64 – 1024 |
46
+ | `authentication.password.rejectCommon` | boolean | `true` | offline list |
47
+ | `authentication.password.hashing.memoryKiB` | int | `19456` (19 MiB) | ≥ 19456 when `iterations` ≥ 2; ≥ 47104 when `iterations` = 1 (SEC-HASH-002) |
48
+ | `authentication.password.hashing.iterations` | int | `2` | 1 – 10 |
49
+ | `authentication.password.hashing.parallelism` | int | `1` | 1 – 16 |
50
+ | `authentication.sessions.strategy` | `"database"` | `"database"` | ADR 0008 |
51
+ | `authentication.sessions.idleTimeoutMinutes` | int | `10080` (7 days) | 5 – `absoluteTimeoutMinutes` |
52
+ | `authentication.sessions.absoluteTimeoutMinutes` | int | `43200` (30 days) | 5 – 525600 (365 days) |
53
+ | `authentication.sessions.touchIntervalSeconds` | int | `60` | 0 – 3600; minimum time between idle-expiry writes |
54
+ | `authentication.sessions.cookie.name` | string | `"__Host-session"` | `__Host-` prefix requires `secure: true` |
55
+ | `authentication.sessions.cookie.sameSite` | `"lax" \| "strict" \| "none"` | `"lax"` | `none` requires `csrf.mode = "token"` |
56
+ | `authentication.sessions.cookie.secure` | boolean | `true` | `false` only for localhost development |
57
+ | `authentication.rateLimit.<op>.perAccount` | `{limit, windowSeconds}` | see below | limit ≥ 1; window 1 – 86400 |
58
+ | `authentication.rateLimit.<op>.perAddress` | `{limit, windowSeconds}` | see below | |
59
+ | `authorization.strategy` | `"rbac"` | `"rbac"` | |
60
+ | `authorization.permissions` | string[] | `[]` | AUTHZ-PERM-001 format; no `auth.` prefix; unique |
61
+ | `authorization.roles` | `{ [role]: string[] }` | `{ user: [] }` | permissions must be defined or `auth.*` system permissions |
62
+ | `authorization.defaultRoles` | string[] | `["user"]` | must name defined roles; MUST NOT include `admin` |
63
+ | `authorization.reauthenticationWindowMinutes` | int | `15` | 1 – 1440; recent-auth window for admin operations |
64
+ | `http.basePath` | string | `"/auth"` | starts with `/` |
65
+ | `http.bodyLimitBytes` | int | `16384` (16 KiB) | 1024 – 1048576 |
66
+ | `http.trustedOrigins` | string[] (origins) | `[]` | used by CSRF origin check and CORS |
67
+ | `http.trustProxy` | `false \| int \| string[]` | `false` | hop count or proxy CIDRs |
68
+ | `http.csrf.mode` | `"header" \| "token"` | `"header"` | SEC-CSRF-004 |
69
+ | `http.csrf.headerName` | string | `"X-SelfAuth-CSRF"` | |
70
+
71
+ Rate-limit operations (`<op>`) and defaults (limit per window, window 900 s):
72
+
73
+ | op | perAccount | perAddress |
74
+ | --- | --- | --- |
75
+ | `login` | 5 | 100 |
76
+ | `passwordChange` | 5 | 100 |
77
+ | `register` | 3 | 20 |
78
+ | `passwordResetRequest` | 3 | 20 |
79
+ | `verificationResend` | 3 | 20 |
80
+
81
+ ## Environment variables
82
+
83
+ Names are the defaults used by generated code; applications may rename them.
84
+
85
+ | Variable | Required | Purpose |
86
+ | --- | --- | --- |
87
+ | `SELFAUTH_APP_BASE_URL` | Yes | Absolute URL used to build email links (AUTHN-VERIFY-009) |
88
+ | `SELFAUTH_CSRF_SECRET` | When `csrf.mode = "token"` | ≥ 32 random bytes, base64url |
89
+ | `SELFAUTH_CSRF_SECRET_PREVIOUS` | No | Previous key during rotation |
90
+ | `NODE_ENV` (or adapter equivalent) | Yes | `production` enables strict checks (SEC-COOKIE-003) |
91
+ | `DATABASE_URL` | App-owned | Used by the app's ORM; SelfAuth does not define it |
92
+
93
+ Email delivery is an application-provided adapter; its credentials are
94
+ application-owned environment variables.
95
+
96
+ ## Example
97
+
98
+ ```ts
99
+ import { defineConfig } from "@selfauth/spec";
100
+
101
+ export default defineConfig({
102
+ adapter: { frontend: "vue", backend: "express", database: "postgresql", orm: "prisma" },
103
+ authentication: {
104
+ emailVerification: { mode: "required" },
105
+ sessions: { idleTimeoutMinutes: 1440 },
106
+ },
107
+ authorization: {
108
+ permissions: ["users.manage", "orders.create", "orders.view", "orders.view_any"],
109
+ roles: {
110
+ user: ["orders.create", "orders.view"],
111
+ support: ["orders.view_any"],
112
+ admin: ["users.manage"],
113
+ },
114
+ },
115
+ http: { trustedOrigins: ["https://app.example.com"] },
116
+ });
117
+ ```
@@ -0,0 +1,125 @@
1
+ # Conformance
2
+
3
+ - **specVersion:** 0.1 (draft — open for review)
4
+
5
+ The conformance suite proves that an adapter implements this specification. It
6
+ is language-neutral: cases are JSON documents in `conformance/cases/` that
7
+ describe **operations and expected outcomes**, not HTTP routes or framework
8
+ calls. Each adapter provides a small *driver* that maps operations to its
9
+ implementation (for the MVP adapters, via the HTTP binding in
10
+ [AUTHENTICATION_SPEC §11](AUTHENTICATION_SPEC.md#11-http-binding-non-normative-used-by-mvp-adapters)).
11
+
12
+ ## Coverage rule
13
+
14
+ Every `MUST` / `MUST NOT` requirement is covered by at least one conformance
15
+ case **or** by an entry in `conformance/verification.json` naming another
16
+ verification method (ADR 0007). `pnpm test` fails otherwise. Coverage is
17
+ reported per requirement by `@selfauth/conformance`.
18
+
19
+ Verification methods other than conformance cases:
20
+
21
+ | Method | Meaning |
22
+ | --- | --- |
23
+ | `schema-test` | Enforced by `selfAuthConfigSchema`; covered by `@selfauth/spec` tests |
24
+ | `adapter-test` | Requires adapter-internal inspection (e.g. library choice, async hashing); each adapter must include a named test |
25
+ | `code-review` | Checked in review against a checklist item in the adapter's `CONFORMANCE.md` |
26
+ | `documentation` | The adapter must document the item; checked in review |
27
+ | `static-analysis` | Checked by linting/scanning rules in the adapter's CI |
28
+ | `migration-test` | Checked by the migration test suite (Phase 4) |
29
+
30
+ ## Case format
31
+
32
+ ```jsonc
33
+ {
34
+ "id": "CT-LOGIN-002", // unique, never reused
35
+ "title": "Wrong password and unknown user are indistinguishable",
36
+ "category": "login",
37
+ "level": "core", // core | authorization | production
38
+ "requirements": ["AUTHN-LOGIN-002", "SEC-ENUM-001"],
39
+ "config": {}, // optional partial config overrides
40
+ "given": [ // fixtures the driver creates directly
41
+ { "user": "alice", "email": "alice@example.test", "password": "correct horse battery", "state": "active" }
42
+ ],
43
+ "steps": [
44
+ { "op": "login", "input": { "email": "alice@example.test", "password": "wrong password!!" },
45
+ "expect": { "outcome": "error", "code": "INVALID_CREDENTIALS" }, "save": "wrong" },
46
+ { "op": "login", "input": { "email": "nobody@example.test", "password": "wrong password!!" },
47
+ "expect": { "outcome": "error", "code": "INVALID_CREDENTIALS", "indistinguishableFrom": "wrong" } }
48
+ ]
49
+ }
50
+ ```
51
+
52
+ - `as` on a step names the client (cookie jar) performing it; default
53
+ `"default"`. Clients are created on first use.
54
+ - `save` stores the step result under a name; later steps reference saved
55
+ values with `"$name.path"` strings (e.g. `"$resetMail.token"`).
56
+ - `indistinguishableFrom` compares status, body (ignoring request IDs), and
57
+ headers (ignoring `Date`, request IDs) with a saved result.
58
+ - Timing assertions are not part of the core suite; the timing requirement
59
+ AUTHN-LOGIN-003 is verified by `adapter-test`.
60
+
61
+ ### Operations
62
+
63
+ | Group | Operations |
64
+ | --- | --- |
65
+ | Authentication | `register`, `login`, `logout`, `logoutAll`, `getCurrentUser`, `listSessions`, `revokeSession`, `requestEmailVerification`, `verifyEmail`, `changePassword`, `requestPasswordReset`, `resetPassword`, `deleteAccount` |
66
+ | Authorization | `callProtected` (`{permission?, resource?}` against a driver-provided test route), `listOwned` |
67
+ | Administration | `assignRole`, `removeRole`, `setAccountState` |
68
+ | Harness | `advanceClock` (`{minutes}`), `readLastEmail` (`{to}` → `{token?, kind, link}`), `concurrent` (`{steps}` run in parallel), `inspectStorage` (`{entity, where?}` → records), `mutateStorage` (`{entity, where, set}` — bypasses services, for defense-in-depth cases), `inspectEvents` (`{type}`, `*` for all), `inspectLogs`, `rawRequest` (transport-level request for CSRF/header cases) |
69
+
70
+ Case-level fields besides those shown above: `environment`
71
+ (`development` | `production`, default `development`) selects the runtime mode
72
+ the driver simulates. Values starting with `$config.` refer to the effective
73
+ configuration (e.g. `$config.appBaseUrl`), and fixture names (`$alice.id`)
74
+ refer to `given` users and resources.
75
+
76
+ ### Expectations
77
+
78
+ | Key | Meaning |
79
+ | --- | --- |
80
+ | `outcome` | `"success"` or `"error"` (required) |
81
+ | `code` | error code from [ERRORS](ERRORS.md) (required when outcome is error) |
82
+ | `codeOneOf` | alternative to `code` where the spec permits several codes (e.g. `NOT_FOUND` or `FORBIDDEN`, AUTHZ-RES-004) |
83
+ | `indistinguishableFrom` | saved result name |
84
+ | `sessionCreated` | whether a session cookie was issued |
85
+ | `successCount` | for `concurrent`: exact number of successful sub-steps |
86
+ | `assert` | operation-specific assertions (e.g. cookie attributes, storage fields) |
87
+
88
+ > **Draft status.** The `assert` vocabulary is intentionally open in specVersion
89
+ > 0.1. It is frozen into a typed schema when the first executable driver (the
90
+ > Express reference implementation, Phase 3) is written, so that the
91
+ > vocabulary is shaped by a real runner rather than guessed.
92
+
93
+ ## Running the suite
94
+
95
+ `@selfauth/conformance` exports `runCase(case, driverFactory)`, a TypeScript
96
+ interpreter for the cases. An adapter provides a `Driver`
97
+ (`conformance/src/runner/driver.ts`): an HTTP request function plus harness
98
+ hooks for time, captured email, storage, events and logs. Adapters in other
99
+ languages can either implement the same driver contract behind an HTTP test
100
+ API, or port the interpreter.
101
+
102
+ Drivers mount these harness routes in the application under test:
103
+
104
+ | Route | Guard |
105
+ | --- | --- |
106
+ | `POST /__conformance/permission/:permission` | `requirePermission(permission)` |
107
+ | `POST /__conformance/resource/:permission/:type/:id` | resource policy for `type` (`order` uses the ownership helper) |
108
+ | `POST /__conformance/unconfigured` | none — must be denied by default |
109
+ | `GET /__conformance/list/order` | owner-filtered list, `{ ids }` |
110
+ | `GET /__conformance/fault` | throws an unexpected error |
111
+
112
+ The runner's default request models a same-origin browser:
113
+ `Sec-Fetch-Site: same-origin`, the CSRF header, and the client's cookie jar.
114
+
115
+ ## Compliance levels
116
+
117
+ | Level | Requirement |
118
+ | --- | --- |
119
+ | **Core compliant** | All `level: core` cases pass; all core `adapter-test` items pass |
120
+ | **Authorization compliant** | Core + all `level: authorization` cases |
121
+ | **Production-profile compliant** | All cases + every `code-review`, `documentation`, and `static-analysis` item signed off for the adapter release |
122
+
123
+ An adapter is never labelled production-ready because its generator runs.
124
+ Every released adapter publishes its support matrix, conformance results,
125
+ known limitations, and the `specVersion` it targets.
@@ -0,0 +1,140 @@
1
+ # Logical data model
2
+
3
+ - **specVersion:** 0.1 (draft — open for review)
4
+
5
+ This is a **logical** model. Database adapters map it to native structures
6
+ (tables for PostgreSQL/Prisma, collections/embedded documents for
7
+ MongoDB/Mongoose). Physical names, types, and shapes may differ; behavior may
8
+ not.
9
+
10
+ Default physical names are prefixed `auth_` to avoid colliding with application
11
+ tables. The user entity name is configurable because applications often
12
+ already have a `users` table (integration with an existing user table is a
13
+ Phase 4 concern).
14
+
15
+ ## Entities
16
+
17
+ Types: `id` = opaque identifier (UUIDv7 recommended); `timestamp` = UTC instant;
18
+ `hash` = hex/base64 digest string.
19
+
20
+ ### User — default `auth_users`
21
+
22
+ | Field | Type | Constraints |
23
+ | --- | --- | --- |
24
+ | id | id | PK, immutable |
25
+ | email | string ≤ 254 | as entered (trimmed); nullable after deletion |
26
+ | emailNormalized | string ≤ 254 | **unique among non-deleted users**; nullable after deletion |
27
+ | emailVerifiedAt | timestamp? | |
28
+ | state | enum `pending, active, suspended, disabled, deleted` | |
29
+ | createdAt, updatedAt | timestamp | |
30
+ | deletedAt | timestamp? | set when state = deleted |
31
+
32
+ ### Credential — `auth_credentials`
33
+
34
+ | Field | Type | Constraints |
35
+ | --- | --- | --- |
36
+ | id | id | PK |
37
+ | userId | id | FK → User, cascade on user hard-delete |
38
+ | type | enum `password` | (future: `totp`, `webauthn`) unique per (userId, type) for `password` |
39
+ | secretHash | string | PHC string; never exposed |
40
+ | createdAt, updatedAt | timestamp | |
41
+
42
+ ### Session — `auth_sessions`
43
+
44
+ | Field | Type | Constraints |
45
+ | --- | --- | --- |
46
+ | id | id | PK (public handle used to list/revoke; **not** the token) |
47
+ | tokenHash | hash | unique, indexed |
48
+ | userId | id | FK → User, indexed |
49
+ | createdAt, lastSeenAt | timestamp | |
50
+ | idleExpiresAt, absoluteExpiresAt | timestamp | indexed for purging |
51
+ | revokedAt | timestamp? | |
52
+ | revokedReason | enum? `logout, logout_all, password_changed, password_reset, state_changed, admin, rotated` | |
53
+ | ipAddress, userAgent | string? | informational only |
54
+ | reauthenticatedAt | timestamp? | for recent-auth checks |
55
+
56
+ ### Role — `auth_roles`
57
+
58
+ | Field | Type | Constraints |
59
+ | --- | --- | --- |
60
+ | id | id | PK |
61
+ | name | string | unique |
62
+ | description | string? | |
63
+ | isSystem | boolean | `admin`, `user` are system roles |
64
+
65
+ ### Permission — `auth_permissions`
66
+
67
+ | Field | Type | Constraints |
68
+ | --- | --- | --- |
69
+ | id | id | PK |
70
+ | name | string | unique; format per AUTHZ-PERM-001 |
71
+ | description | string? | |
72
+
73
+ ### UserRole — `auth_user_roles`
74
+
75
+ `(userId, roleId)` composite unique; `assignedAt`, `assignedBy?`.
76
+
77
+ ### RolePermission — `auth_role_permissions`
78
+
79
+ `(roleId, permissionId)` composite unique.
80
+
81
+ ### PasswordResetToken — `auth_password_reset_tokens`
82
+
83
+ | Field | Type | Constraints |
84
+ | --- | --- | --- |
85
+ | id | id | PK |
86
+ | userId | id | FK, indexed |
87
+ | tokenHash | hash | unique |
88
+ | expiresAt | timestamp | |
89
+ | usedAt | timestamp? | consume = conditional update `WHERE usedAt IS NULL AND expiresAt > now` |
90
+ | invalidatedAt | timestamp? | set when superseded or revoked |
91
+ | createdAt | timestamp | |
92
+
93
+ ### EmailVerificationToken — `auth_email_verification_tokens`
94
+
95
+ As PasswordResetToken, plus `email` (normalized address the token was issued
96
+ for; must equal the user's current `emailNormalized` at use).
97
+
98
+ ### SecurityEvent — `auth_security_events`
99
+
100
+ | Field | Type | Constraints |
101
+ | --- | --- | --- |
102
+ | id | id | PK |
103
+ | type | string | e.g. `auth.login.failed` |
104
+ | outcome | enum `success, failure` | |
105
+ | occurredAt | timestamp | indexed |
106
+ | userId, actorId | id? | not FKs (events outlive users) |
107
+ | ipAddress, userAgent, requestId | string? | |
108
+ | metadata | JSON object | redacted per SEC-AUDIT-003 |
109
+ | seq | monotonic integer (optional) | insertion order, since timestamps can tie |
110
+
111
+ ### RateLimit — `auth_rate_limits` (optional)
112
+
113
+ Shared limiter state for multi-instance deployments (SEC-RATE-006): `key`
114
+ (PK), `count`, `windowEndsAt`, `blockedUntil`, `strikes`, `lastBlockAt`.
115
+ Updates of one key MUST be serialized (e.g. row lock). Adapters MAY use
116
+ another shared store (Redis) instead.
117
+
118
+ ### Not modeled here
119
+
120
+ - **MFA, OAuth accounts, passkeys, API tokens** — see
121
+ [OPTIONAL_CAPABILITIES](OPTIONAL_CAPABILITIES.md).
122
+
123
+ ## Mapping rules
124
+
125
+ - **[DATA-MODEL-001]** (MUST) Database adapters MUST enforce, in the database,
126
+ the uniqueness constraints marked above (normalized email among non-deleted
127
+ users, token hashes, session token hash, role and permission names, join
128
+ pairs).
129
+ - **[DATA-MODEL-002]** (MUST) One-time token consumption and session revocation
130
+ MUST be atomic at the database level (conditional update or transaction), so
131
+ concurrent requests cannot both succeed.
132
+ - **[DATA-MODEL-003]** (MUST) Schema changes MUST be delivered as native
133
+ migration files in the application repository; adapters MUST NOT change the
134
+ schema at application startup.
135
+ - **[DATA-MODEL-004]** (MUST NOT) Adapters MUST NOT modify or drop tables,
136
+ collections, columns, or indexes they do not own (per the SelfAuth manifest)
137
+ without explicit developer approval.
138
+ - **[DATA-MODEL-005]** (SHOULD) Document databases MAY embed `UserRole` in the
139
+ user document and `RolePermission` in the role document; they SHOULD keep
140
+ credentials and sessions in separate collections.
@@ -0,0 +1,50 @@
1
+ # Errors
2
+
3
+ - **specVersion:** 0.1 (draft — open for review)
4
+
5
+ ## Envelope
6
+
7
+ - **[ERR-FORMAT-001]** (MUST) Every failed operation MUST return an error with a
8
+ stable machine-readable `code` from the table below and a human-readable
9
+ `message`. Over HTTP the body is:
10
+
11
+ ```json
12
+ {
13
+ "error": {
14
+ "code": "INVALID_CREDENTIALS",
15
+ "message": "Email or password is incorrect.",
16
+ "requestId": "01J…",
17
+ "details": [{ "field": "email", "issue": "invalid_format" }]
18
+ }
19
+ }
20
+ ```
21
+
22
+ - **[ERR-FORMAT-002]** (MUST) `details` MAY be present only for
23
+ `VALIDATION_FAILED` and `PASSWORD_POLICY_VIOLATION`, and MUST describe only
24
+ the client's own input.
25
+ - **[ERR-FORMAT-003]** (MUST) Clients and conformance tests MUST rely on `code`,
26
+ never on `message` text; messages MAY be localized.
27
+ - **[ERR-FORMAT-004]** (MUST NOT) Errors MUST NOT be more specific than this table
28
+ allows (e.g. no "user not found" vs "wrong password", no "token expired" vs
29
+ "token used").
30
+
31
+ ## Codes
32
+
33
+ | Code | HTTP | When | Enumeration-safe? |
34
+ | --- | --- | --- | --- |
35
+ | `VALIDATION_FAILED` | 400 | Malformed or missing input | Yes |
36
+ | `PASSWORD_POLICY_VIOLATION` | 400 | Password fails policy (details list the rule) | Yes |
37
+ | `INVALID_CREDENTIALS` | 401 | Unknown user, deleted user, or wrong password | Yes — identical for all causes |
38
+ | `UNAUTHENTICATED` | 401 | No valid session for a protected operation | Yes |
39
+ | `EMAIL_NOT_VERIFIED` | 403 | Correct password, account `pending` | Revealed only after password verified |
40
+ | `ACCOUNT_UNAVAILABLE` | 403 | Correct password, account `suspended`/`disabled` | Revealed only after password verified |
41
+ | `FORBIDDEN` | 403 | Authenticated but not permitted | — |
42
+ | `REAUTHENTICATION_REQUIRED` | 403 | Operation needs recent password entry | — |
43
+ | `CSRF_FAILED` | 403 | Origin/CSRF verification failed | — |
44
+ | `NOT_FOUND` | 404 | Resource absent or hidden from subject | Yes |
45
+ | `TOKEN_INVALID` | 400 | Any one-time-token failure | Yes — identical for all causes |
46
+ | `EMAIL_TAKEN` | 409 | Only when `registration.revealExistingEmail` is enabled | **No** (opt-in trade-off, SEC-ENUM-004) |
47
+ | `CONFLICT` | 409 | State conflict (e.g. removing last admin) | — |
48
+ | `RATE_LIMITED` | 429 | Rate limit exceeded; `Retry-After` header | Yes |
49
+ | `PAYLOAD_TOO_LARGE` | 413 | Body exceeds limit | Yes |
50
+ | `INTERNAL_ERROR` | 500 | Unexpected failure; no internals exposed | Yes |
@@ -0,0 +1,63 @@
1
+ # Optional capabilities — extension contracts
2
+
3
+ - **specVersion:** 0.1 (draft — informative)
4
+
5
+ These capabilities are **not** part of the MVP. Each gets its own normative
6
+ specification, adapter contract, tests, and migration plan before
7
+ implementation (roadmap Phase 11). This document fixes the boundaries now so
8
+ the core model does not have to change later.
9
+
10
+ General rules for every extension:
11
+
12
+ - It extends the core data model with new entities; it does not change the
13
+ meaning of existing fields.
14
+ - It reuses core sessions: completing any login method creates a normal core
15
+ session (AUTHN-SESS-*).
16
+ - It emits security events using the core event format.
17
+ - It keeps the core enumeration, rate-limiting, and token rules.
18
+ - It is off by default and enabled in configuration.
19
+
20
+ ## OAuth 2.0 / OpenID Connect login
21
+
22
+ - Entities: `ExternalAccount (id, userId, provider, providerSubject, email?, linkedAt)`
23
+ unique on `(provider, providerSubject)`.
24
+ - Authorization Code flow with PKCE and `state`; OIDC `nonce`; ID token
25
+ validated by a maintained OIDC library.
26
+ - Identity is the provider's subject (`sub`), **never** the email claim alone.
27
+ - Provider secrets are environment variables; no SelfAuth-operated broker.
28
+
29
+ ## Account linking
30
+
31
+ - Linking an external account to an existing user requires that user to be
32
+ authenticated (or to complete a fresh login) — never automatic by matching
33
+ email, even when the provider asserts `email_verified`.
34
+
35
+ ## MFA — TOTP and recovery codes
36
+
37
+ - Entities: `Credential(type = "totp")` holding an encrypted secret;
38
+ `RecoveryCode (id, userId, codeHash, usedAt)`.
39
+ - Login becomes two-step: password success yields a short-lived, single-use
40
+ *MFA challenge*, not a session.
41
+ - TOTP per RFC 6238 via a maintained library, ±1 step skew, replay of a used
42
+ step rejected. Recovery codes hashed, single-use.
43
+ - Enrolling/removing factors requires recent authentication.
44
+
45
+ ## Passkeys / WebAuthn
46
+
47
+ - Entity: `Credential(type = "webauthn")` with credential ID, public key, sign
48
+ count, transports.
49
+ - Implemented with a maintained WebAuthn server library; relying-party ID from
50
+ configuration, never from request headers.
51
+
52
+ ## API access tokens
53
+
54
+ - For non-browser clients only; browser sessions remain cookie-based
55
+ (ADR 0008).
56
+ - Opaque tokens with a visible prefix (e.g. `sa_`), stored hashed, scoped to a
57
+ subset of the user's permissions, with expiry and revocation.
58
+
59
+ ## Email change
60
+
61
+ - Requires recent authentication; a verification token is sent to the **new**
62
+ address and the change applies only after verification; the **old** address
63
+ is notified; outstanding reset tokens are invalidated.