@deslop/auth 0.1.1268 → 0.1.1272

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/dist/server.js CHANGED
@@ -5700,6 +5700,28 @@ const toSeconds = (self) => match$7(fromInputUnsafe$1(self), {
5700
5700
  onNegativeInfinity: () => -Infinity
5701
5701
  });
5702
5702
  /**
5703
+ * Converts a Duration to minutes.
5704
+ *
5705
+ * **Example** (Converting durations to minutes)
5706
+ *
5707
+ * ```ts import.meta.vitest
5708
+ * import { Duration } from "effect"
5709
+ *
5710
+ * Duration.toMinutes(Duration.seconds(120)) // => 2
5711
+ * Duration.toMinutes(Duration.hours(1)) // => 60
5712
+ * ```
5713
+ *
5714
+ * @stability stable
5715
+ * @category getters
5716
+ * @since 3.8.0
5717
+ */
5718
+ const toMinutes = (self) => match$7(fromInputUnsafe$1(self), {
5719
+ onMillis: (millis) => millis / 6e4,
5720
+ onNanos: (nanos) => nanosToUnit(nanos, 6e10),
5721
+ onInfinity: () => Infinity,
5722
+ onNegativeInfinity: () => -Infinity
5723
+ });
5724
+ /**
5703
5725
  * Gets the duration in nanoseconds as a bigint.
5704
5726
  *
5705
5727
  * **When to use**
@@ -89617,7 +89639,6 @@ var AuthError = class extends TaggedError()("AuthError", {
89617
89639
  "invalid_client_metadata",
89618
89640
  "invalid_redirect_uri",
89619
89641
  "invalid_grant",
89620
- "invalid_target",
89621
89642
  "invalid_scope",
89622
89643
  "unsupported_grant_type",
89623
89644
  "unsupported_response_type",
@@ -90411,6 +90432,12 @@ function layerOtlp(serviceName, url, runtime, version) {
90411
90432
  const AUTH_URL = "https://auth.mp281x.xyz";
90412
90433
  const ISSUER_PATH = "/api/auth";
90413
90434
  const APPS_PATH = "/api/apps";
90435
+ const COOKIE = {
90436
+ httpOnly: true,
90437
+ path: "/",
90438
+ sameSite: "lax",
90439
+ secure: true
90440
+ };
90414
90441
  const SESSION_COOKIE = "__Host-session";
90415
90442
  function matchingSessions(saved, userId) {
90416
90443
  return sort(filter$6(getSomes(saved), (session) => session.value.user.id === userId), mapInput(flip$1(Number$6), (session) => session.value.expiresAt));
@@ -91926,13 +91953,6 @@ function layerMcpAuth(resource) {
91926
91953
  // ../../packages/runtime/src/server.ts
91927
91954
  const LOOPBACK = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/iu;
91928
91955
  const OTLP = ["/v1/traces", "/v1/logs"];
91929
- const COOKIE$1 = {
91930
- httpOnly: true,
91931
- path: "/",
91932
- sameSite: "lax",
91933
- secure: true
91934
- };
91935
- const SIGN_IN_COOKIE = "__Host-sign-in";
91936
91956
  const packageRoot = match$1(endsWith(".ts")(import.meta.url), {
91937
91957
  onFalse: () => fileURLToPath(new URL("..", import.meta.url)),
91938
91958
  onTrue: cwd
@@ -92067,112 +92087,6 @@ const layerRoutes = use((router) => gen(function* () {
92067
92087
  }, { headers: { "cache-control": "no-store" } });
92068
92088
  }));
92069
92089
  }));
92070
- const SignInState = fromJsonString(Struct({
92071
- next: String$6,
92072
- state: String$6,
92073
- verifier: String$6
92074
- }));
92075
- const CallbackParams$1 = Struct({
92076
- code: optionalKey(String$6),
92077
- error: optionalKey(String$6),
92078
- iss: optionalKey(String$6),
92079
- state: optionalKey(String$6)
92080
- });
92081
- function signedOut(next, cause) {
92082
- return as(logWarning("The sign-in did not complete", cause), expireCookieUnsafe(redirect(next), SIGN_IN_COOKIE, COOKIE$1));
92083
- }
92084
- function layerSignIn(issuer) {
92085
- return use((router) => gen(function* () {
92086
- const sessions = yield* Sessions;
92087
- const random = yield* SecureRandom;
92088
- const digest = yield* Digest;
92089
- const canonical = new URL(yield* String$5("APP_URL")).origin;
92090
- const callback = new URL(CALLBACK_PATH, canonical).href;
92091
- const clientId = yield* cached(map$5(appName, (name) => clientIdOf({
92092
- name: capitalize(name),
92093
- redirects: [callback]
92094
- })));
92095
- function ended(headers) {
92096
- return match$8(sessionIdOf(headers), {
92097
- onNone: () => void_$1,
92098
- onSome: (id) => ignore$1(sessions.end(id), {
92099
- log: "Warn",
92100
- message: "The session could not be ended"
92101
- })
92102
- });
92103
- }
92104
- function toNext(handle) {
92105
- return flatMap$2(HttpServerRequest, (request) => match$8(filter$8(liftThrowable(() => new URL(new URL(request.url, canonical).searchParams.get("next") ?? canonical, canonical))(), (next) => next.origin === canonical), {
92106
- onNone: () => succeed$5(empty({ status: 400 })),
92107
- onSome: (next) => handle(request, next)
92108
- }));
92109
- }
92110
- yield* router.add("GET", "/auth/sign-in", toNext(fnUntraced(function* (_, next) {
92111
- const verifier = encode$3(yield* random.randomBytes(32));
92112
- const state = encode$3(yield* random.randomBytes(16));
92113
- const authorize = new URL(AUTHORIZE_PATH, issuer);
92114
- authorize.search = `${new URLSearchParams({
92115
- client_id: yield* clientId,
92116
- code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
92117
- code_challenge_method: "S256",
92118
- redirect_uri: callback,
92119
- response_type: "code",
92120
- scope: "deslop offline_access",
92121
- state
92122
- })}`;
92123
- return setCookieUnsafe(redirect(authorize.href), SIGN_IN_COOKIE, yield* encodeEffect(SignInState)({
92124
- next: next.href,
92125
- state,
92126
- verifier
92127
- }), {
92128
- ...COOKIE$1,
92129
- maxAge: "10 minutes"
92130
- });
92131
- })));
92132
- yield* router.add("GET", CALLBACK_PATH, gen(function* () {
92133
- const request = yield* HttpServerRequest;
92134
- return yield* match$8(yield* option$1(decodeUnknownEffect(SignInState)(request.cookies[SIGN_IN_COOKIE])), {
92135
- onNone: () => signedOut(canonical, "The sign-in expired or began in another browser"),
92136
- onSome: fnUntraced(function* (saved) {
92137
- const started = yield* result$1(gen(function* () {
92138
- const params = yield* schemaSearchParams(CallbackParams$1);
92139
- if (params.state !== saved.state) return yield* AuthError.make({ message: "The sign-in began in another browser" });
92140
- if (params.error !== void 0 || params.code === void 0) return yield* AuthError.make({ message: `Auth answered ${params.error ?? "without a code"}` });
92141
- if (params.iss !== new URL("/api/auth", issuer).href) return yield* AuthError.make({ message: "The answer came from another issuer" });
92142
- return yield* sessions.start({
92143
- client_id: yield* clientId,
92144
- code: params.code,
92145
- code_verifier: saved.verifier,
92146
- redirect_uri: callback
92147
- });
92148
- }));
92149
- if (isFailure$1(started)) return yield* signedOut(saved.next, started.failure);
92150
- return pipe(redirect(saved.next), expireCookieUnsafe(SIGN_IN_COOKIE, COOKIE$1), setCookieUnsafe(SESSION_COOKIE, started.success, {
92151
- ...COOKIE$1,
92152
- maxAge: "365 days"
92153
- }));
92154
- })
92155
- });
92156
- }));
92157
- yield* router.add("POST", "/auth/session", gen(function* () {
92158
- const started = yield* result$1(pipe(schemaBodyJson(CodeGrant), rejected("The sign-in request is invalid"), flatMap$2(sessions.start)));
92159
- if (isFailure$1(started)) return text(started.failure.message, failureOptions(started.failure, 400));
92160
- return yield* schemaJson(SessionHandle)({ session: started.success }, { headers: { "cache-control": "no-store" } });
92161
- }));
92162
- yield* router.add("GET", "/auth/sign-out", toNext((request, next) => as(ended(request.headers), expireCookieUnsafe(redirect(`${new URL("/", issuer).href}?${new URLSearchParams({
92163
- next: next.href,
92164
- "sign-out": ""
92165
- })}`), SESSION_COOKIE, COOKIE$1))));
92166
- yield* router.add("POST", "/auth/sign-out", as(flatMap$2(HttpServerRequest, (request) => ended(request.headers)), empty({ status: 204 })));
92167
- }));
92168
- }
92169
- const notConfigured = text("Sign-in is not configured for this app", { status: 503 });
92170
- const layerSessionRoutes = unwrap$7(gen(function* () {
92171
- return match$8(yield* option(String$5("AUTH_URL")), {
92172
- onNone: () => mergeAll$1(add("GET", "/auth/sign-in", notConfigured), add("GET", "/auth/sign-out", notConfigured)),
92173
- onSome: layerSignIn
92174
- });
92175
- }));
92176
92090
  const layerAnnounce = effectDiscard(gen(function* () {
92177
92091
  const origin = new URL(yield* String$5("APP_URL")).origin;
92178
92092
  const client = pipe(yield* HttpClient, filterStatusOk, timeout("10 seconds"), retryTransient({
@@ -92302,6 +92216,113 @@ var AiGateway = class AiGateway extends Service$1()("@deslop/runtime/ai/service/
92302
92216
  });
92303
92217
  }));
92304
92218
  };
92219
+ // ../../packages/runtime/src/auth/routes.ts
92220
+ const SIGN_IN_COOKIE = "__Host-sign-in";
92221
+ const SignInState = fromJsonString(Struct({
92222
+ next: String$6,
92223
+ state: String$6,
92224
+ verifier: String$6
92225
+ }));
92226
+ const CallbackParams$1 = Struct({
92227
+ code: optionalKey(String$6),
92228
+ error: optionalKey(String$6),
92229
+ iss: optionalKey(String$6),
92230
+ state: optionalKey(String$6)
92231
+ });
92232
+ function signedOut(next, cause) {
92233
+ return as(logWarning("The sign-in did not complete", cause), expireCookieUnsafe(redirect(next), SIGN_IN_COOKIE, COOKIE));
92234
+ }
92235
+ function layerSignIn(issuer) {
92236
+ return use((router) => gen(function* () {
92237
+ const sessions = yield* Sessions;
92238
+ const random = yield* SecureRandom;
92239
+ const digest = yield* Digest;
92240
+ const canonical = new URL(yield* String$5("APP_URL")).origin;
92241
+ const callback = new URL(CALLBACK_PATH, canonical).href;
92242
+ const clientId = yield* cached(map$5(appName, (name) => clientIdOf({
92243
+ name: capitalize(name),
92244
+ redirects: [callback]
92245
+ })));
92246
+ function ended(headers) {
92247
+ return match$8(sessionIdOf(headers), {
92248
+ onNone: () => void_$1,
92249
+ onSome: (id) => ignore$1(sessions.end(id), {
92250
+ log: "Warn",
92251
+ message: "The session could not be ended"
92252
+ })
92253
+ });
92254
+ }
92255
+ function toNext(handle) {
92256
+ return flatMap$2(HttpServerRequest, (request) => match$8(filter$8(liftThrowable(() => new URL(new URL(request.url, canonical).searchParams.get("next") ?? canonical, canonical))(), (next) => next.origin === canonical), {
92257
+ onNone: () => succeed$5(empty({ status: 400 })),
92258
+ onSome: (next) => handle(request, next)
92259
+ }));
92260
+ }
92261
+ yield* router.add("GET", "/auth/sign-in", toNext(fnUntraced(function* (_, next) {
92262
+ const verifier = encode$3(yield* random.randomBytes(32));
92263
+ const state = encode$3(yield* random.randomBytes(16));
92264
+ const authorize = new URL(AUTHORIZE_PATH, issuer);
92265
+ authorize.search = `${new URLSearchParams({
92266
+ client_id: yield* clientId,
92267
+ code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
92268
+ code_challenge_method: "S256",
92269
+ redirect_uri: callback,
92270
+ response_type: "code",
92271
+ scope: "deslop offline_access",
92272
+ state
92273
+ })}`;
92274
+ return setCookieUnsafe(redirect(authorize.href), SIGN_IN_COOKIE, yield* encodeEffect(SignInState)({
92275
+ next: next.href,
92276
+ state,
92277
+ verifier
92278
+ }), {
92279
+ ...COOKIE,
92280
+ maxAge: "10 minutes"
92281
+ });
92282
+ })));
92283
+ yield* router.add("GET", CALLBACK_PATH, gen(function* () {
92284
+ const request = yield* HttpServerRequest;
92285
+ return yield* match$8(yield* option$1(decodeUnknownEffect(SignInState)(request.cookies[SIGN_IN_COOKIE])), {
92286
+ onNone: () => signedOut(canonical, "The sign-in expired or began in another browser"),
92287
+ onSome: fnUntraced(function* (saved) {
92288
+ const started = yield* result$1(gen(function* () {
92289
+ const params = yield* schemaSearchParams(CallbackParams$1);
92290
+ if (params.state !== saved.state) return yield* AuthError.make({ message: "The sign-in began in another browser" });
92291
+ if (params.error !== void 0 || params.code === void 0) return yield* AuthError.make({ message: `Auth answered ${params.error ?? "without a code"}` });
92292
+ if (params.iss !== new URL("/api/auth", issuer).href) return yield* AuthError.make({ message: "The answer came from another issuer" });
92293
+ return yield* sessions.start({
92294
+ client_id: yield* clientId,
92295
+ code: params.code,
92296
+ code_verifier: saved.verifier,
92297
+ redirect_uri: callback
92298
+ });
92299
+ }));
92300
+ if (isFailure$1(started)) return yield* signedOut(saved.next, started.failure);
92301
+ return pipe(redirect(saved.next), expireCookieUnsafe(SIGN_IN_COOKIE, COOKIE), setCookieUnsafe(SESSION_COOKIE, started.success, {
92302
+ ...COOKIE,
92303
+ maxAge: "365 days"
92304
+ }));
92305
+ })
92306
+ });
92307
+ }));
92308
+ yield* router.add("POST", "/auth/session", gen(function* () {
92309
+ const started = yield* result$1(pipe(schemaBodyJson(CodeGrant), rejected("The sign-in request is invalid"), flatMap$2(sessions.start)));
92310
+ if (isFailure$1(started)) return text(started.failure.message, failureOptions(started.failure, 400));
92311
+ return yield* schemaJson(SessionHandle)({ session: started.success }, { headers: { "cache-control": "no-store" } });
92312
+ }));
92313
+ yield* router.add("GET", "/auth/sign-out", toNext((request, next) => as(ended(request.headers), expireCookieUnsafe(redirect(`${new URL("/", issuer).href}?${new URLSearchParams({
92314
+ next: next.href,
92315
+ "sign-out": ""
92316
+ })}`), SESSION_COOKIE, COOKIE))));
92317
+ yield* router.add("POST", "/auth/sign-out", as(flatMap$2(HttpServerRequest, (request) => ended(request.headers)), empty({ status: 204 })));
92318
+ }));
92319
+ }
92320
+ const layerSessionRoutes = unwrap$7(gen(function* () {
92321
+ return match$8(yield* option(String$5("AUTH_URL")), {
92322
+ onNone: () => empty$11,
92323
+ onSome: layerSignIn
92324
+ });
92325
+ }));
92305
92326
  // ../../packages/runtime/src/cli/schema.ts
92306
92327
  var AppError = class extends TaggedError()("AppError", {
92307
92328
  cause: optional$8(Defect()),
@@ -92535,7 +92556,6 @@ function runApp(app) {
92535
92556
  // src/services/apps/schema.ts
92536
92557
  const App = Struct({
92537
92558
  name: NonEmptyString,
92538
- open: NonEmptyString,
92539
92559
  origin: SecureOrigin
92540
92560
  });
92541
92561
  const Catalog = ArraySchema(App);
@@ -92564,16 +92584,8 @@ var Apps = class Apps extends Service$1()("@deslop/auth/services/apps/service/Ap
92564
92584
  error: "access_denied",
92565
92585
  message: `${origin} signs in elsewhere`
92566
92586
  });
92567
- const web = yield* pipe(client.get(new URL(MANIFEST_PATH, origin).href), flatMap$2((response) => {
92568
- if (response.status === 404) return succeed$5(false);
92569
- return as(filterStatusOk$1(response), true);
92570
- }), timeout$1("10 seconds"), rejected(`${origin} did not answer ${MANIFEST_PATH}`));
92571
92587
  const app = App.make({
92572
92588
  name: runtime.name,
92573
- open: match$1(web, {
92574
- onFalse: () => `${runtime.name}://`,
92575
- onTrue: () => new URL(origin).origin
92576
- }),
92577
92589
  origin: new URL(origin).origin
92578
92590
  });
92579
92591
  yield* pipe(updateEffect(state, (current) => {
@@ -92677,10 +92689,10 @@ const SessionVia = Literals([
92677
92689
  "GitHub",
92678
92690
  "Passkey"
92679
92691
  ]);
92692
+ const StoredOrigin = Struct({ address: optionalKey(String$6) });
92680
92693
  const Grants = Record$1(String$6, Struct({
92681
92694
  ...CredentialOwner.fields,
92682
92695
  client: String$6,
92683
- createdAt: Finite,
92684
92696
  credential: TaggedUnion({
92685
92697
  App: {
92686
92698
  clientId: NonEmptyString,
@@ -92697,21 +92709,18 @@ const Grants = Record$1(String$6, Struct({
92697
92709
  }),
92698
92710
  device: String$6,
92699
92711
  lastActive: Finite,
92700
- origin: Origin,
92712
+ origin: StoredOrigin,
92701
92713
  parent: optionalKey(NonEmptyString)
92702
92714
  }));
92703
92715
  const SignedInApp = Struct({
92704
92716
  address: optionalKey(String$6),
92705
92717
  client: String$6,
92706
- createdAt: Finite,
92707
92718
  device: String$6,
92708
- expiresAt: Finite,
92709
92719
  family: NonEmptyString,
92710
92720
  kind: Literals(["App", "Browser"]),
92711
92721
  lastActive: Finite,
92712
92722
  parent: optionalKey(NonEmptyString)
92713
92723
  });
92714
- Struct({ family: NonEmptyString });
92715
92724
  const RevokeParams = Struct({
92716
92725
  client_id: NonEmptyString,
92717
92726
  token: NonEmptyString
@@ -92753,7 +92762,195 @@ const AdmitParams = Struct({
92753
92762
  allow: Boolean$5,
92754
92763
  id: NonEmptyString
92755
92764
  });
92756
- Struct({ id: NonEmptyString });
92765
+ // src/services/tokens/lib/utils.ts
92766
+ const WORKERS = {
92767
+ "77.237.236.132": "dev",
92768
+ "100.68.201.107": "dev",
92769
+ "100.97.120.3": "desktop",
92770
+ "100.115.207.60": "macbook-pro"
92771
+ };
92772
+ function browserToken(headers) {
92773
+ return parseHeader(headers["cookie"] ?? "")["__Host-session"] ?? "";
92774
+ }
92775
+ function sameOwner(left, right) {
92776
+ return left.user.id === right.user.id && left.incarnation === right.incarnation;
92777
+ }
92778
+ function storedOrigin(origin) {
92779
+ return match$8(fromUndefinedOr(origin.address), {
92780
+ onNone: () => ({}),
92781
+ onSome: (address) => ({ address })
92782
+ });
92783
+ }
92784
+ function randomTokenOf(random) {
92785
+ return (bytes) => map$5(random.randomBytes(bytes), encode$3);
92786
+ }
92787
+ function hashOf(digest) {
92788
+ return (value) => map$5(digest.digest(sha256, new TextEncoder().encode(value)), encode$3);
92789
+ }
92790
+ function live$1(grants, now) {
92791
+ const current = filter$7(grants, (grant) => grant.credential.expiresAt > now);
92792
+ return filter$7(current, (grant) => grant.parent === void 0 || exists(get$13(current, grant.parent), (parent) => parent.credential._tag === "Browser"));
92793
+ }
92794
+ function signedInApps(grants, now, owner) {
92795
+ return pipe(toEntries(live$1(grants, now)), filter$6((entry) => sameOwner(entry[1], owner)), map$8((entry) => ({
92796
+ client: entry[1].client,
92797
+ device: entry[1].device,
92798
+ family: entry[0],
92799
+ kind: entry[1].credential._tag,
92800
+ lastActive: entry[1].lastActive,
92801
+ ...pick(entry[1], ["parent"]),
92802
+ ...match$8(fromUndefinedOr(entry[1].origin.address), {
92803
+ onNone: () => ({}),
92804
+ onSome: (address) => ({ address })
92805
+ })
92806
+ })), sort(flip$1(mapInput(Number$6, (app) => app.lastActive))));
92807
+ }
92808
+ function withChildActivity(signIns) {
92809
+ const children = groupBy(filter$6(signIns, (signIn) => signIn.parent !== void 0), (signIn) => signIn.parent ?? "");
92810
+ return map$8(filter$6(signIns, (signIn) => signIn.parent === void 0), (signIn) => {
92811
+ const latest = reduce(getOrElse(get$13(children, signIn.family), () => []), signIn, max$2(mapInput(Number$6, (app) => app.lastActive)));
92812
+ return {
92813
+ ...omit(signIn, ["address"]),
92814
+ lastActive: latest.lastActive,
92815
+ ...pick(latest, ["address"])
92816
+ };
92817
+ });
92818
+ }
92819
+ function parsedAddress(address) {
92820
+ return pipe(getSuccess(ipFromString(address)), map$11((ip) => {
92821
+ if (isIpv6Address(ip)) return getOrElse(fromIpv4Mapped(ip), () => ip);
92822
+ return ip;
92823
+ }));
92824
+ }
92825
+ function isPrivateOrUniqueLocal(ip) {
92826
+ if (isIpv4Address(ip)) return isPrivate(ip);
92827
+ return isUniqueLocal(ip);
92828
+ }
92829
+ function addressGroup(address) {
92830
+ return match$8(parsedAddress(address), {
92831
+ onNone: () => address,
92832
+ onSome: (ip) => {
92833
+ if (isIpv4Address(ip)) return formatIp(ip);
92834
+ return join$2(map$8(take$3(ipv6ToSegments(ip), 4), (segment) => segment.toString(16)), ":");
92835
+ }
92836
+ });
92837
+ }
92838
+ function clientAddress(headers, remote) {
92839
+ return pipe(get$6(headers, "x-forwarded-for"), flatMap$7((forwarded) => last(split$2(",")(forwarded))), map$11(trim), filter$8(isNonEmpty$1), orElse$3(() => remote));
92840
+ }
92841
+ function originFrom(headers, remote) {
92842
+ return {
92843
+ ...match$8(clientAddress(headers, remote), {
92844
+ onNone: () => ({}),
92845
+ onSome: (address) => ({ address })
92846
+ }),
92847
+ ...match$8(get$6(headers, "user-agent"), {
92848
+ onNone: () => ({}),
92849
+ onSome: (agent) => ({ userAgent: slice$1(0, 200)(agent) })
92850
+ })
92851
+ };
92852
+ }
92853
+ function clientLabel(name) {
92854
+ return pipe(name, replace(/\s*\([^)]*\)$/u, ""), trim, capitalize, liftPredicate(isNonEmpty$1), getOrElse(() => "Unknown client"));
92855
+ }
92856
+ function platform(userAgent) {
92857
+ if (includes("iPhone")(userAgent)) return some$1("iPhone");
92858
+ if (includes("iPad")(userAgent)) return some$1("iPad");
92859
+ if (includes("CFNetwork/")(userAgent)) return some$1("iPhone");
92860
+ if (includes("Android")(userAgent)) return some$1("Android");
92861
+ if (includes("Macintosh")(userAgent)) return some$1("Mac");
92862
+ if (includes("Windows")(userAgent)) return some$1("Windows");
92863
+ if (includes("Linux")(userAgent)) return some$1("Linux");
92864
+ return none();
92865
+ }
92866
+ function browserLabel(origin) {
92867
+ const agent = origin.userAgent ?? "";
92868
+ if (includes("Edg/")(agent)) return "Edge";
92869
+ if (includes("Firefox/")(agent)) return "Firefox";
92870
+ if (includes("Chrome/")(agent)) return "Chrome";
92871
+ if (includes("Safari/")(agent)) return "Safari";
92872
+ return "Browser";
92873
+ }
92874
+ function deviceLabel(origin) {
92875
+ return pipe(flatMap$7(fromUndefinedOr(origin.address), (address) => {
92876
+ if (exists(parsedAddress(address), (ip) => isLinkLocal(ip) || isLoopback(ip) || isPrivateOrUniqueLocal(ip))) return some$1("dev");
92877
+ return get$13(WORKERS, address);
92878
+ }), orElse$3(() => flatMap$7(fromUndefinedOr(origin.userAgent), platform)), getOrElse(() => origin.address ?? "unknown"));
92879
+ }
92880
+ function loopback(redirect) {
92881
+ return filter$8(getSuccess(fromString(redirect)), (target) => target.protocol === "http:" && contains([
92882
+ "127.0.0.1",
92883
+ "[::1]",
92884
+ "localhost"
92885
+ ], target.hostname) && isEmpty$1(target.username) && isEmpty$1(target.password) && isEmpty$1(target.search) && isEmpty$1(target.hash));
92886
+ }
92887
+ function webRedirect(redirect) {
92888
+ return isSome(match$3(/^https:\/\/[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.mp281x\.xyz\/auth\/callback$/u)(redirect));
92889
+ }
92890
+ function allowedRedirect(redirect) {
92891
+ return webRedirect(redirect) || isSome(match$3(/^https:\/\/gateway\.mp281x\.xyz\/oauth\/callback\/[a-z0-9][a-z0-9_-]{0,23}$/u)(redirect)) || contains([
92892
+ "stash://auth/callback",
92893
+ "stash-dev://auth/callback",
92894
+ "opm://auth/callback",
92895
+ "opm-dev://auth/callback",
92896
+ "trips://auth/callback",
92897
+ "trips-dev://auth/callback"
92898
+ ], redirect) || isSome(loopback(redirect));
92899
+ }
92900
+ function clientOf(clientId) {
92901
+ return pipe(decodeString$2(clientId), getSuccess, flatMap$7(decodeUnknownOption(fromJsonString(ClientInfo))), filter$8((client) => every$1(client.redirects, allowedRedirect)));
92902
+ }
92903
+ function portless(redirect) {
92904
+ return map$11(filter$8(match$3(/^(?<origin>http:\/\/(?:127\.0\.0\.1|\[::1\]|localhost))(?::\d{1,5})?(?<rest>\/.*)?$/u)(redirect), () => isSome(loopback(redirect))), (found) => `${found.groups?.["origin"] ?? ""}${found.groups?.["rest"] ?? ""}`);
92905
+ }
92906
+ function matchingRedirect(client, requested) {
92907
+ return match$8(requested, {
92908
+ onNone: () => filter$8(head(client.redirects), () => client.redirects.length === 1),
92909
+ onSome: (asked) => as$2(findFirst(client.redirects, (redirect) => {
92910
+ if (redirect === asked) return true;
92911
+ return isSome(flatMap$7(portless(redirect), (saved) => filter$8(portless(asked), (target) => target === saved)));
92912
+ }), asked)
92913
+ });
92914
+ }
92915
+ function given(value) {
92916
+ return filter$8(fromUndefinedOr(value), isNonEmpty$1);
92917
+ }
92918
+ const clientRequest = fnUntraced(function* (asked, client, params) {
92919
+ if (isNone(given(params.response_type))) return yield* AuthError.make({ message: "Send response_type=code" });
92920
+ if (params.response_type !== "code") return yield* AuthError.make({
92921
+ error: "unsupported_response_type",
92922
+ message: "Only response_type=code is supported"
92923
+ });
92924
+ if (params.code_challenge === void 0 || params.code_challenge_method !== "S256") return yield* AuthError.make({ message: "Send a PKCE code_challenge with code_challenge_method=S256" });
92925
+ if (!every$1(filter$6(split$2(params.scope ?? "", " "), isNonEmpty$1), (scope) => scope === "deslop" || scope === "offline_access")) return yield* AuthError.make({
92926
+ error: "invalid_scope",
92927
+ message: "Only the deslop scope is supported"
92928
+ });
92929
+ return ClientRequest.make({
92930
+ challenge: params.code_challenge,
92931
+ clientId: asked.client_id,
92932
+ clientName: client.clientName,
92933
+ redirectUri: client.redirectUri,
92934
+ ...match$8(given(asked.state), {
92935
+ onNone: () => ({}),
92936
+ onSome: (state) => ({ state })
92937
+ })
92938
+ });
92939
+ });
92940
+ function callbackUrl(request, answer, issuer) {
92941
+ const target = new URL(request.redirectUri);
92942
+ for (const entry of toEntries(answer)) target.searchParams.set(entry[0], entry[1]);
92943
+ map$11(given(request.state), (sent) => target.searchParams.set("state", sent));
92944
+ target.searchParams.set("iss", issuer);
92945
+ return target.href;
92946
+ }
92947
+ function returnable(next, url) {
92948
+ const domain = "mp281x.xyz";
92949
+ return match$6(fromString(next), {
92950
+ onFailure: () => false,
92951
+ onSuccess: (target) => (target.origin === new URL(url).origin || target.protocol === "https:" && (target.hostname === domain || endsWith(`.${domain}`)(target.hostname))) && isEmpty$1(target.username) && isEmpty$1(target.password)
92952
+ });
92953
+ }
92757
92954
  // src/services/github/service.ts
92758
92955
  const HEADERS = {
92759
92956
  accept: "application/vnd.github+json",
@@ -92766,13 +92963,12 @@ const DEVELOPER_PROFILE = GitHubUser.make({
92766
92963
  });
92767
92964
  var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/service/GitHub") {
92768
92965
  static layer = effect(GitHub, gen(function* () {
92769
- const random = yield* SecureRandom;
92770
92966
  const flows = yield* make$22({
92771
92967
  capacity: 256,
92772
92968
  lookup: () => fail$8(AuthError.make({ message: "The sign-in expired" })),
92773
92969
  timeToLive: "10 minutes"
92774
92970
  });
92775
- const nonce = map$5(random.randomBytes(32), encode$3);
92971
+ const nonce = randomTokenOf(yield* SecureRandom)(32);
92776
92972
  const take = fnUntraced(function* (state) {
92777
92973
  const flow = yield* get$2(flows, state);
92778
92974
  yield* invalidate(flows, state);
@@ -92803,7 +92999,7 @@ var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/serv
92803
92999
  })
92804
93000
  });
92805
93001
  const client = filterStatusOk(yield* HttpClient);
92806
- const digest = yield* Digest;
93002
+ const hash = hashOf(yield* Digest);
92807
93003
  const provider = yield* all({
92808
93004
  clientId: String$5("GITHUB_CLIENT_ID"),
92809
93005
  secret: Redacted("GITHUB_CLIENT_SECRET")
@@ -92840,7 +93036,7 @@ var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/serv
92840
93036
  const url = new URL("https://github.com/login/oauth/authorize");
92841
93037
  url.search = toString$1(fromInput({
92842
93038
  client_id: provider.clientId,
92843
- code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
93039
+ code_challenge: yield* hash(verifier),
92844
93040
  code_challenge_method: "S256",
92845
93041
  redirect_uri: CALLBACK,
92846
93042
  state
@@ -92946,18 +93142,14 @@ const StoredPasskeys = ArraySchema(Struct({
92946
93142
  ...StoredOwner.fields,
92947
93143
  addedFrom: String$6,
92948
93144
  counter: Int$1,
92949
- createdAt: Finite,
92950
93145
  id: NonEmptyString,
92951
- lastUsed: Finite,
92952
93146
  publicKey: NonEmptyString,
92953
93147
  synced: Boolean$5,
92954
93148
  transports: ArraySchema(Transport)
92955
93149
  }));
92956
93150
  const Passkey = Struct({
92957
93151
  addedFrom: String$6,
92958
- createdAt: Finite,
92959
93152
  id: NonEmptyString,
92960
- lastUsed: Finite,
92961
93153
  synced: Boolean$5
92962
93154
  });
92963
93155
  const PasskeyParams = Struct({ id: NonEmptyString });
@@ -114442,185 +114634,6 @@ async function verifyAuthenticationResponse(options) {
114442
114634
  }
114443
114635
  };
114444
114636
  }
114445
- // src/services/tokens/lib/utils.ts
114446
- const WORKERS = {
114447
- "77.237.236.132": "dev",
114448
- "100.68.201.107": "dev",
114449
- "100.97.120.3": "desktop",
114450
- "100.115.207.60": "macbook-pro"
114451
- };
114452
- function browserToken(headers) {
114453
- return parseHeader(headers["cookie"] ?? "")["__Host-session"] ?? "";
114454
- }
114455
- function sameOwner(left, right) {
114456
- return left.user.id === right.user.id && left.incarnation === right.incarnation;
114457
- }
114458
- function live$1(grants, now) {
114459
- const current = filter$7(grants, (grant) => grant.credential.expiresAt > now);
114460
- return filter$7(current, (grant) => grant.parent === void 0 || exists(get$13(current, grant.parent), (parent) => parent.credential._tag === "Browser"));
114461
- }
114462
- function signedInApps(grants, now, owner) {
114463
- return pipe(toEntries(live$1(grants, now)), filter$6((entry) => sameOwner(entry[1], owner)), map$8((entry) => ({
114464
- client: entry[1].client,
114465
- createdAt: entry[1].createdAt,
114466
- device: entry[1].device,
114467
- expiresAt: entry[1].credential.expiresAt,
114468
- family: entry[0],
114469
- kind: entry[1].credential._tag,
114470
- lastActive: entry[1].lastActive,
114471
- ...pick(entry[1], ["parent"]),
114472
- ...match$8(fromUndefinedOr(entry[1].origin.address), {
114473
- onNone: () => ({}),
114474
- onSome: (address) => ({ address })
114475
- })
114476
- })), sort(flip$1(mapInput(Number$6, (app) => app.lastActive))));
114477
- }
114478
- function withChildActivity(signIns) {
114479
- const children = groupBy(filter$6(signIns, (signIn) => signIn.parent !== void 0), (signIn) => signIn.parent ?? "");
114480
- return map$8(filter$6(signIns, (signIn) => signIn.parent === void 0), (signIn) => {
114481
- const latest = reduce(getOrElse(get$13(children, signIn.family), () => []), signIn, max$2(mapInput(Number$6, (app) => app.lastActive)));
114482
- return {
114483
- ...omit(signIn, ["address"]),
114484
- lastActive: latest.lastActive,
114485
- ...pick(latest, ["address"])
114486
- };
114487
- });
114488
- }
114489
- function parsedAddress(address) {
114490
- return pipe(getSuccess(ipFromString(address)), map$11((ip) => {
114491
- if (isIpv6Address(ip)) return getOrElse(fromIpv4Mapped(ip), () => ip);
114492
- return ip;
114493
- }));
114494
- }
114495
- function isPrivateOrUniqueLocal(ip) {
114496
- if (isIpv4Address(ip)) return isPrivate(ip);
114497
- return isUniqueLocal(ip);
114498
- }
114499
- function addressGroup(address) {
114500
- return match$8(parsedAddress(address), {
114501
- onNone: () => address,
114502
- onSome: (ip) => {
114503
- if (isIpv4Address(ip)) return formatIp(ip);
114504
- return join$2(map$8(take$3(ipv6ToSegments(ip), 4), (segment) => segment.toString(16)), ":");
114505
- }
114506
- });
114507
- }
114508
- function clientAddress(headers, remote) {
114509
- return pipe(get$6(headers, "x-forwarded-for"), flatMap$7((forwarded) => last(split$2(",")(forwarded))), map$11(trim), filter$8(isNonEmpty$1), orElse$3(() => remote));
114510
- }
114511
- function originFrom(headers, remote) {
114512
- return {
114513
- ...match$8(clientAddress(headers, remote), {
114514
- onNone: () => ({}),
114515
- onSome: (address) => ({ address })
114516
- }),
114517
- ...match$8(get$6(headers, "user-agent"), {
114518
- onNone: () => ({}),
114519
- onSome: (agent) => ({ userAgent: slice$1(0, 200)(agent) })
114520
- })
114521
- };
114522
- }
114523
- function clientLabel(name) {
114524
- return pipe(name, replace(/\s*\([^)]*\)$/u, ""), trim, capitalize, liftPredicate(isNonEmpty$1), getOrElse(() => "Unknown client"));
114525
- }
114526
- function platform(userAgent) {
114527
- if (includes("iPhone")(userAgent)) return some$1("iPhone");
114528
- if (includes("iPad")(userAgent)) return some$1("iPad");
114529
- if (includes("CFNetwork/")(userAgent)) return some$1("iPhone");
114530
- if (includes("Android")(userAgent)) return some$1("Android");
114531
- if (includes("Macintosh")(userAgent)) return some$1("Mac");
114532
- if (includes("Windows")(userAgent)) return some$1("Windows");
114533
- if (includes("Linux")(userAgent)) return some$1("Linux");
114534
- return none();
114535
- }
114536
- function browserLabel(origin) {
114537
- const agent = origin.userAgent ?? "";
114538
- if (includes("Edg/")(agent)) return "Edge";
114539
- if (includes("Firefox/")(agent)) return "Firefox";
114540
- if (includes("Chrome/")(agent)) return "Chrome";
114541
- if (includes("Safari/")(agent)) return "Safari";
114542
- return "Browser";
114543
- }
114544
- function deviceLabel(origin) {
114545
- return pipe(flatMap$7(fromUndefinedOr(origin.address), (address) => {
114546
- if (exists(parsedAddress(address), (ip) => isLinkLocal(ip) || isLoopback(ip) || isPrivateOrUniqueLocal(ip))) return some$1("dev");
114547
- return get$13(WORKERS, address);
114548
- }), orElse$3(() => flatMap$7(fromUndefinedOr(origin.userAgent), platform)), getOrElse(() => origin.address ?? "unknown"));
114549
- }
114550
- function loopback(redirect) {
114551
- return filter$8(getSuccess(fromString(redirect)), (target) => target.protocol === "http:" && contains([
114552
- "127.0.0.1",
114553
- "[::1]",
114554
- "localhost"
114555
- ], target.hostname) && isEmpty$1(target.username) && isEmpty$1(target.password) && isEmpty$1(target.search) && isEmpty$1(target.hash));
114556
- }
114557
- function webRedirect(redirect) {
114558
- return isSome(match$3(/^https:\/\/[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.mp281x\.xyz\/auth\/callback$/u)(redirect));
114559
- }
114560
- function allowedRedirect(redirect) {
114561
- return webRedirect(redirect) || isSome(match$3(/^https:\/\/gateway\.mp281x\.xyz\/oauth\/callback\/[a-z0-9][a-z0-9_-]{0,23}$/u)(redirect)) || contains([
114562
- "stash://auth/callback",
114563
- "stash-dev://auth/callback",
114564
- "opm://auth/callback",
114565
- "opm-dev://auth/callback",
114566
- "trips://auth/callback",
114567
- "trips-dev://auth/callback"
114568
- ], redirect) || isSome(loopback(redirect));
114569
- }
114570
- function clientOf(clientId) {
114571
- return pipe(decodeString$2(clientId), getSuccess, flatMap$7(decodeUnknownOption(fromJsonString(ClientInfo))), filter$8((client) => every$1(client.redirects, allowedRedirect)));
114572
- }
114573
- function portless(redirect) {
114574
- return map$11(filter$8(match$3(/^(?<origin>http:\/\/(?:127\.0\.0\.1|\[::1\]|localhost))(?::\d{1,5})?(?<rest>\/.*)?$/u)(redirect), () => isSome(loopback(redirect))), (found) => `${found.groups?.["origin"] ?? ""}${found.groups?.["rest"] ?? ""}`);
114575
- }
114576
- function matchingRedirect(client, requested) {
114577
- return match$8(requested, {
114578
- onNone: () => filter$8(head(client.redirects), () => client.redirects.length === 1),
114579
- onSome: (asked) => as$2(findFirst(client.redirects, (redirect) => {
114580
- if (redirect === asked) return true;
114581
- return isSome(flatMap$7(portless(redirect), (saved) => filter$8(portless(asked), (target) => target === saved)));
114582
- }), asked)
114583
- });
114584
- }
114585
- function given(value) {
114586
- return filter$8(fromUndefinedOr(value), isNonEmpty$1);
114587
- }
114588
- const clientRequest = fnUntraced(function* (asked, client, params) {
114589
- if (isNone(given(params.response_type))) return yield* AuthError.make({ message: "Send response_type=code" });
114590
- if (params.response_type !== "code") return yield* AuthError.make({
114591
- error: "unsupported_response_type",
114592
- message: "Only response_type=code is supported"
114593
- });
114594
- if (params.code_challenge === void 0 || params.code_challenge_method !== "S256") return yield* AuthError.make({ message: "Send a PKCE code_challenge with code_challenge_method=S256" });
114595
- if (!every$1(filter$6(split$2(params.scope ?? "", " "), isNonEmpty$1), (scope) => scope === "deslop" || scope === "offline_access")) return yield* AuthError.make({
114596
- error: "invalid_scope",
114597
- message: "Only the deslop scope is supported"
114598
- });
114599
- return ClientRequest.make({
114600
- challenge: params.code_challenge,
114601
- clientId: asked.client_id,
114602
- clientName: client.clientName,
114603
- redirectUri: client.redirectUri,
114604
- ...match$8(given(asked.state), {
114605
- onNone: () => ({}),
114606
- onSome: (state) => ({ state })
114607
- })
114608
- });
114609
- });
114610
- function callbackUrl(request, answer, issuer) {
114611
- const target = new URL(request.redirectUri);
114612
- for (const entry of toEntries(answer)) target.searchParams.set(entry[0], entry[1]);
114613
- map$11(given(request.state), (sent) => target.searchParams.set("state", sent));
114614
- target.searchParams.set("iss", issuer);
114615
- return target.href;
114616
- }
114617
- function returnable(next, url) {
114618
- const domain = "mp281x.xyz";
114619
- return match$6(fromString(next), {
114620
- onFailure: () => false,
114621
- onSuccess: (target) => (target.origin === new URL(url).origin || target.protocol === "https:" && (target.hostname === domain || endsWith(`.${domain}`)(target.hostname))) && isEmpty$1(target.username) && isEmpty$1(target.password)
114622
- });
114623
- }
114624
114637
  // src/services/passkeys/service.ts
114625
114638
  const LIFETIME = 3e5;
114626
114639
  function invalid(cause) {
@@ -114693,9 +114706,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114693
114706
  return [...current, {
114694
114707
  addedFrom: `${browserLabel(from)} · ${deviceLabel(from)}`,
114695
114708
  counter: credential.counter,
114696
- createdAt: now,
114697
114709
  id: credential.id,
114698
- lastUsed: now,
114699
114710
  publicKey: encode$3(credential.publicKey),
114700
114711
  synced: verified.registrationInfo.credentialDeviceType === "multiDevice",
114701
114712
  transports,
@@ -114709,9 +114720,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114709
114720
  }, rejected("Cannot remove the account’s passkeys")),
114710
114721
  list: (owner) => map$3(changes(state), (current) => map$8(filter$6(current, (found) => sameOwner(found, owner)), (found) => ({
114711
114722
  addedFrom: found.addedFrom,
114712
- createdAt: found.createdAt,
114713
114723
  id: found.id,
114714
- lastUsed: found.lastUsed,
114715
114724
  synced: found.synced
114716
114725
  }))),
114717
114726
  registration: fn("Passkeys.registration")(function* (owner, via) {
@@ -114781,8 +114790,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114781
114790
  if (stored.id !== found.id) return stored;
114782
114791
  return {
114783
114792
  ...stored,
114784
- counter: max(stored.counter, verified.authenticationInfo.newCounter),
114785
- lastUsed: now
114793
+ counter: max(stored.counter, verified.authenticationInfo.newCounter)
114786
114794
  };
114787
114795
  })));
114788
114796
  return {
@@ -114798,7 +114806,6 @@ const SignInKind = Literals(["App", "Browser"]);
114798
114806
  const PendingAuthorization = Struct({
114799
114807
  address: optionalKey(String$6),
114800
114808
  clientName: String$6,
114801
- createdAt: Finite,
114802
114809
  device: String$6,
114803
114810
  expiresAt: Finite,
114804
114811
  id: NonEmptyString,
@@ -114871,9 +114878,6 @@ var RpcContracts = class extends make$31(make$35("auth.lookup", {
114871
114878
  }), make$35("auth.addPasskey", {
114872
114879
  error: AuthError,
114873
114880
  payload: AddPasskeyParams
114874
- }), make$35("auth.removePasskey", {
114875
- error: AuthError,
114876
- payload: PasskeyParams
114877
114881
  })).middleware(RpcAuth).middleware(RpcOwner).merge(make$31(make$35("auth.account", {
114878
114882
  error: AuthError,
114879
114883
  stream: true,
@@ -114886,9 +114890,9 @@ var RpcContracts = class extends make$31(make$35("auth.lookup", {
114886
114890
  }))) {};
114887
114891
  // src/services/people/lib/utils.ts
114888
114892
  const ROLE_ORDER = {
114889
- Admin: 0,
114893
+ Admin: 1,
114890
114894
  Member: 2,
114891
- Waiting: 1
114895
+ Waiting: 0
114892
114896
  };
114893
114897
  function ownerOf(row) {
114894
114898
  return {
@@ -114992,6 +114996,21 @@ function parts(token) {
114992
114996
  function end(grants, family) {
114993
114997
  return filter$7(grants, (grant, key) => key !== family && grant.parent !== family);
114994
114998
  }
114999
+ function touch(current, family, now) {
115000
+ return match$8(get$13(current, family), {
115001
+ onNone: () => current,
115002
+ onSome: (grant) => match$1(now - grant.lastActive > 6e4, {
115003
+ onFalse: () => current,
115004
+ onTrue: () => ({
115005
+ ...current,
115006
+ [family]: {
115007
+ ...grant,
115008
+ lastActive: now
115009
+ }
115010
+ })
115011
+ })
115012
+ });
115013
+ }
114995
115014
  var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/service/Tokens") {
114996
115015
  static layer = effect(Tokens, gen(function* () {
114997
115016
  const storage = yield* KeyValueStore;
@@ -115015,14 +115034,8 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115015
115034
  const signature = yield* Signature;
115016
115035
  const codes = yield* make$58(empty$4());
115017
115036
  const redeeming = yield* make$71(1);
115018
- const random = yield* SecureRandom;
115019
- const digest = yield* Digest;
115020
- function secret(bytes) {
115021
- return map$5(random.randomBytes(bytes), encode$3);
115022
- }
115023
- const hash = fnUntraced(function* (value) {
115024
- return encode$3(yield* digest.digest(sha256, new TextEncoder().encode(value)));
115025
- });
115037
+ const randomToken = randomTokenOf(yield* SecureRandom);
115038
+ const hash = hashOf(yield* Digest);
115026
115039
  const change = fnUntraced(function* (update) {
115027
115040
  return yield* modifyEffect(grants, (current) => gen(function* () {
115028
115041
  const now = yield* currentTimeMillis;
@@ -115073,19 +115086,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115073
115086
  grant: signedIn,
115074
115087
  now
115075
115088
  };
115076
- if (found.now - found.grant.lastActive > 6e4) yield* pipe(change((current) => succeed$5([void 0, match$8(get$13(current, found.family), {
115077
- onNone: () => current,
115078
- onSome: (grant) => match$1(found.now - grant.lastActive > 6e4, {
115079
- onFalse: () => current,
115080
- onTrue: () => ({
115081
- ...current,
115082
- [found.family]: {
115083
- ...grant,
115084
- lastActive: found.now
115085
- }
115086
- })
115087
- })
115088
- })])), ignore$1({
115089
+ if (found.now - found.grant.lastActive > 6e4) yield* pipe(change((current) => succeed$5([void 0, touch(current, found.family, found.now)])), ignore$1({
115089
115090
  log: "Warn",
115090
115091
  message: "The token’s last use could not be saved"
115091
115092
  }));
@@ -115095,7 +115096,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115095
115096
  };
115096
115097
  }, rejected("Sign in first"));
115097
115098
  const mint = fnUntraced(function* (family, generation, owner, client, now) {
115098
- const refreshSecret = yield* secret(32);
115099
+ const refreshSecret = yield* randomToken(32);
115099
115100
  const iat = Math.floor(now / 1e3);
115100
115101
  const access = yield* provideService(sign(AccessClaims, {
115101
115102
  aud: "deslop",
@@ -115128,7 +115129,6 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115128
115129
  const minted = yield* pipe(mint(family, 0, owner, clientLabel(request.clientName), now), rejected("Cannot sign the access token"));
115129
115130
  const grant = {
115130
115131
  client: clientLabel(request.clientName),
115131
- createdAt: now,
115132
115132
  credential: {
115133
115133
  _tag: "App",
115134
115134
  clientId: request.clientId,
@@ -115138,7 +115138,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115138
115138
  },
115139
115139
  device: deviceLabel(origin),
115140
115140
  lastActive: now,
115141
- origin,
115141
+ origin: storedOrigin(origin),
115142
115142
  ...pick(request, ["parent"]),
115143
115143
  ...owner
115144
115144
  };
@@ -115151,7 +115151,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115151
115151
  const redeem = fnUntraced(function* (params, origin, allowed) {
115152
115152
  const key = yield* hash(params.code);
115153
115153
  const verifier = yield* hash(params.code_verifier);
115154
- const family = yield* secret(16);
115154
+ const family = yield* randomToken(16);
115155
115155
  const result = yield* change((current, now) => gen(function* () {
115156
115156
  const code = yield* pipe(get$4(yield* get$7(codes), key), filter$8((entry) => entry.expiresAt > now), fromOption, mapError$2(() => expired$1));
115157
115157
  if (code.state._tag === "Used") return [Exchange.cases.Replayed.make({ message: "This authorization code was already used, so the tokens it gave are revoked; sign in again" }), remove$6(current, code.state.family)];
@@ -115200,7 +115200,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115200
115200
  },
115201
115201
  device: deviceLabel(origin),
115202
115202
  lastActive: now,
115203
- origin
115203
+ origin: storedOrigin(origin)
115204
115204
  }
115205
115205
  }];
115206
115206
  }));
@@ -115228,7 +115228,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115228
115228
  };
115229
115229
  }),
115230
115230
  device: fn("Tokens.device")(function* (request, owner, origin) {
115231
- const family = yield* secret(16);
115231
+ const family = yield* randomToken(16);
115232
115232
  return yield* change((current, now) => signIn(current, now, family, request, owner, origin));
115233
115233
  }, rejected("Cannot sign the command in")),
115234
115234
  disconnect: fn("Tokens.disconnect")(function* (family, owner) {
@@ -115252,7 +115252,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115252
115252
  yield* update$3(codes, filter((entry) => entry.state._tag === "Used" || !sameOwner(entry.state.owner, owner)));
115253
115253
  }, rejected("Cannot sign this account out")),
115254
115254
  issue: fn("Tokens.issue")(function* (request, owner) {
115255
- const code = yield* secret(32);
115255
+ const code = yield* randomToken(32);
115256
115256
  const key = yield* hash(code);
115257
115257
  const now = yield* currentTimeMillis;
115258
115258
  yield* update$3(codes, (current) => set$1(filter(current, (entry) => entry.expiresAt > now), key, {
@@ -115282,8 +115282,8 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115282
115282
  session,
115283
115283
  sessionVia,
115284
115284
  startSession: fn("Tokens.startSession")(function* (owner, origin, via, previousToken) {
115285
- const family = yield* secret(16);
115286
- const sessionSecret = yield* secret(32);
115285
+ const family = yield* randomToken(16);
115286
+ const sessionSecret = yield* randomToken(32);
115287
115287
  const seconds = pipe(value(via), when("Code", () => 2592e3), when("GitHub", () => 31536e3), when("Passkey", () => 31536e3), exhaustive);
115288
115288
  const sessionHash = yield* hash(sessionSecret);
115289
115289
  const previous = yield* transposeOption(map$11(parts(previousToken), (prior) => map$5(hash(prior.secret), (presented) => ({
@@ -115302,7 +115302,6 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115302
115302
  ...retained,
115303
115303
  [family]: {
115304
115304
  client: browserLabel(origin),
115305
- createdAt: now,
115306
115305
  credential: {
115307
115306
  _tag: "Browser",
115308
115307
  expiresAt: now + seconds * 1e3,
@@ -115311,7 +115310,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115311
115310
  },
115312
115311
  device: deviceLabel(origin),
115313
115312
  lastActive: now,
115314
- origin,
115313
+ origin: storedOrigin(origin),
115315
115314
  ...owner
115316
115315
  }
115317
115316
  }]);
@@ -115337,8 +115336,8 @@ var People = class People extends Service$1()("@deslop/auth/services/people/serv
115337
115336
  const passkeys = yield* Passkeys;
115338
115337
  const github = yield* GitHub;
115339
115338
  const admins = yield* adminIds;
115340
- const random = yield* SecureRandom;
115341
115339
  const local = yield* localAuth;
115340
+ const randomToken = randomTokenOf(yield* SecureRandom);
115342
115341
  const developer = {
115343
115342
  incarnation: "local",
115344
115343
  user: DEVELOPER
@@ -115439,7 +115438,7 @@ var People = class People extends Service$1()("@deslop/auth/services/people/serv
115439
115438
  return registerMember(current, admins, profile, since, yield* match$8(member(`github:${profile.id}`, current), {
115440
115439
  onNone: () => {
115441
115440
  if (local && profile.id === 0) return succeed$5("local");
115442
- return map$5(random.randomBytes(32), encode$3);
115441
+ return randomToken(32);
115443
115442
  },
115444
115443
  onSome: (row) => succeed$5(row.incarnation)
115445
115444
  }));
@@ -115476,6 +115475,7 @@ const layerIssuerAuth = effectContext(gen(function* () {
115476
115475
  }));
115477
115476
  // src/services/sign-ins/lib/utils.ts
115478
115477
  const CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
115478
+ const SIGN_IN_LIFETIME = minutes(10);
115479
115479
  function typedCode(text) {
115480
115480
  return toUpperCase(replaceAll(/[^a-z]/giu, "")(text));
115481
115481
  }
@@ -122744,7 +122744,7 @@ const start = start$1;
122744
122744
  // src/services/sign-ins/service.ts
122745
122745
  const REQUEST_COOKIE = "__Host-request-";
122746
122746
  const expired = AuthError.make({ message: "This sign-in expired. Start it again in the app." });
122747
- const notWaiting = AuthError.make({ message: "No waiting sign-in has this code: it is mistyped, already answered or expired after 10 minutes. Read the code again from the page or command that is still waiting; start a new sign-in only if none is." });
122747
+ const notWaiting = AuthError.make({ message: `No waiting sign-in has this code: it is mistyped, already answered or expired after ${toMinutes(SIGN_IN_LIFETIME)} minutes. Read the code again from the page or command that is still waiting; start a new sign-in only if none is.` });
122748
122748
  const deliver = fnUntraced(function* (input) {
122749
122749
  const tokens = yield* Tokens;
122750
122750
  const people = yield* People;
@@ -122805,7 +122805,7 @@ const SignIn = make({
122805
122805
  }),
122806
122806
  input: SignInInput,
122807
122807
  root: SignInStates,
122808
- timers: { lifetime: "10 minutes" }
122808
+ timers: { lifetime: SIGN_IN_LIFETIME }
122809
122809
  }).handle({
122810
122810
  initial: {
122811
122811
  data: (transition) => transition.input,
@@ -122876,13 +122876,11 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122876
122876
  const tokens = yield* Tokens;
122877
122877
  const people = yield* People;
122878
122878
  const random = yield* SecureRandom;
122879
- const digest = yield* Digest;
122879
+ const randomToken = randomTokenOf(random);
122880
+ const hash = hashOf(yield* Digest);
122880
122881
  const scope$2 = yield* scope;
122881
122882
  const open = yield* make$18(empty$4());
122882
122883
  const answering = yield* make$71(1);
122883
- const hash = fnUntraced(function* (value) {
122884
- return encode$3(yield* digest.digest(sha256, new TextEncoder().encode(value)));
122885
- });
122886
122884
  function find(code) {
122887
122885
  return map$5(get(open), get$4(typedCode(code)));
122888
122886
  }
@@ -122963,7 +122961,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122963
122961
  start: fn("SignIns.start")(function* (delivery, origin) {
122964
122962
  const code = codeFrom(yield* random.randomBytes(8));
122965
122963
  const now = yield* currentTimeMillis;
122966
- const receiver = encode$3(yield* random.randomBytes(32));
122964
+ const receiver = yield* randomToken(32);
122967
122965
  const owned = yield* fork(scope$2);
122968
122966
  const ref = yield* pipe(run({
122969
122967
  delivery,
@@ -122992,8 +122990,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122992
122990
  kind: "App"
122993
122991
  })
122994
122992
  }),
122995
- createdAt: now,
122996
- expiresAt: now + 6e5,
122993
+ expiresAt: now + toMillis(SIGN_IN_LIFETIME),
122997
122994
  id: code
122998
122995
  }),
122999
122996
  receiver: yield* hash(receiver),
@@ -123032,12 +123029,6 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
123032
123029
  }));
123033
123030
  };
123034
123031
  // src/http/handlers.ts
123035
- const COOKIE = {
123036
- httpOnly: true,
123037
- path: "/",
123038
- sameSite: "lax",
123039
- secure: true
123040
- };
123041
123032
  const LOGIN_COOKIE = "__Host-login";
123042
123033
  function session(seconds) {
123043
123034
  return {
@@ -123199,7 +123190,7 @@ const HttpHandlers = use((router) => gen(function* () {
123199
123190
  }, originOf(request));
123200
123191
  return jsonUnsafe({
123201
123192
  device_code: started.receiver,
123202
- expires_in: 600,
123193
+ expires_in: toSeconds(SIGN_IN_LIFETIME),
123203
123194
  interval: 2,
123204
123195
  user_code: started.code,
123205
123196
  verification_uri: `${origin}/`,
@@ -123308,9 +123299,6 @@ const RpcHandlers = RpcContracts.toLayer(gen(function* () {
123308
123299
  }),
123309
123300
  "auth.passkeys": () => unwrap$4(map$5(CurrentOwner, passkeys.list)),
123310
123301
  "auth.people": () => unwrap$4(map$5(CurrentUser, people.people)),
123311
- "auth.removePasskey": fnUntraced(function* (input) {
123312
- yield* passkeys.remove(input.id, yield* CurrentOwner);
123313
- }),
123314
123302
  "auth.wait": (input, options) => onStart(signIns.status(input.request, options.headers), annotateCurrentSpan("rpc.stream", true))
123315
123303
  });
123316
123304
  }));
@@ -123342,6 +123330,18 @@ const Tools = make$15(make$16("answer_request", {
123342
123330
  failure: AuthError,
123343
123331
  parameters: Struct({ id: NonEmptyString }),
123344
123332
  success: Struct({ id: NonEmptyString })
123333
+ }).annotate(Destructive, true), make$16("list_passkeys", {
123334
+ dependencies: [CurrentOwner],
123335
+ description: "Each passkey of yours with its id, browser and device, and whether it is synced; remove one with remove_passkey.",
123336
+ failure: AuthError,
123337
+ parameters: EmptyParams,
123338
+ success: Struct({ passkeys: ArraySchema(Passkey) })
123339
+ }).annotate(Readonly, true), make$16("remove_passkey", {
123340
+ dependencies: [CurrentOwner],
123341
+ description: "Remove one of your passkeys by the id list_passkeys returns.",
123342
+ failure: AuthError,
123343
+ parameters: PasskeyParams,
123344
+ success: Struct({ id: NonEmptyString })
123345
123345
  }).annotate(Destructive, true), make$16("remove_person", {
123346
123346
  dependencies: [CurrentOwner],
123347
123347
  description: "Remove a member by their GitHub login; admins cannot be removed.",
@@ -123369,6 +123369,7 @@ const layerMcpOwner = unwrap$7(gen(function* () {
123369
123369
  })), (owner) => provideService(effect, CurrentOwner, owner))).layer;
123370
123370
  }));
123371
123371
  const ToolHandlers = Tools.toLayer(gen(function* () {
123372
+ const passkeys = yield* Passkeys;
123372
123373
  const people = yield* People;
123373
123374
  const signIns = yield* SignIns;
123374
123375
  const tokens = yield* Tokens;
@@ -123376,6 +123377,9 @@ const ToolHandlers = Tools.toLayer(gen(function* () {
123376
123377
  answer_request: fnUntraced(function* (input) {
123377
123378
  return yield* signIns.answer(input, yield* CurrentOwner, "Token");
123378
123379
  }),
123380
+ list_passkeys: fnUntraced(function* () {
123381
+ return { passkeys: getOrElse(yield* runHead(passkeys.list(yield* CurrentOwner)), () => []) };
123382
+ }),
123379
123383
  list_sessions: fnUntraced(function* () {
123380
123384
  return { sessions: map$8(withChildActivity(getOrElse(yield* runHead(tokens.apps(yield* CurrentOwner)), () => [])), (app) => ({
123381
123385
  ...pick(app, [
@@ -123387,6 +123391,12 @@ const ToolHandlers = Tools.toLayer(gen(function* () {
123387
123391
  id: app.family
123388
123392
  })) };
123389
123393
  }),
123394
+ remove_passkey: fnUntraced(function* (input) {
123395
+ const owner = yield* CurrentOwner;
123396
+ yield* pipe(findFirst(getOrElse(yield* runHead(passkeys.list(owner)), () => []), (found) => found.id === input.id), fromOption, mapError$2(() => AuthError.make({ message: "No passkey of yours has that id" })));
123397
+ yield* passkeys.remove(input.id, owner);
123398
+ return { id: input.id };
123399
+ }),
123390
123400
  remove_person: fnUntraced(function* (input) {
123391
123401
  const owner = yield* CurrentOwner;
123392
123402
  const wanted = toLowerCase(input.login);
@@ -123400,7 +123410,7 @@ const ToolHandlers = Tools.toLayer(gen(function* () {
123400
123410
  });
123401
123411
  }));
123402
123412
  // src/main.server.ts
123403
- const layerServices = pipe(mergeAll$1(SignIns.layer, layer$2), provideMerge(People.layer), provideMerge(mergeAll$1(Tokens.layer, Passkeys.layer, GitHub.layer, Apps.layer, layerStoreMemory)), provide$2(layerDataStore), provide$2(succeed$6(RequestInit, { redirect: "error" })));
123413
+ const layerServices = pipe(mergeAll$1(SignIns.layer, provide$2(layer$2, layerStoreMemory)), provideMerge(People.layer), provideMerge(mergeAll$1(Tokens.layer, Passkeys.layer, GitHub.layer, Apps.layer)), provide$2(succeed$6(RequestInit, { redirect: "error" })));
123404
123414
  runApp({
123405
123415
  auth: provide$2(layerIssuerAuth, layerServices),
123406
123416
  icon: icon_default,