@nauticana/sail 1.1.7 → 1.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -144,7 +144,9 @@ bootstrapApplication(App, {
144
144
  });
145
145
  ```
146
146
 
147
- > **Auth-loop breaker.** `authInterceptor` carries a built-in circuit breaker: after 5 `401`/`403`s on token-bearing keel API calls within 10s it opens for 30s and refuses those requests **locally** (never sent), so a stale/rejected session can't drive the app to hammer the API and the edge/CDN. A later success closes it; login (no bearer) is never blocked, so recovery works. No wiring needed beyond registering `authInterceptor`.
147
+ > **Auth-loop breaker.** `authInterceptor` carries a built-in circuit breaker: after 5 `401`s on token-bearing keel API calls within 10s it opens for 30s and refuses those requests **locally** (never sent), so a stale/rejected session can't drive the app to hammer the API and the edge/CDN. Only `401` counts — a `403` is a legitimate permission denial, not a session failure. A later success **or accepting a new token** (login) closes it, so a freshly authenticated session is never blocked. No wiring needed beyond registering `authInterceptor`.
148
+
149
+ > **Phone-number change (opt-in).** `ProfileEditorComponent` and `MyAccountComponent` gate phone change behind a `phoneChangeEnabled` input (default `false`, since it needs an SMS provider — keel returns 503 without `Notify`). Enable it once your backend has SMS wired: `<sail-my-account [phoneChangeEnabled]="true" />` or `<sail-profile-editor [phoneChangeEnabled]="true" />`.
148
150
 
149
151
  ### 5. Create the root component
150
152
 
@@ -506,7 +508,7 @@ readonly meters = toSignal(this.billing.listUsage(), { initialValue: [] });
506
508
 
507
509
  ### Redirect-action (v1.0.0)
508
510
 
509
- A `TableAction` with `kind: 'redirect'` makes `BaseTable.executeAction` POST and then follow the returned `{ url }` instead of refreshing — so checkout / portal / any provider-hosted handoff can be declared as a basis `table_action` row with **no bespoke component**. The backend action handler returns `{ "url": "https://…" }`.
511
+ A `TableAction` with `kind: 'R'` (redirect — the `constant_value` code) makes `BaseTable.executeAction` POST and then follow the returned `{ url }` instead of refreshing — so checkout / portal / any provider-hosted handoff can be declared as a basis `table_action` row with **no bespoke component**. The backend action handler returns `{ "url": "https://…" }`.
510
512
 
511
513
  > **Response-shape contract.** The generic redirect-action path reads a bare `url` because it's polymorphic — one dispatch for checkout / portal / export / etc., where the action's identity lives in the metadata, not the payload. keel's `WrapTableAction` enforces no shape; your inner handler must return `{ url }`. The *typed* billing endpoints keep specific names instead (`createCheckout()` → `checkoutUrl`, `createPortalSession()` → `portalUrl`). So the same portal concept has two response shapes depending on the path: wire it as `<sail-portal-button>` (typed → `portalUrl`) **or** as a `table_action` redirect (generic → `url`), not both.
512
514
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nauticana/sail",
3
- "version": "1.1.7",
3
+ "version": "1.1.8",
4
4
  "description": "Metadata-driven Angular component library for CRUD admin frontends backed by the keel Go backend. Tables, forms, navigation, OTP/2FA/social auth, billing, payout onboarding.",
5
5
  "main": "src/index.ts",
6
6
  "scripts": {
@@ -2,7 +2,7 @@
2
2
  <div class="auth-card">
3
3
  <h2 class="auth-title">My Account</h2>
4
4
 
5
- <sail-profile-editor></sail-profile-editor>
5
+ <sail-profile-editor [phoneChangeEnabled]="phoneChangeEnabled()"></sail-profile-editor>
6
6
 
7
7
  <section class="account-section">
8
8
  <h3>Security</h3>
@@ -1,4 +1,4 @@
1
- import { ChangeDetectionStrategy, Component } from '@angular/core';
1
+ import { ChangeDetectionStrategy, Component, input } from '@angular/core';
2
2
  import { RouterLink } from '@angular/router';
3
3
  import { MatButtonModule } from '@angular/material/button';
4
4
  import { ProfileEditorComponent } from './profile_editor';
@@ -12,4 +12,8 @@ import { ProfileEditorComponent } from './profile_editor';
12
12
  changeDetection: ChangeDetectionStrategy.OnPush,
13
13
  imports: [RouterLink, MatButtonModule, ProfileEditorComponent],
14
14
  })
15
- export class MyAccountComponent {}
15
+ export class MyAccountComponent {
16
+ /** Opt-in: set true once the host's backend has an SMS provider, to expose
17
+ * phone-number change in the embedded profile editor. */
18
+ readonly phoneChangeEnabled = input(false);
19
+ }
@@ -45,6 +45,26 @@
45
45
 
46
46
  <section class="account-section">
47
47
  <h3>Phone</h3>
48
- <p>{{ phone() || 'Not set' }}</p>
49
- @if (!phoneChangeEnabled) { <p class="auth-instructions">Phone change is coming soon.</p> }
48
+ @if (!phoneChangeEnabled()) {
49
+ <p>{{ phone() || 'Not set' }}</p>
50
+ } @else if (phonePhase() === 'idle') {
51
+ <p>{{ phone() || 'Not set' }}</p>
52
+ <button matButton (click)="startPhoneChange()">Change phone</button>
53
+ } @else if (phonePhase() === 'enter') {
54
+ <mat-form-field appearance="outline">
55
+ <mat-label>New phone</mat-label>
56
+ <input matInput type="tel" [formControl]="newPhone" required>
57
+ </mat-form-field>
58
+ <button matButton="elevated" class="primary" (click)="sendPhoneCode()" [disabled]="newPhone.invalid || loading()">Send code</button>
59
+ <button matButton (click)="cancelPhoneChange()">Cancel</button>
60
+ } @else {
61
+ @if (phoneMsg()) { <p>{{ phoneMsg() }}</p> }
62
+ <mat-form-field appearance="outline">
63
+ <mat-label>Confirmation code</mat-label>
64
+ <input matInput [formControl]="phoneCode" inputmode="numeric" required>
65
+ </mat-form-field>
66
+ <button matButton="elevated" class="primary" (click)="confirmPhoneChange()" [disabled]="phoneCode.invalid || loading()">Confirm</button>
67
+ <button matButton (click)="cancelPhoneChange()">Cancel</button>
68
+ }
69
+ @if (phoneErr()) { <div class="auth-error" role="alert">{{ phoneErr() }}</div> }
50
70
  </section>
@@ -1,4 +1,4 @@
1
- import { ChangeDetectionStrategy, Component, OnInit, inject, signal } from '@angular/core';
1
+ import { ChangeDetectionStrategy, Component, OnInit, inject, input, signal } from '@angular/core';
2
2
  import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
3
3
  import { MatButtonModule } from '@angular/material/button';
4
4
  import { MatFormFieldModule } from '@angular/material/form-field';
@@ -6,9 +6,9 @@ import { MatInputModule } from '@angular/material/input';
6
6
  import { BaseAuthService } from '../../service/auth.service';
7
7
  import { UserProfile } from '../../model/auth';
8
8
 
9
- // Self-service profile editor: name/locale save immediately; email change is
10
- // verify-before-apply (code to the new address). Phone change is gated until
11
- // the backend has an SMS provider.
9
+ // Self-service profile editor: name/locale save immediately; email and phone
10
+ // change are verify-before-apply (code to the new value). Phone change is shown
11
+ // only when the host enables phoneChangeEnabled (its backend has an SMS provider).
12
12
  @Component({
13
13
  selector: 'sail-profile-editor',
14
14
  templateUrl: './profile_editor.html',
@@ -19,8 +19,8 @@ export class ProfileEditorComponent implements OnInit {
19
19
  private readonly auth = inject(BaseAuthService);
20
20
  private readonly fb = inject(FormBuilder);
21
21
 
22
- // Flip true once the backend wires an SMS provider for phone codes.
23
- readonly phoneChangeEnabled = false;
22
+ // Set by the host once its backend wires an SMS provider for phone codes.
23
+ readonly phoneChangeEnabled = input(false);
24
24
 
25
25
  readonly loading = signal(false);
26
26
  readonly profileMsg = signal('');
@@ -40,6 +40,12 @@ export class ProfileEditorComponent implements OnInit {
40
40
  readonly newEmail = new FormControl('', [Validators.required, Validators.email]);
41
41
  readonly emailCode = new FormControl('', [Validators.required]);
42
42
 
43
+ readonly phonePhase = signal<'idle' | 'enter' | 'code'>('idle');
44
+ readonly phoneMsg = signal('');
45
+ readonly phoneErr = signal('');
46
+ readonly newPhone = new FormControl('', [Validators.required]);
47
+ readonly phoneCode = new FormControl('', [Validators.required]);
48
+
43
49
  ngOnInit(): void {
44
50
  this.auth.getProfile().subscribe({
45
51
  next: (p: UserProfile) => {
@@ -95,6 +101,38 @@ export class ProfileEditorComponent implements OnInit {
95
101
  });
96
102
  }
97
103
 
104
+ startPhoneChange(): void {
105
+ this.phonePhase.set('enter');
106
+ this.phoneMsg.set('');
107
+ this.phoneErr.set('');
108
+ }
109
+
110
+ cancelPhoneChange(): void {
111
+ this.phonePhase.set('idle');
112
+ this.newPhone.reset();
113
+ this.phoneCode.reset();
114
+ }
115
+
116
+ sendPhoneCode(): void {
117
+ if (this.newPhone.invalid) return;
118
+ this.loading.set(true);
119
+ this.phoneErr.set('');
120
+ this.auth.requestPhoneChange(this.newPhone.value!).subscribe({
121
+ next: () => { this.loading.set(false); this.phonePhase.set('code'); this.phoneMsg.set('We sent a code to your new number.'); },
122
+ error: (e) => { this.loading.set(false); this.phoneErr.set(this.msg(e, 'Could not send a code.')); },
123
+ });
124
+ }
125
+
126
+ confirmPhoneChange(): void {
127
+ if (this.phoneCode.invalid) return;
128
+ this.loading.set(true);
129
+ this.phoneErr.set('');
130
+ this.auth.confirmPhoneChange(this.newPhone.value!, Number(this.phoneCode.value)).subscribe({
131
+ next: () => { this.loading.set(false); this.phone.set(this.newPhone.value!); this.cancelPhoneChange(); this.profileMsg.set('Phone updated.'); },
132
+ error: (e) => { this.loading.set(false); this.phoneErr.set(this.msg(e, 'Invalid or expired code.')); },
133
+ });
134
+ }
135
+
98
136
  private msg(e: { error?: { detail?: string; message?: string } }, fallback: string): string {
99
137
  return e?.error?.detail || e?.error?.message || fallback;
100
138
  }
@@ -19,22 +19,24 @@ export class EntitySelectorComponent {
19
19
  readonly entities = input<EntityOption[]>([]);
20
20
  readonly selected = input<string | undefined>(undefined);
21
21
  readonly label = input<string>('Business');
22
- readonly selectionChange = output<string>();
22
+ readonly selectionChange = output<string | undefined>();
23
23
 
24
24
  readonly value = signal<string | undefined>(undefined);
25
25
 
26
26
  constructor() {
27
27
  // Explicit selection wins; else keep the current pick if still valid; else the
28
- // first active entity. Emit whenever the resolved value actually changes.
28
+ // first active entity. "Valid" means present AND active, so a scope that goes
29
+ // inactive (or vanishes) is dropped. Emit on every change, including a clear
30
+ // (undefined) when no active option remains, so the host stops showing stale data.
29
31
  effect(() => {
30
32
  const opts = this.entities();
31
- const want = this.selected();
33
+ const isActive = (id?: string) => !!id && opts.some((e) => e.id === id && e.active !== false);
32
34
  const cur = this.value();
33
35
  const resolved =
34
- want && opts.some((e) => e.id === want) ? want
35
- : cur && opts.some((e) => e.id === cur) ? cur
36
+ isActive(this.selected()) ? this.selected()
37
+ : isActive(cur) ? cur
36
38
  : opts.find((e) => e.active !== false)?.id;
37
- if (resolved && resolved !== cur) {
39
+ if (resolved !== cur) {
38
40
  this.value.set(resolved);
39
41
  this.selectionChange.emit(resolved);
40
42
  }
@@ -9,6 +9,9 @@
9
9
  @if (loggedOut) {
10
10
  <p class="auth-message" role="status" aria-live="polite">You have been logged out successfully.</p>
11
11
  }
12
+ @if (sessionHandoffError()) {
13
+ <p class="auth-error" role="alert">{{ sessionHandoffError() }}</p>
14
+ }
12
15
  <form [formGroup]="loginForm" (ngSubmit)="login()" class="auth-form">
13
16
  <mat-form-field appearance="outline">
14
17
  <mat-label>Username</mat-label>
@@ -1,7 +1,7 @@
1
1
  import { ChangeDetectionStrategy, Component, computed, inject, ViewEncapsulation } from '@angular/core';
2
2
  import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
3
3
  import { BaseAuthService } from '../../service/auth.service';
4
- import { ActivatedRoute, Router, RouterLink } from '@angular/router';
4
+ import { ActivatedRoute, RouterLink } from '@angular/router';
5
5
  import { MatButtonModule } from '@angular/material/button';
6
6
  import { MatFormFieldModule } from "@angular/material/form-field";
7
7
  import { MatInputModule } from '@angular/material/input';
@@ -25,10 +25,11 @@ import { SocialLoginComponent } from './social_login';
25
25
  })
26
26
  export class LoginComponent {
27
27
  private auth = inject(BaseAuthService);
28
- private router = inject(Router);
29
28
  protected fb = inject(FormBuilder);
30
29
  protected readonly guiConfig: SailGuiConfig = inject(SAIL_GUI_CONFIG, {optional: true}) ?? DEFAULT_CONFIG;
31
30
  protected readonly loggedOut = inject(ActivatedRoute).snapshot.queryParamMap.get('loggedOut') === 'true';
31
+ /** OAuth session-cookie handoff failure from BaseAuthService, shown below. */
32
+ protected readonly sessionHandoffError = this.auth.sessionHandoffError;
32
33
 
33
34
  /**
34
35
  * Auto-show the embedded SocialLoginComponent whenever at least one
@@ -58,14 +59,12 @@ export class LoginComponent {
58
59
  }
59
60
 
60
61
  /**
61
- * SocialLoginComponent emits the response after BaseAuthService.loginSocial
62
- * persists the JWT internally. Mirror the same post-login navigation that
63
- * password-login uses (root route by default; consumers override via
64
- * BaseAuthService.navigateToRoleHome when role-aware routing lands).
62
+ * loginSocial already ran completeLogin, which owns post-login navigation
63
+ * (route init, or the OAuth cookie handoff). Handlers must NOT navigate here —
64
+ * doing so abandons a pending handoff before its cookie is set. Downstream
65
+ * social-login handlers should follow the same rule.
65
66
  */
66
- protected onSocialSuccess(_: LoginResponseSocial): void {
67
- this.router.navigateByUrl('/');
68
- }
67
+ protected onSocialSuccess(_: LoginResponseSocial): void {}
69
68
 
70
69
  protected onSocialError(err: Error): void {
71
70
  console.error('social login failed:', err);
@@ -83,7 +83,7 @@ export interface TableAction {
83
83
  confirmMessage?: string;
84
84
  authorityObject: string; // uppercased table_name — for canExecute()
85
85
  authorityCheck: string; // uppercased action_name — for canExecute()
86
- kind?: 'P' | 'R' | 'V'; // P post (default) / R redirect (follow {url}) / V reveal (show returned secret once)
86
+ kind?: 'P' | 'R' | 'V'; // constant_value codes: P post (default) / R redirect (follow {url}) / V reveal (show returned secret once)
87
87
  }
88
88
 
89
89
  export interface ForeignKey {
@@ -2,12 +2,11 @@ import { HttpErrorResponse, HttpEventType, HttpInterceptorFn } from '@angular/co
2
2
  import { catchError, tap, throwError } from 'rxjs';
3
3
  import { isKeelApiUrl } from './rest_url';
4
4
 
5
- // Auth-loop breaker: repeated 401/403s on token-bearing API calls (a stale or
6
- // rejected session) can drive the app to hammer the API — and the edge/CDN in
7
- // front of it — indefinitely. After AUTH_FAIL_THRESHOLD failures within
8
- // AUTH_FAIL_WINDOW_MS the circuit opens for AUTH_CIRCUIT_COOLDOWN_MS: authed API
9
- // requests are refused locally (never sent) so the storm stops at the browser. A
10
- // later success closes it; login (no bearer) is never blocked, so recovery works.
5
+ // Auth-loop breaker: repeated 401s on token-bearing API calls (a stale session) can
6
+ // drive the app to hammer the API/CDN. After AUTH_FAIL_THRESHOLD within
7
+ // AUTH_FAIL_WINDOW_MS the circuit opens for AUTH_CIRCUIT_COOLDOWN_MS — authed
8
+ // requests are refused locally. Only 401 counts (403 is a permission denial); a
9
+ // success or accepting a new token closes it.
11
10
  const AUTH_FAIL_WINDOW_MS = 10_000;
12
11
  const AUTH_FAIL_THRESHOLD = 5;
13
12
  const AUTH_CIRCUIT_COOLDOWN_MS = 30_000;
@@ -36,7 +35,7 @@ export const authInterceptor: HttpInterceptorFn = (req, next) => {
36
35
  }
37
36
  }),
38
37
  catchError((err: HttpErrorResponse) => {
39
- if (authedApi && (err.status === 401 || err.status === 403)) {
38
+ if (authedApi && err.status === 401) {
40
39
  recordAuthFailure();
41
40
  }
42
41
  return throwError(() => err);
@@ -70,3 +69,9 @@ function clearAuthFailures(): void {
70
69
  sessionStorage.removeItem(FAIL_KEY);
71
70
  sessionStorage.removeItem(OPEN_KEY);
72
71
  }
72
+
73
+ /** Close the circuit on accepting a new token, so a freshly logged-in session
74
+ * isn't blocked by failures from a prior stale session. */
75
+ export function resetAuthCircuit(): void {
76
+ clearAuthFailures();
77
+ }
@@ -16,6 +16,7 @@ import { ApplicationMenu, ConstantValue } from '../model/common';
16
16
  import { CanActivateFn, CanDeactivateFn, Router, Routes } from '@angular/router';
17
17
  import { SAIL_GUI_CONFIG, SailGuiConfig, DEFAULT_CONFIG } from '../config';
18
18
  import { BaseRestService } from './base_rest.service';
19
+ import { resetAuthCircuit } from './auth.interceptor';
19
20
 
20
21
  /** Sort dropdown options by their visible label so long lookup lists are scannable. */
21
22
  const byCaption = (a: ConstantValue, b: ConstantValue) =>
@@ -61,6 +62,10 @@ export abstract class BaseAuthService extends BaseRestService {
61
62
  token: string | null = null;
62
63
  readonly isLoggedIn = signal(false);
63
64
 
65
+ /** Set when the OAuth session-cookie handoff fails; the UI shows it and lets the
66
+ * user retry instead of being redirected into a cookieless login loop. */
67
+ readonly sessionHandoffError = signal<string | null>(null);
68
+
64
69
  /**
65
70
  * Multi-role app support. Consumers that distinguish rider/driver/admin
66
71
  * (or any equivalent split) call setRole() after login, then
@@ -117,15 +122,22 @@ export abstract class BaseAuthService extends BaseRestService {
117
122
  this.token = token;
118
123
  this.isLoggedIn.set(true);
119
124
  localStorage.setItem('jwt', token);
125
+ resetAuthCircuit(); // a new session must not inherit a prior session's open circuit
120
126
  const ret = this.validatedReturnUrl();
121
127
  if (ret && this.guiConfig.sessionCookieUrl) {
122
128
  // OAuth flow: mirror the bearer into a cookie, then hand off to the
123
- // (cross-origin) authorization server via a full navigation.
129
+ // (cross-origin) authorization server via a full navigation. Only hand off
130
+ // once the cookie is actually set — redirecting after a failed cookie request
131
+ // sends the user on without a session and loops them back to login.
132
+ this.sessionHandoffError.set(null);
124
133
  this.http.post(this.url(this.guiConfig.sessionCookieUrl), {}, { withCredentials: true })
125
134
  .pipe(take(1))
126
135
  .subscribe({
127
136
  next: () => window.location.assign(ret),
128
- error: () => window.location.assign(ret),
137
+ error: (err) => {
138
+ console.error('Session cookie handoff failed:', err);
139
+ this.sessionHandoffError.set('Could not complete sign-in. Please try again.');
140
+ },
129
141
  });
130
142
  return;
131
143
  }