@nebulr-group/bridge-svelte 1.0.0-alpha.13 → 1.0.0-alpha.15

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
@@ -74,7 +74,7 @@ In your app's settings in Bridge, add your app's address as a browser address an
74
74
  | Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `QuotaGate`, `Entitled`, `CheckoutNotice`, `UpgradeDialog`, `bridgeFetch` |
75
75
  | Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `WorkspaceForm`, `ProfileForm` |
76
76
  | State | `session`, `user`, `workspace`, `workspaces`, `me`, `flags`, `billing`, `plans`, `usage`, `liveStatus`, `getBridge()` |
77
- | Server | `@nebulr-group/bridge-svelte/server`: `bridgeHandle`, `requireActor`, `meter`, `flagsFor` |
77
+ | Server | `@nebulr-group/bridge-svelte/server`: `bridgeHandle`, `requireActor`, `requireFlag`, `meter`, `flagsFor` |
78
78
  | Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
79
79
  | Hosted mode | `hosted: {}` in the config: `/auth/sign-in` sends people to the page Bridge hosts for the app, and `/auth/callback` (`HostedCallback`) finishes the sign-in when they come back. Register the page's origin as a browser address and `https://<your app>/auth/callback` as a sign-in return |
80
80
  | Several sign-in pages | `linkAddress` in the config: which of the app's registered email-links addresses its emails link to |
package/dist/bootstrap.js CHANGED
@@ -48,18 +48,33 @@ function followLink(config, url) {
48
48
  return;
49
49
  redirect(307, `${page}${hash}`);
50
50
  }
51
+ /**
52
+ * Whether the workspace is locked for payment, asked when the app's active flag is off. The flag is off both for a
53
+ * workspace with no plan and for one that is locked; only the first goes to the paywall. The flag can turn off before
54
+ * the lock held for the page is read again, so the lock is read now rather than taken from what is held.
55
+ */
56
+ async function lockedNow(client) {
57
+ if (client.isLocked())
58
+ return true;
59
+ const facts = await within(client.billing.gate(), READY_WAIT_MS);
60
+ return facts?.access === 'blocked';
61
+ }
51
62
  async function guard(client, config, url) {
52
63
  await within(client.ready, READY_WAIT_MS);
53
64
  const flagsNeeded = authPageAt(normalizePath(url.pathname), config.authBase) === null;
54
65
  if (flagsNeeded && get(client.flags.status) !== 'ready')
55
66
  await within(client.flags.load(), READY_WAIT_MS);
56
- return decide(config, {
67
+ const input = {
57
68
  path: url.pathname,
58
69
  target: `${normalizePath(url.pathname)}${url.search}`,
59
70
  session: client.session.get(),
60
71
  flags: client.flags,
61
72
  returnTo: readReturnTo(url, config.returnToParam),
62
- });
73
+ };
74
+ const decision = decide(config, input);
75
+ if (decision.type !== 'redirect' || decision.reason !== 'paywall')
76
+ return decision;
77
+ return (await lockedNow(client)) ? decide(config, { ...input, locked: true }) : decision;
63
78
  }
64
79
  /**
65
80
  * Makes the root layout's load function. Set `export const ssr = false`
@@ -6,6 +6,10 @@
6
6
  *
7
7
  * It fails closed: while Bridge cannot be reached, a protected page sends
8
8
  * the visitor to sign-in, and a flag that has no result is off.
9
+ *
10
+ * The paywall is for a workspace that has no plan yet. A workspace locked for
11
+ * payment keeps its page: it can still be read, and the lock screen covers it
12
+ * where the person is (`<BillingNotice mode="hard">`), as in 0.9.
9
13
  */
10
14
  import { type SessionState } from '@nebulr-group/bridge-auth-core';
11
15
  import type { FlagRequirement, ResolvedConfig, RouteRule } from './config.js';
@@ -46,6 +50,8 @@ export interface GuardInput {
46
50
  readonly flags: FlagReader;
47
51
  /** The return address already on the URL, on an auth page. */
48
52
  readonly returnTo: string | null;
53
+ /** Whether the workspace is locked for payment: then the page stays and shows the lock, rather than the paywall. */
54
+ readonly locked?: boolean;
49
55
  }
50
56
  /** Decides one navigation. */
51
57
  export declare function decide(config: ResolvedConfig, given: GuardInput): GuardDecision;
@@ -6,6 +6,10 @@
6
6
  *
7
7
  * It fails closed: while Bridge cannot be reached, a protected page sends
8
8
  * the visitor to sign-in, and a flag that has no result is off.
9
+ *
10
+ * The paywall is for a workspace that has no plan yet. A workspace locked for
11
+ * payment keeps its page: it can still be read, and the lock screen covers it
12
+ * where the person is (`<BillingNotice mode="hard">`), as in 0.9.
9
13
  */
10
14
  import { sanitizeReturnTo, withReturnTo } from '@nebulr-group/bridge-auth-core';
11
15
  import { authPageAt, isUnder } from './routes.js';
@@ -78,7 +82,7 @@ export function decide(config, given) {
78
82
  return { type: 'redirect', to, reason: 'flag' };
79
83
  }
80
84
  const billingPage = isUnder(input.path, config.billingBase);
81
- if (signedIn && !isPublic && !billingPage && config.paywall !== null && !input.flags.enabled(config.flagKeys.appActive)) {
85
+ if (signedIn && !isPublic && !billingPage && config.paywall !== null && input.locked !== true && !input.flags.enabled(config.flagKeys.appActive)) {
82
86
  if (config.paywall === input.path)
83
87
  return { type: 'allow' };
84
88
  return { type: 'redirect', to: withReturnTo(config.paywall, input.target, config.returnToParam), reason: 'paywall' };
@@ -14,14 +14,18 @@
14
14
  * export const handle = bridgeHandle({ issuer: pub.PUBLIC_BRIDGE_ISSUER, appKey: env.BRIDGE_APP_KEY });
15
15
  *
16
16
  * // src/routes/api/reports/+server.ts
17
- * import { requireActor, meter } from '@nebulr-group/bridge-svelte/server';
17
+ * import { requireFlag, meter } from '@nebulr-group/bridge-svelte/server';
18
18
  * export const POST = async (event) => {
19
- * const actor = requireActor(event);
19
+ * const actor = await requireFlag(event, 'reports'); // a person, or a key the flag's rule lets in
20
20
  * meter(event, 'reports');
21
21
  * ...
22
22
  * };
23
23
  * ```
24
24
  *
25
+ * A request that comes with a Bridge key is protected by default: it reaches
26
+ * an endpoint only through `requireFlag` (the key must match the flag's rule),
27
+ * or one marked open with `requireActor(event, { openToKeys: true })`.
28
+ *
25
29
  * Token checks follow the app's revocation list, so a session that ended or
26
30
  * a member who was removed is refused within seconds. While Bridge cannot be
27
31
  * checked, the answer is 503, never yes.
@@ -32,7 +36,11 @@ export type { Actor, BridgeServerOptions };
32
36
  export { FlagSet };
33
37
  /** What `bridgeHandle` puts on `event.locals.bridge`. */
34
38
  export interface BridgeLocals {
35
- /** Who called: the person or key behind the request's credential, or null when it carried none. */
39
+ /**
40
+ * Who called: the person or key behind the request's credential, or null
41
+ * when it carried none. A key is null here until the endpoint lets keys in
42
+ * with `requireFlag` or `requireActor(event, { openToKeys: true })`.
43
+ */
36
44
  readonly actor: Actor | null;
37
45
  /** The caller's flag results, worked out by Bridge. Fetched once per request, when first asked. */
38
46
  flags(hints?: Readonly<Record<string, Hint>>): Promise<FlagSet>;
@@ -69,8 +77,25 @@ export interface BridgeHandleOptions extends BridgeServerOptions {
69
77
  * a route with `requireActor`, and leave routes out with `skip`.
70
78
  */
71
79
  export declare function bridgeHandle(options: BridgeHandleOptions): Handle;
72
- /** The caller, or a 401 when the request carried no credential. */
73
- export declare function requireActor(event: Pick<RequestEvent, 'locals'>): Actor;
80
+ /**
81
+ * The caller, or a 401 when the request carried no credential.
82
+ *
83
+ * A request that came with a Bridge key is refused 403 unless the endpoint
84
+ * says keys may come in: pass `{ openToKeys: true }` for an endpoint that is
85
+ * open to every valid key, or gate it with `requireFlag`. People are
86
+ * unaffected.
87
+ */
88
+ export declare function requireActor(event: Pick<RequestEvent, 'locals'>, options?: {
89
+ readonly openToKeys?: boolean;
90
+ }): Actor;
91
+ /**
92
+ * The caller, once the flag is on for them: a 401 when the request carried no
93
+ * credential, a 403 when the flag is off. Bridge works the flag out for the
94
+ * caller. For a key, rules on the key's privileges apply, so only a key whose
95
+ * privileges match the flag's rule gets in; this is what lets a key through
96
+ * an endpoint. Fails closed: while Bridge cannot answer, every flag is off.
97
+ */
98
+ export declare function requireFlag(event: Pick<RequestEvent, 'locals'>, flag: string, hints?: Readonly<Record<string, Hint>>): Promise<Actor>;
74
99
  /** Counts usage of a metric for the caller's workspace ("count this"). Needs the app key in `bridgeHandle`. */
75
100
  export declare function meter(event: Pick<RequestEvent, 'locals'>, metric: string, quantity?: number, options?: {
76
101
  readonly id?: string;
@@ -14,14 +14,18 @@
14
14
  * export const handle = bridgeHandle({ issuer: pub.PUBLIC_BRIDGE_ISSUER, appKey: env.BRIDGE_APP_KEY });
15
15
  *
16
16
  * // src/routes/api/reports/+server.ts
17
- * import { requireActor, meter } from '@nebulr-group/bridge-svelte/server';
17
+ * import { requireFlag, meter } from '@nebulr-group/bridge-svelte/server';
18
18
  * export const POST = async (event) => {
19
- * const actor = requireActor(event);
19
+ * const actor = await requireFlag(event, 'reports'); // a person, or a key the flag's rule lets in
20
20
  * meter(event, 'reports');
21
21
  * ...
22
22
  * };
23
23
  * ```
24
24
  *
25
+ * A request that comes with a Bridge key is protected by default: it reaches
26
+ * an endpoint only through `requireFlag` (the key must match the flag's rule),
27
+ * or one marked open with `requireActor(event, { openToKeys: true })`.
28
+ *
25
29
  * Token checks follow the app's revocation list, so a session that ended or
26
30
  * a member who was removed is refused within seconds. While Bridge cannot be
27
31
  * checked, the answer is 503, never yes.
@@ -47,6 +51,11 @@ function serverFor(options) {
47
51
  }
48
52
  return server;
49
53
  }
54
+ /** A key's caller: anything that is neither a person nor a job. A kind added later is protected too. */
55
+ function isKey(actor) {
56
+ return actor.kind !== 'person' && actor.kind !== 'job';
57
+ }
58
+ const states = new WeakMap();
50
59
  const WRITES = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
51
60
  /** The `iss` of a JWT, read without checking it, or null for anything that is not one. */
52
61
  function issuerOf(token) {
@@ -100,19 +109,29 @@ export function bridgeHandle(options) {
100
109
  actor = checked.actor;
101
110
  }
102
111
  let flags = null;
112
+ const state = { actor, admitted: actor === null || !isKey(actor) };
103
113
  const locals = {
104
- actor,
114
+ get actor() {
115
+ return state.admitted ? state.actor : null;
116
+ },
105
117
  server,
106
118
  flags(hints) {
119
+ // A credential nothing checked (a `skip` route) is never forwarded: it may be a key
120
+ // from someone else's Bridge app, and that app's flag results would come back.
121
+ if (actor === null && carriesBridgeCredential(event.request, options.issuer))
122
+ return Promise.resolve(new FlagSet());
107
123
  flags ??= server.flags.forRequest(event.request, hints).catch(() => new FlagSet());
108
124
  return flags;
109
125
  },
110
126
  meter(metric, quantity, countOptions) {
111
- if (actor === null)
127
+ if (state.actor === null)
112
128
  throw new Error('[bridge] meter() needs a signed-in caller: check with requireActor first.');
113
- server.usage.count(actor, metric, quantity, countOptions);
129
+ if (!state.admitted)
130
+ error(403, KEY_REFUSAL);
131
+ server.usage.count(state.actor, metric, quantity, countOptions);
114
132
  },
115
133
  };
134
+ states.set(locals, state);
116
135
  event.locals.bridge = locals;
117
136
  return resolve(event);
118
137
  };
@@ -123,12 +142,45 @@ function localsOf(event) {
123
142
  throw new Error('[bridge] No Bridge on this request. Add `export const handle = bridgeHandle({ ... })` to hooks.server.ts.');
124
143
  return locals;
125
144
  }
126
- /** The caller, or a 401 when the request carried no credential. */
127
- export function requireActor(event) {
128
- const { actor } = localsOf(event);
129
- if (actor === null)
145
+ const KEY_REFUSAL = 'This endpoint is not open to keys. Gate it with requireFlag, or mark it open with requireActor(event, { openToKeys: true }).';
146
+ function stateOf(event) {
147
+ return states.get(localsOf(event));
148
+ }
149
+ /**
150
+ * The caller, or a 401 when the request carried no credential.
151
+ *
152
+ * A request that came with a Bridge key is refused 403 unless the endpoint
153
+ * says keys may come in: pass `{ openToKeys: true }` for an endpoint that is
154
+ * open to every valid key, or gate it with `requireFlag`. People are
155
+ * unaffected.
156
+ */
157
+ export function requireActor(event, options = {}) {
158
+ const state = stateOf(event);
159
+ if (state.actor === null)
160
+ error(401, 'Sign in first.');
161
+ if (!state.admitted) {
162
+ if (options.openToKeys !== true)
163
+ error(403, KEY_REFUSAL);
164
+ state.admitted = true;
165
+ }
166
+ return state.actor;
167
+ }
168
+ /**
169
+ * The caller, once the flag is on for them: a 401 when the request carried no
170
+ * credential, a 403 when the flag is off. Bridge works the flag out for the
171
+ * caller. For a key, rules on the key's privileges apply, so only a key whose
172
+ * privileges match the flag's rule gets in; this is what lets a key through
173
+ * an endpoint. Fails closed: while Bridge cannot answer, every flag is off.
174
+ */
175
+ export async function requireFlag(event, flag, hints) {
176
+ const state = stateOf(event);
177
+ if (state.actor === null)
130
178
  error(401, 'Sign in first.');
131
- return actor;
179
+ const flags = await localsOf(event).flags(hints);
180
+ if (!flags.enabled(flag))
181
+ error(403, 'Not available.');
182
+ state.admitted = true;
183
+ return state.actor;
132
184
  }
133
185
  /** Counts usage of a metric for the caller's workspace ("count this"). Needs the app key in `bridgeHandle`. */
134
186
  export function meter(event, metric, quantity, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nebulr-group/bridge-svelte",
3
- "version": "1.0.0-alpha.13",
3
+ "version": "1.0.0-alpha.15",
4
4
  "description": "The Bridge for SvelteKit: sign-in in your own pages, workspaces, flag-based route guards, plans and checkout, the team panel and live updates, on one setting: the issuer.",
5
5
  "author": "Iman Pouya",
6
6
  "license": "MIT",
@@ -60,7 +60,7 @@
60
60
  "@sveltejs/kit": "^2.0.0"
61
61
  },
62
62
  "dependencies": {
63
- "@nebulr-group/bridge-auth-core": "1.0.0-alpha.11"
63
+ "@nebulr-group/bridge-auth-core": "1.0.0-alpha.13"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@sveltejs/kit": "^2.16.0",