Compare commits
2 Commits
1b7d7362de
...
b81e8ddad2
| Author | SHA1 | Date |
|---|---|---|
|
|
b81e8ddad2 | |
|
|
38f58ee3b1 |
|
|
@ -1,26 +1,27 @@
|
|||
# Phase 1B: identity and access API
|
||||
|
||||
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. There are no public account-creation or owner-creation endpoints. Staff account provisioning is available to authorized administrators; storefront self-registration and verified email onboarding can be added with the customer milestone.
|
||||
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. Customers create their own accounts with `/auth/register`; there is no public owner-creation endpoint. Staff accounts are provisioned by authorized administrators. Email verification is not yet implemented.
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method | Path | Permission | Request / result |
|
||||
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------- |
|
||||
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
|
||||
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
|
||||
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
||||
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
||||
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
|
||||
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
|
||||
| GET | /users | users.read | Paginated safe user records |
|
||||
| POST | /users | users.create | name, email, password → PENDING account |
|
||||
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
|
||||
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
|
||||
| GET | /roles/permissions | roles.read | Current permission catalogue |
|
||||
| GET | /roles | roles.read | Paginated roles |
|
||||
| POST | /roles | roles.manage | name, permissions |
|
||||
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
|
||||
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
|
||||
| Method | Path | Permission | Request / result |
|
||||
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
|
||||
| POST | /auth/register | Public; throttled | organizationId, email, name, password → active customer + session; 409 duplicate; 10/hour per IP |
|
||||
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
|
||||
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
||||
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
||||
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
|
||||
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
|
||||
| GET | /users | users.read | Paginated safe user records |
|
||||
| POST | /users | users.create | name, email, password → PENDING account |
|
||||
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
|
||||
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
|
||||
| GET | /roles/permissions | roles.read | Current permission catalogue |
|
||||
| GET | /roles | roles.read | Paginated roles |
|
||||
| POST | /roles | roles.manage | name, permissions |
|
||||
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
|
||||
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
|
||||
|
||||
List queries accept `limit` (1–100, default 25) and `offset` (0–10000, default 0). Unknown fields, malformed UUIDs, duplicate role assignments/permissions and unknown permissions are rejected. Errors use Nest's JSON error contract: 400 invalid input, 401 unauthenticated, 403 denied, 404 missing/out-of-scope target, 409 duplicate record, 429 throttled, 503 unavailable.
|
||||
|
||||
|
|
@ -36,7 +37,7 @@ Example login:
|
|||
|
||||
## Access rules
|
||||
|
||||
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. New accounts have no roles and cannot sign in until approved. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
|
||||
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. Staff-created accounts have no roles and cannot sign in until approved. Self-registered customers are active immediately with no roles: they can use their own cart, checkout, addresses, orders and wishlist, and nothing that requires a permission. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
|
||||
|
||||
Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them.
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
Get,
|
||||
Header,
|
||||
HttpCode,
|
||||
Ip,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
|
|
@ -12,7 +13,12 @@ import { AuthService } from './auth.service';
|
|||
import { AuthStore } from './auth.store';
|
||||
import { AuthRateGuard } from './auth-rate.guard';
|
||||
import { CurrentPrincipal, Public } from './access.decorator';
|
||||
import { loginSchema, type LoginInput } from './identity.schemas';
|
||||
import {
|
||||
loginSchema,
|
||||
registerSchema,
|
||||
type LoginInput,
|
||||
type RegisterInput,
|
||||
} from './identity.schemas';
|
||||
import type { Principal } from './identity.types';
|
||||
|
||||
@Controller('auth')
|
||||
|
|
@ -30,6 +36,17 @@ export class AuthController {
|
|||
return this.auth.login(input);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('register')
|
||||
@HttpCode(201)
|
||||
@Header('Cache-Control', 'no-store')
|
||||
register(
|
||||
@Body(new SchemaPipe(registerSchema)) input: RegisterInput,
|
||||
@Ip() ip: string,
|
||||
) {
|
||||
return this.auth.register(input, ip);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@Header('Cache-Control', 'no-store')
|
||||
me(@CurrentPrincipal() principal: Principal) {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { AuthStore } from './auth.store';
|
|||
import { PasswordService } from './password.service';
|
||||
import { RateLimitService } from './rate-limit.service';
|
||||
import { issueToken } from './tokens';
|
||||
import type { LoginInput } from './identity.schemas';
|
||||
import type { LoginInput, RegisterInput } from './identity.schemas';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
|
|
@ -36,6 +36,19 @@ export class AuthService {
|
|||
: 'ACCOUNT_INACTIVE';
|
||||
throw new AppError('AUTH_INVALID_CREDENTIALS', reason);
|
||||
}
|
||||
return this.startSession(user);
|
||||
}
|
||||
// Customers get an active account with no roles: cart, checkout, addresses and orders need only a session.
|
||||
async register(input: RegisterInput, ip: string) {
|
||||
await this.limits.consume(`register-ip:${ip}`, 10, 3600);
|
||||
const { password, ...profile } = input;
|
||||
const user = await this.store.createCustomer({
|
||||
...profile,
|
||||
passwordHash: await this.passwords.hash(password),
|
||||
});
|
||||
return this.startSession(user);
|
||||
}
|
||||
private async startSession(user: { id: string; passwordHash: string }) {
|
||||
const { token, tokenHash } = issueToken();
|
||||
const expiresAt = new Date(
|
||||
Date.now() + this.env.SESSION_TTL_MINUTES * 60_000,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,26 @@ export class AuthStore {
|
|||
where: { organizationId_email: { organizationId, email } },
|
||||
});
|
||||
}
|
||||
createCustomer(input: {
|
||||
organizationId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
passwordHash: string;
|
||||
}) {
|
||||
return this.db.$transaction(async (tx) => {
|
||||
const user = await tx.user.create({
|
||||
data: { ...input, status: 'ACTIVE' },
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
user.organizationId,
|
||||
user.id,
|
||||
'user.registered',
|
||||
user.id,
|
||||
);
|
||||
return user;
|
||||
});
|
||||
}
|
||||
async createSession(
|
||||
userId: string,
|
||||
expectedHash: string,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,9 @@ export const loginSchema = z
|
|||
password: z.string().min(1).max(128),
|
||||
})
|
||||
.strict();
|
||||
export const registerSchema = z
|
||||
.object({ organizationId: z.uuid(), email, name, password })
|
||||
.strict();
|
||||
export const recoveryRequestSchema = loginSchema.omit({ password: true });
|
||||
export const recoveryResetSchema = z
|
||||
.object({
|
||||
|
|
@ -49,6 +52,7 @@ export const pageSchema = z
|
|||
})
|
||||
.strict();
|
||||
export type LoginInput = z.infer<typeof loginSchema>;
|
||||
export type RegisterInput = z.infer<typeof registerSchema>;
|
||||
export type RecoveryInput = z.infer<typeof recoveryRequestSchema>;
|
||||
export type CreateUserInput = z.infer<typeof createUserSchema>;
|
||||
export type RoleInput = z.infer<typeof roleSchema>;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,95 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
|
||||
describe('customer self-registration', () => {
|
||||
let ctx: IdentityApp;
|
||||
const customer = {
|
||||
email: 'Buyer@Example.com',
|
||||
name: 'Asha Buyer',
|
||||
password: 'a long enough customer password',
|
||||
};
|
||||
const register = (body: object) =>
|
||||
ctx.api().post('/api/v1/auth/register').send(body);
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
it('creates an active role-less customer with a working session', async () => {
|
||||
const response = await register({
|
||||
organizationId: ctx.owner.organizationId,
|
||||
...customer,
|
||||
}).expect(201);
|
||||
expect(response.body).toMatchObject({ tokenType: 'Bearer' });
|
||||
expect(JSON.stringify(response.body)).not.toContain(customer.password);
|
||||
const me = await ctx
|
||||
.api()
|
||||
.get('/api/v1/auth/me')
|
||||
.auth(response.body.accessToken, { type: 'bearer' })
|
||||
.expect(200);
|
||||
expect(me.body.permissions).toEqual([]);
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/cart')
|
||||
.auth(response.body.accessToken, { type: 'bearer' })
|
||||
.expect(200);
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/users')
|
||||
.auth(response.body.accessToken, { type: 'bearer' })
|
||||
.expect(403);
|
||||
const user = await ctx.db.user.findFirstOrThrow({
|
||||
where: { email: 'buyer@example.com' },
|
||||
include: { roles: true },
|
||||
});
|
||||
expect(user).toMatchObject({ status: 'ACTIVE', isOwner: false, roles: [] });
|
||||
expect(
|
||||
await ctx.db.auditEvent.count({
|
||||
where: { action: 'user.registered', targetId: user.id },
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(
|
||||
(await ctx.login('buyer@example.com', customer.password)).status,
|
||||
).toBe(200);
|
||||
});
|
||||
|
||||
it('rejects duplicates, weak passwords, unknown organizations and extra fields', async () => {
|
||||
const organizationId = ctx.owner.organizationId;
|
||||
await register({ organizationId, ...customer, email: 'dup@example.com' });
|
||||
await register({
|
||||
organizationId,
|
||||
...customer,
|
||||
email: 'DUP@example.com',
|
||||
}).expect(409);
|
||||
await register({ organizationId, ...customer, password: 'short' }).expect(
|
||||
400,
|
||||
);
|
||||
await register({ ...customer, organizationId: randomUUID() }).expect(
|
||||
(response) => expect(response.status).toBeGreaterThanOrEqual(400),
|
||||
);
|
||||
await register({ organizationId, ...customer, isOwner: true }).expect(400);
|
||||
expect(
|
||||
await ctx.db.user.count({ where: { email: 'dup@example.com' } }),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('limits registrations per client address', async () => {
|
||||
const organizationId = ctx.owner.organizationId;
|
||||
for (let index = 0; index < 10; index++)
|
||||
await register({
|
||||
organizationId,
|
||||
...customer,
|
||||
email: `bulk${index}@example.com`,
|
||||
}).expect(201);
|
||||
await register({
|
||||
organizationId,
|
||||
...customer,
|
||||
email: 'bulk-over@example.com',
|
||||
}).expect(429);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue