From 135b4640b228d87d06ae68f031e445fd7b30e1e5 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:03:58 +0100 Subject: [PATCH] Teach the Dart model generator allOf and dotted enum values npm run generate stopped at NewApiToken (an allOf of ApiToken and the token), so the phone app's models missed the sign-in and security schemas. allOf parts are now merged into one class, keeping the inline types of the schema they come from (NewApiToken.scope is an ApiTokenScope). Enum values with dots become camelCase names (page.created -> pageCreated) and "*" becomes all, for WebhookEvent. The regenerated models add the OAuth, TOTP, API token, audit log and webhook types. Co-Authored-By: Claude Opus 5.5 --- Phone-App/lib/api/generated/models.dart | 627 +++++++++++++++++++++++- Phone-App/tool/generate_api.dart | 63 ++- 2 files changed, 672 insertions(+), 18 deletions(-) diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 52a0055..6b51ed5 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -5,7 +5,13 @@ // ignore_for_file: constant_identifier_names class ApiError { - const ApiError({required this.error, this.message, this.fields, this.mfaId}); + const ApiError({ + required this.error, + this.message, + this.fields, + this.mfaId, + this.challenge, + }); factory ApiError.fromJson(Map json) => ApiError( error: json['error'] as String, @@ -16,9 +22,10 @@ class ApiError { (k, e) => MapEntry(k, e as String), ), mfaId: json['mfaId'] == null ? null : json['mfaId'] as String, + challenge: json['challenge'] == null ? null : json['challenge'] as String, ); - /// invalid_json, validation, invalid_credentials, mfa_required, unauthorized, forbidden, account_disabled, signup_disabled, domain_not_allowed, invalid_token, invalid, not_found, conflict, internal + /// invalid_json, validation, invalid_credentials, mfa_required, totp_required (with challenge), invalid_code, unauthorized, forbidden, account_disabled, signup_disabled, domain_not_allowed, invalid_token, invalid, not_found, conflict, internal final String error; /// Human-readable explanation @@ -28,11 +35,15 @@ class ApiError { final String? mfaId; + /// With totp_required; send it to /api/v1/auth/totp/verify + final String? challenge; + Map toJson() => { 'error': error, 'message': ?message, 'fields': ?fields, 'mfaId': ?mfaId, + 'challenge': ?challenge, }; } @@ -100,6 +111,7 @@ class User { required this.role, required this.organization, required this.organizationName, + this.totp, }); factory User.fromJson(Map json) => User( @@ -115,6 +127,7 @@ class User { role: Role.fromJson(json['role'] as String), organization: json['organization'] as String, organizationName: json['organizationName'] as String, + totp: json['totp'] == null ? null : json['totp'] as bool, ); final String id; @@ -142,6 +155,9 @@ class User { final String organizationName; + /// Signs in with an authenticator app too + final bool? totp; + Map toJson() => { 'id': id, 'email': email, @@ -155,6 +171,7 @@ class User { 'role': role.toJson(), 'organization': organization, 'organizationName': organizationName, + 'totp': ?totp, }; } @@ -1067,12 +1084,29 @@ class UserList { }; } +class AuthMethodsProviders { + const AuthMethodsProviders({required this.name, required this.displayName}); + + factory AuthMethodsProviders.fromJson(Map json) => + AuthMethodsProviders( + name: json['name'] as String, + displayName: json['displayName'] as String, + ); + + final String name; + + final String displayName; + + Map toJson() => {'name': name, 'displayName': displayName}; +} + class AuthMethods { const AuthMethods({ required this.password, required this.otp, required this.mfa, required this.oauth2, + required this.providers, required this.signup, }); @@ -1081,6 +1115,9 @@ class AuthMethods { otp: json['otp'] as bool, mfa: json['mfa'] as bool, oauth2: (json['oauth2'] as List).map((e) => e as String).toList(), + providers: (json['providers'] as List) + .map((e) => AuthMethodsProviders.fromJson(e as Map)) + .toList(), signup: json['signup'] as bool, ); @@ -1092,6 +1129,8 @@ class AuthMethods { final List oauth2; + final List providers; + final bool signup; Map toJson() => { @@ -1099,6 +1138,7 @@ class AuthMethods { 'otp': otp, 'mfa': mfa, 'oauth2': oauth2.map((e) => e).toList(), + 'providers': providers.map((e) => e.toJson()).toList(), 'signup': signup, }; } @@ -1493,16 +1533,589 @@ class InstanceSettingsUpdate { }; } -class AuthSettings { - const AuthSettings({required this.magicLink}); +class OAuthStart { + const OAuthStart({required this.url, required this.state}); - factory AuthSettings.fromJson(Map json) => - AuthSettings(magicLink: json['magicLink'] as bool); + factory OAuthStart.fromJson(Map json) => + OAuthStart(url: json['url'] as String, state: json['state'] as String); + + final String url; + + final String state; + + Map toJson() => {'url': url, 'state': state}; +} + +class TotpStatus { + const TotpStatus({required this.enabled, required this.recoveryCodesLeft}); + + factory TotpStatus.fromJson(Map json) => TotpStatus( + enabled: json['enabled'] as bool, + recoveryCodesLeft: (json['recoveryCodesLeft'] as num).toInt(), + ); + + final bool enabled; + + final int recoveryCodesLeft; + + Map toJson() => { + 'enabled': enabled, + 'recoveryCodesLeft': recoveryCodesLeft, + }; +} + +class TotpSetup { + const TotpSetup({required this.secret, required this.url, required this.qr}); + + factory TotpSetup.fromJson(Map json) => TotpSetup( + secret: json['secret'] as String, + url: json['url'] as String, + qr: json['qr'] as String, + ); + + /// For typing into the app by hand + final String secret; + + /// The otpauth:// address + final String url; + + /// PNG data URL of the QR code + final String qr; + + Map toJson() => {'secret': secret, 'url': url, 'qr': qr}; +} + +enum ApiTokenScope { + read('read'), + write('write'); + + const ApiTokenScope(this.value); + final String value; + + static ApiTokenScope fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown ApiTokenScope', value), + ); + + String toJson() => value; +} + +/// In admin listings +class ApiTokenUser { + const ApiTokenUser({ + required this.id, + required this.email, + required this.name, + }); + + factory ApiTokenUser.fromJson(Map json) => ApiTokenUser( + id: json['id'] as String, + email: json['email'] as String, + name: json['name'] as String, + ); + + final String id; + + final String email; + + final String name; + + Map toJson() => {'id': id, 'email': email, 'name': name}; +} + +class ApiToken { + const ApiToken({ + required this.id, + required this.name, + required this.prefix, + required this.scope, + required this.lastUsed, + required this.expires, + required this.created, + this.user, + }); + + factory ApiToken.fromJson(Map json) => ApiToken( + id: json['id'] as String, + name: json['name'] as String, + prefix: json['prefix'] as String, + scope: ApiTokenScope.fromJson(json['scope'] as String), + lastUsed: json['lastUsed'] as String, + expires: json['expires'] as String, + created: json['created'] as String, + user: json['user'] == null + ? null + : ApiTokenUser.fromJson(json['user'] as Map), + ); + + final String id; + + final String name; + + /// The token's first characters + final String prefix; + + final ApiTokenScope scope; + + final String lastUsed; + + /// Empty when it never expires + final String expires; + + final String created; + + /// In admin listings + final ApiTokenUser? user; + + Map toJson() => { + 'id': id, + 'name': name, + 'prefix': prefix, + 'scope': scope.toJson(), + 'lastUsed': lastUsed, + 'expires': expires, + 'created': created, + 'user': ?user?.toJson(), + }; +} + +class NewApiToken { + const NewApiToken({ + required this.id, + required this.name, + required this.prefix, + required this.scope, + required this.lastUsed, + required this.expires, + required this.created, + this.user, + required this.token, + }); + + factory NewApiToken.fromJson(Map json) => NewApiToken( + id: json['id'] as String, + name: json['name'] as String, + prefix: json['prefix'] as String, + scope: ApiTokenScope.fromJson(json['scope'] as String), + lastUsed: json['lastUsed'] as String, + expires: json['expires'] as String, + created: json['created'] as String, + user: json['user'] == null + ? null + : ApiTokenUser.fromJson(json['user'] as Map), + token: json['token'] as String, + ); + + final String id; + + final String name; + + /// The token's first characters + final String prefix; + + final ApiTokenScope scope; + + final String lastUsed; + + /// Empty when it never expires + final String expires; + + final String created; + + /// In admin listings + final ApiTokenUser? user; + + /// The token; it is not shown again + final String token; + + Map toJson() => { + 'id': id, + 'name': name, + 'prefix': prefix, + 'scope': scope.toJson(), + 'lastUsed': lastUsed, + 'expires': expires, + 'created': created, + 'user': ?user?.toJson(), + 'token': token, + }; +} + +class AuditEntry { + const AuditEntry({ + required this.id, + required this.created, + required this.action, + required this.actorId, + required this.actorEmail, + required this.targetType, + required this.targetId, + required this.status, + required this.ip, + required this.userAgent, + required this.meta, + }); + + factory AuditEntry.fromJson(Map json) => AuditEntry( + id: json['id'] as String, + created: json['created'] as String, + action: json['action'] as String, + actorId: json['actorId'] as String, + actorEmail: json['actorEmail'] as String, + targetType: json['targetType'] as String, + targetId: json['targetId'] as String, + status: (json['status'] as num).toInt(), + ip: json['ip'] as String, + userAgent: json['userAgent'] as String, + meta: json['meta'] == null ? null : json['meta'] as Map, + ); + + final String id; + + final String created; + + /// A sign-in step ("auth.login", "auth.login.failed") or the route of a change ("PATCH /pages/{id}") + final String action; + + final String actorId; + + final String actorEmail; + + final String targetType; + + final String targetId; + + final int status; + + final String ip; + + final String userAgent; + + final Map? meta; + + Map toJson() => { + 'id': id, + 'created': created, + 'action': action, + 'actorId': actorId, + 'actorEmail': actorEmail, + 'targetType': targetType, + 'targetId': targetId, + 'status': status, + 'ip': ip, + 'userAgent': userAgent, + 'meta': meta, + }; +} + +class AuditPage { + const AuditPage({ + required this.items, + required this.total, + required this.page, + }); + + factory AuditPage.fromJson(Map json) => AuditPage( + items: (json['items'] as List) + .map((e) => AuditEntry.fromJson(e as Map)) + .toList(), + total: (json['total'] as num).toInt(), + page: (json['page'] as num).toInt(), + ); + + final List items; + + final int total; + + final int page; + + Map toJson() => { + 'items': items.map((e) => e.toJson()).toList(), + 'total': total, + 'page': page, + }; +} + +enum WebhookEvent { + all('*'), + pageCreated('page.created'), + pageUpdated('page.updated'), + pageMoved('page.moved'), + pageTrashed('page.trashed'), + pageRestored('page.restored'), + pageDeleted('page.deleted'), + commentCreated('comment.created'), + commentResolved('comment.resolved'), + spaceCreated('space.created'), + spaceDeleted('space.deleted'); + + const WebhookEvent(this.value); + final String value; + + static WebhookEvent fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown WebhookEvent', value), + ); + + String toJson() => value; +} + +class Webhook { + const Webhook({ + required this.id, + required this.name, + required this.url, + required this.events, + required this.active, + this.secret, + required this.created, + }); + + factory Webhook.fromJson(Map json) => Webhook( + id: json['id'] as String, + name: json['name'] as String, + url: json['url'] as String, + events: (json['events'] as List) + .map((e) => WebhookEvent.fromJson(e as String)) + .toList(), + active: json['active'] as bool, + secret: json['secret'] == null ? null : json['secret'] as String, + created: json['created'] as String, + ); + + final String id; + + final String name; + + final String url; + + final List events; + + final bool active; + + /// Only when just created + final String? secret; + + final String created; + + Map toJson() => { + 'id': id, + 'name': name, + 'url': url, + 'events': events.map((e) => e.toJson()).toList(), + 'active': active, + 'secret': ?secret, + 'created': created, + }; +} + +class WebhookInput { + const WebhookInput({this.name, this.url, this.events, this.active}); + + factory WebhookInput.fromJson(Map json) => WebhookInput( + name: json['name'] == null ? null : json['name'] as String, + url: json['url'] == null ? null : json['url'] as String, + events: json['events'] == null + ? null + : (json['events'] as List) + .map((e) => WebhookEvent.fromJson(e as String)) + .toList(), + active: json['active'] == null ? null : json['active'] as bool, + ); + + final String? name; + + final String? url; + + /// Defaults to all ("*") + final List? events; + + final bool? active; + + Map toJson() => { + 'name': ?name, + 'url': ?url, + 'events': ?events?.map((e) => e.toJson()).toList(), + 'active': ?active, + }; +} + +enum WebhookDeliveryStatus { + pending('pending'), + success('success'), + failed('failed'); + + const WebhookDeliveryStatus(this.value); + final String value; + + static WebhookDeliveryStatus fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown WebhookDeliveryStatus', value), + ); + + String toJson() => value; +} + +class WebhookDelivery { + const WebhookDelivery({ + required this.id, + required this.event, + required this.deliveryId, + required this.status, + required this.attempts, + required this.responseCode, + required this.error, + required this.durationMs, + required this.created, + }); + + factory WebhookDelivery.fromJson(Map json) => + WebhookDelivery( + id: json['id'] as String, + event: json['event'] as String, + deliveryId: json['deliveryId'] as String, + status: WebhookDeliveryStatus.fromJson(json['status'] as String), + attempts: (json['attempts'] as num).toInt(), + responseCode: (json['responseCode'] as num).toInt(), + error: json['error'] as String, + durationMs: (json['durationMs'] as num).toInt(), + created: json['created'] as String, + ); + + final String id; + + final String event; + + /// The payload's id (X-Docwell-Delivery) + final String deliveryId; + + final WebhookDeliveryStatus status; + + final int attempts; + + final int responseCode; + + final String error; + + final int durationMs; + + final String created; + + Map toJson() => { + 'id': id, + 'event': event, + 'deliveryId': deliveryId, + 'status': status.toJson(), + 'attempts': attempts, + 'responseCode': responseCode, + 'error': error, + 'durationMs': durationMs, + 'created': created, + }; +} + +enum OAuthProviderSettingsName { + google('google'), + github('github'), + microsoft('microsoft'), + oidc('oidc'); + + const OAuthProviderSettingsName(this.value); + final String value; + + static OAuthProviderSettingsName fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => + throw FormatException('unknown OAuthProviderSettingsName', value), + ); + + String toJson() => value; +} + +class OAuthProviderSettings { + const OAuthProviderSettings({ + required this.name, + required this.clientId, + this.clientSecret, + required this.displayName, + required this.authUrl, + required this.tokenUrl, + required this.userInfoUrl, + }); + + factory OAuthProviderSettings.fromJson(Map json) => + OAuthProviderSettings( + name: OAuthProviderSettingsName.fromJson(json['name'] as String), + clientId: json['clientId'] as String, + clientSecret: json['clientSecret'] == null + ? null + : json['clientSecret'] as String, + displayName: json['displayName'] as String, + authUrl: json['authUrl'] as String, + tokenUrl: json['tokenUrl'] as String, + userInfoUrl: json['userInfoUrl'] as String, + ); + + final OAuthProviderSettingsName name; + + final String clientId; + + /// Write-only; leave out to keep the stored one + final String? clientSecret; + + final String displayName; + + /// OpenID Connect only + final String authUrl; + + /// OpenID Connect only + final String tokenUrl; + + /// OpenID Connect only + final String userInfoUrl; + + Map toJson() => { + 'name': name.toJson(), + 'clientId': clientId, + 'clientSecret': ?clientSecret, + 'displayName': displayName, + 'authUrl': authUrl, + 'tokenUrl': tokenUrl, + 'userInfoUrl': userInfoUrl, + }; +} + +class AuthSettings { + const AuthSettings({ + required this.magicLink, + required this.oauth2, + this.callbackUrl, + }); + + factory AuthSettings.fromJson(Map json) => AuthSettings( + magicLink: json['magicLink'] as bool, + oauth2: (json['oauth2'] as List) + .map((e) => OAuthProviderSettings.fromJson(e as Map)) + .toList(), + callbackUrl: json['callbackUrl'] == null + ? null + : json['callbackUrl'] as String, + ); /// Email a one-time sign-in link and code final bool magicLink; - Map toJson() => {'magicLink': magicLink}; + /// Sign-in providers; saving replaces the list (leave it out to keep it) + final List oauth2; + + /// Read-only: the address to register with each provider + final String? callbackUrl; + + Map toJson() => { + 'magicLink': magicLink, + 'oauth2': oauth2.map((e) => e.toJson()).toList(), + 'callbackUrl': ?callbackUrl, + }; } enum InviteStatus { diff --git a/Phone-App/tool/generate_api.dart b/Phone-App/tool/generate_api.dart index cdf7e2e..0ff3b0d 100644 --- a/Phone-App/tool/generate_api.dart +++ b/Phone-App/tool/generate_api.dart @@ -5,7 +5,8 @@ // dart run tool/generate_api.dart (from Phone-App/) // // Handles what the contract uses: objects, string enums, $ref, arrays, maps -// (additionalProperties) and "object or null". Inline objects and enums become +// (additionalProperties), "object or null" and allOf of objects (merged into +// one class). Inline objects and enums become // classes named after their parent and property (WorkspaceMember.user -> // WorkspaceMemberUser). import 'dart:io'; @@ -18,7 +19,7 @@ const _outPath = 'lib/api/generated/models.dart'; void main() { final spec = loadYaml(File(_specPath).readAsStringSync()) as YamlMap; final schemas = (spec['components'] as YamlMap)['schemas'] as YamlMap; - final gen = _Generator({ + final gen = _Generator(schemas, { for (final e in schemas.entries) if ((e.value as YamlMap)['enum'] != null) e.key as String, }); @@ -70,10 +71,13 @@ class _Type { } class _Generator { - _Generator(this.enumSchemas); + _Generator(this.schemas, this.enumSchemas); + final YamlMap schemas; final Set enumSchemas; final _out = []; + // Classes and enums written so far; an allOf reuses its parts' inline types. + final _done = {}; String render() => [ '// SPDX-License-Identifier: AGPL-3.0-or-later', @@ -88,6 +92,8 @@ class _Generator { void schema(String name, YamlMap s) { if (s['enum'] != null) { _enum(name, s); + } else if (s['allOf'] != null) { + _class(name, _merge(name, s)); } else if (s['type'] == 'object') { _class(name, s); } else { @@ -96,13 +102,16 @@ class _Generator { } void _enum(String name, YamlMap s) { + if (!_done.add(name)) return; final values = (s['enum'] as YamlList).cast(); final b = StringBuffer(); _doc(b, s['description'] as String?, ''); b.writeln('enum $name {'); for (final v in values) { - // An empty value means "none" (e.g. SpaceCallerRole). - b.writeln(" ${v.isEmpty ? 'none' : _ident(v)}('$v'),"); + // An empty value means "none" (e.g. SpaceCallerRole), "*" means all + // (WebhookEvent). + final id = v.isEmpty ? 'none' : (v == '*' ? 'all' : _ident(v)); + b.writeln(" $id('$v'),"); } b.writeln(' ;'); b.writeln(); @@ -120,10 +129,42 @@ class _Generator { _out.add(b.toString()); } - void _class(String name, YamlMap s) { - final required = ((s['required'] as YamlList?) ?? YamlList()) - .cast(); - final props = (s['properties'] as YamlMap?) ?? YamlMap(); + /// Merges the object schemas of an allOf ($refs included) into one. Inline + /// types keep the name of the schema they come from (ApiToken.scope stays + /// ApiTokenScope in NewApiToken). + Map _merge(String name, YamlMap s) { + final props = {}; + final owners = {}; + final required = []; + for (final part in (s['allOf'] as YamlList).cast()) { + final ref = part[r'$ref'] as String?; + final o = ref == null ? part : schemas[ref.split('/').last] as YamlMap; + if (o['type'] != 'object') { + throw UnsupportedError('schema $name: allOf of non-objects'); + } + final p = (o['properties'] as Map?) ?? const {}; + props.addAll(p); + for (final k in p.keys) { + owners[k as String] = ref == null + ? name + : _className(ref.split('/').last); + } + required.addAll(((o['required'] as List?) ?? const []).cast()); + } + return { + 'type': 'object', + 'description': s['description'], + 'required': required, + 'properties': props, + 'owners': owners, + }; + } + + void _class(String name, Map s) { + if (!_done.add(name)) return; + final owners = (s['owners'] as Map?) ?? const {}; + final required = ((s['required'] as List?) ?? const []).cast(); + final props = (s['properties'] as Map?) ?? const {}; final fields = <_Field>[]; for (final e in props.entries) { final prop = e.key as String; @@ -131,7 +172,7 @@ class _Generator { fields.add( _Field( prop, - _type(name + _pascal(prop), ps), + _type((owners[prop] ?? name) + _pascal(prop), ps), required.contains(prop), ps['description'] as String?, ), @@ -297,7 +338,7 @@ class _Generator { static String _ident(String s) { final id = s.replaceAllMapped( - RegExp(r'[-_ ](\w)'), + RegExp(r'[-_. ](\w)'), (m) => m[1]!.toUpperCase(), ); return _reserved.contains(id) ? '${id}_' : id;